【问题标题】:How to display data from database to android app text view using JSON and PHP?如何使用 JSON 和 PHP 将数据从数据库显示到 android 应用程序文本视图?
【发布时间】:2014-01-08 15:37:46
【问题描述】:

我有一个连接到我的数据库的 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>

【问题讨论】:

    标签: java php android json


    【解决方案1】:

    您正在从后台线程调用的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));
    

    【讨论】:

    • 抱歉回复晚了!嗯...你知道我的朋友和我只是 java eclipse 和 PHP 的初学者,我们真的很想了解你的帮助,但问题是,我们不知道 String name 和 @987654330 的用途是什么@ 因为当我们尝试将它插入到我们的代码中时,我们只收到消息“变量未使用”和另外一件事,当我们执行 return json 时,我们也会收到一个错误,即它似乎无法将 json 读取为变量也是,当我们解析 json 并更新 onPostExecute 中的 ui 时,它无法识别变量 x。抱歉,请您详细说明一下。
    • 我还应该详细说明什么。您当然需要先阅读文档。其次,通过在 oyur 代码中放置一个编辑部分来发布更新的代码
    • 我已经编辑了我的代码并插入了您的建议。我已经对我遇到的错误发表了一些评论。
    • @IamMe。 new LoadProfile().execute(); 错误执行中没有参数! 1个错误。第二个错误 new LoadProfile().execute(username,password); 在 doInbackground 中完全错误。3 在 doinbackground 中再次更新或访问 ui 再次错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-08
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多