如何在android活动中阅读Json Response。

时间:2015-11-26 11:03:19

标签: php android json android-activity android-asynctask

当textedit中没有填写详细信息时,我从php获取json响应为{"success":0,"message":"Please Enter the Valid detail."}。所以我想阅读成功和消息值,我想将该消息显示为Toast。我怎么能这样做。

这是AsyncTask:

  class CreateUser extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    boolean failure = false;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Register.this);
        pDialog.setMessage("Creating User...");
        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;

        // try {
        // Building Parameters
        HashMap<String, String> Params = new HashMap<String, String>();
        Params.put("username", username);
        Params.put("password", password);
        Params.put("email", email);
        Params.put("ph", ph);

        Log.d("request!", "starting");
        String encodedStr = getEncodedData(Params);

        //Will be used if we want to read some data from server
        BufferedReader reader = null;

        //Connection Handling
        try {
            //Converting address String to URL
            URL url = new URL(LOGIN_URL);
            //Opening the connection (Not setting or using CONNECTION_TIMEOUT)
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            //Post Method
            con.setRequestMethod("POST");
            //To enable inputting values using POST method
            //(Basically, after this we can write the dataToSend to the body of POST method)
            con.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
            //Writing dataToSend to outputstreamwriter
            writer.write(encodedStr);
            //Sending the data to the server - This much is enough to send data to server
            //But to read the response of the server, you will have to implement the procedure below
            writer.flush();

            //Data Read Procedure - Basically reading the data comming line by line
            StringBuilder sb = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

            String line;
            while((line = reader.readLine()) != null) { //Read till there is something available
                sb.append(line + "\n");     //Reading and saving line by line - not all at once
            }
            line = sb.toString();           //Saving complete data received in string, you can do it differently

            //Just check to the values received in Logcat
            Log.i("custom_check","The values :");
            Log.i("custom_check",line);

            //Object b = line;
            Log.i("length", String.valueOf(line.length()));



            if (line.length() == 55) {
                Log.d("User Created!", line);
                SharedPreferences set = getSharedPreferences (UserNum, 0);
                set.edit().putString(uu,username).commit();
               // Toast.makeText(Register.this, "User Registered", Toast.LENGTH_SHORT).show();
                Intent i=new Intent(getApplicationContext(),MainActivity.class);
                startActivity(i);
                finish();
                //return line.getString(TAG_MESSAGE);
            }else{
                  Log.d("Login Failure!", "failed");
                 // return b.getString(TAG_MESSAGE);
                Toast.makeText(Register.this, "Username already in use", Toast.LENGTH_SHORT).show();

            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(reader != null) {
                try {
                    reader.close();     //Closing the
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //Same return null, but if you want to return the read string (stored in line)
        //then change the parameters of AsyncTask and return that type, by converting
        //the string - to say JSON or user in your case
        return null;
    }

    private String getEncodedData(Map<String,String> data) {
        StringBuilder sb = new StringBuilder();
        for(String key : data.keySet()) {
            String value = null;
            try {
                value = URLEncoder.encode(data.get(key), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            if(sb.length()>0)
                sb.append("&");

            sb.append(key + "=" + value);
        }
        return sb.toString();
    }


    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted

        pDialog.dismiss();
                     if (file_url != null){
            Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
        }

    }

} 

1 个答案:

答案 0 :(得分:2)

这很简单,把这段代码放在line = sb.toString()下面;

JSONObject jsonObject = new JSONObject(line);

String sucess=jsonObject.getString("success");
String message=jsonObject.getString("message");