retrieve data using json in android

311 Views Asked by At

I need to display the result in android text view that I obtained by json result. I only get the success message when I run the app. I want to get the textview displayed.

Java Code:

JSONObject hay;
// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();


private static final String LOGIN_URL = "//////////////////////  "; // change to the webhost

//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";

//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //setup input fields
    user = (EditText) findViewById(R.id.user);
    txtFname = (TextView) findViewById(R.id.fname);
    txtMname = (TextView) findViewById(R.id.lname);
    txtLname = (TextView) findViewById(R.id.mname);


    //setup buttons
    get = (Button) findViewById(R.id.get);

    //register listeners
    get.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    new AttemptLogin().execute();
}

class AttemptLogin extends AsyncTask < String, String, String > {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    boolean failure = false;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Attempt login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }


    @Override
    protected String doInBackground(String...args) {
        // TODO Auto-generated method stub
        // Check for success tag
        int success;
        String username = user.getText().toString();


        try {
            // Building Parameters
            List < NameValuePair > params = new ArrayList < NameValuePair > ();
            params.add(new BasicNameValuePair("username", username));

            Log.d("request!", "starting");
            // getting product details by making HTTP request
            JSONObject json = jsonParser.makeHttpRequest(
            LOGIN_URL, "POST", params);

            // check your log for json response
            Log.d("Login attempt", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("Login Successful!", json.toString());
                //
                //Intent i = new Intent(Login.this, MainActivity.class);

                //finish();
                //startActivity(i);
                //finish();
                return json.getString(TAG_MESSAGE);
            } else {
                Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                return json.getString(TAG_MESSAGE);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;

    }
    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        try {
            JSONObject json = null;
            JSONObject hay = new JSONObject((Map) json);
            JSONArray user = hay.getJSONArray("user");
            JSONObject jb = user.getJSONObject(0);
            String firstname = jb.getString("firstname");
            String middlename = jb.getString("middlename");
            String lastname = jb.getString("lastname");

            // displaying all data in textview

            txtFname.setText("Firstname: " + firstname);
            txtMname.setText("Middle Name: " + middlename);
            txtLname.setText("Last Name " + lastname);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (file_url != null) {
            Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
        }
    }
}

PHP Code:

<?php


require('config.inc.php');


if (!empty($_POST)) {

    //initial query
    $query = "Select last_name, first_name, middle_initial FROM admin where username = :user";

    $query_params = array(':user' => $_POST['username']);

    //execute query
    try {
        $stmt = $db -> prepare($query);
        $result = $stmt -> execute($query_params);
    } catch (PDOException $ex) {
        $response["success"] = 0;
        $response["message"] = "Database Error!";
        die(json_encode($response));
    }

    // Finally, we can retrieve all of the found rows into an array using fetchAll 
    $rows = $stmt -> fetchAll();

    if ($rows) {
        $response["success"] = 1;
        $response["message"] = "Post Available!";
        $response["user"] = array();

        foreach($rows as $row) {
            $user = array();
           // $user["designation"] = $row["designation"];
            $user["middlename"] = $row["middle_initial"];
            $user["firstname"] = $row["first_name"];
            $user["lastname"] = $row["last_name"];

            //update our repsonse JSON data
            array_push($response["user"], $user);
        }

        // echoing JSON response
        echo json_encode($response);

    } else {
        $response["success"] = 0;
        $response["message"] = "No user available!";
        die(json_encode($response));
    }

} else {}


       ?>

 <form action="test.php" method="POST">
 Username: <input type="text" name="username">
 <input type="submit" value="Submit">
 </form>
2

There are 2 best solutions below

9
On

the problem is with your this code segment:

            JSONObject json = null;
            JSONObject hay = new JSONObject((Map) json);
            JSONArray user = hay.getJSONArray("user");
            JSONObject jb = user.getJSONObject(0);
            String firstname = jb.getString("firstname");
            String middlename = jb.getString("middlename");
            String lastname = jb.getString("lastname");

here what you are doing is: making another JSONObject as

JSONObject json = null;

that is creating a variable with local scope, the local variable will have more priority than global, that you understood. actually you need the json which is created from doInBackgrounnd(). so pass the json from doInBackground to onPostExecute: it is simple,

change the statements:

return json.getString(TAG_MESSAGE); => return json;
return json.getString(TAG_MESSAGE); => return json;

also change the type of doInBackground to JSONObject and avoid making a new local JSONObject and trying to get datafrom that (bcz it is null you initialized with).

        JSONObject json = null;                           //remove this
        JSONObject hay = new JSONObject((Map) json);      //remove this
        JSONArray user = hay.getJSONArray("user");        // change hay to json

also change the

protected void onPostExecute(String file_url)// to protected void onPostExecute(JSONObject json)

EDIT 2

here is your changed code, let me know what you are getting if some errors.

//edited1
  public static JSONObject json = null;
  // Progress Dialog
  private ProgressDialog pDialog;

   // JSON parser class
  JSONParser jsonParser = new JSONParser();


private static final String LOGIN_URL = "//////////////////////  "; // change to the webhost

//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";

//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_USER = "user";

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //setup input fields
    user = (EditText) findViewById(R.id.user);
    txtFname = (TextView) findViewById(R.id.fname);
    txtMname = (TextView) findViewById(R.id.lname);
    txtLname = (TextView) findViewById(R.id.mname);


    //setup buttons
    get = (Button) findViewById(R.id.get);

    //register listeners
    get.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    new AttemptLogin().execute();
}

class AttemptLogin extends AsyncTask < String, String, String > {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    boolean failure = false;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Attempt login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }


    @Override
    protected String doInBackground(String...args) {
        // TODO Auto-generated method stub
        // Check for success tag
        int success;
        String username = user.getText().toString();


        try {
            // Building Parameters
            List < NameValuePair > params = new ArrayList < NameValuePair > ();
            params.add(new BasicNameValuePair("username", username));

            Log.d("request!", "starting");
            // getting product details by making HTTP request

     // edited2
          json = jsonParser.makeHttpRequest(
            LOGIN_URL, "POST", params);

            // check your log for json response
            Log.d("Login attempt", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("Login Successful!", json.toString());
                //
                //Intent i = new Intent(Login.this, MainActivity.class);

                //finish();
                //startActivity(i);
                //finish();

              //edited3  
                 return json.getString(TAG_MESSAGE);   
                //return json;
            } else {
                Log.d("Login Failure!", json.getString(TAG_MESSAGE));

               //edited4 
                 return json.getString(TAG_MESSAGE);
                //return json;

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;

    }
    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String message) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        try {
            //JSONObject json = null;
            //JSONObject hay = new JSONObject((Map) json);
            JSONArray user = json.getJSONArray("user");
            JSONObject jb = user.getJSONObject(0);
            String firstname = jb.getString("firstname");
            String middlename = jb.getString("middlename");
            String lastname = jb.getString("lastname");

            // displaying all data in textview

            txtFname.setText("Firstname: " + firstname);
            txtMname.setText("Middle Name: " + middlename);
            txtLname.setText("Last Name " + lastname);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (file_url != null) {
            Toast.makeText(MainActivity.this, json.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
        }
    }
}

did four changes in total: mentioned as edited# wherever I did. please fins them and make it in your file,

2
On

sorry can't comment but what you getting at post execute from background task is file_url as string which is your param at on post execute......i think if you are getting result all params like first name ,lastName etc then you needed to pass jsonObject at onpost Execute so you can parse at onPostExecute...your jsonResult and display it in textbox Problem is in you current code is

txtFname.setText("Firstname: " + firstname);

in which firstName is from

String firstname = jb.getString("firstname");
JSONObject jb= user.getJSONObject(0);
JSONArray user =  hay.getJSONArray("user");
JSONObject hay = new JSONObject ((Map) json);
JSONObject json = null;

i have reversed it so you can find problem here json is null so here is problem and pls try logging at each point and let we know so we and you can have exact idea....or give us json format...