Я и мой друг делаем это через чатGPT, поэтому приносим извинения, если возникнут серьезные проблемы, мы оба нубы, мы просто хотим иметь возможность правильно читать и записывать данные, а с остальным у нас все будет в порядке (надеюсь, лол)
Просто интересно, может ли кто-нибудь объяснить, что происходит. Я пытаюсь записать данные в таблицу «пользователи», просто при тестировании для упрощения я просто использую имя пользователя и пароль.
android-end.php (в настоящее время находится в Интернете) сервер)
Код: Выделить всё
Код: Выделить всё
package com.example.androidapp1;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class RegisterActivity extends AppCompatActivity {
private EditText usernameEditText;
private EditText passwordEditText;
private EditText confirmPasswordEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
// Initialize UI elements
usernameEditText = findViewById(R.id.username_edit_text);
passwordEditText = findViewById(R.id.password_edit_text);
confirmPasswordEditText = findViewById(R.id.confirm_password_edit_text);
Button registerButton = findViewById(R.id.register_button);
// Set OnClickListener for register button
registerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Get user input from EditText fields
String username = usernameEditText.getText().toString().trim();
String password = passwordEditText.getText().toString().trim();
String confirmPassword = confirmPasswordEditText.getText().toString().trim();
// Validate user input
if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmPassword)) {
Toast.makeText(RegisterActivity.this, "Please fill in all fields", Toast.LENGTH_SHORT).show();
} else if (!password.equals(confirmPassword)) {
Toast.makeText(RegisterActivity.this, "Passwords do not match", Toast.LENGTH_SHORT).show();
} else {
// Proceed with registration
new RegisterTask().execute(username, password);
}
}
});
}
// AsyncTask for registering a new user
private class RegisterTask extends AsyncTask {
protected String doInBackground(String... params) {
String username = params[0];
String password = params[1];
try {
// Configure the URL for your registration endpoint
URL url = new URL("http://18.171.184.64/endpoint/android-end.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
// Create JSON object with username and password
JSONObject postData = new JSONObject();
postData.put("register", true); // Indicate registration request
postData.put("username", username);
postData.put("password", password); // Remember to hash the password before sending it
// Write JSON data to output stream
OutputStream os = connection.getOutputStream();
os.write(postData.toString().getBytes(StandardCharsets.UTF_8));
os.flush();
os.close();
// Read response from the server
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// Registration successful
return "Registration successful";
} else {
// Registration failed, read error message from the server
String errorMessage = readResponse(connection);
Log.d("RegisterActivity", errorMessage);
return errorMessage; // Return the error message
}
} catch (IOException | JSONException e) {
Log.d("RegisterActivity", e.getMessage());
return "Error: " + e.getMessage();
}
}
// Method to read response from HttpURLConnection
private String readResponse(HttpURLConnection connection) throws IOException {
StringBuilder response = new StringBuilder();
// Read response body if available
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} else {
// If response code is not OK, read error message from error stream
BufferedReader errorIn = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
String inputLine;
while ((inputLine = errorIn.readLine()) != null) {
response.append(inputLine);
}
errorIn.close();
}
return response.toString();
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Display registration result to the user
Toast.makeText(RegisterActivity.this, result, Toast.LENGTH_SHORT).show();
// If registration is successful, proceed to login activity
if (result.equals("Registration successful")) {
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
finish();
}
}
}
}
Я пробовал использовать phpmyadmin для вставки данных, и он работает отлично, просто когда мы делаем это из приложения, он говорит, что регистрация прошла успешно, но данные в базу данных фактически не сохраняются.
Подробнее здесь: https://stackoverflow.com/questions/782 ... oing-wrong
Мобильная версия