AsyncTask - doInBackground中的JSON Android Studio错误

时间:2015-06-03 09:20:44

标签: android json android-asynctask

我正在学习如何创建一个简单的注册程序,将用户输入注册到MySQL数据库中。但每当我点击注册按钮时,我的应用程序将被强制关闭。那是为什么?

这是我的logcat:

    06-03 08:53:33.841    1529-1539/com.example.minzhe.sqltest E/Buffer Error﹕ Error         06-03 08:53:33.851    1529-1539/com.example.minzhe.sqltest E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
    06-03 08:53:33.851    1529-1539/com.example.minzhe.sqltest W/dalvikvm﹕ threadid=9: thread exiting with uncaught exception (group=0x40015560)
    06-03 08:53:33.861    1529-1539/com.example.minzhe.sqltest E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
        java.lang.RuntimeException: An error occured while executing         doInBackground()
                at android.os.AsyncTask$3.done(AsyncTask.java:200)
                at         java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
                at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
                at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
    at java.lang.Thread.run(Thread.java:1019)

 Caused by: java.lang.NullPointerException
                at com.example.minzhe.sqltest.Register$CreateUser.doInBackground(Register.java:112)
                at com.example.minzhe.sqltest.Register$CreateUser.doInBackground(Register.java:70)
                at android.os.AsyncTask$2.call(AsyncTask.java:185)
                at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
                at java.util.concurrent.FutureTask.run(FutureTask.java:138)
                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
                at java.lang.Thread.run(Thread.java:1019)

这是Register类的代码:

    package com.example.minzhe.sqltest;

    import java.util.ArrayList;
    import java.util.List;
    import org.apache.http.NameValuePair;
    import org.apache.http.message.BasicNameValuePair;
    import org.json.JSONException;
    import org.json.JSONObject;
    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

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

        //php login script

        private static final String LOGIN_URL =  "http://127.0.0.1/webservice/register.php";


        //ids
        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);

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

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

        }

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            new CreateUser().execute();

        }

        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) {
                // TODO Auto-generated method stub
                // Check for success tag
                int success;
                EditText user = (EditText)findViewById(R.id.username);
                EditText pass = (EditText)findViewById(R.id.password);
                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");

                    //Posting user data to script
                    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;

            }

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

            }

        }

        @Override
        public void onDestroy(){
            super.onDestroy();
            if ( pDialog!=null && pDialog.isShowing() ){
                pDialog.cancel();
            }
        }


    }

这是我的JSONParser代码:

    package com.example.minzhe.sqltest;

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

    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 android.util.Log;

    public class JSONParser {

        static InputStream is = null;
        static JSONObject jObj;
        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;

        }
    }

2 个答案:

答案 0 :(得分:0)

您在以下行中获得了nullPointer异常

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

这意味着你的json.toString()只是你的json从

返回
//Posting user data to script
                    JSONObject json = jsonParser.makeHttpRequest(
                            LOGIN_URL, "POST", params);

为空。用json添加一些值然后打印日志。

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

修改

问题在于你的json响应。因此,您需要使用任何工具来检查响应

我建议使用POSTMAN

答案 1 :(得分:0)

jObj = new JSONObject(json);

我认为回复有问题/你没有得到完整的答复。所以最终这行代码失败了,当然还有函数  public JSONObject makeHttpRequest(String url, String method,List<NameValuePair> params) 返回jObj,它是null。 然后在课程Register中,您只需对该null值执行一些操作。

然后在这里执行http调用后修复应该是这个

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

您应该检查返回值是否为null

if (json != null) {
 // perform something here
} else {
 // null return from JSONParser
}

无论如何,你不应该创建一个实际在JSONParser类中执行HTTP调用的类。它有误导性。