0

Собственно вот какая задача:

Есть http://dancecrm.ru/templates/register.php На данной странице как вы уже поняли сылка на регистрацию на сайте. Мне необходимо сделать мобильное приложение под android, а именно форму регистрации. Как это делать ?

Из разных источников узнал что надо делать через post запросы и json. Но сам не владею этими вещами, а тем более делать с их помощью регистрацию.

P.S. Сайт моего друга, так что все данные у меня есть, если они будут необходимы.

1 ответ 1

3

Здравствуйте!

Для начала вам необходимо создать форму. Для этого нужно создать .xml файл. Путь создания: res/layout/activity_registration.xml

activity_registration.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<EditText
    android:id="@+id/editText_username"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginEnd="32dp"
    android:layout_marginStart="32dp"
    android:layout_marginTop="128dp"
    android:ems="10"
    android:inputType="textPersonName"
    android:text=""
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />


<TextView
    android:id="@+id/textView_username"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginLeft="32dp"
    android:layout_marginStart="32dp"
    android:text="Фамилия имя: "
    app:layout_constraintBottom_toTopOf="@+id/editText_username"
    app:layout_constraintStart_toStartOf="parent" />

<EditText
    android:id="@+id/editText_email"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginEnd="32dp"
    android:layout_marginStart="32dp"
    android:layout_marginTop="32dp"
    android:ems="10"
    android:inputType="textEmailAddress"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/editText_username" />

<TextView
    android:id="@+id/textView_email"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginLeft="32dp"
    android:layout_marginStart="32dp"
    android:text="E-Mail:"
    app:layout_constraintBottom_toTopOf="@+id/editText_email"
    app:layout_constraintStart_toStartOf="parent" />

<EditText
    android:id="@+id/editText_password"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginEnd="32dp"
    android:layout_marginStart="32dp"
    android:layout_marginTop="32dp"
    android:ems="10"
    android:inputType="textPassword"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/editText_email" />


<TextView
    android:id="@+id/textView_password"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginLeft="32dp"
    android:layout_marginStart="32dp"
    android:text="Пароль:"
    app:layout_constraintBottom_toTopOf="@+id/editText_password"
    app:layout_constraintStart_toStartOf="parent" />

<Button
    android:id="@+id/button"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginBottom="32dp"
    android:layout_marginEnd="32dp"
    android:layout_marginStart="32dp"
    android:text="Зарегестрироваться"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />


</android.support.constraint.ConstraintLayout>

Далее вам необходимо создать класс.

public class RegistrationActivity extends AppCompatActivity{

private UserRegistrationTask userRegistrationTask;


@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_registration);
    final EditText editTextUsername = findViewById(R.id.editText_username);
    final EditText editTextEmail = findViewById(R.id.editText_email);
    final EditText editTextPassword = findViewById(R.id.editText_password);
    Button registration = findViewById(R.id.button_registration);

    registration.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String username = String.valueOf(editTextUsername.getText());
            String email = String.valueOf(editTextEmail.getText());
            String password = String.valueOf(editTextPassword.getText());

            userRegistrationTask = new UserRegistrationTask(username, email, password);
            userRegistrationTask.execute((Void) null);

        }
    });
}


public class UserRegistrationTask extends AsyncTask<Void, Void, Boolean> {

    private final String mUsername;
    private final String mEmail;
    private final String mPassword;

    UserRegistrationTask(String username, String email, String password) {
        mUsername = username;
        mEmail = email;
        mPassword = password;
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        // TODO: attempt authentication against a network service.

        try {
            URL url = new URL("http://dancecrm.ru/templates/register.php");
            Map<String,Object> requestParams = new LinkedHashMap<>();
            requestParams.put("name", mUsername);
            requestParams.put("email", mEmail);
            requestParams.put("password", mPassword);

            StringBuilder postData = new StringBuilder();
            for (Map.Entry<String,Object> param : requestParams.entrySet()) {
                if (postData.length() != 0) postData.append('&');
                postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                postData.append('=');
                postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
            }
            byte[] postDataBytes = postData.toString().getBytes("UTF-8");

            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
            conn.setDoOutput(true);
            conn.getOutputStream().write(postDataBytes);
            conn.getResponseCode();
        } catch (Exception e) {
            e.printStackTrace();
        }


        // TODO: register the new account here.
        return true;
    }

 }
}

После чего добавить в файл AndroidManifest.xml разрешение на интернет и задекларировать вашу RegistrationActivity.

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="devs.mulham.raee.sample">

      <uses-permission android:name="android.permission.INTERNET" />

      <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:theme="@style/AppTheme">
        <activity
          android:name=".RegistrationActivity"
          android:theme="@style/AppTheme.NoActionBar">
          <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

    </manifest>

Это простое решение, используя встроенный класс в Java HTTPUrlConnection. Также можно посмотреть в сторону OkHttp, Retrofit. Надеюсь вам помог мой ответ!

1
  • У моего друга https это помешает ? 5 мар 2018 в 15:11

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.