通过json在textview中显示数据

时间:2014-01-13 14:37:25

标签: android json textview

我想通过php在mysql数据库中显示用户详细信息,并在android textview中显示。场景是这样的:当用户登录到他的帐户时,他将被重定向到包含4个按钮的仪表板,即:新闻源,个人资料,日历和约。当用户单击配置文件按钮时,将在textview中显示用户详细信息,如姓氏,名字,初始信息等。当我运行我的应用程序时,它不会显示任何内容,但在我的PHP脚本中它返回用户详细信息。这里似乎有什么问题?

这是我的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.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<String, String, String> {


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<NameValuePair> params = new ArrayList<NameValuePair>();
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();

}

}
}

这是我的php脚本:

<?php


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 {}


       ?>

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

这里是我的php脚本(JSON Response)的输出:

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

3 个答案:

答案 0 :(得分:3)

这是json对象

JSONObject json = jsonParser.makeHttpRequest(PROFILE_URL, "POST",
    params);

您需要在json中返回doInbackground。返回的结果是onPostExecute

的参数

然后

 test(json);

然后在测试中你可以解析json

编辑:

您还需要更改

 AsyncTask<String, String, String>

AsyncTask<String, String, JSONObject>   

然后

protected JSONObject doInBackground(String... args) {

JSONObject json=null;  
    // Building Parameters

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(AdProfile.this);
String post_username = sp.getString("username", "anon");
List<NameValuePair> params = new ArrayList<NameValuePair>();
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;
}

然后在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);
}

test

public void test(JSONObject response){
{
       // parse response here and set text to textview
}

或者

您是否在on doInbackgrond更新textview中解析onPostExecute

编辑:

enter image description here

代码:

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<String, String, String> {



        @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<NameValuePair> params = new ArrayList<NameValuePair>();
                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();
            }

        }

    }
}

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"
        }
    ]
}

浏览器快照

enter image description here

答案 1 :(得分:1)

首先,进行解析的方法应该有一个带字符串

的参数

我们说parseFromPhp(字符串响应)

您的json对象还包含一个内部Json对象,即“user”:[{“names”:“学生事务办公室主管”,“中间名”:“”,“名字”:“测试”,“姓氏” “:” 测试“}]}

要解析这个,你会做

        JSONObject jsonRespone = new JSONObject(response); 
        JSONObject user= jsonRespone.getJSONObject("user");
        String lastName  = user.optString ("lastName");

如果你想收到消息,你会这样做:

        String message= jsonResponse.optString ("message");

答案 2 :(得分:0)

做这个 doInBackground()方法

try {
       // profile json object
       user = json.getJSONArray(TAG_PROFILE);
       for (int i = 0; i < user.length(); i++)
       {
         JSONObject FObject = json.getJSONObject(i);

          hay = FObject.getJSONObject("user");
        }

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

然后在 test()

中删除它
hay = new JSONObject();