致命异常:AsyncTask#1和android.view.WindowLeaked

时间:2015-05-26 08:37:52

标签: php android mysql multithreading android-asynctask

我今天刚刚开始使用android studio,并按照一个工作教程制作用户登录页面。 第一个活动显示,但是当我按下登录按钮时,应用程序崩溃时出现以下错误代码:

第一个

  

9505-9538 /? E / AndroidRuntime:FATAL EXCEPTION:AsyncTask#1       处理:com.example.aks.mobilepos,PID:9505       java.lang.RuntimeException:执行doInBackground()时发生错误               在android.os.AsyncTask $ 3.done(AsyncTask.java:300)               在java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)               at java.util.concurrent.FutureTask.setException(FutureTask.java:222)               在java.util.concurrent.FutureTask.run(FutureTask.java:242)               在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)               在java.lang.Thread.run(Thread.java:841)        引发者:java.lang.IllegalStateException:目标主机不能为null,或者在参数中设置。 scheme = null,host = null,path = 192.168.1.141 / login.php               at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:591)               在org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:293)               在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)               在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)               在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)               在com.example.aks.mobilepos.JSONParser.makeHttpRequest(JSONParser.java:110)               at com.example.aks.mobilepos.LoginActivity $ AttemptLogin.doInBackground(LoginActivity.java:80)               at com.example.aks.mobilepos.LoginActivity $ AttemptLogin.doInBackground(LoginActivity.java:53)               在android.os.AsyncTask $ 2.call(AsyncTask.java:288)               在java.util.concurrent.FutureTask.run(FutureTask.java:237)   在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)   在java.lang.Thread.run(Thread.java:841)

第二个:

  

9505-9505 /? E / WindowManager:android.view.WindowLeaked:Activity com.example.aks.mobilepos.LoginActivity泄露了窗口com.android.internal.policy.impl.PhoneWindow $ DecorView {41c35f60 VE .... R ......最初添加的D 0,0-456,144}               在android.view.ViewRootImpl。(ViewRootImpl.java:346)               在android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)               在android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)               在android.app.Dialog.show(Dialog.java:286)               at com.example.aks.mobilepos.LoginActivity $ AttemptLogin.onPreExecute(LoginActivity.java:63)               在android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)               在android.os.AsyncTask.execute(AsyncTask.java:535)               在com.example.aks.mobilepos.LoginActivity.onClick(LoginActivity.java:50)               在android.view.View.performClick(View.java:4445)               在android.view.View $ PerformClick.run(View.java:18446)               在android.os.Handler.handleCallback(Handler.java:733)               在android.os.Handler.dispatchMessage(Handler.java:95)               在android.os.Looper.loop(Looper.java:136)               在android.app.ActivityThread.main(ActivityThread.java:5146)               at java.lang.reflect.Method.invokeNative(Native Method)               在java.lang.reflect.Method.invoke(Method.java:515)               在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:732)               在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)               在dalvik.system.NativeStart.main(本地方法)

我似乎无法弄清楚什么是错的,localhost / index.php可通过移动浏览器访问,它们位于同一个wifi网络上。

这是文件 LoginActivity:

public class LoginActivity extends ActionBarActivity implements View.OnClickListener{

Button bLogin;
EditText etUsername, etPassword;
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "192.168.1.141/login.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    etUsername = (EditText) findViewById(R.id.etUsername);
    etPassword = (EditText) findViewById(R.id.etPassword);
    bLogin = (Button) findViewById(R.id.bLogin);
    bLogin.setOnClickListener(this);

}

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

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

    boolean failure = false;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(LoginActivity.this);
        pDialog.setMessage("Attempting for login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }
     @Override
     protected String doInBackground(String... args) {
         // TODO Auto-generated method stub
         // here Check for success tag
         int success;
         String username = etUsername.getText().toString();
         String password = etPassword.getText().toString();
         try {

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

             // checking  log for json response
             Log.d("Login attempt", json.toString());

             // success tag for json
             success = json.getInt(TAG_SUCCESS);
             if (success == 1) {
                 Log.d("Successfully Login!", json.toString());

                 Intent ii = new Intent(LoginActivity.this,BillActivity.class);
                 finish();
                 // this finish() method is used to tell android os that we are done with current //activity now! Moving to other activity
                 startActivity(ii);
                 return json.getString(TAG_MESSAGE);
             }else{

                 return json.getString(TAG_MESSAGE);

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

         return null;
     }
     /**
      * Once the background process is done we need to  Dismiss the progress dialog asap
      * **/
     protected void onPostExecute(String message) {

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

JSONParser:

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

// default no argument constructor for jsonpaser class
public JSONParser() {

}


public JSONObject getJSONFromUrl(final String url) {

    // Making HTTP request
    try {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        // Executing POST request & storing the response from server  locally.
        HttpResponse httpResponse = httpClient.execute(httpPost);

        HttpEntity httpEntity = httpResponse.getEntity();

        is = httpEntity.getContent();

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

    try {


        // Create a BufferedReader
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        // Declaring string builder
        StringBuilder str = new StringBuilder();
        //  string to store the JSON object.
        String strLine = null;

        // Building while we have string !equal null.
        while ((strLine = reader.readLine()) != null) {
            str.append(strLine + "\n");
        }

        // Close inputstream.
        is.close();
        // string builder data conversion  to string.
        json = str.toString();
    } catch (Exception e) {
        Log.e("Error", " something wrong with converting result " + e.toString());
    }

    // Try block used for pasrseing String to a json object
    try {
        jsonObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("json Parsering", "" + e.toString());
    }

    // Returning json Object.
    return jsonObj;

}



public JSONObject makeHttpRequest(String url, String method,
                                  List<NameValuePair> params) {

    // Make HTTP request
    try {

        // checking request method
        if(method == "POST"){

            // now defaultHttpClient object
            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 str = new StringBuilder();
        String strLine = null;
        while ((strLine = reader.readLine()) != null) {
            str.append(strLine + "\n");
        }
        is.close();
        json = str.toString();
    } catch (Exception e) {

    }

    // now will try to parse the string into JSON object
    try {
        jsonObj = new JSONObject(json);
    } catch (JSONException e) {

    }


    return jsonObj;

}

}

BillActivity是android studio生成的默认空白活动。

我也可以发布login.php文件,任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

使用http://或https://启动您的网址。否则,它无法找出协议并将整个URL视为路径而不是主机后跟路径