0

I am trying to run a simple android code on my real device but it keeps crashing, it works fine on emulator.

my code is

 package com.example.new1;


     import java.io.BufferedReader;
     import java.io.InputStreamReader;
     import java.net.HttpURLConnection;
     import java.net.URL;
     import android.os.AsyncTask;
     import android.os.Bundle;
     import android.app.Activity;
     import android.view.Menu;
     import android.view.View;
     import android.widget.TextView;

     public class MainActivity extends Activity {
     TextView tx;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tx= (TextView)findViewById(R.id.text);
    }

    public void func(View view)
    {
        //tx.setText("Working fine till here.");
         new FetchSQL().execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    private class FetchSQL  extends AsyncTask<String,Void,String>

    {   

        @Override
        protected String doInBackground(String... arg0) {
                URL url = null;
                BufferedReader reader = null;
                StringBuilder stringBuilder;
                String myUrl = "http://10.22.35.4:80/conc2.php";
            try
            { url =new URL(myUrl);
              HttpURLConnection connection = (HttpURLConnection)      url.openConnection();
              connection.setRequestMethod("GET");
              connection.setReadTimeout(15*10000);
              connection.connect();
              reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
              stringBuilder = new StringBuilder();
              String line = null;
              while ((line = reader.readLine()) != null)
              {
                stringBuilder.append(line + "\n");

              }
            // TODO Auto-generated method stub
            return stringBuilder.toString();
            }
            catch(Exception e)
            {
                tx.setText(e.toString());
            }
            return null;
        } 

        protected void onPostExecute(String result)
        {
             tx.setText(result);
        }


    }
}

it works fine on emulator , the output it gives

V. M. ARORADr. C. P. REDDYARTI CHOWDHARYJAGDISH SINGH but on running same on my device. it gives following error code.

05-03 11:49:39.002: E/AndroidRuntime(19934): FATAL EXCEPTION: AsyncTask #1
05-03 11:49:39.002: E/AndroidRuntime(19934): java.lang.RuntimeException: An error occured while executing doInBackground()
05-03 11:49:39.002: E/AndroidRuntime(19934):    at    android.os.AsyncTask$3.done(AsyncTask.java:200)
05-03 11:49:39.002: E/AndroidRuntime(19934):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
05-03 11:49:39.002: E/AndroidRuntime(19934):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
05-03 11:49:39.002: E/AndroidRuntime(19934):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
05-03 11:49:39.002: E/AndroidRuntime(19934):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
05-03 11:49:39.002: E/AndroidRuntime(19934):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
05-03 11:49:39.002: E/AndroidRuntime(19934):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
05-03 11:49:39.002: E/AndroidRuntime(19934):    at java.lang.Thread.run(Thread.java:1096)
05-03 11:49:39.002: E/AndroidRuntime(19934): Caused by: android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
05-03 11:49:39.002: E/AndroidRuntime(19934):    at android.view.ViewRoot.checkThread(ViewRoot.java:2811)
05-03 11:49:39.002: E/AndroidRuntime(19934):    at   android.view.ViewRoot.requestLayout(ViewRoot.java:594)
05-03 11:49:39.002: E/AndroidRuntime(19934):    at android.view.View.requestLayout(View.java:8180)
05-03 11:49:39.002: E/AndroidRuntime(19934):    at android.view.View.requestLayout(View.java:8180)
05-03 11:49:39.002: E/AndroidRuntime(19934):    at android.view.View.requestLayout(View.java:8180)
05-03 11:49:39.002: E/AndroidRuntime(19934):    at android.view.View.requestLayout(View.java:8180)
05-03 11:49:39.002: E/AndroidRuntime(19934):    at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:257)
05-03 11:49:39.002: E/AndroidRuntime(19934):    at android.view.View.requestLayout(View.java:8180)
05-03 11:49:39.002: E/AndroidRuntime(19934):    at android.widget.TextView.checkForRelayout(TextView.java:5383)
05-03 11:49:39.002: E/AndroidRuntime(19934):    at android.widget.TextView.setText(TextView.java:2688)
05-03 11:49:39.002: E/AndroidRuntime(19934):    at android.widget.TextView.setText(TextView.java:2556)
05-03 11:49:39.002: E/AndroidRuntime(19934):    at android.widget.TextView.setText(TextView.java:2531)
05-03 11:49:39.002: E/AndroidRuntime(19934):    at com.example.new1.MainActivity$FetchSQL.doInBackground(MainActivity.java:66)
05-03 11:49:39.002: E/AndroidRuntime(19934):    at com.example.new1.MainActivity$FetchSQL.doInBackground(MainActivity.java:1)
05-03 11:49:39.002: E/AndroidRuntime(19934):    at android.os.AsyncTask$2.call(AsyncTask.java:185)
05-03 11:49:39.002: E/AndroidRuntime(19934):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
05-03 11:49:39.002: E/AndroidRuntime(19934):    ... 4 more

please help, how to run this stupid code on my real device. ive got my device

GTI-9003 , ANDROID 2.2.1 (FROYO).. AND IN THIS APP I'VE PUT MIN SDK ..OF 1.5(CUPCAKE).

Shruti
  • 1
  • 13
  • 55
  • 95
Yogesh Kumar
  • 682
  • 1
  • 10
  • 29

4 Answers4

1

Its because you are trying to change the UI, setText actually, in your doInBackground method which is not meant to do any UI tasks.

Here:

catch(Exception e)
            {
                tx.setText(e.toString());
            }

You can simply do this:

catch(Exception e)
            {
                return e.toString();
            }

and in onPostExecute, this will be set as text to your TextView.

Archie.bpgc
  • 23,812
  • 38
  • 150
  • 226
0

You have to move the portion of the background task that updates the ui onto the main thread.

You are trying to access UI components from a background thread in your case inside the doInBackground() method. It is not allowed.

Refer here

doInBackground(......)
{
  runOnUiThread(new Runnable() {
  public void run() {
     // your code
  }
 });
}
Linga
  • 10,379
  • 10
  • 52
  • 104
0

Your views were created on the main thread(UI thread), but you are updating that view(textview in your case) from a background thread(exception handling in doinbackground() method). So you are getting this exception. So do the updating in onPOstExecute() method as this will be run on the UI thread. And you are getting this exception only on device because while trying to connect from device you are getting an exception (probably while opening a connection, because i faced it many times) and hence the error. While connecting through emulator probably the connection is successful. So you may have to look at that as well.

Ashwin
  • 132
  • 3
  • 13
0

doInbackground() runs on the background thread. You cannot update ui from the background thread. You should update ui on the main UI thread

You can update UI in doinBackground() as

     runOnUiThread(new Runnable() //run on ui thread
                 {
                  public void run() 
                  { 

                      tv.setText("value");

                 }
                 });

Alternatively you can return result in doInbackground(). The result is a parameter to onPostExecute(). In onPostExecute() update UI.

Check the topic under the heading The 4 steps in the below link

http://developer.android.com/reference/android/os/AsyncTask.html

You can also use a handler

Edit:

I would suggest not to set Exception to a textview.

Its better you just print the exception stack trace

          catch(Exception e)
        {
            e.printStacktrace();
        }

I would have 1 return statement after catch and remove the statement before close of try

        return stringBuilder.toString(); 
        // remove this in try
        // return the same after catch.
        // print stack trace. don't set it to textview.

instead of

        return null;  
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • http://stackoverflow.com/questions/16353561/java-net-socketexceptionoperation-time-out-when-running-app-on-real-device – Yogesh Kumar May 03 '13 at 07:17
  • @yug din't understand you comment. you cannot update ui from background thread. Can u explain clearly what won't work? – Raghunandan May 03 '13 at 10:34