[英]How to display data from database to android app text view using JSON and PHP?
我有一个连接到数据库的php文件。 当它从表中获取选定的用户数据时,它将显示在PHP的文本框中。 这似乎很好。 问题是当我和我的朋友尝试连接并将其显示到android应用程序中的textview时,它不起作用! 这里似乎是什么问题? 我尝试在上面放一些JSON,但我不明白! 我在这里附加了我的PHP文件和Java代码。
Java的
package sscr.stag;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class AdminProfile extends Activity {
TextView fname;
TextView lname;
TextView designation;
EditText useradmin, passadmin;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// Profile JSON url
private static final String ADMIN_PROFILE = "http://www.stagconnect.com/StagConnect/admin/arrayProfile.php";
// ALL JSON node names
private static final String TAG_LNAME = "last_name";
private static final String TAG_FNAME = "first_name";
private static final String TAG_DESIGNATION = "designation";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_POST = "post";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adminprofile);
fname = (TextView) findViewById(R.id.fname);
lname = (TextView) findViewById(R.id.lname);
designation = (TextView) findViewById(R.id.designation);
useradmin = (EditText) findViewById(R.id.useradmin);
passadmin = (EditText) findViewById(R.id.adminpass);
// Loading Profile in Background Thread
new LoadProfile().execute();
}
class LoadProfile extends AsyncTask<String, String, String> {
boolean failure = false;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AdminProfile.this);
pDialog.setMessage("Loading Profile. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting user details in background thread
* */
protected String doInBackground(String... args) {
int success;
String username = useradmin.getText().toString();
String password = passadmin.getText().toString();
String name = args[0]; //variable is not used
String pwd = args[1] ; //variable is not used
new LoadProfile().execute(username,password);
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.makeHttpRequest(
ADMIN_PROFILE, "POST", params);
// check your log for json response
Log.d("Load Profile", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received user details
JSONArray productObj = json
.getJSONArray(TAG_POST); // JSON Array
// get first product object from JSON Array
JSONObject x = productObj.getJSONObject(0);
// user info with this username found
// Edit Text
fname = (TextView) findViewById(R.id.fname);
lname = (TextView) findViewById(R.id.lname);
designation = (TextView) findViewById(R.id.designation);
// display product data in EditText
fname.setText(x.getString(TAG_FNAME));
lname.setText(x.getString(TAG_LNAME));
designation.setText(x.getString(TAG_DESIGNATION));
}else{
// user info with username not found
}
} catch (JSONException e) {
e.printStackTrace();
}
return json; //error here: json cannot be resolved to a variable
}
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
/*error here: x cannot be resolved*/ fname.setText(x.getString(TAG_FNAME));
lname.setText(x.getString(TAG_LNAME));
designation.setText(x.getString(TAG_DESIGNATION));
}
}
}
的PHP:
<?php
$response=array();
if(isset($_POST['username'])&&isset($_POST['password'])){
$username=$_POST['username']; // variables used to compare query to user inputed data from $/_POST.
$password=$_POST['password']; // variable used to compare query to user inputed data from $/_POST.
if(!empty($username)&&!empty($password)){ //check if the fields are all filled up.
$query="
SELECT
`username`,
`last_name`,
`first_name`,
`designation`
FROM
`admin`
WHERE
`username` = '$username'
AND
`password` = '$password'
"; // used to get data from the table admin on the database.
if($query_run =mysql_query($query)){ // used to check if the query was able to run properly.
$query_num_rows = mysql_num_rows($query_run); // assign the result of the query
// to the variable $query_num_rows.
if($query_num_rows==0){ // check if it gets data from database.
// 0 means theres none found during the query.
$response["success"] = 0;
$response["message"] = "No Data Found!";
die(json_encode($response));
}
else if($query_num_rows==1){
?>
<h1>Profile</h1>
<form action="<?php echo $current_file ?>" method="POST">
Username:<br />
<input type="text" name="username"
value='<?php echo $user_id=mysql_result($query_run, 0, 'username') ?>'>
<br /><br />
Last Name:<br />
<input type="text" name="last_name"
value='<?php echo $user_id=mysql_result($query_run, 0, 'last_name') ?>'>
<br /><br />
First Name:<br />
<input type="text" name="first_name"
value='<?php echo $user_id=mysql_result($query_run, 0, 'first_name') ?>'>
<br /><br />
Designation:<br/>
<input type="text" name="designation"
value='<?php echo $user_id=mysql_result($query_run, 0, 'designation') ?>'>
<br /><br />
<?php
$response["success"] = 1;
$response["message"] = "Login successful!";
die(json_encode($response));
}
}
}
else{
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
}
?>
<form action="<?php echo $current_file ?>" method="POST">
Username: <input type="text" name="username">Password: <input type="password" name="password">
<input type="submit" value="Log in">
</form>
您正在从在后台线程上调用的doInbackground
访问/更新ui。 你不能那样做。
String username = useradmin.getText().toString();
String password = passadmin.getText().toString();
new LoadProfile().execute(username,password); // can pass param to doInbackground directly
访问参数
protected String doInBackground(String... args) {
String name = args[0];
String pwd = args[1] ;
onCreate中的所有初始化
fname = (TextView) findViewById(R.id.fname);
lname = (TextView) findViewById(R.id.lname);
designation = (TextView) findViewById(R.id.designation);
您可以在doInbackground
返回结果
return json;
现在在onPostExecute
解析json并更新ui
fname.setText(x.getString(TAG_FNAME));
lname.setText(x.getString(TAG_LNAME));
designation.setText(x.getString(TAG_DESIGNATION));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.