-3

Activity.java

//Activity stuff
MyClass mc = new MyClass();
mc.getText();

public void dosomething() {
    textview.setText(mc.getText());
}

MyClass.java

class MyClass { 
    String text;
    public void setText() {
        class GetTextFromWEB extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... urls) {
                String url = urls[0];
                String output;
                //Getting text from web
                return output;
            }
            @Override
            protected void onPostExecute(String _text) {
                text = _text;
            }
        }
        String url = "google.com";
        //Doing with url something
        new GetText().execute(url);
    }
    public String getText() {return text;}
}

Promblem is - in activity setText do faster, then AsyncTask do it's job.
So when setText run, it's run like setText(null) I need to check in activity, is asynk ended, so i have my text to set. I hope i explained it

And i don't even need exactly AsyncTask, i need jsoup working, so if there is solution with another thread-class, with which jsoup will work, i can use it

Edit

class GetLyrics extends AsyncTask<String, Void, String> { //Class for getting lyrics
    private Context con;

    public GetLyrics(Context con) {
        this.con = con;
    }

    @Override
    protected String doInBackground(String... urls) {
        //do something
    }
    @Override
    protected void onPostExecute(String _lyrics) {
        lyrics = _lyrics;
        con.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ((TextView) findViewById(R.id.lyricsOutput)).setText(lyrics);
            }
        });
    }
}
Masafi
  • 151
  • 2
  • 15
  • 2
    Refer this http://stackoverflow.com/a/33918300/5567009 – Nigam Patro Dec 19 '15 at 13:18
  • @NigamPatro thanks, i'll try – Masafi Dec 19 '15 at 13:20
  • @NigamPatro nope, this doen't work for me, because i can't setText neither in `onPostExecute` nor in `new Asynctaskclass().execute(url);` I need to listen in anouther place... – Masafi Dec 19 '15 at 13:29
  • Have you created listener class and called the method in the `onPostExecute()` as given? – Nigam Patro Dec 19 '15 at 13:30
  • That is what I given answer there, can you post what you tried so far. So that I can give proper explanation as per your code. – Nigam Patro Dec 19 '15 at 13:35
  • @NigamPatro i have given more code. I tried your answers. But I CANT `setText` in `setLyrics()` ,because i don't have any TextView in it. I must `setText` outside `setLyrics()` -> i can't setText neither in `onPostExecute` nor in `new Asynctaskclass().execute(url);` – Masafi Dec 19 '15 at 13:39
  • @NigamPatro i edit my question, may be now you will understand my problem – Masafi Dec 19 '15 at 13:47

2 Answers2

0

1: Make my first project from my previous post and add some new lines in it to get data from http: api's.

public class Example extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_example);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("parameter1", "xyz"));
        params.add(new BasicNameValuePair("parameter2", "abc"));
        params.add(new BasicNameValuePair("parameter3", "opqr"));
        ServerConnection task = new ServerConnection(this, new ResultListener() {
            @Override
            public void result(String response) {
                Toast.make(this, response, Toast.LENGTH_LONG).show();
            }

            @Override
            public void loader(boolean visble) {
            }

            @Override
            public void connectionLost(String error) {
                Toast.make(this, error, Toast.LENGTH_LONG).show();
            }
        });
    }


    public class ServerConnection extends AsyncTask<String, String, String> implements Constant {
        ResultListener listener;
        private String Method = "GET";
        private List<NameValuePair> params = new ArrayList<NameValuePair>();

        private Context context;
        private ConnectionDetector cd;

        // public static Drawable drawable;
        public ServerConnection(Context context, ResultListener r) {
            this.context = context;
            this.listener = r;
            cd = new ConnectionDetector(context);
            this.execute();
        }

        public boolean isConnection() {
            return cd.isConnectingToInternet();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... arg0) {
            if (!isConnection()) {
                cancel(true);
                return "Sorry!connection lost,try again or later";
            }
            ApiResponse air = new ApiResponse();
            System.out.println("working hre" + "hi");
            String json;

            try {
                json = air.makeHttpRequest(URL, getMethod(), getParams());
            } catch (Exception e) {
                json = e.getMessage();
                cancel(true);
                return json;
            }

            return json;
        }

        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        @Override
        protected void onCancelled(String result) {
            listener.connectionLost(result);
            rl.connectionLost("Sorry!connection lost,try again or later");
            super.onCancelled(result);
        }

        @Override
        protected void onPostExecute(String result) {
            System.out.println("onpost" + result);
            listener.result(result);
            listener.loader(true);
            super.onPostExecute(result);
        }

        public String getMethod() {
            return Method;
        }

        public void setMethod(String method) {
            Method = method;
        }

        public List<NameValuePair> getParams() {
            return params;
        }

        public void setParams(List<NameValuePair> params) {
            this.params = params;
        }
    }         

Example

Mike
  • 4,550
  • 4
  • 33
  • 47
AndroidLad
  • 687
  • 7
  • 14
0

Call the method setting your text in the postExecute inside your AsyncTask or set the text directly on your postExecute method.

And wrap the line with setText() inside runOnUIThread (otherwise you will get an exception saying that the view can be accessed only by the thread that created it, since you are setting the text from async task).

Setting the text would be something like this

    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            ((TextView) findViewById(R.id.txtFieldName)).setText("your text");
        }
    });

That way you can quit worrying about checking if the async task is finished. But avoid doing complex ui operations like this. Since this is just setting the text on TextView, it should be allright.

Viral Patel
  • 32,418
  • 18
  • 82
  • 110
  • I'm sorry, it sounds like what i need, but where i must paste it? In activity/settext/asynctask? – Masafi Dec 19 '15 at 16:20
  • the line where you are setting the text should be replaced by the given snippet. Just remove the line inside the run block and paste your set text line of code. – Viral Patel Dec 19 '15 at 16:21
  • also, like i said, set the text directly as above in postExecute. – Viral Patel Dec 19 '15 at 16:23
  • I have an error `Cannot resolve getActivity()` in activity and in postExecute – Masafi Dec 19 '15 at 16:27
  • you can pass the activity context as a parameter to the AsyncTask class constructor and use the context instead of getActivity() – Viral Patel Dec 19 '15 at 16:41
  • How to right write it? `context.getActivity()...` and `context.runOnUiThread...` not seems to be working – Masafi Dec 19 '15 at 16:48
  • where did you put it? can you share the code here? inside the postExecute in your AsyncTask or somewhere in the main activity as a method? Also try getApplicationContext() – Viral Patel Dec 19 '15 at 16:51
  • that's correct. is this class for AsyncTask inside your activity class? if not, take this class inside the activity class and getActivity() will work just fine. – Viral Patel Dec 19 '15 at 17:04
  • That's the problem. AsyncTask is inside anouther class. But i think i can replace it to activity, thanks – Masafi Dec 19 '15 at 17:07