0

我尝试完成本教程教程第 5 部分,我在 Regisert.java 中的代码行中得到了 NullPointerException:

Log.d("Login attempt", json.toString());

我正在使用 WAMP 服务器,并且我已经将我的 php 文件保存在 www 目录下。这意味着我的字符串变量 URL ist

"http://10.0.2.2:80/www/login_tutorial/register.php"

. Hier ist my log.txt

07-13 19:56:20.266: E/AndroidRuntime(29385): FATAL EXCEPTION: AsyncTask #1
07-13 19:56:20.266: E/AndroidRuntime(29385): java.lang.RuntimeException: An error    occured while executing doInBackground()
07-13 19:56:20.266: E/AndroidRuntime(29385):    at android.os.AsyncTask$3.done(AsyncTask.java:278)
07-13 19:56:20.266: E/AndroidRuntime(29385):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
07-13 19:56:20.266: E/AndroidRuntime(29385):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
07-13 19:56:20.266: E/AndroidRuntime(29385):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
07-13 19:56:20.266: E/AndroidRuntime(29385):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
07-13 19:56:20.266: E/AndroidRuntime(29385):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
07-13 19:56:20.266: E/AndroidRuntime(29385):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
07-13 19:56:20.266: E/AndroidRuntime(29385):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
07-13 19:56:20.266: E/AndroidRuntime(29385):    at java.lang.Thread.run(Thread.java:856)
07-13 19:56:20.266: E/AndroidRuntime(29385): Caused by: java.lang.NullPointerException
07-13 19:56:20.266: E/AndroidRuntime(29385):    at com.example.mysqltest.Register$CreateUser.doInBackground(Register.java:105)
07-13 19:56:20.266: E/AndroidRuntime(29385):    at com.example.mysqltest.Register$CreateUser.doInBackground(Register.java:1)
07-13 19:56:20.266: E/AndroidRuntime(29385):    at android.os.AsyncTask$2.call(AsyncTask.java:264)
07-13 19:56:20.266: E/AndroidRuntime(29385):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
07-13 19:56:20.266: E/AndroidRuntime(29385):    ... 5 more

有人能告诉我为什么它对我不起作用吗?!

谢谢

我从上面的链接中获取了代码,但没关系,我会再次在这里发布。

public class Register extends Activity implements OnClickListener {

private EditText user, pass;
private Button mRegister;

// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();

private static final String LOGIN_URL = "http://10.0.2.2:80/www/login_tutorial/register.php";

private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";



@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.register);

    user = (EditText) findViewById(R.id.username);
    pass = (EditText) findViewById(R.id.password);

    mRegister = (Button) findViewById(R.id.register);
    mRegister.setOnClickListener(this);
}



@Override
public void onClick(View v) {
    new CreateUser().execute();

}

@Override
protected void onPause() {
    super.onPause();
    if (pDialog != null) {
        pDialog.dismiss();
    }
}

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

    /**
     * Before starting background thread Show Progress Dialog
     */
    boolean failure = false;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Register.this);
        pDialog.setMessage("Creating user...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {
        int success;
        String username = user.getText().toString();
        String password = pass.getText().toString();
        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));

            Log.d("request", "starting");

            JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);

                // full json response
                Log.d("Login attempt", json.toString());

                // json success element
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("User created", json.toString());
                    finish();
                    return json.getString(TAG_MESSAGE);
                }
                else {
                    Log.d("Login Failure", json.getString(TAG_MESSAGE));
                    return json.getString(TAG_MESSAGE);
                }

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

    /**
     * After completing background task Dismiss the progress dialog
     */
    @Override
    protected void onPostExecute(String result) {
        if (pDialog != null) {
            pDialog.dismiss();
        }
        if (result != null) {
            Toast.makeText(Register.this, result, Toast.LENGTH_LONG).show();
        }
    }
}
}

传递 JSON 的方法在这里:

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") {


            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 jObj;
}

为什么它给我 null 作为 JSON 的结果?

4

2 回答 2

2

我认为您的 jsonParser 没有抛出异常,而是为您的请求返回 null 。修改您的 jsonParser 以在出现错误时始终抛出异常或在此处为您的 json 对象添加 null 处理

JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
if(json == null)
    return null;
于 2013-07-13T18:08:17.720 回答
0

在第 105 行的 doInBackground() 中必须有一些具有空值的东西,并且您正在尝试访问它,这会导致错误。可以参考Source Attachment 不包含源码的文件 ThreadPoolExecutor.class供参考。

希望这会帮助你。

于 2013-07-13T17:53:55.530 回答