当前位置: 首页 > 知识库问答 >
问题:

致命异常:AsyncTask #1和Android . view . window泄漏

齐振
2023-03-14

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

第一个

9505-9538/?E/AndroidRuntime致命异常:async task # 1 Process:com . example . aks . mobile pos,PID:9505 Java . lang . runtime异常:在android.os执行doInBackground()时出错. async task $ 3 . done(async task . Java:300)在Java . util . concurrent . future task . finish completion(future task . Java:355)在Java . util . concurrent . future task . set EXCEPTION(future task . Javascheme=null,host=null,path = 192 . 168 . 1 . 141/log in . PHP at org . Apache . http . impl . client . defaultrequestdirector .限定词oute(defaultrequestdirector . Java:591)at org . Apache . http . impl . impl . client . defaultrequestdirector . execute(defaultrequestdirector . Java:293)at org . Apache . http . impl . client . abstract http client . execute(abstracthttpclient . Java:555

第二个:

9505-9505/? E/WindowManager﹕ android.view。窗口泄漏:Activity com.example.aks.mobilepos。LoginActivity已泄漏到com.android.internal.policy.impl窗口。PhoneWindow$DecorView{41c35f60 V.E..R..d0,0-456144}最初在android.view.ViewRootImpl.(ViewRootImpl.java:346)的android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)的android.view.windowManagerMapl.addView.windowManageMapl.addView(WindowManagerImpl.java:69)在android.app.Dialog.show(Dialog.java:286)的com.example.aks.mobilepos.LoginActivity$AttemptLogin.onPreExecute(loginactive.java:63)在android.os.AsyncTask.executeOnExecutor(asyncttask.java:587)在android.os.AsyncTask.execute(AsyncTask.java:535)在com.exchange.ak.mobilepos.loginastivity.onClick(loginacivity.java:50)在Android.view.view.view.performClick(view.java:4445)在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(ActivityThead.java:5146)在java.lang.reflect.Method。java.lang.reflect.Method.invoke(Method.java:515)和com.android.internal.os.zgoteInit$MethodAndArgsCaller.run(zgoteinit.java:732)上的java.lang.reflect.Method(本机方法)和dalvik.system.NativeStart上的com.andro.internal.os.ygoteInIT.main(zgotInit.java:566)。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个答案

朱昊乾
2023-03-14

以http://或https://开始您的URL。否则,它无法确定协议,并将整个URL视为一个路径,而不是一个主机后跟一个路径

 类似资料: