【问题标题】:json null pointer error in async task [duplicate]异步任务中的json空指针错误[重复]
【发布时间】:2015-05-08 08:23:47
【问题描述】:

我有一个忘记密码活动,它连接到 mysql 数据库并生成一个新密码。然而; json 对象总是返回一个空指针异常。 php 脚本有一个用于测试的 html 表单,并且它运行良好,因此在 java 代码中肯定会出现错误。

这是 Json Parser 类:

package test.example.com.test;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class JSONParser {

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

    // constructor
    public JSONParser() {

    }
    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
                                      List<NameValuePair> params) {
        // Making HTTP request
        try {
            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                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) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            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) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        // return JSON String
        return jObj;
    }
}

这是异步任务:

class ForgetPass extends AsyncTask<String, String, String> {

    boolean failure = false;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(forg1.this);
        pDialog.setTitle("Generating New Password...");
        pDialog.setCancelable(true);
        pDialog.setIndeterminate(false);
        pDialog.show();

    }

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
        // Check for success tag
        int success;
        String Email;

        Email = etMailfrpass.getText().toString();

        try {

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("Email", Email));
            JSONObject json5 = js.makeHttpRequest(
                    FORGET_URL, "POST", params);

           // Log.d("Ibrahim forget pass", "Ibrahim forget pass");
            success = json5.getInt(TAG_SUCCESS);

            if (success == 1) {
                //Log.d("Password generated", json5.toString());
                pDialog.dismiss();

                return json5.getString(TAG_MESSAGE);
            } else {
              //  Log.d("generation Failure!", json5.getString(TAG_MESSAGE));
                return json5.getString(TAG_MESSAGE);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(String file_url1) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        if (file_url1 != null) {
            Toast.makeText(forg1.this, file_url1, Toast.LENGTH_LONG).show();
        }
    }
}

这是日志,错误在 json.getInt

05-08 11:12:28.336  16229-16554/test.example.com.test E/JSON Parser﹕ Error parsing data org.json.JSONException: Value fetet of type java.lang.String cannot be converted to JSONObject
05-08 11:12:28.336  16229-16554/test.example.com.test W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x40aa5228)
05-08 11:12:28.346  16229-16554/test.example.com.test E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:278)
            at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
            at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
            at java.util.concurrent.FutureTask.run(FutureTask.java:137)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
            at java.lang.Thread.run(Thread.java:864)
     Caused by: java.lang.NullPointerException
            at test.example.com.test.forg1$ForgetPass.doInBackground(forg1.java:107)
            at test.example.com.test.forg1$ForgetPass.doInBackground(forg1.java:73)
            at android.os.AsyncTask$2.call(AsyncTask.java:264)
            at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
            at java.util.concurrent.FutureTask.run(FutureTask.java:137)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
            at java.lang.Thread.run(Thread.java:864)

【问题讨论】:

    标签: java php android mysql json


    【解决方案1】:

    假设出了点问题,所以这部分在 jObj 中返回 null:

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    // return JSON String
    return jObj;
    

    现在您的AsyncTask 尝试在返回的jObj 中调用getString() 方法,该方法本身为空(无论成功与否为1):

        if (success == 1) {
            //Log.d("Password generated", json5.toString());
            pDialog.dismiss();
    
            return json5.getString(TAG_MESSAGE);
        } else {
          //  Log.d("generation Failure!", json5.getString(TAG_MESSAGE));
            return json5.getString(TAG_MESSAGE);
    
        }
    

    你可以使用 NPE。

    【讨论】:

      猜你喜欢
      • 2013-08-26
      • 1970-01-01
      • 2011-09-24
      • 1970-01-01
      • 1970-01-01
      • 2012-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多