1

我正在为我的应用程序创建登录系统。它将登录信息发送到 API 并返回一个 json。

这是 LoginActivity.java

public class LoginActivity extends Activity{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        // Login Button Click event
        Button btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLogin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                this.retrieveLogin();
            }

            private void retrieveLogin() {
                LoginAsyncTask task = new LoginAsyncTask();
                task.execute();
            }

        });

        // Link to Register Screen
        Button btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegister);
        btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    Intent i = new Intent(getApplicationContext(),RegisterActivity.class);
                    startActivity(i);
                    finish();
                }
        });   
    }

    private class LoginAsyncTask extends AsyncTask<Void, Void, Void> {
        Login login2;
        private Activity activity;

        final EditText inputEmail = (EditText) findViewById(R.id.loginEmail);
        final EditText inputPassword = (EditText) findViewById(R.id.loginPassword);
        final TextView loginErrorMsg = (TextView) findViewById(R.id.login_error);

        String email = inputEmail.getText().toString();
        String pwrd = inputPassword.getText().toString();


        @Override
        protected Void doInBackground(Void... params) {
            //System.out.println(loginURL);
            try {
                //Create an HTTP client
                DefaultHttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost(loginURL);

                //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);
                    } 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();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

        }
    }

    @Override
    protected void onPause() {

        super.onPause();
        //finish();
    }
    private void failedLoading() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(LoginActivity.this, "Failed to Register. look at LogCat.", Toast.LENGTH_SHORT).show();
            }
        });
    }   
}

如果我输入无效数据进行登录,则返回以下 json:

{
"result":"KO",
"message":["Make sure you did not misspell your password."]
}

该消息已成功显示在文本视图上。

但是,当我输入有效数据进行登录时,它会返回以下 json:

{
"result":"OK",
"message":["Successfull login."],
"values":{"id":"1809","fname":"me","gender":"male"}
}

在这种情况下,我的应用程序强制关闭并获得以下 logcat:

    09-30 12:55:05.445: E/AndroidRuntime(14593): FATAL EXCEPTION: main
09-30 12:55:05.445: E/AndroidRuntime(14593): java.lang.NullPointerException
09-30 12:55:05.445: E/AndroidRuntime(14593):    at com.kabelash.sk.LoginActivity$LoginAsyncTask.onPostExecute(LoginActivity.java:128)
09-30 12:55:05.445: E/AndroidRuntime(14593):    at com.kabelash.sk.LoginActivity$LoginAsyncTask.onPostExecute(LoginActivity.java:1)
09-30 12:55:05.445: E/AndroidRuntime(14593):    at android.os.AsyncTask.finish(AsyncTask.java:631)
09-30 12:55:05.445: E/AndroidRuntime(14593):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
09-30 12:55:05.445: E/AndroidRuntime(14593):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
09-30 12:55:05.445: E/AndroidRuntime(14593):    at android.os.Handler.dispatchMessage(Handler.java:99)
09-30 12:55:05.445: E/AndroidRuntime(14593):    at android.os.Looper.loop(Looper.java:137)
09-30 12:55:05.445: E/AndroidRuntime(14593):    at android.app.ActivityThread.main(ActivityThread.java:4898)
09-30 12:55:05.445: E/AndroidRuntime(14593):    at java.lang.reflect.Method.invokeNative(Native Method)
09-30 12:55:05.445: E/AndroidRuntime(14593):    at java.lang.reflect.Method.invoke(Method.java:511)
09-30 12:55:05.445: E/AndroidRuntime(14593):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
09-30 12:55:05.445: E/AndroidRuntime(14593):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
09-30 12:55:05.445: E/AndroidRuntime(14593):    at dalvik.system.NativeStart.main(Native Method)

但我找不到任何解决方案。有人请帮忙。

4

3 回答 3

2

我需要你的价值观课。因为您的变量可能是类中的整数减值。在 Json 中,数据id字符串

于 2013-09-30T11:15:19.517 回答
0
// try this way
public void setId(String id){
            this.id = Integer.parseInt(id);
}
于 2013-09-30T12:00:40.673 回答
0

我以前从未尝试过gson,但我总是使用解析器类来解决json的解决方案

public class JSONParser {

static InputStream is;
static JSONObject jObj;
static String json = "";

public JSONParser()
{

}
public JSONObject makeHttpRequest(String Url, String Method, List<NameValuePair> params)
{
    try {

        if (Method == "POST")
        {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(Url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }
        else if(Method == "GET")
        {
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            Url += "?" + paramString;

             HttpGet httpGet = new HttpGet(Url);
             HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();

            is = httpEntity.getContent();
        }   
    } catch (UnsupportedEncodingException e) {
        // TODO: handle exception
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO: handle exception
        e.printStackTrace();
    } catch (IOException e) {
        // TODO: handle exception
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String Line = null;

        while ((Line = reader.readLine()) != null)
        {
            sb.append(Line + "\n");
        }

        is.close();
        json = sb.toString();
    } catch (Exception e) {
        // TODO: handle exception
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    try{
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        // TODO: handle exception
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    return jObj;
} }

关于登录活动:

------------------------------已编辑------------------- ---

protected String doInBackground(String... p) {
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("email", email));
            params.add(new BasicNameValuePair("password", password));
JSONObject json = new JSONParser.makeHttpRequest(loginURL, "POST/GET", params);

在参数的第一个元素(名称)中指的是您在 php 脚本中使用的 $_POST['email']。而且我不知道你在使用什么 get 或 POST 所以你需要在函数的第二个参数中指定它然后你可以检索结果为

success = json.getString("success");
if (success.equals("ok")
// do something
}// try } // background
于 2013-09-30T11:31:28.217 回答