Unfortunately the application stopped working

*爱你&永不变心* 提交于 2019-12-14 03:22:26

问题


I'm a beginner in android development.I have been looking for a week now. Followed all the tutorials word by word. Whenever I start my android emulator it first shows ProcessSystem isn't responding. Wait or Exit? Second the application loads but as soon as I click on the Register or Login button after filling out the form, after a few seconds of showing process dialog box, "Unfortunately the app has stopped working" is shown and it exits. My Login.java file is

public class Login extends Activity implements OnClickListener{

    private EditText user, pass;
    private Button mSubmit, mRegister;

     // Progress Dialog
    private ProgressDialog pDialog;

    // JSON parser class
    JSONParser jsonParser = new JSONParser();
    private static final String LOGIN_URL = "http://localhost/webservice/login.php";
    //JSON element ids from repsonse of php script:
    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.login);

        //setup input fields
        user = (EditText)findViewById(R.id.username);
        pass = (EditText)findViewById(R.id.password);
        //setup buttons
        mSubmit = (Button)findViewById(R.id.login);
        mRegister = (Button)findViewById(R.id.register);
        //register listeners
        mSubmit.setOnClickListener(this);
        mRegister.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.login:
                new AttemptLogin().execute();
            break;
        case R.id.register:
                Intent i = new Intent(this, Register.class);
                startActivity(i);
            break;
        default:
            break;
        }
    }

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


        boolean failure = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Login.this);
            pDialog.setMessage("Attempting login...");
            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 = 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");
                // getting product details by making HTTP request
                JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
                // check your log for json response
                Log.d("Login attempt", json.toString());
                // json success tag
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("Login Successful!", json.toString());
                    Intent i = new Intent(Login.this, Display.class);
                    finish();
                    startActivity(i);
                    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(Login.this, file_url, Toast.LENGTH_LONG).show();
            }
        }
    }
}

And my Register.java is

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://localhost/webservice/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) {
        // TODO Auto-generated method stub

                new CreateUser().execute();
    }

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

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

            pDialog.dismiss();
            if (file_url != null){
                Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
            }
        }
    }
}

THe JSONParser.java file is

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;

    }
}

the logcat is:

05-13 06:57:20.120: D/gralloc_goldfish(1219): Emulator without GPU emulation detected.
05-13 06:57:25.540: I/Choreographer(1219): Skipped 282 frames!  The application may be doing too much work on its main thread.
05-13 06:57:41.450: D/dalvikvm(1219): GC_FOR_ALLOC freed 138K, 6% free 3395K/3604K, paused 38ms, total 43ms
05-13 06:57:41.590: D/dalvikvm(1219): GC_FOR_ALLOC freed 35K, 6% free 3496K/3684K, paused 34ms, total 40ms
05-13 06:57:41.590: I/dalvikvm-heap(1219): Grow heap (frag case) to 4.085MB for 635812-byte allocation
05-13 06:57:42.280: D/request!(1219): starting
05-13 06:57:42.600: I/Choreographer(1219): Skipped 100 frames!  The application may be doing too much work on its main thread.
05-13 06:57:42.770: I/Choreographer(1219): ...and 8 more
05-13 06:58:08.680: W/System.err(1219): java.net.UnknownHostException: Unable to resolve host "http": No address associated with hostname
05-13 06:58:08.800: I/Choreographer(1219): Skipped 37 frames!  The application may be doing too much work on its main thread.
05-13 06:58:08.880: W/System.err(1219):     at java.net.InetAddress.lookupHostByName(InetAddress.java:424)
05-13 06:58:08.880: W/System.err(1219):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
05-13 06:58:08.880: W/System.err(1219):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
05-13 06:58:08.970: W/System.err(1219):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
05-13 06:58:08.970: W/System.err(1219):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-13 06:58:08.970: W/System.err(1219):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-13 06:58:09.720: W/System.err(1219):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
05-13 06:58:09.720: W/System.err(1219):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-13 06:58:09.720: W/System.err(1219):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-13 06:58:09.740: W/System.err(1219):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-13 06:58:09.740: W/System.err(1219):     at com.example.mysqltest.JSONParser.makeHttpRequest(JSONParser.java:89)
05-13 06:58:09.740: W/System.err(1219):     at com.example.mysqltest.Register$CreateUser.doInBackground(Register.java:94)
05-13 06:58:10.220: W/System.err(1219):     at com.example.mysqltest.Register$CreateUser.doInBackground(Register.java:1)
05-13 06:58:10.470: W/System.err(1219):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
05-13 06:58:10.470: W/System.err(1219):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
05-13 06:58:10.530: W/System.err(1219):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
05-13 06:58:10.530: W/System.err(1219):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
05-13 06:58:10.540: W/System.err(1219):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
05-13 06:58:10.540: W/System.err(1219):     at java.lang.Thread.run(Thread.java:841)
05-13 06:58:10.540: W/System.err(1219): Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
05-13 06:58:10.610: I/Choreographer(1219): Skipped 47 frames!  The application may be doing too much work on its main thread.
05-13 06:58:11.070: W/System.err(1219):     at libcore.io.Posix.getaddrinfo(Native Method)
05-13 06:58:11.070: W/System.err(1219):     at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
05-13 06:58:11.070: W/System.err(1219):     at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
05-13 06:58:11.080: W/System.err(1219):     ... 18 more
05-13 06:58:11.080: E/Buffer Error(1219): Error converting result java.lang.NullPointerException: lock == null
05-13 06:58:11.180: E/JSON Parser(1219): Error parsing data org.json.JSONException: End of input at character 0 of 
05-13 06:58:11.180: W/dalvikvm(1219): threadid=11: thread exiting with uncaught exception (group=0xb3af1ba8)
05-13 06:58:11.420: E/AndroidRuntime(1219): FATAL EXCEPTION: AsyncTask #1
05-13 06:58:11.420: E/AndroidRuntime(1219): Process: com.example.mysqltest, PID: 1219
05-13 06:58:11.420: E/AndroidRuntime(1219): java.lang.RuntimeException: An error occured while executing doInBackground()
05-13 06:58:11.420: E/AndroidRuntime(1219):     at android.os.AsyncTask$3.done(AsyncTask.java:300)
05-13 06:58:11.420: E/AndroidRuntime(1219):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
05-13 06:58:11.420: E/AndroidRuntime(1219):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
05-13 06:58:11.420: E/AndroidRuntime(1219):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
05-13 06:58:11.420: E/AndroidRuntime(1219):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
05-13 06:58:11.420: E/AndroidRuntime(1219):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
05-13 06:58:11.420: E/AndroidRuntime(1219):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
05-13 06:58:11.420: E/AndroidRuntime(1219):     at java.lang.Thread.run(Thread.java:841)
05-13 06:58:11.420: E/AndroidRuntime(1219): Caused by: java.lang.NullPointerException
05-13 06:58:11.420: E/AndroidRuntime(1219):     at com.example.mysqltest.Register$CreateUser.doInBackground(Register.java:97)
05-13 06:58:11.420: E/AndroidRuntime(1219):     at com.example.mysqltest.Register$CreateUser.doInBackground(Register.java:1)
05-13 06:58:11.420: E/AndroidRuntime(1219):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
05-13 06:58:11.420: E/AndroidRuntime(1219):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
05-13 06:58:11.420: E/AndroidRuntime(1219):     ... 4 more
05-13 06:58:15.100: E/WindowManager(1219): android.view.WindowLeaked: Activity com.example.mysqltest.Register has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b3e3c660 V.E..... R.....ID 0,0-456,144} that was originally added here
05-13 06:58:15.100: E/WindowManager(1219):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:348)
05-13 06:58:15.100: E/WindowManager(1219):  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
05-13 06:58:15.100: E/WindowManager(1219):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
05-13 06:58:15.100: E/WindowManager(1219):  at android.app.Dialog.show(Dialog.java:286)
05-13 06:58:15.100: E/WindowManager(1219):  at com.example.mysqltest.Register$CreateUser.onPreExecute(Register.java:77)
05-13 06:58:15.100: E/WindowManager(1219):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
05-13 06:58:15.100: E/WindowManager(1219):  at android.os.AsyncTask.execute(AsyncTask.java:535)
05-13 06:58:15.100: E/WindowManager(1219):  at com.example.mysqltest.Register.onClick(Register.java:61)
05-13 06:58:15.100: E/WindowManager(1219):  at android.view.View.performClick(View.java:4438)
05-13 06:58:15.100: E/WindowManager(1219):  at android.view.View$PerformClick.run(View.java:18422)
05-13 06:58:15.100: E/WindowManager(1219):  at android.os.Handler.handleCallback(Handler.java:733)
05-13 06:58:15.100: E/WindowManager(1219):  at android.os.Handler.dispatchMessage(Handler.java:95)
05-13 06:58:15.100: E/WindowManager(1219):  at android.os.Looper.loop(Looper.java:136)
05-13 06:58:15.100: E/WindowManager(1219):  at android.app.ActivityThread.main(ActivityThread.java:5017)
05-13 06:58:15.100: E/WindowManager(1219):  at java.lang.reflect.Method.invokeNative(Native Method)
05-13 06:58:15.100: E/WindowManager(1219):  at java.lang.reflect.Method.invoke(Method.java:515)
05-13 06:58:15.100: E/WindowManager(1219):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-13 06:58:15.100: E/WindowManager(1219):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-13 06:58:15.100: E/WindowManager(1219):  at dalvik.system.NativeStart.main(Native Method)

EDIT After all the answers received. I made == to equals() and changed the url address to 10.0.2.2/webservices and had already added the internet permission but still no success. Still it exits and shows connection denied. Please help me with this. Now my logcat file is:

05-14 07:09:16.291     895-1191/com.example.mysqltest.app W/System.err﹕ org.apache.http.conn.HttpHostConnectException: Connection to http://10.0.2.2 refused
05-14 07:09:16.501     895-1191/com.example.mysqltest.app W/System.err﹕ at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
05-14 07:09:16.501     895-1191/com.example.mysqltest.app W/System.err﹕ at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-14 07:09:16.501     895-1191/com.example.mysqltest.app W/System.err﹕ at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-14 07:09:16.501     895-1191/com.example.mysqltest.app W/System.err﹕ at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
05-14 07:09:16.501     895-1191/com.example.mysqltest.app W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-14 07:09:16.501     895-1191/com.example.mysqltest.app W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-14 07:09:16.501     895-1191/com.example.mysqltest.app W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-14 07:09:16.501     895-1191/com.example.mysqltest.app W/System.err﹕ at com.example.mysqltest.app.JSONParser.makeHttpRequest(JSONParser.java:90)
05-14 07:09:16.501     895-1191/com.example.mysqltest.app W/System.err﹕ at com.example.mysqltest.app.Register$CreateUser.doInBackground(Register.java:94)
05-14 07:09:16.511     895-1191/com.example.mysqltest.app W/System.err﹕ at com.example.mysqltest.app.Register$CreateUser.doInBackground(Register.java:64)
05-14 07:09:16.511     895-1191/com.example.mysqltest.app W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:288)
05-14 07:09:16.561     895-1191/com.example.mysqltest.app W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
05-14 07:09:16.561     895-1191/com.example.mysqltest.app W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
05-14 07:09:16.571     895-1191/com.example.mysqltest.app W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
05-14 07:09:16.571     895-1191/com.example.mysqltest.app W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
05-14 07:09:16.571     895-1191/com.example.mysqltest.app W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
05-14 07:09:16.571     895-1191/com.example.mysqltest.app W/System.err﹕ Caused by: java.net.ConnectException: socket failed: EACCES (Permission denied)
05-14 07:09:17.191     895-1191/com.example.mysqltest.app W/System.err﹕ at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:181)
05-14 07:09:17.281     895-1191/com.example.mysqltest.app W/System.err﹕ ... 15 more
05-14 07:09:17.441     895-1191/com.example.mysqltest.app W/System.err﹕ Caused by: java.net.SocketException: socket failed: EACCES (Permission denied)
05-14 07:09:17.671     895-1191/com.example.mysqltest.app W/System.err﹕ at libcore.io.IoBridge.socket(IoBridge.java:576)
05-14 07:09:18.601     895-1191/com.example.mysqltest.app W/System.err﹕ Caused by: libcore.io.ErrnoException: socket failed: EACCES (Permission denied)
05-14 07:09:19.031     895-1191/com.example.mysqltest.app W/System.err﹕ at libcore.io.Posix.socket(Native Method)
05-14 07:09:19.031     895-1191/com.example.mysqltest.app W/System.err﹕ at libcore.io.BlockGuardOs.socket(BlockGuardOs.java:181)
05-14 07:09:19.131     895-1191/com.example.mysqltest.app W/System.err﹕ at libcore.io.IoBridge.socket(IoBridge.java:561)
05-14 07:09:19.131     895-1191/com.example.mysqltest.app W/System.err﹕ ... 20 more
05-14 07:09:19.141     895-1191/com.example.mysqltest.app E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null
05-14 07:09:19.141     895-1191/com.example.mysqltest.app E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
05-14 07:09:19.221     895-1191/com.example.mysqltest.app W/dalvikvm﹕ threadid=12: thread exiting with uncaught exception (group=0xb4afeba8)
05-14 07:09:19.271     895-1191/com.example.mysqltest.app E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
    Process: com.example.mysqltest.app, PID: 895
    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:841)
     Caused by: java.lang.NullPointerException
            at com.example.mysqltest.app.Register$CreateUser.doInBackground(Register.java:97)
            at com.example.mysqltest.app.Register$CreateUser.doInBackground(Register.java:64)
            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:841)
05-14 07:09:26.021      895-895/com.example.mysqltest.app E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.mysqltest.app.Register has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b4e28230 V.E..... R.....ID 0,0-563,96} that was originally added here
            at android.view.ViewRootImpl.<init>(ViewRootImpl.java:348)
            at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
            at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
            at android.app.Dialog.show(Dialog.java:286)
            at com.example.mysqltest.app.Register$CreateUser.onPreExecute(Register.java:77)
            at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
            at android.os.AsyncTask.execute(AsyncTask.java:535)
            at com.example.mysqltest.app.Register.onClick(Register.java:61)
            at android.view.View.performClick(View.java:4438)

回答1:


As Apoorv says, you need to have permission to access any network.

<uses-permission android:name="android.permission.INTERNET" />

If adding the above to your manifest doesn't fix it (or you already have that permission), the likely problem is your addresses...

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

I'm assuming your php server is running on the same computer as the emulator (but not on the emulator itself). If that's the case using localhost wont work. On an emulator localhost is the actual emulated device's loopback address and NOT the loopback address of the computer.

When using networking on an emulator you need to use 10.0.2.2 to connect to the computer's localhost / loopback address. Example...

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

See Using The Emulator documentation in the Emulator Networking section.

EDIT: One very likely reason for the Window Leaked error is you are trying to access objects that are in the main body of the Activities from the doInBackground methods of your AsyncTasks. You cannot do this as doInBackground runs on a separate thread.

In your AsyncTasks declare your username and password strings in the main body where you declare your failure boolean. Also your static final strings. Example...

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

    private static final String LOGIN_URL =  "http://localhost/webservice/register.php";
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";

    boolean failure = false;
    String username, password;

    ...
}

Get the text strings from the EditTexts in the onPreExecute() method of the AsyncTasks (this method runs on the main/UI thread). Example...

@Override
protected void onPreExecute() {
    super.onPreExecute();
    username = user.getText().toString();
    password = pass.getText().toString();
    pDialog = new ProgressDialog(Login.this);

    ...
}

Move your JSONParser declaration and initialisation into the doInBackgoround method of the AsyncTasks. Example...

@Override
protected String doInBackground(String... args) {
    // Check for success tag
    int success;
    JSONParser jsonParser = new JSONParser();

    ...
}



回答2:


There are few things which you may have missed
1. Add internet permission in your application
2. When you are calling asynctask class add where the request is of POST or GET type
3. As can be seen clearly from your logcat the url you are accessing is not valid even i tried it in my browser, it is not valid



来源:https://stackoverflow.com/questions/23646793/unfortunately-the-application-stopped-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!