0

我正在尝试为我的项目创建一个登录系统。我想创建一个过程,比如在填写表单后单击注册按钮时,它将带有 URL 的数据发送到 API 并返回以下 json 字符串:

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

结果字符串仅返回 OK 或 No。现在我想 在结果返回“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());
                    }
                    }


                }
            });

        }

有人可以帮我解决注册过程吗?我只想知道如何解析它以获取“消息”字符串数据。

已编辑:将登录对象更改如下并创建值类。

日志猫:

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
4

2 回答 2

0

您的 Java 类Login不代表 JSON 响应的结构!

首先message,您的 JSON 中的字段是一个数组 ( "message": [...]),而不是String像您的 class 中的Login

此外,values您的 JSON 中的字段是一个对象 ( values: {...}),而不是ArrayList像您的 class 中的那样Login

因此,尝试通过以下方式替换 Login 类中的属性:

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

您还需要创建一个Values具有以下属性的类:

long id;
String fname;
String gender;
于 2013-09-28T16:36:29.773 回答
0

当您收到强制关闭消息时,LogCat 中应该有一些诊断输出。例如,它仍然可能是 NullPointerException。如果是这样,您需要查看 logcat 中提到的行号,并查看代码中的哪一行。您还可以使用 Eclipse 调试器来单步调试代码并查看问题出在哪里。鳃

于 2013-09-29T13:46:44.053 回答