10-23 00:41:00.705: E/AndroidRuntime(3622): FATAL EXCEPTION: AsyncTask #1
10-23 00:41:00.705: E/AndroidRuntime(3622): java.lang.RuntimeException: An error occured while executing doInBackground()
10-23 00:41:00.705: E/AndroidRuntime(3622): at android.os.AsyncTask$3.done(AsyncTask.java:299)
10-23 00:41:00.705: E/AndroidRuntime(3622): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
10-23 00:41:00.705: E/AndroidRuntime(3622): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
10-23 00:41:00.705: E/AndroidRuntime(3622): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
10-23 00:41:00.705: E/AndroidRuntime(3622): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
10-23 00:41:00.705: E/AndroidRuntime(3622): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
10-23 00:41:00.705: E/AndroidRuntime(3622): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
10-23 00:41:00.705: E/AndroidRuntime(3622): at java.lang.Thread.run(Thread.java:856)
10-23 00:41:00.705: E/AndroidRuntime(3622): Caused by: java.lang.IllegalStateException: Content has been consumed
10-23 00:41:00.705: E/AndroidRuntime(3622): at org.apache.http.entity.BasicHttpEntity.getContent(BasicHttpEntity.java:84)
10-23 00:41:00.705: E/AndroidRuntime(3622): at org.apache.http.entity.BasicHttpEntity.writeTo(BasicHttpEntity.java:126)
10-23 00:41:00.705: E/AndroidRuntime(3622): at org.apache.http.entity.HttpEntityWrapper.writeTo(HttpEntityWrapper.java:101)
10-23 00:41:00.705: E/AndroidRuntime(3622): at org.apache.http.conn.BasicManagedEntity.writeTo(BasicManagedEntity.java:126)
10-23 00:41:00.705: E/AndroidRuntime(3622): at com.firstgroup.webservice.RequestTask.doInBackground(RequestTask.java:51)
10-23 00:41:00.705: E/AndroidRuntime(3622): at com.firstgroup.webservice.RequestTask.doInBackground(RequestTask.java:1)
10-23 00:41:00.705: E/AndroidRuntime(3622): at android.os.AsyncTask$2.call(AsyncTask.java:287)
10-23 00:41:00.705: E/AndroidRuntime(3622): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
10-23 00:41:00.705: E/AndroidRuntime(3622): ... 4 more
Hi
I am calling my web service using gson library I am getting exception.I don't know why it is occur .could you please tell me removing this error
I will give you steps what I did ..
1 )Main activity
public class Appliacationload extends Activity implements WebserviceCallBack{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appliacationload);
/*WebserviceMethod callDepartudeDashboard=new WebserviceMethod();
callDepartudeDashboard.setObserver(this);
callDepartudeDashboard.getwebService(ConstantVariable.dashboardWebServiceURL+"a/"+"arrival"+"?crsCode=hnh");*/
RequestTask callWebService=new RequestTask();
callWebService.setObserver(this);
callWebService.execute(ConstantVariable.dashboardWebServiceURL+"a/"+"arrival"+"?crsCode=vic");
}
#Override
public void getWebserviceResponse(String response) {
// TODO Auto-generated method stub
Log.d("response", response);
}
}
and I have one holder and RequestTask class to call webservice and return call back .
public class RequestTask extends AsyncTask<String, String, String>{
private WebserviceCallBack callBack;
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressDialog= new ProgressDialog((Context) callBack);
super.onPreExecute();
progressDialog.setTitle("Please Wait...");
progressDialog.setMessage("Webservice Call...");
progressDialog.setCancelable(true);
progressDialog.show();
}
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
Reader reader = new InputStreamReader(response.getEntity().getContent());
Gson gson = new Gson();
Holder response1 = gson.fromJson(reader, Holder.class);
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..\
progressDialog.hide();
} catch (IOException e) {
//TODO Handle problems..
progressDialog.hide();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do anything with response..
if(callBack!=null){
callBack.getWebserviceResponse(result);
}
progressDialog.hide();
}
public void setObserver(WebserviceCallBack callback){
callBack=callback;
}
}
Holder class;
public class Holder {
List<deparaturedaseboarddto> data;
}
New Update when I change my request task like that ..
public class RequestTask extends AsyncTask<String, String, InputStream>{
private WebserviceCallBack callBack;
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressDialog= new ProgressDialog((Context) callBack);
super.onPreExecute();
progressDialog.setTitle("Please Wait...");
progressDialog.setMessage("Webservice Call...");
progressDialog.setCancelable(true);
progressDialog.show();
}
#Override
protected InputStream doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
/*Reader reader = new InputStreamReader(response.getEntity().getContent());
Gson gson = new Gson();
Holder response1 = gson.fromJson(reader, Holder.class);
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();*/
return response.getEntity().getContent();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..\
progressDialog.hide();
} catch (IOException e) {
//TODO Handle problems..
progressDialog.hide();
}
return null;
}
#Override
protected void onPostExecute(InputStream result) {
super.onPostExecute(result);
//Do anything with response..
if(callBack!=null){
callBack.getWebserviceResponse(result);
}
progressDialog.dismiss();
progressDialog=null;
}
public void setObserver(WebserviceCallBack callback){
callBack=callback;
}
}
and call back like that
public interface WebserviceCallBack {
public void getWebserviceResponse(InputStream result);
}
and main activity like that
public class Appliacationload extends Activity implements WebserviceCallBack{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appliacationload);
/*WebserviceMethod callDepartudeDashboard=new WebserviceMethod();
callDepartudeDashboard.setObserver(this);
callDepartudeDashboard.getwebService(ConstantVariable.dashboardWebServiceURL+"a/"+"arrival"+"?crsCode=hnh");*/
RequestTask callWebService=new RequestTask();
callWebService.setObserver(this);
callWebService.execute(ConstantVariable.dashboardWebServiceURL+"a/"+"arrival"+"?crsCode=vic");
}
#Override
public void getWebserviceResponse(InputStream result) {
// TODO Auto-generated method stub
Reader reader = new InputStreamReader(result);
Gson gson = new Gson();
Holder response1 = gson.fromJson(reader, Holder.class);
Log.d("-----", "naveen");
}
I got this exception why ..?I am sending the input stream on call back and make here in main activity ..
exception:
10-23 03:07:33.956: E/AndroidRuntime(22412): FATAL EXCEPTION: main
10-23 03:07:33.956: E/AndroidRuntime(22412): android.os.NetworkOnMainThreadException
10-23 03:07:33.956: E/AndroidRuntime(22412): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
10-23 03:07:33.956: E/AndroidRuntime(22412): at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:163)
10-23 03:07:33.956: E/AndroidRuntime(22412): at libcore.io.IoBridge.recvfrom(IoBridge.java:513)
10-23 03:07:33.956: E/AndroidRuntime(22412): at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
10-23 03:07:33.956: E/AndroidRuntime(22412): at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
10-23 03:07:33.956: E/AndroidRuntime(22412): at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
10-23 03:07:33.956: E/AndroidRuntime(22412): at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)
10-23 03:07:33.956: E/AndroidRuntime(22412): at org.apache.http.impl.io.AbstractSessionInputBuffer.read(AbstractSessionInputBuffer.java:134)
10-23 03:07:33.956: E/AndroidRuntime(22412): at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:161)
10-23 03:07:33.956: E/AndroidRuntime(22412): at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:159)
10-23 03:07:33.956: E/AndroidRuntime(22412): at java.io.InputStreamReader.read(InputStreamReader.java:244)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.google.gson.stream.JsonReader.fillBuffer(JsonReader.java:1298)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.google.gson.stream.JsonReader.nextQuotedValue(JsonReader.java:1028)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.google.gson.stream.JsonReader.nextName(JsonReader.java:796)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:178)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:81)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:95)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:183)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.google.gson.Gson.fromJson(Gson.java:805)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.google.gson.Gson.fromJson(Gson.java:743)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.firstgroup.applicationload.Appliacationload.getWebserviceResponse(Appliacationload.java:48)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.firstgroup.webservice.RequestTask.onPostExecute(RequestTask.java:77)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.firstgroup.webservice.RequestTask.onPostExecute(RequestTask.java:1)
10-23 03:07:33.956: E/AndroidRuntime(22412): at android.os.AsyncTask.finish(AsyncTask.java:631)
10-23 03:07:33.956: E/AndroidRuntime(22412): at android.os.AsyncTask.access$600(AsyncTask.java:177)
10-23 03:07:33.956: E/AndroidRuntime(22412): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
10-23 03:07:33.956: E/AndroidRuntime(22412): at android.os.Handler.dispatchMessage(Handler.java:99)
10-23 03:07:33.956: E/AndroidRuntime(22412): at android.os.Looper.loop(Looper.java:137)
10-23 03:07:33.956: E/AndroidRuntime(22412): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-23 03:07:33.956: E/AndroidRuntime(22412): at java.lang.reflect.Method.invokeNative(Native Method)
10-23 03:07:33.956: E/AndroidRuntime(22412): at java.lang.reflect.Method.invoke(Method.java:511)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-23 03:07:33.956: E/AndroidRuntime(22412): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-23 03:07:33.956: E/AndroidRuntime(22412): at dalvik.system.NativeStart.main(Native Method)
The reason is you can only consume Content from Entity once.
You did it twice (maybe without you knowing it) in here
Reader reader = new InputStreamReader(response.getEntity().getContent());
and here
response.getEntity().writeTo(out);
I know this is sounds a little weird but actually the writeTo() function will get content from the entity to write to the OutputStream. You can see it in the documentation here
Another workaround you can use is turning it to string and let GSON handle it
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
responseString = EntityUtils.toString(response.getEntity()); // content will be consume only once
Gson gson = new Gson();
Holder response1 = gson.fromJson(responseString, Holder.class);
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..\
progressDialog.hide();
} catch (IOException e) {
//TODO Handle problems..
progressDialog.hide();
}
return responseString;
}
I hope my answer can help you!
Related
I want to download a 100MB file using streams:
I used an AsyncTask class to make download:
#Override
protected Void doInBackground(String... params) {
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
inputStream = connection.getInputStream();
outputStream = new FileOutputStream(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), params[1]));
byte[] data = new byte[104857600];
int length = inputStream.read(data);
outputStream.write(data, 0, length);
} catch (Exception e) {
Log.e(TAG, "Unable to download file with DownloadTask: " + e.getMessage());
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
connection.disconnect();
} catch (Exception e) {
Log.e(TAG, "Unable to cancel download file with DownloadTask: " + e.getMessage());
}
}
return null;
}
I'm sure I used the following permissions:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
But when I test my app, it crashes and I see in logcat Out of memory on a 104857616-byte allocation:
10-02 10:28:35.578 29630-2246/com.example.myapp E/dalvikvm-heap: Out of memory on a 104857616-byte allocation.
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at android.os.AsyncTask$3.done(AsyncTask.java:299)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:239)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.lang.Thread.run(Thread.java:856)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: Caused by: java.lang.OutOfMemoryError
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at com.example.myapp.DownloaderActivity$DownloadTask.doInBackground(DownloaderActivity.java:126)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at com.example.myapp.DownloaderActivity$DownloadTask.doInBackground(DownloaderActivity.java:107)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at android.os.AsyncTask$2.call(AsyncTask.java:287)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:234)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.lang.Thread.run(Thread.java:856)
Is there some way to download large files or accept 104857600 bytes (100MB)?
You have write data portion by portion as chunk. System don't provide huge memory at once for an operation.
Replace those lines:
byte[] data = new byte[104857600];
int length = inputStream.read(data);
outputStream.write(data, 0, length);
by:
byte [] buffer = new byte[1024];
int bytesRead = 0;
while((bytesRead =input.read(buffer)) != -1) {
outputStream .write(buffer, 0,
bytesRead);
}
I am trying to create an application that sends a file to a server. The application consists of one button that when clicked, will upload a file to a server. Here is the code that I have so far:
public class MainActivity extends Activity implements OnClickListener {
final String TAG = "sendButton";
final String TAG2 = "messageButton";
TextView messageText;
Button uploadButton;
int serverResponseCode = 0;
String result = null;
String url = "http://192.168.1.18";
File file = new File("example.txt");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// findViewById(R.id.button2).setOnClickListener(this);
//findViewById(R.id.button2).setOnClickListener(this);
setupsendMessage();
//setupmessageButton();
uploadButton = (Button)findViewById(R.id.button1);
messageText = (TextView)findViewById(R.id.button2);
}
private void setupsendMessage() {
// do something when the button is pressed
//
Button sendButton = (Button) findViewById(R.id.button1);
sendButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody = new FileBody(file);
builder.addPart("file", fileBody);
final HttpEntity yourEntity = builder.build();
post.setEntity(yourEntity);
HttpResponse response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
result = EntityUtils.toString(httpEntity);
Log.v("result", result);
}
catch(Exception e)
{
e.printStackTrace();}
Log.i(TAG, "File Sent to Server");
Toast.makeText(MainActivity.this, "File Sent to Server", Toast.LENGTH_LONG).show();
}
});
};
When I run the code the application everything appears fine, but when I press the button nothing happens and I get an error on the trace.
The error is as follows:
04-14 17:20:39.504: W/IInputConnectionWrapper(1693): showStatusIcon on inactive InputConnection
04-14 17:20:46.121: W/System.err(1693): java.net.SocketException: Permission denied
04-14 17:20:46.121: W/System.err(1693): at org.apache.harmony.luni.platform.OSNetworkSystem.socket(Native Method)
04-14 17:20:46.121: W/System.err(1693): at dalvik.system.BlockGuard$WrappedNetworkSystem.socket(BlockGuard.java:335)
04-14 17:20:46.121: W/System.err(1693): at org.apache.harmony.luni.net.PlainSocketImpl.create(PlainSocketImpl.java:216)
04-14 17:20:46.121: W/System.err(1693): at java.net.Socket.checkOpenAndCreate(Socket.java:802)
04-14 17:20:46.121: W/System.err(1693): at java.net.Socket.connect(Socket.java:948)
04-14 17:20:46.121: W/System.err(1693): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
04-14 17:20:46.121: W/System.err(1693): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:143)
04-14 17:20:46.121: W/System.err(1693): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
04-14 17:20:46.121: W/System.err(1693): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
04-14 17:20:46.121: W/System.err(1693): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
04-14 17:20:46.121: W/System.err(1693): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
04-14 17:20:46.121: W/System.err(1693): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
04-14 17:20:46.121: W/System.err(1693): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
04-14 17:20:46.121: W/System.err(1693): at school.project.application.MainActivity$1.onClick(MainActivity.java:117)
04-14 17:20:46.121: W/System.err(1693): at android.view.View.performClick(View.java:2485)
04-14 17:20:46.131: W/System.err(1693): at android.view.View$PerformClick.run(View.java:9081)
04-14 17:20:46.131: W/System.err(1693): at android.os.Handler.handleCallback(Handler.java:587)
04-14 17:20:46.131: W/System.err(1693): at android.os.Handler.dispatchMessage(Handler.java:92)
04-14 17:20:46.131: W/System.err(1693): at android.os.Looper.loop(Looper.java:130)
04-14 17:20:46.131: W/System.err(1693): at android.app.ActivityThread.main(ActivityThread.java:3696)
04-14 17:20:46.131: W/System.err(1693): at java.lang.reflect.Method.invokeNative(Native Method)
04-14 17:20:46.131: W/System.err(1693): at java.lang.reflect.Method.invoke(Method.java:507)
04-14 17:20:46.131: W/System.err(1693): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
04-14 17:20:46.131: W/System.err(1693): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
04-14 17:20:46.131: W/System.err(1693): at dalvik.system.NativeStart.main(Native Method)
04-14 17:20:46.131: I/sendButton(1693): File Sent to Server
You may need to enable Internet access in the project's manifest file:
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
You need to have permission to send data via internet, Add the following line to your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
I have a problem.
I want to know where did the android.os.NetworkOnMainThreadException and
java.lang.reflect.InvocationTargetException Exception come from !
Please, I'm new to Android and I need your help guys!
My LogCat:
12-19 13:00:27.049: E/AndroidRuntime(1170): FATAL EXCEPTION: main
12-19 13:00:27.049: E/AndroidRuntime(1170): java.lang.IllegalStateException: Could not execute method of the activity
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.view.View$1.onClick(View.java:3633)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.view.View.performClick(View.java:4240)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.view.View$PerformClick.run(View.java:17721)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.os.Handler.handleCallback(Handler.java:730)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.os.Handler.dispatchMessage(Handler.java:92)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.os.Looper.loop(Looper.java:137)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.lang.reflect.Method.invokeNative(Native Method)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.lang.reflect.Method.invoke(Method.java:525)
12-19 13:00:27.049: E/AndroidRuntime(1170): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-19 13:00:27.049: E/AndroidRuntime(1170): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-19 13:00:27.049: E/AndroidRuntime(1170): at dalvik.system.NativeStart.main(Native Method)
12-19 13:00:27.049: E/AndroidRuntime(1170): Caused by: java.lang.reflect.InvocationTargetException
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.lang.reflect.Method.invokeNative(Native Method)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.lang.reflect.Method.invoke(Method.java:525)
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.view.View$1.onClick(View.java:3628)
12-19 13:00:27.049: E/AndroidRuntime(1170): ... 11 more
12-19 13:00:27.049: E/AndroidRuntime(1170): Caused by: android.os.NetworkOnMainThreadException
12-19 13:00:27.049: E/AndroidRuntime(1170): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
12-19 13:00:27.049: E/AndroidRuntime(1170): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
12-19 13:00:27.049: E/AndroidRuntime(1170): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
12-19 13:00:27.049: E/AndroidRuntime(1170): at libcore.io.IoBridge.connect(IoBridge.java:112)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
12-19 13:00:27.049: E/AndroidRuntime(1170): at java.net.Socket.connect(Socket.java:842)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-19 13:00:27.049: E/AndroidRuntime(1170): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-19 13:00:27.049: E/AndroidRuntime(1170): at com.ensem.sehaty.MainActivity.recupererListMed(MainActivity.java:58)
12-19 13:00:27.049: E/AndroidRuntime(1170): ... 14 more
12-19 13:05:27.366: I/Process(1170): Sending signal. PID: 1170 SIG: 9
MainActivity.java
public class MainActivity extends Activity {
Button btnRecupListMed = null;
ListView listeMed = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRecupListMed = (Button) findViewById(R.id.btnListMed);
listeMed = (ListView) findViewById(R.id.listMed);
}
public void recupererListMed(View v){
BufferedReader br = null;
StringBuffer sb = new StringBuffer("");
try {
HttpClient client = new DefaultHttpClient();
HttpProtocolParams.setUseExpectContinue(client.getParams(), false);
HttpGet get = new HttpGet();
URI uri = new URI("http://105.153.20.252");
get.setURI(uri);
HttpResponse reponse = client.execute(get);
InputStream is = reponse.getEntity().getContent();
br = new BufferedReader(new InputStreamReader(is));
String str = br.readLine();
while(str != null){
sb.append(str);
sb.append("\n");
str = br.readLine();
}
} catch (URISyntaxException e) {
e.printStackTrace();
System.out.println("Erreur 1");
} catch (ClientProtocolException e) {
e.printStackTrace();
System.out.println("Erreur 2");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Erreur 3");
}
try {
//ArrayList<HashMap<String, String>> medecins = new ArrayList<HashMap<String, String>>();
JSONArray js = new JSONArray(sb.toString());
List<String> listM = new ArrayList<String>();
for(int i=0; i<js.length(); i++){
JSONObject jsObj = js.getJSONObject(i);
String nom = jsObj.getString("NOMMED");
listM.add(nom);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, R.id.listMed, listM);
listeMed.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
System.out.println("Erreur 4");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
activity_main.xml
<TextView
android:text="#string/lbl_sehaty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/btnListMed"
android:text="#string/lbl_btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:onClick="recupererListMed"
/>
<ListView
android:id="#+id/listMed"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginTop="60dp">
</ListView>
And my Manifest contains the following permission
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Thanks.
This error comes when you try to make a server call on UI thread.
You should create an AsyncTask and put your server call in it.
And on click of button call execute on the object of asynctask.
Ex:
public class ServiceTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
BufferedReader br = null;
StringBuffer sb = new StringBuffer("");
try {
HttpClient client = new DefaultHttpClient();
HttpProtocolParams.setUseExpectContinue(client.getParams(), false);
HttpGet get = new HttpGet();
URI uri = new URI("http://105.153.20.252");
get.setURI(uri);
HttpResponse reponse = client.execute(get);
InputStream is = reponse.getEntity().getContent();
br = new BufferedReader(new InputStreamReader(is));
String str = br.readLine();
while(str != null){
sb.append(str);
sb.append("\n");
str = br.readLine();
}
} catch (URISyntaxException e) {
e.printStackTrace();
System.out.println("Erreur 1");
} catch (ClientProtocolException e) {
e.printStackTrace();
System.out.println("Erreur 2");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Erreur 3");
}
return sb;
}
#Override
protected void onPostExecute(String result) {
try {
//ArrayList<HashMap<String, String>> medecins = new ArrayList<HashMap<String, String>>();
JSONArray js = new JSONArray(result.toString());
List<String> listM = new ArrayList<String>();
for(int i=0; i<js.length(); i++){
JSONObject jsObj = js.getJSONObject(i);
String nom = jsObj.getString("NOMMED");
listM.add(nom);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, R.id.listMed, listM);
listeMed.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
System.out.println("Erreur 4");
}
}
}
And inside your onClick event:
public void recupererListMed(View v){
new ServiceTask().execute();
}
This will execute doInBackground method on a different thread and once result is fetched onPostExecute is called on UI thread.
Sorry,this is my first time to put questions in this site
My Function: I set two Buttons to restore and save the information in the Spinner and EditText with the function Sharedpreferences.
I execute the program at the first time. The program will appear the error state,if I click the Button "restore" to restore the information in Spinner. But I haven't met the problem when I restore the information in EditText.
This is the code in Spinner
private Spinner.OnItemSelectedListener getfeet = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
feet_out = parent.getSelectedItemPosition() + 2;
select_f = feet.getSelectedItemPosition(); //save the position you choose
Toast.makeText(MainActivity.this,
"you chose " + parent.getSelectedItem().toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
};
private Spinner.OnItemSelectedListener getinch = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
inch_out = parent.getSelectedItemPosition();
select_i = inch.getSelectedItemPosition(); //save the position you choose
Toast.makeText(MainActivity.this,
"you chose " + parent.getSelectedItem().toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
};
This is the code which executes the function of save in Sharedpreferences
private void save_() {
settings = getSharedPreferences("DATA", 0);
settings.edit().putInt("DATA_FEET", select_f) //store the position in DATA_FEET and DATA_INCH
.putInt("DATA_INCH", select_i)
.putString("DATA_WEIGHT", weight.getText().toString()).commit();
Toast.makeText(MainActivity.this, R.string.done, Toast.LENGTH_SHORT) //save done
.show();
}
This is the code which executes the function of restore in Sharedpreferences
private void restore_() {
feet.setSelection(settings.getInt("DATA_FEET", select_f)); //restore the position
inch.setSelection(settings.getInt("DATA_INCH", select_i));
weight.setText(settings.getString("DATA_WEIGHT", "EMPTY"));
}
My problem is that I can't use the function of restore at the program executing at the first time. Is there any solution to solve the problem?? Because it is normal in EditText,but it is abnormal in Spinner. Thanks :))
This is the state. :))
10-23 23:14:11.677: D/TextLayoutCache(26370): Using debug level: 0 - Debug Enabled: 0
10-23 23:14:11.747: D/libEGL(26370): loaded /system/lib/egl/libGLES_android.so
10-23 23:14:11.797: D/libEGL(26370): loaded /system/lib/egl/libEGL_mali.so
10-23 23:14:11.827: D/libEGL(26370): loaded /system/lib/egl/libGLESv1_CM_mali.so
10-23 23:14:11.827: D/libEGL(26370): loaded /system/lib/egl/libGLESv2_mali.so
10-23 23:14:11.887: D/OpenGLRenderer(26370): Enabling debug mode 0
10-23 23:14:16.762: D/AndroidRuntime(26370): Shutting down VM
10-23 23:14:16.762: W/dalvikvm(26370): threadid=1: thread exiting with uncaught exception (group=0x40aaa210)
10-23 23:14:16.802: E/AndroidRuntime(26370): FATAL EXCEPTION: main
10-23 23:14:16.802: E/AndroidRuntime(26370): java.lang.NullPointerException
10-23 23:14:16.802: E/AndroidRuntime(26370): at com.example.bmi.MainActivity.restore_(MainActivity.java:44)
10-23 23:14:16.802: E/AndroidRuntime(26370): at com.example.bmi.MainActivity.access$1(MainActivity.java:43)
10-23 23:14:16.802: E/AndroidRuntime(26370): at com.example.bmi.MainActivity$2.onClick(MainActivity.java:99)
10-23 23:14:16.802: E/AndroidRuntime(26370): at android.view.View.performClick(View.java:3574)
10-23 23:14:16.802: E/AndroidRuntime(26370): at android.view.View$PerformClick.run(View.java:14293)
10-23 23:14:16.802: E/AndroidRuntime(26370): at android.os.Handler.handleCallback(Handler.java:605)
10-23 23:14:16.802: E/AndroidRuntime(26370): at android.os.Handler.dispatchMessage(Handler.java:92)
10-23 23:14:16.802: E/AndroidRuntime(26370): at android.os.Looper.loop(Looper.java:137)
10-23 23:14:16.802: E/AndroidRuntime(26370): at android.app.ActivityThread.main(ActivityThread.java:4448)
10-23 23:14:16.802: E/AndroidRuntime(26370): at java.lang.reflect.Method.invokeNative(Native Method)
10-23 23:14:16.802: E/AndroidRuntime(26370): at java.lang.reflect.Method.invoke(Method.java:511)
10-23 23:14:16.802: E/AndroidRuntime(26370): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
10-23 23:14:16.802: E/AndroidRuntime(26370): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
10-23 23:14:16.802: E/AndroidRuntime(26370): at dalvik.system.NativeStart.main(Native Method)
This is the method to call the restore_()
private OnClickListener reback_1 = new OnClickListener() {
public void onClick(View v) {
restore_();
}
};
After I replaced the select_f and select_i into 0, it appeared the problem
10-24 00:01:30.957: D/TextLayoutCache(28836): Using debug level: 0 - Debug Enabled: 0
10-24 00:01:31.017: D/libEGL(28836): loaded /system/lib/egl/libGLES_android.so
10-24 00:01:31.037: D/libEGL(28836): loaded /system/lib/egl/libEGL_mali.so
10-24 00:01:31.057: D/libEGL(28836): loaded /system/lib/egl/libGLESv1_CM_mali.so
10-24 00:01:31.057: D/libEGL(28836): loaded /system/lib/egl/libGLESv2_mali.so
10-24 00:01:31.087: D/OpenGLRenderer(28836): Enabling debug mode 0
10-24 00:01:36.262: D/AndroidRuntime(28836): Shutting down VM
10-24 00:01:36.262: W/dalvikvm(28836): threadid=1: thread exiting with uncaught exception (group=0x40aaa210)
10-24 00:01:36.282: E/AndroidRuntime(28836): FATAL EXCEPTION: main
10-24 00:01:36.282: E/AndroidRuntime(28836): java.lang.NullPointerException
10-24 00:01:36.282: E/AndroidRuntime(28836): at com.example.bmi.MainActivity.restore_(MainActivity.java:44)
10-24 00:01:36.282: E/AndroidRuntime(28836): at com.example.bmi.MainActivity.access$1(MainActivity.java:43)
10-24 00:01:36.282: E/AndroidRuntime(28836): at com.example.bmi.MainActivity$2.onClick(MainActivity.java:99)
10-24 00:01:36.282: E/AndroidRuntime(28836): at android.view.View.performClick(View.java:3574)
10-24 00:01:36.282: E/AndroidRuntime(28836): at android.view.View$PerformClick.run(View.java:14293)
10-24 00:01:36.282: E/AndroidRuntime(28836): at android.os.Handler.handleCallback(Handler.java:605)
10-24 00:01:36.282: E/AndroidRuntime(28836): at android.os.Handler.dispatchMessage(Handler.java:92)
10-24 00:01:36.282: E/AndroidRuntime(28836): at android.os.Looper.loop(Looper.java:137)
10-24 00:01:36.282: E/AndroidRuntime(28836): at android.app.ActivityThread.main(ActivityThread.java:4448)
10-24 00:01:36.282: E/AndroidRuntime(28836): at java.lang.reflect.Method.invokeNative(Native Method)
10-24 00:01:36.282: E/AndroidRuntime(28836): at java.lang.reflect.Method.invoke(Method.java:511)
10-24 00:01:36.282: E/AndroidRuntime(28836): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
10-24 00:01:36.282: E/AndroidRuntime(28836): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
10-24 00:01:36.282: E/AndroidRuntime(28836): at dalvik.system.NativeStart.main(Native Method)
10-24 00:01:37.803: I/Process(28836): Sending signal. PID: 28836 SIG: 9
You are using the SharedPrefs wrong.
feet.setSelection(settings.getInt("DATA_FEET", select_f));
when you try to fetch the integer-value from sharedPref, you get returned null! because i think that you misunderstand how it is done:
settings.getInt("myKey", defaultValue);
returns you the value for the key "myKey". if "myKey" has no value set, then it returns you the "defaultValue". In your case it returns the current value of "select_f". And as it looks, the value of select_f is null, when you run your application for the first time.
So you have to decide whether to initialize "select_f" before you retrieve the sharedPrefs or you enter another defaultValue here.
I was trying to read the HTML contents from a url. I tried with many samples and code examples from many sites, but it didn't work for me. When I run the code it leaves the default text in textview. I even tried with edittext as well. I have even added permission in the manifest file.
One of the codes I used is here: I have added the complete code here. I tried with all the code below with no success.
package com.adn;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
public class REEActivity extends Activity {
private static BufferedReader reader = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText ed = (EditText) findViewById(R.id.editText1);
try {
ed.append(getStringFromUrl("http://www.google.com"));
//getInputStreamFromUrl("").close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static InputStream getInputStreamFromUrl(String url){
InputStream contentStream = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
contentStream = response.getEntity().getContent();
} catch(Exception e){
e.printStackTrace();
}
System.out.println("Content stream is " + contentStream);
return contentStream;
}
public static String getStringFromUrl(String url) throws IOException{
reader = new BufferedReader(new InputStreamReader(getInputStreamFromUrl(url)));
StringBuilder sb = new StringBuilder();
try{
String line = null;
while((line = reader.readLine()) != null)
{
sb.append(line);
}
}catch (IOException e){
e.printStackTrace();
}
getInputStreamFromUrl(url).close();
return sb.toString();
}
}
Here is the logcat:
06-20 21:25:18.022: E/AndroidRuntime(14095): FATAL EXCEPTION: main
06-20 21:25:18.022: E/AndroidRuntime(14095): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.adn/com.adn.REEActivity}: java.lang.NullPointerException
06-20 21:25:18.022: E/AndroidRuntime(14095): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
06-20 21:25:18.022: E/AndroidRuntime(14095): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
06-20 21:25:18.022: E/AndroidRuntime(14095): at android.app.ActivityThread.access$600(ActivityThread.java:123)
06-20 21:25:18.022: E/AndroidRuntime(14095): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
06-20 21:25:18.022: E/AndroidRuntime(14095): at android.os.Handler.dispatchMessage(Handler.java:99)
06-20 21:25:18.022: E/AndroidRuntime(14095): at android.os.Looper.loop(Looper.java:137)
06-20 21:25:18.022: E/AndroidRuntime(14095): at android.app.ActivityThread.main(ActivityThread.java:4424)
06-20 21:25:18.022: E/AndroidRuntime(14095): at java.lang.reflect.Method.invokeNative(Native Method)
06-20 21:25:18.022: E/AndroidRuntime(14095): at java.lang.reflect.Method.invoke(Method.java:511)
06-20 21:25:18.022: E/AndroidRuntime(14095): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
06-20 21:25:18.022: E/AndroidRuntime(14095): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
06-20 21:25:18.022: E/AndroidRuntime(14095): at dalvik.system.NativeStart.main(Native Method)
06-20 21:25:18.022: E/AndroidRuntime(14095): Caused by: java.lang.NullPointerException
06-20 21:25:18.022: E/AndroidRuntime(14095): at java.io.Reader.<init>(Reader.java:64)
06-20 21:25:18.022: E/AndroidRuntime(14095): at java.io.InputStreamReader.<init>(InputStreamReader.java:79)
06-20 21:25:18.022: E/AndroidRuntime(14095): at com.adn.REEActivity.getStringFromUrl(REEActivity.java:49)
06-20 21:25:18.022: E/AndroidRuntime(14095): at com.adn.REEActivity.onCreate(REEActivity.java:28)
06-20 21:25:18.022: E/AndroidRuntime(14095): at android.app.Activity.performCreate(Activity.java:4465)
06-20 21:25:18.022: E/AndroidRuntime(14095): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
06-20 21:25:18.022: E/AndroidRuntime(14095): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
06-20 21:25:18.022: E/AndroidRuntime(14095): ... 11 more
Here is the Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.adn"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".REEActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Can someone please help me with this. I am new to Android as well.
replace
StringBuffer sb = new StringBuffer();
with
StringBuffer sb = new StringBuilder();
and also close your InputStrem using close() method
try to use this code in your second method, hope this will solve the problem
public static String getStringFromUrl(String url) throws UnsupportedEncodingException{
BufferedReader br = new BufferedReader(new InputStreamReader(getInputStreamFromUrl(url)));
StringBuilder sb = new StringBuilder();
try{
String line = null;
while((line = reader.readLine()) != null)
{
sb.append(line);
}
}catch (IOException e){
e.printStackTrace();
}
getInputStreamFromUrl(url).close();
return sb.toString();
}
I tried your updated code and it works now, and this is what I get:
Can you try this code
public String getUrlContents(String url){
String content = "";
HttpClient hc = new DefaultHttpClient();
HttpGet hGet = new HttpGet(url);
ResponseHandler<String> rHand = new BasicResponseHandler();
try {
content = hc.execute(hGet,rHand);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content;
}