-1

First I will describe the process/problem briefly in words. Afterwards, I'll attach all of the code.

  1. I start the android application in debug mode.
  2. Main activity gets called.
  3. It calls Activity2 via "intent".
  4. Then (in onCreate) I start an Async activity in order to get information from a webserver. I do that with this command "new Kontakt(info1, info2, information).execute();"

  5. I've put a break point at the onPostExecute method in "Kontakt" to see what happens. But!! It doesn't stop there. So then I figured, "okey, the doInBackground method didn't get called for some reason"

  6. When I continue to run the code, as a surprise, onPostExecute gets called (somewhere at the end of onClick) and stops at the break point just the way I want it but than it's too late, because I'd like to have the output already in the onCreate method where I called "new Kontakt(info1, info2, information).execute();".

  7. So why does it call onPostExecute too late and what can I do to make the process call it properly already in onCreate at the line "new Kontakt(info1, info2, information).execute();" in Activity2?

The code is below

MainActivity.java

    package com.example.myapplication;

    import android.content.Context;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.graphics.Color;
    import android.graphics.PorterDuff;
    import android.graphics.drawable.Drawable;
    import android.preference.PreferenceManager;
    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;


    public class MainActivity extends ActionBarActivity implements View.OnClickListener {
        Button button1;

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

            button1 = (Button) findViewById(R.id.button1);
            button1.setOnClickListener(this);
        }


        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.button1:
                    Intent intent = new Intent(this, Activity2.class);
                    startActivity(intent);
                    break;
            }
        }
    }

Activity2.java

        package com.example.myapplication;

        import android.app.AlertDialog;
        import android.content.Context;
        import android.content.DialogInterface;
        import android.content.SharedPreferences;
        import android.net.ConnectivityManager;
        import android.net.NetworkInfo;
        import android.preference.PreferenceManager;
        import android.support.v7.app.ActionBarActivity;
        import android.os.Bundle;
        import android.text.InputType;
        import android.text.TextUtils;
        import android.util.Log;
        import android.view.Menu;
        import android.view.MenuItem;
        import android.view.View;
        import android.view.WindowManager;
        import android.view.inputmethod.InputMethodManager;
        import android.widget.Button;
        import android.widget.EditText;

        import org.apache.http.NameValuePair;
        import org.apache.http.client.HttpClient;
        import org.apache.http.client.entity.UrlEncodedFormEntity;
        import org.apache.http.client.methods.HttpPost;
        import org.apache.http.impl.client.DefaultHttpClient;
        import org.apache.http.message.BasicNameValuePair;
        import org.apache.http.params.BasicHttpParams;
        import org.apache.http.params.HttpConnectionParams;
        import org.apache.http.params.HttpParams;

        import java.io.IOException;
        import java.net.MalformedURLException;
        import java.util.ArrayList;


public class Activty2 extends ActionBarActivity implements View.OnClickListener {

    Button button;
    Context information;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity2);
        information=this;
        String info1="Yeah";
        String info2="Yeah";
        new Kontakt(info1, info2, information).execute();

        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.button) {
        }
    }

Kontakt.java

package com.example.myapplication;

import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;



import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;

import java.util.ArrayList;

public class Kontakt extends AsyncTask<Void, Void, Integer> {

    public static final int CONNECTION_TIMEOUT = 1000 * 15;
    public static final String SERVER_ADDRESS = "http://test.site.net/";

    String info1;
    String info2;
    private final Context information;

public Kontakt(String info1, String info2, Context context) {
this.info1=info1;
this.Info2=info2;
    this.information=context;
}


        @Override
        protected Integer doInBackground(Void... params) {


            ArrayList<NameValuePair> dataToSend = new ArrayList<>();
            dataToSend.add(new BasicNameValuePair("user", info1));
            dataToSend.add(new BasicNameValuePair("password", info2));

            HttpParams httpRequestParams = getHttpRequestParams();

            HttpClient client = new DefaultHttpClient(httpRequestParams);
            HttpPost post = new HttpPost(SERVER_ADDRESS
                    + "Register.php");

            try {
                post.setEntity(new UrlEncodedFormEntity(dataToSend));
                client.execute(post);
                int result=1;
                return result;

            } catch (Exception e) {
                e.printStackTrace();
                int result=0;
                return result;
            }
//return null;

        }

    private HttpParams getHttpRequestParams() {
        HttpParams httpRequestParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpRequestParams,
                CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpRequestParams,
                CONNECTION_TIMEOUT);
        return httpRequestParams;
    }

    @Override
    protected void onPostExecute(Integer result)
    {
        super.onPostExecute(result);
        SharedPreferences.Editor editor = information.getSharedPreferences("INTERNET_KOLL", Context.MODE_PRIVATE).edit();
        editor.putString("internet_status", String.valueOf(result));
        editor.commit();
    }

}
user5095266
  • 119
  • 2
  • 7
  • Not again... AsyncTask using threads... You will not get results in onCreate... Why? because it is **async** task http://ideone.com/PPHi95 – Selvin Aug 08 '15 at 10:06
  • @Selvin I don't understand your comment: there is no thread in this code. ?? – Xebax Aug 08 '15 at 10:11
  • Seriously you don't see similarities? maybe some day... Anyway, with AsyncTask you even can be sure that it will not run onPostExecute until onCreate finishes as it's using handler to post execution to main thread.. – Selvin Aug 08 '15 at 10:20
  • @Selvin I misunderstood your "Not again... AsyncTask using threads... ". I understood "Not again... You wrote AsyncTask using threads... " but now I guess you meant "Not again... AsyncTask does use threads...". – Xebax Aug 08 '15 at 11:24

1 Answers1

0

In Activity2, when onCreate() calls new Kontakt(info1, info2, information).execute();:

  • an asynchronous task (Kontakt) is started in the background
  • the execution of onCreate() continues

so it's normal that you don't have the response immediately.

Xebax
  • 432
  • 4
  • 11