casaoui
casaoui

Reputation: 151

Read text file from web

I recover my text file distant, my text contains number one "1". I tried to convert my text "1"(char)to int, but it is giving error. I used method Integer.parseInt(String)

this is my code: MainActivity.java

package mypackage;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

PackageInfo pinfo;
String contentFichier;
TextView txt;

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

    recoverContentTextFile();

    txt = (TextView) findViewById(R.id.txt);

    try {
        pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
    } catch (NameNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    //Here error
    int i = Integer.parseInt(contentFichier);


}


public void recoverContentTextFile() {
    new Thread() {
        @Override
        public void run() {
            String path ="my_url_text_file";
            URL u = null;
            try {
                u = new URL(path);
                HttpURLConnection c = (HttpURLConnection) u.openConnection();
                c.setRequestMethod("GET");
                c.connect();
                InputStream in = c.getInputStream();
                final ByteArrayOutputStream bo = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                in.read(buffer); // Read from Buffer.
                bo.write(buffer); // Write Into Buffer.

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        contentFichier = bo.toString();
                        try {
                            bo.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });

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

        }
    }.start();
}

}

thank you in advance.

Upvotes: 0

Views: 68

Answers (3)

Squeazer
Squeazer

Reputation: 1254

The problem here is probably that you are trying to convert the String before the thread has finished. And also, Android has a better way than Threads to handle most (simple) background tasks, the AsyncTask. You could do something like this:

public class MainActivity extends Activity {

    PackageInfo pinfo;
    String contentFichier;
    TextView txt;

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

        //Setup your activity here

        new ContentFetcher().execute("http://......");

    }

    private class ContentFetcher extends AsyncTask<String, Void, String>{

        @Override
        protected String doInBackground(String... params) {
            String stringResponse = null;

            try{
                HttpResponse httpResponse = new DefaultHttpClient().execute(new HttpGet(params[0]));
                stringResponse = EntityUtils.toString(httpResponse.getEntity());
            } catch (IOException ignored) {
            }

            return stringResponse;
        }


        @Override
        protected void onPostExecute(String s) {
            //DO something with the response here - maybe test if the s variable is indeed an integer
            int i = Integer.parseInt(s);

        }
    }
}

To execute the task run:

new ContentFetcher().execute("http://whatever.com/mytext.txt");

Upvotes: 1

Audrius Meškauskas
Audrius Meškauskas

Reputation: 21738

Add log statement to show the value of the contentFichier:

Log.i("contentFichier", "["+contentFichier+"]"

You will see which content is being parsed. Maybe there is a whitespace on the beginning or the end. Also the server may be returning wrong value or empty string.

Upvotes: 0

Aldo Borrero
Aldo Borrero

Reputation: 547

First of all it's not a good idea at all to use threads in the way you're implementing in your method recoverContextTextFile. What happens if the user rotate the device and the petition takes 8 minutes to complete? You have created a memory leak!

The second thing as you have created a thread the variable contentFichier will be sometimes null (because recoverContextTextFile does create a thread) and calling the Integer.parseInt(contentFichier);will raise an Exception.

For this case I think that it's better to use an AsyncTask (which I highly dislike and taking care of not leaking the activity when rotation occurs), do the petition in the onBackground method and in the method onPostExecute call the Integer.parseInt(contentFichier);.

I recommend reading this tutorial by Lars Vogel as it explains a lot about background processing.

Upvotes: 1

Related Questions