2015-11-26 110 views
1

当我在textedit中未填写详细信息时,我得到了来自php的作为{"success":0,"message":"Please Enter the Valid detail."}的json响应。所以我想读取成功和消息值,我想以Toast的形式显示该消息。我怎样才能做到这一点。如何阅读android活动中的Json响应。

这里是的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(); 
     } 

    } 

} 
+0

[JSON解析在Android应用程序]的可能的复制(http://stackoverflow.com/questions/3819273/json-parsing-in-android-application) – Mohit

回答

2

这是简单的把这个代码下面行= sb.toString();

JSONObject jsonObject = new JSONObject(line); 

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

它的工作表示感谢。 –