jsonarray上的NullPointer异常

时间:2013-03-11 05:24:43

标签: android json nullpointerexception

FATAL EXCEPTION: main
java.lang.NullPointerException
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONArray.<init>(JSONArray.java:87)
at org.json.JSONArray.<init>(JSONArray.java:103)
at com.example.accountmanager.MainActivity.onClick(MainActivity.java:132)
at android.view.View.performClick(View.java:3644)
at android.view.View$PerformClick.run(View.java:14313)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4514)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
at dalvik.system.NativeStart.main(Native Method)

代码

package com.example.accountmanager;

public class MainActivity extends Activity implements OnClickListener {

    TextView sign;
    EditText user, pwd;
    Button ok, exit;
    InputStream is;
    String result;
    StringBuilder sb;
    public static String uName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        user = (EditText) findViewById(R.id.txtUser);
        pwd = (EditText) findViewById(R.id.txtPass);
        ok = (Button) findViewById(R.id.btnOk);

        exit = (Button) findViewById(R.id.btnExit);
        sign = (TextView) findViewById(R.id.txtSignUp);
        ok.setOnClickListener(this);
        exit.setOnClickListener(this);
        sign.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {

        case R.id.btnExit:
            finish();
            break;

        case R.id.txtSignUp:
            Intent intent = new Intent(MainActivity.this, Register.class);
            startActivity(intent);
            break;

        case R.id.btnOk:
            Toast.makeText(this, user.getText() + "    " + pwd.getText(),
                    Toast.LENGTH_SHORT).show();
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("username", user
                    .getText().toString()));
            nameValuePairs.add(new BasicNameValuePair("password", pwd.getText()
                    .toString()));
            nameValuePairs.add(new BasicNameValuePair("status", "Login"));
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(
                        "http://www.mpos.webuda.com/Login.php");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
            } catch (Exception e) {
                Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
                // Log.e("log_tag", "Error in http connection" + e.toString());
            } // convert response to string
            try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is, "iso-8859-1"), 8);
                sb = new StringBuilder();
                sb.append(reader.readLine() + "\n");
                String line = "0";
                // int count=0;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                    // Toast.makeText(this, line, Toast.LENGTH_SHORT).show();
                }
                /*
                 * if(count==0||line==null) Toast.makeText(this, "no record",
                 * Toast.LENGTH_SHORT).show();
                 */
                is.close();
                result = sb.toString();
            } catch (Exception e) {
                // Log.e("log_tag", "Error converting result "+e.toString());
            }
            // paring data
            String username = "",
            userType = "",
            password = "";
            try {
                // This is the line where the error is pointing to.
                JSONArray jArray = new JSONArray(result);
                JSONObject json_data = null;
                for (int i = 0; i < jArray.length(); i++) {
                    json_data = jArray.getJSONObject(i);
                    userType = json_data.getString("U_TYPE");
                    password = json_data.getString("U_PASS");
                    username = json_data.getString("U_NAME");
                }
                if (password.equals(pwd.getText().toString())) {
                    uName = username;
                    Toast.makeText(this, "Login Successful", Toast.LENGTH_SHORT)
                            .show();
                    if (userType.equalsIgnoreCase("admin")) {
                        Intent i = new Intent(MainActivity.this, Options.class);
                        startActivity(i);
                    } else {
                        Intent userIntent = new Intent(MainActivity.this,
                                se.anyro.nfc_reader.TagViewer.class);
                        userIntent.putExtra("uName", username);
                        startActivity(userIntent);
                    }
                } else
                    Toast.makeText(this, "Invalid Password", Toast.LENGTH_SHORT)
                            .show();
            } catch (JSONException e1) {
                Toast.makeText(getBaseContext(), "Invalid Username/Password",
                        Toast.LENGTH_LONG).show();
            } catch (ParseException e1) {
                e1.printStackTrace();
            }
        }
    }
}

当我在我的lg optimus p500上运行此代码时,应用程序运行正常,但当我在s3 i9300上运行时,我不知道为什么我在代码中出错 我收到此错误,不知道如何解决这个请帮忙。 这是我的源代码

3 个答案:

答案 0 :(得分:0)

首先,将您的http结果放到JSONObject ---

JSONObject jsonResult = new JSONObject(result);

然后从JSON对象中获取数组。

答案 1 :(得分:0)

问题是因为你的“结果”在这里包含NULL:

JSONArray jArray = new JSONArray(result);

肯定会发生这种情况,因为UI线程中不允许网络操作,并且您的下载代码在没有回退的情况下崩溃并在结果中返回NULL。

答案 2 :(得分:-1)

阅读本文:http://www.androiddesignpatterns.com/2012/06/app-force-close-honeycomb-ics.html

由于对Honeycomb及更高版本的更严格检查,您无法在UI线程上执行网络操作。如建议的那样,使用AsyncTask进行网络操作。