gpt4 book ai didi

java - Android 应用程序不会将数据存储在数据库中

转载 作者:行者123 更新时间:2023-11-30 22:12:54 25 4
gpt4 key购买 nike

---背景---

我完全是菜鸟,初学者程序员的定义。请在回复时记住这一点。 :)

---故事---

简而言之,我正在开发的 android 应用程序应该有一个注册/登录表单和“背后”的主要内容。基本上,用户为了访问应用程序及其内容,首先必须为自己注册一个帐户,帐户详细信息应存储在数据库中,然后当用户尝试使用他们认为的登录时,在登录表单中username 和 password 应用程序应该检查他/她输入的用户名/密码是否正确(显然,如果两者都正确,他会通过登录表单并访问内容,如果不正确,那么他会被提醒他尝试登录的密码、用户名或两者都是错误的)。

---问题---

在我输入注册表单(名字、姓氏、用户名、密码、电子邮件)中所需的所有详细信息并单击按钮后,我的应用程序应该会启动一个新 Activity (登录表单),我在其中应该能够使用我之前选择的用户名和密码登录。但是,问题是,无论我多么努力,数据库都不会更新任何详细信息(用户名、名字、姓氏、密码和电子邮件)。有趣的是我正在学习教程 https://www.youtube.com/playlist?list=PLe60o7ed8E-TztoF2K3y4VdDgT6APZ0ka制作应用程序,即使使用该教程系列的制作者提供的原始文件,我的应用程序在用户完成注册表后仍然不会更新数据库。我使用的托管公司是 https://www.siteground.com/ .

---TLDR---

我的 Android 应用程序应该有隐藏在注册/登录表单后面的内容,如果用户成功注册,他应该能够使用他选择的用户名和密码登录。应用程序在注册过程中要求的详细信息(名字、姓氏、用户名、密码、电子邮件)应存储在数据库中。问题是填写注册表后数据库不会更新。

最后但并非最不重要的一点,代码:

RegisterActivity.java`

公共(public)类 RegisterActivity 扩展 AppCompatActivity {

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

final EditText etEmail = (EditText) findViewById(R.id.etFirstName);
final EditText etLastName = (EditText) findViewById(R.id.etLastName);
final EditText etFirstName = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final EditText etUsername = (EditText) findViewById(R.id.etEmail);
final Button RegisterButton2 = (Button) findViewById(R.id.RegisterButton2);

RegisterButton2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String firstname = etFirstName.getText().toString();
final String lastname = etLastName.getText().toString();
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
final String email = etEmail.getText().toString();

Response.Listener<String> responseListener = new Response.Listener<String>(){
@Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success){
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};

RegisterRequest registerRequest = new RegisterRequest(firstname, lastname, username, password, email, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}

`

RegisterRequest.java

public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://wearelifemap.com/Register.php";
private Map<String, String> params;

public RegisterRequest(String firstname, String lastname, String username, String password, String email, Response.Listener<String> listener){
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("firstname", firstname);
params.put("lastname", lastname);
params.put("username", username);
params.put("password", password);
params.put("email", email);
}

@Override
public Map<String, String> getParams() {
return params;
}

注册.php

<?php
$con = mysqli_connect("localhost", "wearelif_xtreme", "abc123", "wearelif_user2");

$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$username = $_POST["username"];
$password = $_POST["password"];
$email = $_POST["email"];
$statement = mysqli_prepare($con, "INSERT INTO user (firstname, lastname, username, password, email) VALUES (?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "sssss", $firstname, $lastname, $username, $password, $email);
mysqli_stmt_execute($statement);

$response = array();
$response["success"] = true;

echo json_encode($response);

最佳答案

我有一个类似的保存用户名和密码的例子,按照你的想法修改。这个过程非常相似。在这里,我使用“ Volley ”进行网络通话。确保一旦你用谷歌搜索“Android 中的截击是什么?”。

//Layout of Activity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="2dp"
tools:context="com.test.test.ScreenOne">


<EditText
android:layout_width="240dp"
android:layout_height="wrap_content"
android:id="@+id/etUsername"
android:layout_marginTop="150dp"
android:hint="username"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<EditText
android:layout_width="240dp"
android:layout_height="wrap_content"
android:id="@+id/etPassword"
android:hint="password"
android:layout_below="@+id/etUsername"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:id="@+id/bLogin"
android:layout_below="@+id/etPassword"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/bSave"
android:layout_below="@+id/bLogin"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp" />
</RelativeLayout>

Activity 有 2 个按钮和 2 个 EditText,Login 按钮通过服务器登录,Save 按钮将您的数据保存在服务器中:

package com.test.test;

import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import java.util.HashMap;
import java.util.Map;

public class ScreenOne extends AppCompatActivity {

private static final String URL_LOGIN = "http://YOUT_IP_ADDRESS(save file in xampp/any local server)/login.php";
private static final String URL_SAVE = "http://YOUR_IP_ADDRESS(save file in xampp/any local server)/save.php";
private EditText username;
private EditText password;
private Button login;
Button save;
String name;
String pass;

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

username = (EditText) findViewById(R.id.etUsername);
password = (EditText) findViewById(R.id.etPassword);

(login = (Button) findViewById(R.id.bLogin)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
request();
}
});

(save = (Button) findViewById(R.id.bSave)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveRequest();
}
});
}

private void saveRequest() {
//get string data from edittext field,in your case take from name, email, password.......
name = username.getText().toString().trim();
pass = password.getText().toString().trim();

//show progressdialog while loading data
final ProgressDialog mDialog = new ProgressDialog(this);
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDialog.setMessage("Loading...");
mDialog.show();

StringRequest request = new StringRequest(Request.Method.POST, URL_SAVE,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//responce from server, dismiss dialog and print responce in a toast message.
mDialog.dismiss();
Toast.makeText(ScreenOne.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mDialog.dismiss();
Toast.makeText(ScreenOne.this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> key = new HashMap<>();
//map value to match in your php script, update with yours e.g. name,lastname,email.....
key.put("username", name);
key.put("password", pass);
return key;
}
};

NetworkCalls.getInstance().addToRequestQueue(request);
}

private void request() {
name = username.getText().toString().trim();
pass = password.getText().toString().trim();
final ProgressDialog mDialog = new ProgressDialog(this);
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDialog.setMessage("Loading...");
mDialog.show();

StringRequest request = new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
mDialog.dismiss();
Toast.makeText(ScreenOne.this, response, Toast.LENGTH_LONG).show();
username.setText("");
password.setText("");
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mDialog.dismiss();
Toast.makeText(ScreenOne.this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> key = new HashMap<>();
//map the username and password to match with the php script so the user can pass his login values here
key.put("username", name);
key.put("password", pass);
return key;
}
};

NetworkCalls.getInstance().addToRequestQueue(request);
}
}

Volley 请求的单例类:

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

/**
* Created by W4R10CK on 14-09-2016.
*/
public class NetworkCalls {
private RequestQueue requestQueue;
private static Context context;

private static NetworkCalls ourInstance = new NetworkCalls();

public static NetworkCalls getInstance() {
return ourInstance;
}

private NetworkCalls() {
}

public RequestQueue getRequestQueue(){
requestQueue = Volley.newRequestQueue(context.getApplicationContext());
return requestQueue;
}

public <T> void addToRequestQueue(Request<T> request){
getRequestQueue().add(request);
}
}

调用服务器的API:

 //conn.php for connection (file one)
<?php
$host = "localhost"; //update with yours
$user = "root"; //update the phpmyadmin username
$pass = ""; //update with your phpmyadmin password
$db_name = "hello"; //replace with your db name

$con = new mysqli($host,$user,$pass,$db_name);

if($con -> connect_error){
echo "Connection error";
}


//save.php(file two)
<?php
$username = $_POST['username'];
$password = $_POST['password'];
require_once('conn.php');

//here user is one table with username and password field to save the data coming from user to server. Make sure you replace with your own needs.
$sql = "INSERT INTO user (username, password) VALUES ('$username','$password')";

if($con -> query($sql) === TRUE) {
echo "User added";
}
//$con -> close();
?>
?>

//login.php(file three)
<?php
require_once('conn.php');

$username = $_POST['username'];
$password = $_POST['password'];

$sql = "SELECT * FROM user WHERE username = '$username' AND password = '$password'";

$result = mysqli_query($con,$sql);

if(mysqli_fetch_array($result) == NULL){
echo "Invalid Cred.";
}else{
echo "Success";
}

$con->close();
?>

最后创建一个名为 hello 的数据库,并在本地主机 user 中创建一个表,其中包含 2 个字段 usernamepassword

关于java - Android 应用程序不会将数据存储在数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39477402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com