我是一个总的菜鸟,一个初学程序员的定义。请在回复时记住这一点。 :)
简而言之,我工作的Android应用程序应该有一个注册/登录表单和主要内容"背后"那。基本上,用户为了访问应用程序及其内容首先必须注册自己的帐户,帐户详细信息应该存储在数据库中,然后在用户尝试签名时登录表单使用他们认为的用户名和密码,应用程序应检查他/她输入的用户名/密码是否正确(显然,如果两者都是正确的,他会通过登录表单并访问内容,如果没有,那么他得到提醒,他尝试登录的密码,用户名或两者都是错误的)。
在我输入注册表格中所需的所有详细信息(名字,姓氏,用户名,密码,电子邮件)并单击按钮后,我的应用程序应该启动一项新活动(登录表单),我在那里应该能够使用我之前选择的用户名和密码登录。但问题是,无论我怎么努力,数据库都不会更新任何细节(用户名,名字,姓氏,邮件和电子邮件)。有趣的是,我正在按照教程https://www.youtube.com/playlist?list=PLe60o7ed8E-TztoF2K3y4VdDgT6APZ0ka制作应用程序,即使使用该教程系列制作者提供的原始文件,我的应用程序仍然无法在更新数据库之后用户填写注册表。我正在使用的托管公司是 https://www.siteground.com/。
我的Android应用程序应将内容隐藏在注册/登录表单后面,如果用户成功注册他应该能够 使用他选择的用户名和密码登录。应用程序在注册过程中要求的详细信息(名字,姓氏,用户名,密码,电子邮件)应存储在数据库中。问题是填写登记表后 数据库不会得到更新。
RegisterActivity.java `
public class 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;
}
Register.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);
答案 0 :(得分:0)
我有一个类似的例子来保存用户名和密码,尝试根据你的想法进行修改。这个过程非常相似。 在这里,我使用“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,登录按钮通过服务器登录,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请求的Singleton类:
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();
?>
最后在localhost 用户中创建一个名为 hello 的数据库,其中包含2个字段用户名,密码。< / p>