不幸的是,应用程序停止工

时间:2014-05-14 06:05:09

标签: java android android-applicationinfo

我是android开发的初学者。我一直在寻找一周。逐字逐句地遵循所有教程。每当我启动我的Android模拟器时,它首先显示ProcessSystem没有响应。等或退出?其次,应用程序加载但是在我填写表单后单击“注册”或“登录”按钮后,在显示进程对话框几秒钟后,“不幸的是应用程序已停止工作”显示并退出。 我的Login.java文件是

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

我的Register.java是

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

JSONParser.java文件是

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是:

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)

修改 收到所有答案后。我做了== to equals()并将url地址更改为10.0.2.2/webservices并且已经添加了Internet权限但仍然没有成功。它仍然退出并显示连接被拒绝。请帮我解决一下这个。现在我的logcat文件是:

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)

2 个答案:

答案 0 :(得分:1)

正如Apoorv所说,您需要获得访问任何网络的权限。

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

如果将以上内容添加到您的清单中并未修复(或者您已经拥有该权限),则可能出现的问题是您的地址......

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

我假设您的php服务器与模拟器在同一台计算机上运行(但不在模拟器本身上运行)。如果使用localhost的情况不适用。在模拟器上localhost是实际模拟设备的环回地址,而不是计算机的环回地址。

在模拟器上使用网络时,您需要使用10.0.2.2连接到计算机的localhost / loopback地址。实施例...

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

请参阅Using The Emulator部分中的Emulator Networking文档。

编辑:窗口泄露错误的一个非常可能的原因是您尝试从AsyncTasks的doInBackground方法访问活动主体中的对象。你不能这样做,因为doInBackground在一个单独的线程上运行。

在AsyncTasks中,在声明失败布尔值的主体中声明您的用户名和密码字符串。也是你的静态最终字符串。实施例...

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;

    ...
}

从AsyncTasks的onPreExecute()方法中获取EditTexts中的文本字符串(此方法在主/ UI线程上运行)。实施例...

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

    ...
}

将您的JSONParser声明和初始化移动到AsyncTasks的doInBackgoround方法中。实施例...

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

    ...
}

答案 1 :(得分:0)

你可能错过的事情很少 1.在您的申请中添加互联网权限
2.在调用asynctask类时,在请求为POST或GET类型的地方添加 3.从您的logcat中可以清楚地看到,即使我在浏览器中尝试过,您访问的URL也无效,但它无效