I am getting an issue to run the below code.The code gives no error but not giving the expected output. Any suggestions or solution will be highly appreciated.Thanx in advance.
Here’s my xml file:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/readWebpage"
android:text="Load Webpage"
android:onClick="readWebpage"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView1"
android:text="Example Text"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
and here’s my java file:-
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class LoadWebpageAsyncTask extends Activity {
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
tv = (TextView)findViewById(R.id.textView1);
}
public class DownloadWebpageTask extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... urls) {
// TODO Auto-generated method stub
String response = "";
for(String url:urls){
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try{
HttpResponse execute = client.execute(httpGet);
BufferedReader br = new BufferedReader(new
InputStreamReader(execute.getEntity().getContent()));
String s="";
while((s = br.readLine()) != null){
response += s;
}
}
catch(Exception e){
e.printStackTrace();
}
}
return response;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
tv.setText(result);
}
}
public void readWebpage(View view){
DownloadWebpageTask task = new DownloadWebpageTask();
task.execute(new String[]{"http://www.google.com"});
}
}
It looks like you are missing
setContentView(R.layout.<...>);(tvwill be null) in youronCreate()method and never run your task (so you don’t getNullPointerExceptionwhen setting text ontv):edit riha’s answer is also true, since the way you use it is
for (String[] url:urls), notfor (String url:urls)