Json.getString()上的NullPointerException

时间:2013-01-29 23:52:57

标签: java android nullpointerexception

我正在尝试使用我的第一个Android应用程序从mysql数据库登录用户,因此我使用用户名和密码来识别每个用户。

我的问题是eclipse在这一行引发NullPointerException错误:

if (json.getString(KEY_SUCCESS) != null

日志:

FATAL EXCEPTION: AsyncTask #1
01-29 23:32:18.583: E/AndroidRuntime(17340): java.lang.RuntimeException: An error occured while executing doInBackground()
01-29 23:32:18.583: E/AndroidRuntime(17340):    at android.os.AsyncTask$3.done(AsyncTask.java:278)
01-29 23:32:18.583: E/AndroidRuntime(17340):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-29 23:32:18.583: E/AndroidRuntime(17340):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-29 23:32:18.583: E/AndroidRuntime(17340):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-29 23:32:18.583: E/AndroidRuntime(17340):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-29 23:32:18.583: E/AndroidRuntime(17340):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
01-29 23:32:18.583: E/AndroidRuntime(17340):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-29 23:32:18.583: E/AndroidRuntime(17340):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-29 23:32:18.583: E/AndroidRuntime(17340):    at java.lang.Thread.run(Thread.java:856)
01-29 23:32:18.583: E/AndroidRuntime(17340): Caused by: java.lang.NullPointerException
01-29 23:32:18.583: E/AndroidRuntime(17340):    at com.example.androidhive.AsyncLogin.doInBackground(LoginScreen.java:109)
01-29 23:32:18.583: E/AndroidRuntime(17340):    at com.example.androidhive.AsyncLogin.doInBackground(LoginScreen.java:1)
01-29 23:32:18.583: E/AndroidRuntime(17340):    at android.os.AsyncTask$2.call(AsyncTask.java:264)
01-29 23:32:18.583: E/AndroidRuntime(17340):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-29 23:32:18.583: E/AndroidRuntime(17340):    ... 5 more

public class LoginScreen extends Activity {

Button buttonConnecter;
EditText inputUserName, inputPassword;
TextView tv;

StringBuffer buffer;

String codsinc;

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

    inputUserName = (EditText) findViewById(R.id.inputUserName);
    inputPassword = (EditText) findViewById(R.id.inputPassword);
    buttonConnecter = (Button) findViewById(R.id.buttonConnecter);

    tv = (TextView) findViewById(R.id.tv);

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

        public void onClick(View view) {

            String username = inputUserName.getText().toString();
            String password = inputPassword.getText().toString();

            AsyncLogin LoginPass = new AsyncLogin();
            Boolean Result = null;
            try {
                Result = LoginPass.execute(username, password).get();
                if (Result == true) {

                    // Launch Dashboard Screen
                    Intent dashboard = new Intent(LoginScreen.this,
                            Account.class);

                    startActivity(dashboard);

                    // Close Login Screen
                    finish();
                } else {
                    // Error in login
                    tv.setText("Password ou identifiant incorrects");
                }
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    });

}

}

class AsyncLogin extends AsyncTask<String, Void, Boolean> {

private static String KEY_SUCCESS = "success";

protected Boolean doInBackground(String... params) {
    // TODO Auto-generated method stub
    UserFunctions userFunction = new UserFunctions();
    Log.d("Button", "Login");
    JSONObject json = userFunction.loginUser(params[0], params[1]);

    // check for login response
    try {
        if (json.getString(KEY_SUCCESS) != null) {

            String res = json.getString(KEY_SUCCESS);

            if (Integer.parseInt(res) == 1) {

                return true;

            } else {
                return false;
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return null;
}

}

public class UserFunctions {

private JSONParser jsonParser;

private static String loginURL = "http://website.org/android_login_api/";
private static String login_tag = "login";


// constructor
public UserFunctions(){
    jsonParser = new JSONParser();
}

/**
 * function make Login Request
 * @param username
 * @param password
 * */
public JSONObject loginUser(String username, String password){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", login_tag));
    params.add(new BasicNameValuePair("username", username));
    params.add(new BasicNameValuePair("password", password));
    JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
    //Log.e("JSON", json.toString());
    return json;
}


/**
 * Function get Login status
 * */
public boolean isUserLoggedIn(Context context){
    DatabaseHandler db = new DatabaseHandler(context);
    int count = db.getRowCount();
    if(count > 0){
        // user logged in
        return true;
    }
    return false;
}

/**
 * Function to logout user
 * Reset Database
 * */
public boolean logoutUser(Context context){
    DatabaseHandler db = new DatabaseHandler(context);
    db.resetTables();
    return true;
}

}

1 个答案:

答案 0 :(得分:1)

检查你的json文本实际上是什么样的,我在网上搜索了getJSONFromUrl,并在这里找到了源代码:

http://www.androidhive.info/2012/01/android-json-parsing-tutorial/

如果json错误,它实际上返回null。