在textview上显示jsonarray数据

时间:2013-08-26 13:23:06

标签: android

我试图为学校制作一个Android应用程序。这就是我想要发生的事情 首先,当用户登录时,用户名保存在sharedpreferences中 第二,使用共享首选项,我将检索数据库中的用户信息。 第三,解析数据并在textviews中显示信息。 这是我的php文件

       <?php



  /*
    Our "config.inc.php" file connects to database every time we include or require
    it within a php script.  Since we want this script to add a new user to our db,
    we will be talking with our database, and therefore,
    let's require the connection to happen:
    */
    require("config.inc.php");

    if (!empty($_POST)) {

        //initial query
        $query = "Select * FROM userinfo 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["users"] = array();

            foreach($rows as $row) {
                $user = array();
                $user["username"] = $row["username"];
                $user["firstname"] = $row["firstname"];
                $user["middlename"] = $row["middlename"];
                $user["lastname"] = $row["lastname"];
                $user["course"] = $row["course"];

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

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

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

这是我的java代码

    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 ProfileActivity 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://10.0.2.2/webservice1/userprofile.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 = "firstname";
    private static final String TAG_MIDDLENAME = "middlename";
    private static final String TAG_LASTNAME = "lastname";


    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);


    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();
    }

    /**
    * Background Async Task to Load profile by making HTTP Request
    * */
    class LoadProfile extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */

    public void test(){

                /**
                 * Updating parsed JSON data into ListView
                 * */
                // 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

                    txtEmail.setText("Email: " + firstname);
                    txtMobile.setText("Mobile: " + middlename);
                    txtAddress.setText("Add: " + lastname);

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ProfileActivity.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(ProfileActivity.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;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        test();

    }

}
    }

我得到一个nullpointer异常ProfileActivity $ LoadProfile.test 请帮我,我只是一个初学者

1 个答案:

答案 0 :(得分:0)

你还没有初始化嘿。你刚宣布嘿。 如果您的数据在json中,则在postexecute中指定hey = json或直接传递json以进行测试并在那里使用它。