1

I have read txt file from URL but cannot use read text from URL to string in main thread. I have the following code.

How can i get string read from AsyncTask in main thread?

  package np.info.mukesh.utdlive;

/**
 * Created by Mukesh on 4/30/2017.
 */

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.thin.downloadmanager.util.Log;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Calendar;

public class LoadActivity extends AppCompatActivity {
    private Tracker mTracker;


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

        new GetMethodDemo().execute("http://m.live.mukesh.info.np/link.txt");

      //Toast data read from url
        Toast.makeText(this,server_response(), Toast.LENGTH_LONG).show();



    }



    public class GetMethodDemo extends AsyncTask<String , Void ,String> {
        String server_response;

        @Override
        protected String doInBackground(String... strings) {

            URL url;
            HttpURLConnection urlConnection = null;

            try {
                url = new URL(strings[0]);
                urlConnection = (HttpURLConnection) url.openConnection();

                int responseCode = urlConnection.getResponseCode();

                if(responseCode == HttpURLConnection.HTTP_OK){
                    server_response = readStream(urlConnection.getInputStream());
                    Log.v("CatalogClient", server_response);
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);


            TextView tv = (TextView) findViewById(R.id.updateNotice);
            tv.setText(server_response);

        }
    }


// Converting InputStream to String

    private String readStream(InputStream in) {
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return response.toString();
    }



}

I have been searching solution for some days but no luck. I am learning android from stackoverflow and google and some blog post. So, I am not much experienced. Thank you!

United Boy
  • 21
  • 1
  • 3
  • 2
    "but close when it is running in mobile" -- [use LogCat](https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this) to examine the Java stack trace associated with your crash. You will find that you are getting [a `NetworkOnMainThreadException`](http://stackoverflow.com/questions/6343166/how-to-fix-android-os-networkonmainthreadexception). "I am learning android from stackoverflow and google and some blog post" -- I recommend that you read a book, take a course, or otherwise learn Android app development in a more organized fashion. – CommonsWare Apr 29 '17 at 16:34
  • And the solution involves, running the above code in a background thread. You can take this opportunity to learn about AsyncTask and other threading APIs in Android. – Manish Kumar Sharma Apr 29 '17 at 16:37
  • I am learning about AsyncTask now but getting lots of error! :( @pulp_fiction virewing http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html to know more, but confused lot – United Boy Apr 29 '17 at 16:40
  • You should probably use Jsoup. – AlphaQ Apr 29 '17 at 17:31
  • I think it can be done using AsyncTask but i am having difficulty. – United Boy Apr 29 '17 at 17:36
  • Define `cannot use read text` – EpicPandaForce Apr 30 '17 at 09:26
  • Can anyone help me to return result from AsyncTask to main thread as some activities cannot run on onPostExecute() – United Boy Apr 30 '17 at 10:28

0 Answers0