在android中使用json检索数据

时间:2014-11-20 02:17:52

标签: android json android-json

我需要在android文本视图中显示我通过json结果获得的结果。我只在运行应用程序时收到成功消息。我希望显示文本视图。

Java代码:

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代码:

<?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 个答案:

答案 0 :(得分:0)

抱歉无法发表评论,但你在后期任务执行后获得的是file_url as string,这是你在后执行时的参数......我想如果你得到结果所有参数如名字,lastName等然后你需要在onpost Execute传递jsonObject 所以你可以解析onPostExecute ...你的jsonResult并在文本框中显示它 问题在于你当前的代码是

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

其中firstName来自

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

我已经改变它,所以你可以在这里找到问题json是null所以这里是问题,请尝试记录每一点,让我们知道所以我们你可以有确切的想法....或给我们json格式..

答案 1 :(得分:0)

问题在于您的代码段:

            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");

这里你要做的是:将另一个JSONObject作为

JSONObject json = null;

即创建具有局部范围的变量,本地变量将具有比您所理解的全局更高的优先级。实际上你需要从doInBackgrounnd()创建的 json 。所以将 json 从doInBackground传递给onPostExecute:它很简单,

更改声明:

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

还将doInBackground的类型更改为JSONObject,并避免创建新的本地JSONObject并尝试从中获取数据(bcz它是初始化时为null)。

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

也改变了

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

编辑2

这是您更改的代码,如果出现一些错误,请告诉我您的内容。

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

总共进行了四次更改:无论我在哪里,都提到编辑#。请给他们打气并把它放在你的档案里,