单击按钮时应用程序崩溃

时间:2015-02-25 11:36:23

标签: java android mysql android-asynctask

我试图在我的Android应用程序中使用PHP将用户输入的数据存储到MySQL数据库中。但只要点击按钮,我就会收到此消息"不幸的是,[app]已停止工作。"

public class Register extends Activity implements View.OnClickListener {
    private EditText userName, userContact, userAddress, userRequest;
    private Spinner userStore;
    private Button mRegister;

    // Progress Dialog
    private ProgressDialog pDialog;

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

    //php login script

    //localhost :
    //testing on your device
    //put your local ip instead,  on windows, run CMD > ipconfig
    //or in mac's terminal type ifconfig and look for the ip under en0 or en1
    // private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/register.php";

    //testing on Emulator:
    private static final String LOGIN_URL = "http://10.0.2.2/callarocket/register.php";

    //testing from a real server:
    //private static final String LOGIN_URL = "http://www.yourdomain.com/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.first_screen);
        Spinner dropdown = (Spinner)findViewById(R.id.StoreSpinner);
        String[] items = new String[]{"NZ Mamak", "Indo Shop", "NZ Supermarket"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
        dropdown.setAdapter(adapter);

        userName = (EditText)findViewById(R.id.EditName);
        userContact = (EditText)findViewById(R.id.EditContact);
        userAddress = (EditText)findViewById(R.id.EditAddress);
        userStore = (Spinner)findViewById(R.id.StoreSpinner);
        userRequest = (EditText)findViewById(R.id.EditRequest);

        mRegister = (Button)findViewById(R.id.SubmitButton);
        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 Request...");
            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;
            String username = userName.getText().toString();
            String usercontact = userContact.getText().toString();
            String useraddress = userAddress.getText().toString();
            String userstore = userStore.getSelectedItem().toString();
            String userrequest = userRequest.getText().toString();
            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("userName", username));
                params.add(new BasicNameValuePair("userContact", usercontact));
                params.add(new BasicNameValuePair("userAddress", useraddress));
                params.add(new BasicNameValuePair("userStore", userstore));
                params.add(new BasicNameValuePair("userRequest", userrequest));

                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;

        }
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        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();
            }

        }

    }

}

这是我的JSONParser代码。

public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }


    public JSONObject getJSONFromUrl(final String url) {

        // Making HTTP request
        try {
            // Construct the client and the HTTP request.
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            // Execute the POST request and store the response locally.
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // Extract data from the response.
            HttpEntity httpEntity = httpResponse.getEntity();
            // Open an inputStream with the data content.
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            // Create a BufferedReader to parse through the inputStream.
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            // Declare a string builder to help with the parsing.
            StringBuilder sb = new StringBuilder();
            // Declare a string to store the JSON object data in string form.
            String line = null;

            // Build the string until null.
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            // Close the input stream.
            is.close();
            // Convert the string builder data to an actual string.
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // Try to 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 the JSON Object.
        return jObj;

    }


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

    }
}

这是logcat

02-25 11:25:36.224    2445-2460/com.example.user.callarocket D/OpenGLRenderer﹕ Render dirty regions requested: true
02-25 11:25:36.228    2445-2445/com.example.user.callarocket D/﹕ HostConnection::get() New Host Connection established 0xa6c43550, tid 2445
02-25 11:25:36.271    2445-2445/com.example.user.callarocket D/Atlas﹕ Validating map...
02-25 11:25:36.373    2445-2460/com.example.user.callarocket D/﹕ HostConnection::get() New Host Connection established 0xa6c438d0, tid 2460
02-25 11:25:36.423    2445-2460/com.example.user.callarocket I/OpenGLRenderer﹕ Initialized EGL, version 1.4
02-25 11:25:36.457    2445-2460/com.example.user.callarocket D/OpenGLRenderer﹕ Enabling debug mode 0
02-25 11:25:36.500    2445-2460/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 11:25:36.500    2445-2460/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xae1eb880, error=EGL_SUCCESS
02-25 11:25:48.014    2445-2460/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 11:25:48.014    2445-2460/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5b6d2a0, error=EGL_SUCCESS
02-25 11:25:48.303    2445-2460/com.example.user.callarocket D/OpenGLRenderer﹕ endAllStagingAnimators on 0xa6cb7580 (RippleDrawable) with handle 0xa6c43c60
02-25 11:25:59.147    2445-2465/com.example.user.callarocket D/request!﹕ starting
02-25 11:25:59.207    2445-2460/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 11:25:59.207    2445-2460/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xae1f3be0, error=EGL_SUCCESS
02-25 11:25:59.281    2445-2465/com.example.user.callarocket E/JSON Parser﹕ Error parsing data org.json.JSONException: Value Posted of type java.lang.String cannot be converted to JSONObject
02-25 11:25:59.299    2445-2465/com.example.user.callarocket E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
    Process: com.example.user.callarocket, PID: 2445
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
            at com.example.user.callarocket.Register$CreateUser.doInBackground(Register.java:128)
            at com.example.user.callarocket.Register$CreateUser.doInBackground(Register.java:85)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
02-25 11:25:59.599    2445-2460/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 11:25:59.599    2445-2460/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xae1f3e60, error=EGL_SUCCESS
02-25 11:26:00.172    2445-2445/com.example.user.callarocket E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.user.callarocket.Register has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{2dbde5f6 V.E..... R......D 0,0-1026,348} that was originally added here
            at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
            at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
            at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
            at android.app.Dialog.show(Dialog.java:298)
            at com.example.user.callarocket.Register$CreateUser.onPreExecute(Register.java:99)
            at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
            at android.os.AsyncTask.execute(AsyncTask.java:535)
            at com.example.user.callarocket.Register.onClick(Register.java:81)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

在Log.i(&#34; DATA&#34;,json)之后添加

02-25 12:24:16.222    2750-2765/com.example.user.callarocket D/OpenGLRenderer﹕ Render dirty regions requested: true
02-25 12:24:16.225    2750-2750/com.example.user.callarocket D/﹕ HostConnection::get() New Host Connection established 0xa6c3e550, tid 2750
02-25 12:24:16.259    2750-2750/com.example.user.callarocket D/Atlas﹕ Validating map...
02-25 12:24:16.366    2750-2765/com.example.user.callarocket D/﹕ HostConnection::get() New Host Connection established 0xa6c3e6f0, tid 2765
02-25 12:24:16.405    2750-2765/com.example.user.callarocket I/OpenGLRenderer﹕ Initialized EGL, version 1.4
02-25 12:24:16.433    2750-2765/com.example.user.callarocket D/OpenGLRenderer﹕ Enabling debug mode 0
02-25 12:24:16.462    2750-2765/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 12:24:16.462    2750-2765/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6c118a0, error=EGL_SUCCESS
02-25 12:24:24.841    2750-2765/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 12:24:24.842    2750-2765/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5e39720, error=EGL_SUCCESS
02-25 12:24:25.095    2750-2765/com.example.user.callarocket D/OpenGLRenderer﹕ endAllStagingAnimators on 0xa6cb2580 (RippleDrawable) with handle 0xa6c3eab0
02-25 12:24:33.820    2750-2768/com.example.user.callarocket D/request!﹕ starting
02-25 12:24:33.862    2750-2765/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 12:24:33.863    2750-2765/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5605140, error=EGL_SUCCESS
02-25 12:24:34.027    2750-2768/com.example.user.callarocket E/JSON Parser﹕ Error parsing data org.json.JSONException: Value Posted of type java.lang.String cannot be converted to JSONObject
02-25 12:24:34.028    2750-2768/com.example.user.callarocket E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
    Process: com.example.user.callarocket, PID: 2750
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
            at com.example.user.callarocket.Register$CreateUser.doInBackground(Register.java:128)
            at com.example.user.callarocket.Register$CreateUser.doInBackground(Register.java:85)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
02-25 12:24:34.335    2750-2765/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 12:24:34.335    2750-2765/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5af7e00, error=EGL_SUCCESS
02-25 12:24:36.361    2750-2750/com.example.user.callarocket I/Choreographer﹕ Skipped 106 frames!  The application may be doing too much work on its main thread.
02-25 12:24:36.754    2750-2750/com.example.user.callarocket E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.user.callarocket.Register has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{2dbde5f6 V.E..... R......D 0,0-1026,348} that was originally added here
            at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
            at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
            at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
            at android.app.Dialog.show(Dialog.java:298)
            at com.example.user.callarocket.Register$CreateUser.onPreExecute(Register.java:99)
            at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
            at android.os.AsyncTask.execute(AsyncTask.java:535)
            at com.example.user.callarocket.Register.onClick(Register.java:81)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

2 个答案:

答案 0 :(得分:1)

你有问题。

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

        new CreateUser().execute();

    }

在这里你必须使用点击的按钮。通常我们使用

switch(v.getId())
{
    case your button id :
              //Button function

}

答案 1 :(得分:0)

您需要使用解析器来解析字符串,然后将其转换为JSONObject,就像这样 -

JSONParser parser = new JSONParser();

Object obj = parser.parse(json);
JSONObject jsonObj = (JSONObject) obj;

return jsonObj;