【问题标题】:retrieve data using json in android在android中使用json检索数据
【发布时间】:2014-11-20 02:17:52
【问题描述】:

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

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>

【问题讨论】:

  • 您能发布您的 JSON 数据示例吗?
  • 你能告诉我有什么问题吗...如果你得到 json 然后请发布 JSON。
  • 文本视图不显示
  • 您可以在日志中打印并在此处发布。
  • 我是 android 新手,你能帮帮我吗

标签: android json android-json


【解决方案1】:

抱歉无法发表评论,但你在后台任务执行后得到的是 file_url 作为字符串,这是你在后执行时的参数......我想如果你得到结果,所有参数都像名字,姓氏等等然后你需要在 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 为空,所以这是问题所在,请尝试在每个点记录并让我们知道,以便我们和您有确切的想法..或给我们 json 格式.. .

【讨论】:

  • 请勿在此处使用或拼写消息语言中的单词。专业。
  • @ツPratikButaniツ 这就是你被赋予编辑权限的原因。
【解决方案2】:

问题在于您的这段代码:

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

总共做了四次更改:无论我在哪里都提到了已编辑#。请把它们放在你的文件里,

【讨论】:

  • 返回json,表示无法从jsonobject转换为json
  • 您在运行APP前遇到错误?您使用的是哪个IDE?您的 IDE 中显示的建议是什么?
  • 它说将返回类型更改为 JSONobject
  • aaha...阅读我的答案,我告诉您将返回类型更改为 JSONObject...您错过了吗?请改一下
  • 你可以编辑我的代码并发布!这将非常有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多