FATAL EXCEPTION: AsyncTask #1 and android.view.WindowLeaked

I just started messing around with android studio today, and followed a working tutorial to make a user login page.
The first activity shows up, but when i press the login button, the app crashes with the following error codes:

first one

9505-9538/? E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.aks.mobilepos, PID: 9505
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.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=192.168.1.141/login.php
at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:591)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:293)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at 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)
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)

second one:

9505-9505/? E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.aks.mobilepos.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41c35f60 V.E….. R……D 0,0-456,144} that was originally added here
at android.view.ViewRootImpl.(ViewRootImpl.java:346)
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.aks.mobilepos.LoginActivity$AttemptLogin.onPreExecute(LoginActivity.java:63)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.aks.mobilepos.LoginActivity.onClick(LoginActivity.java:50)
at android.view.View.performClick(View.java:4445)
at android.view.View$PerformClick.run(View.java:18446)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5146)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
at dalvik.system.NativeStart.main(Native Method)

I can’t seem to figure out what’s wrong, the localhost/index.php is accesible via the mobile browser, they are on the same wifi network.

here are the files
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 is the default blank activity generated by android studio.

I can post the login.php file as well, any help will be appreciated.


Source: mysql

Leave a Reply