Не могу объеденить 2 проекта?

Ответить
Mestniy96
Сообщения: 3
Зарегистрирован: 29 ноя 2019, 13:52

Не могу объеденить 2 проекта?

Сообщение Mestniy96 » 29 ноя 2019, 13:56

Вот MainActivity.java моего проекта:

Код: Выделить всё

package com.example.kam;

import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.view.Menu;
import android.view.MenuItem;

import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.os.CountDownTimer;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeUnit;


public class MainActivity extends AppCompatActivity {
    TextView tvOut;
    Button btnminus;
    Button btnpls;
    Button btnup;
    Button btndown;
    ProgressBar progressBar;
    int timing1;
    int soundlvl = 0;
    int oneminute = 60000;
    int timingminutes;
    boolean timing2 = false;
    private CountDownTimer countDownTimer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(view -> Snackbar.make(view, "Replace with your own action",
                Snackbar.LENGTH_LONG).setAction("Action", null).show());

        progressBar = findViewById(R.id.progressBar);
        tvOut = findViewById(R.id.tvOut);
        btnminus = findViewById(R.id.btnminus);
        btnpls = findViewById(R.id.btnpls);
        btnup = findViewById(R.id. btnup);
        btndown = findViewById(R.id.btndown);

        btnminus.setOnClickListener(view -> {
            if (soundlvl > 0) {
                soundlvl = soundlvl-1;
                progressBar.setProgress(soundlvl);
            }
        });

        btnpls.setOnClickListener(view -> {
            if (soundlvl < 10) {
                soundlvl = soundlvl + 1;
                progressBar.setProgress(soundlvl);
            }
        });

        btndown.setOnClickListener(view -> {
            if (timing1 > 0) {
                timing1 = timing1 - 10;
                String numberString = String.valueOf(timing1);
                tvOut.setText("" + numberString);
                timing2 = true;
                timingminutes = timing1 * oneminute;
                calculateCountDown();
            }
        });

        btnup.setOnClickListener(view -> {
            if (timing1 < 90) {
                timing1 = timing1 + 10;
                String numberString = String.valueOf(timing1);
                tvOut.setText("" + numberString);
                timing2 = true;
                timingminutes = timing1 * oneminute;
                calculateCountDown();
            }
        });
    }

    private void calculateCountDown() {
        if (timing2 == true) {

            if (countDownTimer != null) {
                countDownTimer.cancel();
            }

            countDownTimer = new CountDownTimer(timingminutes, 1000) {

                //Здесь обновляем текст счетчика обратного отсчета с каждой секундой
                public void onTick(long millisUntilFinished) {

                    String value = String.format("%d мин %d сек",
                            TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
                            TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
                                    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))
                    );;
                    tvOut.setText(value);
                }

                //Задаем действия после завершения отсчета (высвечиваем надпись "Бабах!"):
                public void onFinish() {
                    timing2 = false;
                }
            }
                    .start();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
Вот xml моего проекта:

Код: Выделить всё

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="<a href="http://schemas.android.com/apk/res/android" rel="nofollow">http://schemas.android.com/apk/res/android</a>" xmlns:app="<a href="http://schemas.android.com/apk/res-auto" rel="nofollow">http://schemas.android.com/apk/res-auto</a>" xmlns:tools="<a href="http://schemas.android.com/tools" rel="nofollow">http://schemas.android.com/tools</a>" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context=".MainActivity" tools:layout_editor_absoluteY="56dp" tools:showIn="@layout/activity_main">

    <Button
        android:id="@+id/btnminus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:text="@string/mns"
        app:layout_constraintBottom_toBottomOf="@+id/textView"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/textView"
        tools:text="-" />

    <Button
        android:id="@+id/btndown"
        android:layout_width="76dp"
        android:layout_height="61dp"
        android:layout_marginStart="16dp"
        android:text="@string/timeminus"
        app:layout_constraintBottom_toBottomOf="@+id/textView2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/textView2" />

    <Button
        android:id="@+id/btnpls"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:text="@string/pls"
        app:layout_constraintBottom_toBottomOf="@+id/textView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="@+id/textView" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:layout_width="168dp"
        android:layout_height="42dp"
        android:layout_marginStart="128dp"
        android:layout_marginEnd="115dp"
        android:layout_marginBottom="124dp"
        android:max="10"
        android:progress="0"
        app:layout_constraintBottom_toTopOf="@+id/textView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="18dp"
        android:text="@string/timer"
        android:textSize="24sp"
        app:layout_constraintBottom_toTopOf="@+id/tvOut"
        app:layout_constraintEnd_toStartOf="@+id/btnup"
        app:layout_constraintHorizontal_bias="0.305"
        app:layout_constraintStart_toEndOf="@+id/btndown" />

    <Button
        android:id="@+id/btnup"
        android:layout_width="76dp"
        android:layout_height="61dp"
        android:layout_marginEnd="16dp"
        android:text="@string/UP"
        app:layout_constraintBottom_toBottomOf="@+id/textView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="@+id/textView2" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/sound"
        android:textSize="24sp"
        app:layout_constraintBottom_toTopOf="@+id/progressBar"
        app:layout_constraintEnd_toStartOf="@+id/btnpls"
        app:layout_constraintStart_toEndOf="@+id/btnminus" />

    <TextView
        android:id="@+id/tvOut"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="185dp"
        android:layout_marginEnd="186dp"
        android:layout_marginBottom="202dp"
        android:text="@string/tvouting"
        android:textSize="36sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <ToggleButton android:id="@+id/toggleButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:text="@string/togglebutton" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
А вот MainActivity.java к которому я хочу присобачить мой проект или его присобачить к моему проекту:

Код: Выделить всё

package com.example.kaminone;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;

public class MainActivity extends Activity implements View.OnClickListener {

    public final static String PREF_IP = "PREF_IP_ADDRESS";
    public final static String PREF_PORT = "PREF_PORT_NUMBER";
    // объявление кнопок и текстовых полей ввода
    private Button buttonPin11,buttonPin12,buttonPin13;
    private EditText editTextIPAddress, editTextPortNumber;
    // общие объекты параметров, используемые для сохранения IP адреса и порта, чтобы
    // пользователь не вводил их в следующий раз, когда он открывает приложение
    SharedPreferences.Editor editor;
    SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sharedPreferences = getSharedPreferences("HTTP_HELPER_PREFS",Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();

        // назначить кнопки
        buttonPin11 = (Button)findViewById(R.id.buttonPin11);
        buttonPin12 = (Button)findViewById(R.id.buttonPin12);
        buttonPin13 = (Button)findViewById(R.id.buttonPin13);

        // назначить поля ввода
        editTextIPAddress = (EditText)findViewById(R.id.editTextIPAddress);
        editTextPortNumber = (EditText)findViewById(R.id.editTextPortNumber);

        // назначить слушателя кнопок (этот класс)
        buttonPin11.setOnClickListener(this);
        buttonPin12.setOnClickListener(this);
        buttonPin13.setOnClickListener(this);

        // получить IP адрес и номер порта из последнего раза, когда пользователь использовал
        // приложение, или поместить пустую строку "", если это первый раз
        editTextIPAddress.setText(sharedPreferences.getString(PREF_IP,""));
        editTextPortNumber.setText(sharedPreferences.getString(PREF_PORT,""));
    }


    @Override
    public void onClick(View view) {

        // номер вывода
        String parameterValue = "";
        // получить ip адрес
        String ipAddress = editTextIPAddress.getText().toString().trim();
        // получить номер порта
        String portNumber = editTextPortNumber.getText().toString().trim();


        // сохранить IP адрес и номер порта для следующего использования приложения
        editor.putString(PREF_IP,ipAddress);    // установить значение ip адреса для сохранения
        editor.putString(PREF_PORT,portNumber); // установить номер порта для сохранения
        editor.commit(); // сохранить IP и PORT

        // получить номер порта от кнопки, которая была нажата
        if(view.getId()==buttonPin11.getId())
        {
            parameterValue = "11";
        }
        else if(view.getId()==buttonPin12.getId())
        {
            parameterValue = "12";
        }
        else
        {
            parameterValue = "13";
        }



        // выполнить HTTP запрос
        if(ipAddress.length()>0 && portNumber.length()>0) {
            new HttpRequestAsyncTask(
                    view.getContext(), parameterValue, ipAddress, portNumber, "pin"
            ).execute();
        }
    }

    /**
     * Description: Послать HTTP Get запрос на указанные ip адрес и порт.
     * Также послать параметр "parameterName" со значением "parameterValue".
     * @param parameterValue номер порта, у которого необходимо изменить состояние
     * @param ipAddress ip адрес, на который необходимо послать запрос
     * @param portNumber номер порта ip адреса
     * @param parameterName
     * @return Текст ответа с ip адреса или сообщение ERROR, если не получилось получить ответ
     */
    public String sendRequest(String parameterValue, String ipAddress, String portNumber, String parameterName) {
        String serverResponse = "ERROR";

        try {

            HttpClient httpclient = new DefaultHttpClient(); // создать HTTP клиента
            // установить URL, например, <a href="http://myIpaddress/?pin=13" title="http://myIpaddress:myport/?pin=13" rel="nofollow">http://myIpaddress:myport/?pin=13</a> (например, переключить вывод 13)
            URI website = new URI("http://"+ipAddress+":"+portNumber+"/?"+parameterName+"="+parameterValue);
            HttpGet getRequest = new HttpGet(); // создать объект HTTP GET
            getRequest.setURI(website);         // установить URL для GET запроса
            HttpResponse response = httpclient.execute(getRequest); // выполнить запрос
            // получить ответ сервера с заданным ip адресом
            InputStream content = null;
            content = response.getEntity().getContent();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    content
            ));
            serverResponse = in.readLine();
            // Закрыть соединение
            content.close();
        } catch (ClientProtocolException e) {
            // ошибка HTTP
            serverResponse = e.getMessage();
            e.printStackTrace();
        } catch (IOException e) {
            // ошибка ввода/вывода
            serverResponse = e.getMessage();
            e.printStackTrace();
        } catch (URISyntaxException e) {
            // ошибка синтаксиса URL
            serverResponse = e.getMessage();
            e.printStackTrace();
        }
        // вернуть текст отклика сервера
        return serverResponse;
    }


    /**
     * AsyncTask необходим для выполнения HTTP запроса в фоне, чтобы они не блокировали
     * пользовательский интерфейс.
     */
    private class HttpRequestAsyncTask extends AsyncTask<Void, Void, Void> {

        // объявить необходимые переменные
        private String requestReply,ipAddress, portNumber;
        private Context context;
        private AlertDialog alertDialog;
        private String parameter;
        private String parameterValue;

        /**
         * Description: Конструктор класса asyncTask. Назначить значения, используемые в других методах.
         * @param context контекст приложения, необходим для создания диалога
         * @param parameterValue номер вывода для переключения
         * @param ipAddress ip адрес, на который необходимо послать запрос
         * @param portNumber номер порта ip адреса
         */
        public HttpRequestAsyncTask(Context context, String parameterValue, String ipAddress, String portNumber, String parameter)
        {
            this.context = context;

            alertDialog = new AlertDialog.Builder(this.context)
                    .setTitle("HTTP Response From IP Address:")
                    .setCancelable(true)
                    .create();

            this.ipAddress = ipAddress;
            this.parameterValue = parameterValue;
            this.portNumber = portNumber;
            this.parameter = parameter;
        }

        /**
         * Name: doInBackground
         * Description: Отправляет запрос на ip адрес
         * @param voids
         * @return
         */
        @Override
        protected Void doInBackground(Void... voids) {
            alertDialog.setMessage("Data sent, waiting for reply from server...");
            if(!alertDialog.isShowing())
            {
                alertDialog.show();
            }
            requestReply = sendRequest(parameterValue,ipAddress,portNumber, parameter);
            return null;
        }

        /**
         * Name: onPostExecute
         * Description: Данная функция выполняется после возвращения ответа на HTTP запрос на ip адрес.
         * Функция устанавливает сообщение диалога с текстом ответа от сервера и отображает диалог,
         * если он уже не показан (в случае, если он был закрыт случайно);
         * @param aVoid void параметр
         */
        @Override
        protected void onPostExecute(Void aVoid) {
            alertDialog.setMessage(requestReply);
            if(!alertDialog.isShowing())
            {
                alertDialog.show(); // показать диалог
            }
        }

        /**
         * Name: onPreExecute
         * Description: Данная функция выполняется перед отправкой HTTP запроса на ip адрес.
         * Функция установит сообщение диалога и отобразит диалоговое окно.
         */
        @Override
        protected void onPreExecute() {
            alertDialog.setMessage("Sending data to server, please wait...");
            if(!alertDialog.isShowing())
            {
                alertDialog.show();
            }
        }

    }
}
Вот его xml:

Код: Выделить всё

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="<a href="http://schemas.android.com/apk/res/android" rel="nofollow">http://schemas.android.com/apk/res/android</a>"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">


        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="IP Address:"
            android:id="@+id/textView" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="e.g. 192.168.0.10"
            android:id="@+id/editTextIPAddress" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Port Number:"
            android:id="@+id/textView2" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:ems="10"
            android:hint="e.g. 80"
            android:id="@+id/editTextPortNumber" />

        <Button
            android:id="@+id/buttonPin11"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Pin 11" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Pin 12"
            android:id="@+id/buttonPin12" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Pin 13"
            android:id="@+id/buttonPin13" />
    </LinearLayout>

</ScrollView>
Вот манифест:

Код: Выделить всё

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="<a href="http://schemas.android.com/apk/res/android" rel="nofollow">http://schemas.android.com/apk/res/android</a>"
package="com.example.kaminone">

<uses-permission android:name="android.permission.INTERNET" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>
А вот build.gradle:

Код: Выделить всё

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.kaminone"
        minSdkVersion 24
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    useLibrary 'org.apache.http.legacy'
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}

Mestniy96
Сообщения: 3
Зарегистрирован: 29 ноя 2019, 13:52

Re: Не могу объеденить 2 проекта?

Сообщение Mestniy96 » 29 ноя 2019, 13:57

Что я хочу сделать в моему проекте:

При нажатии кнопок: btnminus, btnpls, btnup, btndown. Отправлять соответствующие значения по принцыпу второго примера.

Например:

btnminus = "btnminus" и т.д..

Mestniy96
Сообщения: 3
Зарегистрирован: 29 ноя 2019, 13:52

Re: Не могу объеденить 2 проекта?

Сообщение Mestniy96 » 29 ноя 2019, 13:57

Вот ссылка на мой проект:
drive.google.com/open?id=1xUj95IVdqFc9JZjIGxQ4VDcPMGA9Y1e4
А вот ссылка на проект по передачи данных — я не могу их соеденить=(((
drive.google.com/open?id=1B_qdYkOkK7cGp-W91HZr8UMV3gYA4r2c

Ответить