2013-09-28 89 views
0

我正在嘗試爲我的項目創建一個登錄系統。我想創建過程有點像當寄存器按鈕填寫表格後點擊,這是一個與URL的API,並返回發送數據如下JSON字符串:使用Gson解析json登錄系統 - 應用程序關閉

{ 
    "result": "OK", 
    "message": [ 
     "Congratulations! You will shortly receive email ." 
    ], 
    "values": { 
     "id": 178964, 
     "fname": "", 
     "gender": "female" 
    } 
} 

結果字符串返回OK或否只。現在,當結果返回'OK'時,我想在loginErrorMsg中顯示'消息'。如果結果返回Ok,那麼應該啓動LoginActivity。但是我在解析json/gson時丟失了某處。

這是我的註冊創建的文件:

public class RegisterActivity extends Activity{ 
     private static String URL = "http://api.eample.com/"; 
     @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.register); 

      final EditText inputFname = (EditText) findViewById(R.id.registerFname); 
      final EditText inputLname = (EditText) findViewById(R.id.registerLname); 
      final EditText inputEmail = (EditText) findViewById(R.id.registerEmail); 
      Button btnRegister = (Button) findViewById(R.id.btnRegister); 
      Button btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLogin); 
      final TextView loginErrorMsg = (TextView) findViewById(R.id.register_error); 

      // Register Button Click event 
      btnRegister.setOnClickListener(new View.OnClickListener() { 
       Login login2; 
       RadioGroup radioSexGroup = (RadioGroup) findViewById(R.id.sex); 
       public void onClick(View view) { 
        String fname = inputFname.getText().toString(); 
        String lname = inputLname.getText().toString(); 
        String email = inputEmail.getText().toString(); 

        // get selected radio button from radioGroup 
        int selectedId = radioSexGroup.getCheckedRadioButtonId(); 
        RadioButton radioSexButton = (RadioButton) findViewById(selectedId); 
        String gender = radioSexButton.getText().toString(); 
        System.out.println(fname); 
        //Toast.makeText(RegisterActivity.this, radioSexButton.getText(), Toast.LENGTH_SHORT).show(); 

        String registerURL = URL +"&user_email="+ email +"&first_name="+ fname +"&last_name="+ lname +"&gender="+ gender; 
        System.out.println(registerURL); 

        if(email.length() == 0) { 
         loginErrorMsg.setText(R.string.empty); 
         //Toast.makeText(view.getContext(), R.string.empty, Toast.LENGTH_SHORT).show(); 
         return; 
        }else{ 

         try { 
          //Create an HTTP client 
          HttpClient client = new DefaultHttpClient(); 
          HttpPost post = new HttpPost(registerURL); 

          //Perform the request and check the status code 
          HttpResponse response = client.execute(post); 
          StatusLine statusLine = response.getStatusLine(); 
          if(statusLine.getStatusCode() == 200) { 
           HttpEntity entity = response.getEntity(); 
           InputStream content = entity.getContent(); 

           try { 
            //Read the server response and attempt to parse it as JSON 
            Reader reader = new InputStreamReader(content); 

            Gson gson = new Gson(); 
            this.login2 = gson.fromJson(reader, Login.class); 

            //handlePostsList(posts); 
           } catch (Exception ex) { 
            //Log.e(TAG, "Failed to parse JSON due to: " + ex); 
            failedLoading(); 
           } 
          } else { 
           //Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode()); 
           failedLoading(); 
          } 
         } catch(Exception ex) { 
          //Log.e(TAG, "Failed to send HTTP POST request due to: " + ex); 
          failedLoading(); 
         } 
//To set register message 
        if(login2.getResult().equals("OK")){ 
         loginErrorMsg.setText(login2.getMessage().toString()); 
        } 
        } 


       } 
      }); 

     } 

有人可以幫我解決註冊過程?我只想知道如何解析它以獲取'消息'字符串數據。

編輯: 更改登錄對象如下並創建值類。

的logcat:

09-29 13:05:13.145: E/AndroidRuntime(9428): FATAL EXCEPTION: main 
09-29 13:05:13.145: E/AndroidRuntime(9428): java.lang.NullPointerException 
09-29 13:05:13.145: E/AndroidRuntime(9428):  at com.kabelash.sk.RegisterActivity$1.onClick(RegisterActivity.java:105) 
09-29 13:05:13.145: E/AndroidRuntime(9428):  at android.view.View.performClick(View.java:4211) 
09-29 13:05:13.145: E/AndroidRuntime(9428):  at android.view.View$PerformClick.run(View.java:17267) 
09-29 13:05:13.145: E/AndroidRuntime(9428):  at android.os.Handler.handleCallback(Handler.java:615) 
09-29 13:05:13.145: E/AndroidRuntime(9428):  at android.os.Handler.dispatchMessage(Handler.java:92) 
09-29 13:05:13.145: E/AndroidRuntime(9428):  at android.os.Looper.loop(Looper.java:137) 
09-29 13:05:13.145: E/AndroidRuntime(9428):  at android.app.ActivityThread.main(ActivityThread.java:4898) 
09-29 13:05:13.145: E/AndroidRuntime(9428):  at java.lang.reflect.Method.invokeNative(Native Method) 
09-29 13:05:13.145: E/AndroidRuntime(9428):  at java.lang.reflect.Method.invoke(Method.java:511) 
09-29 13:05:13.145: E/AndroidRuntime(9428):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006) 
09-29 13:05:13.145: E/AndroidRuntime(9428):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773) 
09-29 13:05:13.145: E/AndroidRuntime(9428):  at dalvik.system.NativeStart.main(Native Method) 
09-29 13:10:21.380: I/Process(9428): Sending signal. PID: 9428 SIG: 9 

回答

0

你的Java類Login並不代表JSON響應的結構!

首先,您的JSON中的字段message是一個數組("message": [...]),而不是String,與您的類Login類似。

此外,在您的JSON領域values是一個對象(values: {...}),而不是在你LoginArrayList,等等。

所以,儘量在你的登錄類替換屬性:

String result; 
List<String> message; 
Values values; 

而且你還需要創建一個類Values具有這些屬性:

long id; 
String fname; 
String gender; 
+0

解決了問題 – Kabe

+0

現在我的應用程序強制關閉,當我點擊註冊按鈕。你能幫我嗎? – Kabe

+0

@Kabe,我很高興幫助!不幸的是,我不能幫助你解決你的新問題,因爲它似乎與Android問題有關,而我所知道的是Gson ...我建議你接受這個答案,並提出有關新問題的新問題,而不是關於Gson ... – MikO

0

當你的力量關閉消息LogCat中應該有一些診斷輸出。例如它可能仍然是一個NullPointerException。如果是這樣,您需要查看logcat中提到的行號,並查看代碼中的哪一行。您也可以使用Eclipse調試器來遍歷代碼並查看問題發生的位置。 Gill