Read text file from web - android

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.

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.

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");

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.

Related

TextView real time update AsyncTask

I'm making an android application that downloads some text from a web page and puts it in a String, then it prints the string in a TextView. But the content of the web page can change every seconds, so i want TextView to update in real-time, showing the new String every seconds. To download text from the webpage and set TextView's text I used AsyncTask, and i called the execute() in onCreate() method, in main Activity. I don't know how update it, without make application crashed.
Sorry for bad English, that's my MainActivity:
package com.example.pack;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity
{
TextView textView;
URL url;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url = null;
try
{
url = new URL("myURL");
}
catch (MalformedURLException e) {}
new VariabileLikeTask(textView).execute(url);
}
}
And that's my aSyncTask:
package com.example.pack;
import android.os.AsyncTask;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class VariabileLikeTask extends AsyncTask<URL, Void, CharSequence>
{
TextView textView;
public VariabileLikeTask(TextView textView)
{
this.textView = textView;
}
#Override
protected String doInBackground(URL... urls)
{
URL url = urls[0];
InputStream in = null;
int risposta = -1;
String text = "";
try
{
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("No connection");
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
risposta = httpConn.getResponseCode();
if (risposta == HttpURLConnection.HTTP_OK)
in = httpConn.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
text = bf.readLine();
in.close();
bf.close();
}
catch (Exception ex) {}
return text;
}
#Override
protected void onPostExecute(CharSequence text)
{
textView.setText(text);
}
}
Sorry if the format code is wrong, this is my first thread.
Isn't it a bad idea to run the AsyncTask frequently? This will make the app heavier in network operations.
If you mean the word real-time push notification or socket connection would be the best match. If you can't use a push notification because you are trying to fetch data from a Web page consider using a service class. Then simply make a timer task and run the AsyncTask after a small interval of time.
Here a simple demo of running the task after an interval of time,
private int m_interval = 5000; // 5 seconds by default, can be changed later
private Handle m_handler;
#Override
protected void onCreate(Bundle bundle)
{
...
m_handler = new Handler();
}
Runnable m_statusChecker = new Runnable()
{
#Override
public void run() {
//this function can change value of m_interval.
new VariabileLikeTask(textView).execute(url);
m_handler.postDelayed(m_statusChecker, m_interval);
}
}
void startRepeatingTask()
{
m_statusChecker.run();
}
void stopRepeatingTask()
{
m_handler.removeCallback(m_statusChecker);
}
In this post the user try to show dialog from AsyncTask, but the code it's the same to change txtBox in runtime, watch it!
Tell me if I helped you and good programming!

How do I get the text from a textfile into a String?

I'm trying to get it so my app can read the words from my textfile separated by a carriage enter and spit them back out from a String array. My app starts up then just gives me a blank page which is pretty frustrating. Here is my code:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.Vector;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView helloTxt= (TextView)findViewById(R.id.hellotxt);
ArrayList<String> list = new ArrayList<String>();
try {
InputStream is = getResources().openRawResource(R.raw.test);
if (is != null) {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader buffythevampireslayer = new BufferedReader(isr);
String line;
do {
line = buffythevampireslayer.readLine();
list.add(line);
} while (line != null);
}
is.close();
} catch (Exception ex) {
}
String[] wordsArray=new String[list.size()];
list.toArray(wordsArray);
Thread timer=new Thread(); {
for (int c=0;c<list.size();c++){
helloTxt.setText(wordsArray[c]);
System.out.println("TEXTSET");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
timer.start();
}
}
I'd really appreciate it if anyone could help, thanks so much!!!
EDIT::::
After getting some help in this post, I now have the working app! Thanks so much! Here is the new code:
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.Vector;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;
import android.content.res.AssetManager;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ReadAndUpdateTextTask readAndUpdateTextTask = new ReadAndUpdateTextTask();
readAndUpdateTextTask.execute();
}
class ReadAndUpdateTextTask extends AsyncTask<Void, String, String> {
public String currentString = "";
String line="";
InputStream isr;
#Override
protected void onPreExecute() {
isr = getResources().openRawResource(R.raw.test);
}
#Override
protected String doInBackground(Void... params) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(isr));
while ((line = reader.readLine())!= null) {
currentString += line + "\n";
publishProgress(currentString);
// I don't think you really need this but you want a sleep for 5000 ms
SystemClock.sleep(5000);
}
isr.close();
} catch (Exception ex) {
}
return currentString;
}
#Override
protected void onProgressUpdate(String... currentString) {
TextView helloTxt= (TextView)findViewById(R.id.hellotxt);
helloTxt.setText(currentString[0]);
}
#Override
protected void onPostExecute(String result) {
TextView helloTxt= (TextView)findViewById(R.id.hellotxt);
helloTxt.setText(result);
}
}
}
I don't know if this will solve anything, but you can try declaring your List as shown in Oracle's documentation. I will look further in a bit.
List<String> list = new ArrayList<String>();
if it's not a typo, your problem is here:
String[] wordsArray=new String[list.size()];
list.toArray(wordsArray);
it should be:
String[] wordsArray = list.toArray( new String[0] );
otherwise the array is filled with nulls
First, you need to store your text file in the assets folder
then you need to call the AssetManager to get the assets in your assets folder
AssetManager assetManager = getAssets();
InputStream inputStream = null;
surround these statements with a try block, in case the file is not found in the stated path
inputStream = assetManager.open("texts/sample.txt"); // path is relative to the assets folder
ByteArrayOutputStream bytesOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[4096];
int length = 0;
read the the bytes and write them in an output stream
while((length = inputStream.read(bytes)) > 0)
bytesOutputStream.write(bytes,0,length);
create a new String, use the constructor with the byteOutputStream
encode it with UTF8(assuming there wont be any chinese, japanese, etc characters)
See this for more details about UTF Details
String yourString = new String(bytesOutputStream.toByteArray(), "UTF8");
Java String class has a method "split", which takes a regex as a parameter
it splits the string and stores it into a single element in an array everytime it encounters a new line
in your case, use '\n' which stands for new line
String[] yourStringArray = yourString.split("\n");
Surround everything with a try-catch clause (IOException), which is thrown in case file is not found
you can now use yourStringArray as
textView.setText(yourStringArray[index]);
You got a blank screen because you have a sleep at your main UI thread. Do reading the file in an AsyncTask and publish its process.
Your onCreate method should look like this:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ReadAndUpdateTextTask readAndUpdateTextTask = new ReadAndUpdateTextTask();
readAndUpdateTextTask.execute();
}
class ReadAndUpdateTextTask extends AsyncTask<Void, String, String> {
InputStream isr;
#Override
protected void onPreExecute() {
isr = getResources().openRawResource(R.raw.test);
}
#Override
protected String doInBackground(Void... params) {
try {
String currentString = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(isr));
while ((line = reader.readLine())!= null) {
currentString += line + "\n";
publishProgress(currentString);
// I don't think you really need this but you want a sleep for 5000 ms
SystemClock.sleep(5000);
}
isr.close();
} catch (Exception ex) {
}
return currentString;
}
#Override
protected void onProgressUpdate(String... currentString) {
TextView helloTxt= (TextView)findViewById(R.id.hellotxt);
helloTxt.setText(currentString[0]);
}
#Override
protected void onPostExecute(String result) {
TextView helloTxt= (TextView)findViewById(R.id.hellotxt);
helloTxt.setText(result);
}
}
}

Display ListView when button Click

I'm new to android and I hope someone could help me here. I have an activity Faculty and a button.
This is my XML layout browse_faculty:
<Button
android:onClick="searchFSTEHandler"
android:id="#+id/bFSTE"
android:layout_width="220dp"
android:layout_height="80dp"
android:layout_alignLeft="#+id/bFBE"
android:layout_below="#+id/bFBE"
android:layout_marginTop="20dp"
android:text="#string/fste" />
and this is my Faculty Activity which displays the buttons:
I use Intent to view ListView
public class Faculty extends Activity{
#Override
protected void onCreate(Bundle BrowseFaculty) {
// TODO Auto-generated method stub
super.onCreate(BrowseFaculty);
setContentView(R.layout.browse_faculty);
}
//on the XML,this is the "searchFSTEHandler" i want to use to show ListView
public void searchFSTEHandler(View target){
Intent courseList = new Intent(this, HttpActivity.class);
startActivity(courseList);
}
}
and below is the "HttpActivity" class is the class that displays my ListView. This class read a php file which gets data from a MySQL server and converts to JSON data then parses it into a array list.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ListActivity;
import android.widget.ArrayAdapter;
public class HttpActivity extends ListActivity {
public String f1 = "FSTE";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.faculty_course);
new getHttp().execute();
getHttp test =new getHttp();
String strJsonData = test.doInBackground(f1);
// Convert String JSON data to Java class
ArrayList<Courses> arrayCourse= test.parseJsonData(strJsonData);
//Create an ArrayAdapter which shows the ArrayList data
this.setListAdapter(new ArrayAdapter<Courses>(this,android.R.layout.simple_list_item_1,arrayCourse));
}
private class getHttp extends AsyncTask<String, Void, String> {
public getHttp() {
}
#Override
protected String doInBackground(String... faculty) {
InputStream is = null;
try {
URL url = new URL("http://10.0.2.2/sqlWebService.php?faculty=FSTE");
URLConnection con = url.openConnection();
con.setConnectTimeout(10000);
con.setReadTimeout(10000);
is = con.getInputStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
String str;
while ((str = br.readLine()) != null) {
sb.append(str);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
return "";
} finally {
try {
if (is != null)
is.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
//------------------------------------------------------
private ArrayList<Courses> parseJsonData(String strJson) {
ArrayList<Courses> Course = new ArrayList<Courses>();
try {
// Generate JSONArray object by JSON String data
JSONArray arr = new JSONArray(strJson);
//from the JSONArray, get one element (row) of JSONData
for (int i = 0; i < arr.length(); i++) {
//Get JSON Object which is one element of the array
JSONObject ob = arr.getJSONObject(i);
Courses exam = new Courses();
//get the value by key, and set to exam class
exam.setCode(ob.optString("code"));
//save exam class to exam array list
Course.add(exam);
}
} catch (JSONException e) {
e.printStackTrace();
}
return Course;
}
}
}
The application crashes as soon as I click on the button and gives a error:
"android.os.NetworkOnMainThreadException"
Help Please !
The problem that you are having is network operation like what you are trying to do cannot and should not be performed on the main UI thread. Doing so will lead to an ANR (Android Not Responding), which is exactly the kind of error you are getting just now. What you want to do is move your code to a separate thread or to an AsyncTask that will perform this action in the background on a different thread using the doInBackground() method which does not have access to your views on the main UI thread. For example,
private class ExampleOperation extends AsyncTask<String, Void, String> {
public ExampleOperation() { //ctor }
#Override
protected void onPreExecute() {
//things that you want to initialize and maybe show dialog to user.
}
#Override
protected String doInBackground(String... params) {
//this is where you perform that network related operation.
}
#Override
protected void onPostExecute(String result) {
//this is where get the results from the network related task.
}
#Override
protected void onProgressUpdate(Void... values) {
//you can update your progressbar if any; otherwise omit method.
}
}
Then all you have to do is call the AsyncTask where ever you want to use it: new ExampleOperation().execute();
You can't make HTTP calls in the main thread, they take too long and would make the UI unresponsive. You need to do it in an AsyncTask.

Android AsyncTask without direct access to UI

I am new to Android. I have an AsyncTask that is downloading the content of a URL.
I didn't want the AsyncTask to manipulate the UI directly and want it to have it as a reusable peice of code so I have put it in a file of its own and it returns a string.
The problem is that the the return happens before the AsyncTask is finished (even though I am using the .get() of the .excecute()), so I get nothing back.
Here is waht I have at the moment:
package com.example.mypackage;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import android.os.AsyncTask;
public class URLContent {
private String content = "default value";
public String getContent(String URL){
try {
new getAsyncContent().execute(URL).get();
} catch (InterruptedException e) {
content = e.getMessage();
} catch (ExecutionException e) {
content = e.getMessage();
}
return content;
}
private class getAsyncContent extends AsyncTask<String, Integer, String>
{
#Override
protected void onPostExecute(String result) {
content = result;
}
#Override
protected String doInBackground(String... urls) {
try{
return URLResponse(urls[0]);
} catch (Exception e){
return e.getMessage();
}
}
}
private String IStoString(InputStream stream) throws IOException, UnsupportedEncodingException {
try {
return new java.util.Scanner(stream, "UTF-8").useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
return "";
}
}
private String URLResponse(String URLToget) throws IOException {
InputStream is = null;
try {
URL url = new URL(URLToget);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = IStoString(is);
return contentAsString;
} finally {
if (is != null) {
is.close();
}
}
}
}
What would be the best way to solve that so that my main thread somehow gets back the results?
I have come accross some articles mentioning events and callbacks. Is that the best way..?
Don't do get(). Simply have whatever logic deals with result of your URL execution right inside doInBackground method. From which you don't have to return anything. In your particular case the problem is that get() is executed right away before the result is delivered
This is asynchronous execution and you can't apply linear logic to it
Thanks for all your help. I will try the solution for extending the asyncTask class by Alex, sounds like a clean solution.
I managed to do what I was trying to by using an interface in the class with the AsyncTask and adding an event listener on the main class.
So my class that gets the content now looks like this:
package com.example.test;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.AsyncTask;
public class URLContent {
public void getContent(String URL){
new getAsyncContent().execute(URL);
}
public interface OnContentDownloadedListener{
public abstract void onContentDownloaded(String content);
}
private OnContentDownloadedListener contentDownloadedListener = null;
public void setOnContentDownloadedListener(OnContentDownloadedListener content){
contentDownloadedListener = content;
}
private class getAsyncContent extends AsyncTask<String, Integer, String>
{
#Override
protected void onPostExecute(String result) {
contentDownloadedListener.onContentDownloaded(result);
}
#Override
protected String doInBackground(String... urls) {
try{
return URLResponse(urls[0]);
} catch (Exception e){
return e.getMessage();
}
}
}
private String IStoString(InputStream stream) throws IOException, UnsupportedEncodingException {
try {
return new java.util.Scanner(stream, "UTF-8").useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
return "";
}
}
private String URLResponse(String URLToget) throws IOException {
InputStream is = null;
try {
URL url = new URL(URLToget);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = IStoString(is);
return contentAsString;
} finally {
if (is != null) {
is.close();
}
}
}
}
And then in my main class I just have an event listener that handles the update of the UI
urlContent.setOnContentDownloadedListener(new URLContent.OnContentDownloadedListener(){
public void onContentDownloaded(String content){
//update UI or do something with the data
}
Updating UI with the results of AsyncTask is the main purpose of onPostExecute(). To keep the implementation and the way it's used in UI separate, your Activity can extend your getAsyncContent class and override the onPostExecute() method. This method will be executed on UI thread.
If You do not need UI updates from Your asynchronous task, just create a simple thread to do the things. When complete, just send a broadcast.
new Thread(new Runnable() {
#Override
public void run() {
// Do the download here...
....
//
sendBroadcast(some_intent);
}).start();

AsyncTask onPreExecute not being called

For some reason the onPreExecute isn't being called. Code:
protected void onPreExcecute() {
hook.createDialog(ticker);
}
Entire class:
package com.evandarwin.finance;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
public class GetTicker extends AsyncTask<String, Integer, String>{
private Context ctx;
private String ticker;
private SimpleFinanceActivity hook;
public GetTicker(Context ctx, String ticker, SimpleFinanceActivity hook) {
this.ctx = ctx;
this.ticker = ticker.toUpperCase();
this.hook = hook;
}
protected void onPreExcecute() {
hook.createDialog(ticker);
}
#SuppressWarnings("unused")
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL("http://finance.yahoo.com/d/quotes.csv?s="+ticker+"&f=a");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream is = urlConnection.getInputStream();
StringBuffer str = new StringBuffer();
int bufferLength = 0; //used to store a temporary size of the buffer
byte[] stream = new byte[1024];
while ( (bufferLength = is.read(stream)) > 0 ) {
str.append(stream);
}
return str.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
hook.destroyDialog();
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
}
This is giving me a NullPointerException, I know I've had this problem before but I don't remember what I did to fix it. Please help! :P
The reason the #Override is causing a problem in Eclipse (and the reason the method isn't being called) is that you have made a typing error.
You are calling it onPreExcecute (note the 'c' after the 'x' shouldn't be there). Correct it to be onPreExecute and use #Override for that.

Categories

Resources