2017-08-07 89 views
-1

我正在開發,我想顯示用戶註冊與否。以下是我的代碼,它在Logcat中顯示正確的響應,但不顯示應用程序端的消息(即註冊成功或註冊失敗消息)。我試圖解析響應,但logcat顯示消息是「org.json.JSONException:沒有值的響應類型「 如何解析json數據?請建議我! 我根據建議做了更改!
我還有什麼要做的嗎?如何解決org.json.JSONException:在Android中沒有響應類型的值?

//以下是來自服務器的響應表明內部logcat的

{"signup":[ 
      {"sessionid":0, 
      "responsetype":"failure", 
      "message"‌​:"Username emailid already register." 
      } 
     ] 
} 

    // Following is my code 

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener { 

    private EditText editTextfName; 
    private EditText editTextlName, editTextDid, editTextBd; 
    private EditText editTextPassword; 
    private EditText editTextEmail; 
    TextView txtBirthDate; 

    private Button buttonRegister; 
    Button buttonBdate; 

    String selected_date=""; 
    int mYear, mMonth, mDay; 
    Calendar myCalendar; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_register); 

     editTextfName = (EditText) findViewById(R.id.editTextfName); 
     editTextlName = (EditText) findViewById(R.id.editTextlName); 
     // editTextDid = (EditText) findViewById(R.id.editTextdid); 
     editTextBd = (EditText) findViewById(R.id.editTextbdate); 
     // txtBirthDate = (TextView) findViewById(R.id.txtBdate); 
     editTextPassword = (EditText) findViewById(R.id.editTextPassword); 
     editTextEmail = (EditText) findViewById(R.id.editTextEmail); 

     buttonRegister = (Button) findViewById(R.id.buttonRegister); 

     buttonRegister.setOnClickListener(this); 

    } 

    @Override 
    public void onClick(View v) { 

     if(v.getId() == R.id.buttonRegister){ 

      // Get the values given in EditText fields 
      String firstname = editTextfName.getText().toString(); 
      String lastname = null; 
      String emailaddress = editTextEmail.getText().toString(); 
      String birthdate = null; 
      String password = editTextPassword.getText().toString(); 
      String deviceid = null; 

      System.out.println("Givennames is :" + firstname + " Given password is :" + password); 

      // Pass those values to connectWithHttpGet() method 
      connectWithHttpGet(firstname,lastname,emailaddress,birthdate,password,deviceid); 
     } 
    } 

    private void connectWithHttpGet(String firstname, String lastname, String emailaddress, String birthdate, String password, String deviceid) { 

// Connect with a server is a time consuming process. 
//Therefore we use AsyncTask to handle it 
// From the three generic types; 
//First type relate with the argument send in execute() 
//Second type relate with onProgressUpdate method which I haven't use in this code 
//Third type relate with the return type of the doInBackground method, which also the input type of the onPostExecute method 
     class HttpGetAsyncTask extends AsyncTask<String, Void, String> { 

      private Context context; 

      private HttpGetAsyncTask(Context context){ 
       this.context=context; 
      } 


      @Override 
      protected String doInBackground(String... params) { 

       // As you can see, doInBackground has taken an Array of Strings as the argument 
       //We need to specifically get the givenUsername and givenPassword 

       String paramFname = params[0]; 
       String paramLname = params[1]; 
       String paramEmail = params[2]; 
       String paramBirthdate = params[3]; 
       String paramPassword = params[4]; 
       String paramDeviceid = params[5]; 
       System.out.println("userID" + paramFname + " password is :" + paramPassword); 

       // Create an intermediate to connect with the Internet 
       HttpClient httpClient = new DefaultHttpClient(); 

       // Sending a GET request to the web page that we want 
       // Because of we are sending a GET request, we have to pass the values through the URL 
       HttpGet httpGet = new HttpGet("http://www.example.com/ypAndroid/api/signUp?firstname="+paramFname+"&lastname="+paramLname+"&emailid="+paramEmail+"&birthdate="+paramBirthdate+"&password="+paramPassword+"&deviceid="+null); 

       try { 
        // execute(); executes a request using the default context. 
        // Then we assign the execution result to HttpResponse 
        HttpResponse httpResponse = httpClient.execute(httpGet); 
        System.out.println("httpResponse// getEntity() ; obtains the message entity of this response"); 
        // getContent() ; creates a new InputStream object of the entity. 
        // Now we need a readable source to read the byte stream that comes as the httpResponse 
        InputStream inputStream = httpResponse.getEntity().getContent(); 

        // We have a byte stream. Next step is to convert it to a Character stream 
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream); 

        // Then we have to wraps the existing reader (InputStreamReader) and buffer the input 
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 

        // InputStreamReader contains a buffer of bytes read from the source stream and converts these into characters as needed. 
        //The buffer size is 8K 
        //Therefore we need a mechanism to append the separately coming chunks in to one String element 
        // We have to use a class that can handle modifiable sequence of characters for use in creating String 
        StringBuilder stringBuilder = new StringBuilder(); 

        String bufferedStrChunk = null; 

        // There may be so many buffered chunks. We have to go through each and every chunk of characters 
        //and assign a each chunk to bufferedStrChunk String variable 
        //and append that value one by one to the stringBuilder 
        while((bufferedStrChunk = bufferedReader.readLine()) != null){ 
         stringBuilder.append(bufferedStrChunk); 
        } 

        // Now we have the whole response as a String value. 
        //We return that value then the onPostExecute() can handle the content 
        System.out.println("Returninge of doInBackground :" + stringBuilder.toString()); 

        // If the Username and Password match, it will return "working" as response 
        // If the Username or Password wrong, it will return "invalid" as response 
        return stringBuilder.toString(); 

       } catch (ClientProtocolException cpe) { 
        System.out.println("Exceptionrates caz of httpResponse :" + cpe); 
        cpe.printStackTrace(); 
       } catch (IOException ioe) { 
        System.out.println("Secondption generates caz of httpResponse :" + ioe); 
        ioe.printStackTrace(); 
       } 

       return null; 
      } 

      // Argument comes for this method according to the return type of the doInBackground() and 
      //it is the third generic type of the AsyncTask 
      @Override 
      protected void onPostExecute(String result) { 
       super.onPostExecute(result); 

       System.out.println("Post result :" + result); 
       try { 
        JSONObject jsonObject = new JSONObject(result); 
        JSONArray login = jsonObject.getJSONArray("signup"); 

        JSONObject jsonObject1 = login.getJSONObject(0); 
        String sessionid = jsonObject1.getString("sessionid"); 
        String responsetype = jsonObject1.getString("responsetype"); 
        String message = jsonObject1.getString("message"); 

        Log.i("response",responsetype); 

        // Toast.makeText(RegisterActivity.this, responsetype, Toast.LENGTH_LONG).show(); 


        if (TextUtils.equals(responsetype, "success")) { 
         Toast.makeText(RegisterActivity.this, "success !!" , Toast.LENGTH_LONG).show(); 
        } else if (TextUtils.equals(responsetype, "failure")) { 
         Toast.makeText(RegisterActivity.this, "failed......!!", Toast.LENGTH_LONG).show(); 
        }else { 
         Toast.makeText(RegisterActivity.this, "Invalid...", Toast.LENGTH_LONG).show(); 
        } 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 

       } 
     } 

     // Initialize the AsyncTask class 
     HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask(RegisterActivity.this); 
// Parameter we pass in the execute() method is relate to the first generic type of the AsyncTask 
// We are passing the connectWithHttpGet() method arguments to that 
     httpGetAsyncTask.execute(firstname,lastname,emailaddress,birthdate,password,deviceid); 
    } 
} 

回答

1

您的JSON有一個名爲responsetype

,而你正在使用responsetypes在你的代碼

String responsetypes = jsonObject1.getString("responsetypes"); 

刪除鍵「 s「,它應該工作。

String responsetypes = jsonObject1.getString("responsetype"); 

還用下面的參數和構造函數更新您的HttpGetAsyncTask類。因此,在您HttpGetAsyncTask添加以下代碼

private Context context; 
//in constructor: 
public HttpGetAsyncTask(Context context){ 
     this.context=context; 
} 

然後初始化這個調用使用的代碼如下 -

HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask(RegisterActivity.this); 

代替 -

HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask(); 

,並顯示出烤麪包用 -

if (TextUtils.equals(responsetypes, "success")) { 
    Toast.makeText(context, "HTTP GET is working...", Toast.LENGTH_LONG).show(); 
} else { 
    Toast.makeText(context, "Invalid...", Toast.LENGTH_LONG).show(); 
} 

這是bec澳洲英語的AsyncTask不繼承方面,因此UI元素不能的AsyncTask

使用 getApplicationContext()
+0

這裏我得到NullPointerException異常的JSONObject的JSONObject =新的JSONObject(結果); – mukund

+0

我檢查了上下文中使用的上下文獲取nullpointerexception錯誤.......但在應用端沒有顯示stiill消息 – mukund

+0

上面的行不使用上下文,所以上下文不能在行中給出錯誤JSONObject jsonObject = new JSONObject (結果); –

0

被稱爲加上了「s」在你的JSON因爲responseTyp的

{"signup":[ 
     {"sessionid":0, 
     "responsetype":"failure", 
     "message"‌​:"Username emailid already register." 
     } 
    ] 
} 
相關問題