java返回json text类型数据,通过JSON显示数据的TextView

I want to display user details from mysql database through php and display it in android textview. The scenario is like this: When the user logged in to his account he will be redirected to the dashboard which contains of 4 buttons namely: newsfeed, profile, calendar and about. When the user clicks the profile button the user details like his lastname, firstname, middleinitial etc will be displayed in the textview. When i run my app, it doesnt display anything but in my php script it returns the user details. What seems to be the problem here?

Here is my java code:

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.content.SharedPreferences;

import android.os.AsyncTask;

import android.os.Bundle;

import android.preference.PreferenceManager;

import android.util.Log;

import android.widget.TextView;

public class AdProfile extends Activity {

// All xml labels

TextView txtFname;

TextView txtMname;

TextView txtLname;

// Progress Dialog

private ProgressDialog pDialog;

// Creating JSON Parser object

JSONParser jsonParser = new JSONParser();

// Profile json object

JSONArray user;

JSONObject hay;

// Profile JSON url

private static final String PROFILE_URL ="http://www.stagconnect.com/StagConnect/admin/TestProfile.php";

// ALL JSON node names

private static final String TAG_PROFILE = "user";

// private static final String TAG_ID = "id";

private static final String TAG_USERNAME = "username";

private static final String TAG_FIRSTNAME = "first_name";

private static final String TAG_MIDDLENAME = "middle_initial";

private static final String TAG_LASTNAME = "last_name";

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.adminprofile);

txtFname = (TextView) findViewById(R.id.fname);

txtMname = (TextView) findViewById(R.id.mname);

txtLname = (TextView) findViewById(R.id.lname);

// Loading Profile in Background Thread

new LoadProfile().execute();

}

class LoadProfile extends AsyncTask {

public void test(){

hay = new JSONObject();

// Storing each json item in variable

try {

String firstname = hay.getString(TAG_FIRSTNAME);

String middlename = hay.getString(TAG_MIDDLENAME);

String lastname = hay.getString(TAG_LASTNAME);

// displaying all data in textview

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

txtMname.setText("Middle Name: " + middlename);

txtLname.setText("Last Name " + lastname);

} catch (JSONException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

@Override

protected void onPreExecute() {

super.onPreExecute();

pDialog = new ProgressDialog(AdProfile.this);

pDialog.setMessage("Loading profile ...");

pDialog.setIndeterminate(false);

pDialog.setCancelable(false);

pDialog.show();

}

/**

* getting Profile JSON

* */

protected String doInBackground(String... args) {

// Building Parameters

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(AdProfile.this);

String post_username = sp.getString("username", "anon");

List params = new ArrayList();

params.add(new BasicNameValuePair("username", post_username));

// getting JSON string from URL

JSONObject json = jsonParser.makeHttpRequest(PROFILE_URL, "POST",

params);

// Check your log cat for JSON reponse

Log.d("Profile JSON: ", json.toString());

try {

// profile json object

user = json.getJSONArray(TAG_PROFILE);

} catch (JSONException e) {

e.printStackTrace();

}

return null;

}

protected void onPostExecute(String file_url) {

// dismiss the dialog after getting all products

pDialog.dismiss();

// updating UI from Background Thread

test();

}

}

}

And here is my php script:

require('admin.config.inc.php');

if (!empty($_POST)) {

//initial query

$query = "Select last_name, first_name, middle_initial, designation 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 {}

?>

Username:

Here the output of my php script(JSON Response):

{"success":1,"message":"Post Available!","user":[{"designation":"Student Affairs Office in charge","middlename":"","firstname":"test","lastname":"test"}]}

解决方案

This is the json object

JSONObject json = jsonParser.makeHttpRequest(PROFILE_URL, "POST",

params);

You need to return json in doInbackground. The result returned is param to onPostExecute

Then

test(json);

And then in test you can parse the json

Edit:

You would also need to change

AsyncTask

to

AsyncTask

Then

protected JSONObject doInBackground(String... args) {

JSONObject json=null;

// Building Parameters

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(AdProfile.this);

String post_username = sp.getString("username", "anon");

List params = new ArrayList();

params.add(new BasicNameValuePair("username", post_username));

// getting JSON string from URL

json = jsonParser.makeHttpRequest(PROFILE_URL, "POST",

params);

// Check your log cat for JSON reponse

Log.d("Profile JSON: ", json.toString());

try {

// profile json object

user = json.getJSONArray(TAG_PROFILE);

} catch (JSONException e) {

e.printStackTrace();

}

return json;

}

Then in onPostExecute

@Override

protected void onPostExecute(JSONObject result) {

super.onPOstExecute(result);

// dismiss the dialog after getting all products

pDialog.dismiss();

// updating UI from Background Thread

test(result);

}

In test

public void test(JSONObject response){

{

// parse response here and set text to textview

}

Or

Do you parsing in doInbackgrond update textview in onPostExecute

Edit:

SEwzN.png

Code:

public class AddProfile extends Activity {

// All xml labels

TextView txtFname;

TextView txtMname;

TextView txtLname;

// Progress Dialog

private ProgressDialog pDialog;

// Profile json object

JSONArray user;

JSONObject hay;

// Profile JSON url

private static final String PROFILE_URL = "http://www.stagconnect.com/StagConnect/admin/TestProfile.php";

// ALL JSON node names

private static final String TAG_PROFILE = "user";

// private static final String TAG_ID = "id";

private static final String TAG_USERNAME = "username";

private static final String TAG_FIRSTNAME = "first_name";

private static final String TAG_MIDDLENAME = "middle_initial";

private static final String TAG_LASTNAME = "last_name";

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.adminprofile);

txtFname = (TextView) findViewById(R.id.fname);

txtMname = (TextView) findViewById(R.id.lname);

txtLname = (TextView) findViewById(R.id.mname);

// Loading Profile in Background Thread

new LoadProfile().execute();

}

class LoadProfile extends AsyncTask {

@Override

protected void onPreExecute() {

super.onPreExecute();

pDialog = new ProgressDialog(AddProfile.this);

pDialog.setMessage("Loading profile ...");

pDialog.setIndeterminate(false);

pDialog.setCancelable(false);

pDialog.show();

}

/**

* getting Profile JSON

* */

protected String doInBackground(String... args) {

// Building Parameters

String json = null;

try {

List params = new ArrayList();

params.add(new BasicNameValuePair("username", "admin"));

HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost(PROFILE_URL);

httppost.setEntity(new UrlEncodedFormEntity(params));

// Execute HTTP Post Request

HttpResponse response = httpclient.execute(httppost);

HttpEntity resEntity = response.getEntity();

json = EntityUtils.toString(resEntity);

Log.i("Profile JSON: ", json.toString());

} catch (Exception e) {

e.printStackTrace();

}

return json;

}

@Override

protected void onPostExecute(String json) {

super.onPostExecute(json);

// dismiss the dialog after getting all products

pDialog.dismiss();

try

{

hay = new JSONObject(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();

}

}

}

}

The json

{ // json object node

"success": 1,

"message": "Post Available!",

"user": [ // json array user

{ // json object node

"designation": "Student Affairs Office in-charge",

"middlename": "",

"firstname": "Jose Patrick",

"lastname": "Ocampo"

}

]

}

Browser snap shot

gITYq.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值