json结果为null。如何检查json为null

时间:2013-01-22 17:25:18

标签: android

我有活动登录

package com.app.DatabaseSample;


import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.app.library.DatabaseHandler;
import com.app.library.UserFunctions;



public class LoginActivity extends Activity {
    Button btnLogin;
    Button btnLinkToRegister;
    EditText inputUsername;
    EditText inputPassword;
    TextView loginErrorMsg;


    // JSON Response node names
    private static String KEY_SUCCESS = "success";
    private static String KEY_ERROR = "error";
    private static String KEY_ERROR_MSG = "error_msg";
    private static String KEY_USER_ID = "userid";
    private static String KEY_UID = "uid";
    private static String KEY_NAME = "name";
    private static String KEY_EMAIL = "email";
    private static String KEY_CREATED_AT = "created_at";

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

        // Importing all assets like buttons, text fields
        inputUsername = (EditText) findViewById(R.id.loginUsername);
        inputPassword = (EditText) findViewById(R.id.loginPassword);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        loginErrorMsg = (TextView) findViewById(R.id.login_error);

     // Login button Click Event
        btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                readLogin(view);
            }
        });

    }

    private class ProcessLogin extends AsyncTask<String, String, JSONObject> {

        private ProgressDialog dialog;
        private ProgressDialog pDialog;
        protected Context applicationContext;
String email,password;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            inputUsername = (EditText) findViewById(R.id.loginUsername);
            inputPassword = (EditText) findViewById(R.id.loginPassword);
             email = inputUsername.getText().toString();
             password = inputPassword.getText().toString();
            pDialog = new ProgressDialog(LoginActivity.this);
            pDialog.setMessage("Loading User ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected JSONObject doInBackground(String... args) {


            UserFunctions userFunction = new UserFunctions();
            JSONObject json = userFunction.loginUser(email, password);

            Log.d("Button", "Login");


            return json;

        }

        @Override
        protected void onPostExecute(JSONObject json) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            UserFunctions userFunction = new UserFunctions();

            try {
                if(!json.has(KEY_SUCCESS)){

                Toast.makeText(getApplicationContext(), "No more data",
                        Toast.LENGTH_LONG).show();   
         }


            else if (json.getString(KEY_SUCCESS) != null){
                    loginErrorMsg.setText("");
                    String res = json.getString(KEY_SUCCESS); 
                    if(Integer.parseInt(res) == 1){
                        // user successfully logged in
                        // Store user details in SQLite Database
                        DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                        JSONObject json_user = json.getJSONObject("user");

                        // Clear all previous data in database
                        userFunction.logoutUser(getApplicationContext());
                        db.addUser(json_user.getString(KEY_USER_ID), json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));                        

                        // Launch Dashboard Screen
                        Intent dashboard = new Intent(getApplicationContext(), DatabaseSample.class);

                        // Close all views before launching Dashboard
                        dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(dashboard);

                        // Close Login Screen
                        finish();
                    }else{
                        // Error in login
                        loginErrorMsg.setText("Username atau Password salah!");
                    }
                }
                           else {
                               loginErrorMsg.setText("koneksi gagal ke server");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
      }

    public void readLogin(View view) {
        new ProcessLogin().execute();

    // check for login response

  }
}

之前,onPostExecute是强制关闭导致json结果为null,如何在执行if (json.getString(KEY_SUCCESS) != null)之前检查onPostExecute中的json是否为null?所以app在结果为null时不强制关闭?

这是我的logcat

01-23 01:05:29.851: E/AndroidRuntime(4513): FATAL EXCEPTION: main
01-23 01:05:29.851: E/AndroidRuntime(4513): java.lang.NullPointerException
01-23 01:05:29.851: E/AndroidRuntime(4513):     at com.app.DatabaseSample.LoginActivity$ProcessLogin.onPostExecute(LoginActivity.java:108)
01-23 01:05:29.851: E/AndroidRuntime(4513):     at com.app.DatabaseSample.LoginActivity$ProcessLogin.onPostExecute(LoginActivity.java:1)
01-23 01:05:29.851: E/AndroidRuntime(4513):     at android.os.AsyncTask.finish(AsyncTask.java:417)
01-23 01:05:29.851: E/AndroidRuntime(4513):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
01-23 01:05:29.851: E/AndroidRuntime(4513):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
01-23 01:05:29.851: E/AndroidRuntime(4513):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-23 01:05:29.851: E/AndroidRuntime(4513):     at android.os.Looper.loop(Looper.java:130)
01-23 01:05:29.851: E/AndroidRuntime(4513):     at android.app.ActivityThread.main(ActivityThread.java:3683)
01-23 01:05:29.851: E/AndroidRuntime(4513):     at java.lang.reflect.Method.invokeNative(Native Method)
01-23 01:05:29.851: E/AndroidRuntime(4513):     at java.lang.reflect.Method.invoke(Method.java:507)
01-23 01:05:29.851: E/AndroidRuntime(4513):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-23 01:05:29.851: E/AndroidRuntime(4513):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-23 01:05:29.851: E/AndroidRuntime(4513):     at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:2)

if (json != null && json.getString(KEY_SUCCESS) != null){
    // PARSE RESULT 
}else{
    // SHOW NOTIFICIATION: URL/SERVER NOT REACHABLE
}

答案 1 :(得分:0)

将您的onPostExecute代码更改为:

@Override
protected void onPostExecute(JSONObject json) {
 // dismiss the dialog after getting all products
pDialog.dismiss();
UserFunctions userFunction = new UserFunctions();

     try {
         if(!json.has(KEY_SUCCESS)){

                  // your code here...       
           }  
          else if (json.getString(KEY_SUCCESS) != null) {
              // your code here..
           }
          else {
             // your code here...  
           }
       }
     } catch (JSONException e) {
       e.printStackTrace();
    }

因为目前您正在尝试在json1方法中创建无效的onPostExecute JsonObject。在将名称值检查为null

之前,使用JSONObject.has(String name)检查json对象是否包含名称