简体   繁体   中英

How to display data from database to android app text view using JSON and PHP?

I have a php file that connects to my database. When it gets the selected user data from the table it will then be displayed to a textbox in PHP. That seems to be working fine. The problem is when my friend and I tried to connect and display it to a textview in the android app it doesn't work! What seems to be the problem here? I tried putting some JSON on it but I don't get it! I've attached here my PHP file and the java code.

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>

You are accessing/updating ui from doInbackground which is invoked on the background thread. You can't do that.

String username = useradmin.getText().toString();
String password = passadmin.getText().toString();
new LoadProfile().execute(username,password); // can pass param to doInbackground directly

To access the params

protected String doInBackground(String... args) {
String name = args[0];
String pwd = args[1] ;

All the initialization in onCreate

fname = (TextView) findViewById(R.id.fname);
lname = (TextView) findViewById(R.id.lname);
designation = (TextView) findViewById(R.id.designation);

You can return result in doInbackground

return json;

Now in onPostExecute parse json and update ui

fname.setText(x.getString(TAG_FNAME));
lname.setText(x.getString(TAG_LNAME));
designation.setText(x.getString(TAG_DESIGNATION));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM