Android json结果为空。如何检查json是否为空

Android json结果为空。如何检查json是否为空,android,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.Asyn

我有活动登录

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
代码更改为:

@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();
    }

因为当前您试图在
onPostExecute
方法内创建无效的
json1
JsonObject。在将名称值检查为null之前,请先检查json对象是否包含名称

json1显然是空的,因为您刚刚创建了它…如果(json.getString(KEY_SUCCESS)==null){@Alexbelek:plz编辑有问题的新日志,并将json与您的问题放在一起,我建议
optString()
如果您不知道该键是否存在。强制关闭内联
如果(!json.has(key_SUCCESS)){
@ρцσѕρєK@Alexbelek:plz post new logi尝试更改代码的
(json.getString(KEY_SUCCESS)!=null){
。现在可以显示消息。
if (json != null && json.getString(KEY_SUCCESS) != null){
    // PARSE RESULT 
}else{
    // SHOW NOTIFICIATION: URL/SERVER NOT REACHABLE
}
@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();
    }