0

I want to retrieve data from php file to my new android app. I tried to do it as background process there for I want to use it without UI thread. I couldn't remove UI thread from this code any one hep me to remove UI thread in this code do it?

I try it but there is lot of red underlines. Actually I try to get data from host using a AlarmManager in every 5 seconds

my AlarmDemo class

    public class AlarmDemo extends Activity {
    Toast mToast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm_demo);

        // repeated alerm
        Intent intent = new Intent(AlarmDemo.this, RepeatingAlarm.class);
        PendingIntent sender = PendingIntent.getBroadcast(AlarmDemo.this, 0,
                intent, 0);

        // We want the alarm to go off 5 seconds from now.
        long firstTime = SystemClock.elapsedRealtime();
        firstTime += 5 * 1000;

        // Schedule the alarm!
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime,
                5 * 1000, sender);

        // Tell the user about what we did.
        if (mToast != null) {
            mToast.cancel();
        }
        mToast = Toast.makeText(AlarmDemo.this, "Rescheduled",
                Toast.LENGTH_LONG);
        mToast.show();
        // end repeatdalarm

    }

}

my RepeatingAlarm class

    public class RepeatingAlarm extends BroadcastReceiver {
Context context;
Button b;
EditText et,pass;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;

 private AutoCompleteTextView autoComplete;
 private MultiAutoCompleteTextView multiAutoComplete;
 private ArrayAdapter<String> adapter;

    @Override
    public void onReceive(Context context, Intent intent) {

        Toast.makeText(context, "OK", Toast.LENGTH_SHORT).show();



        dialog = ProgressDialog.show(RepeatingAlarm.this, "", 
                "Validating user...", true);
         new Thread(new Runnable() {
                public void run() {
                    login();                          
                }
              }).start();       

    }


    void login(){
        try{            

            httpclient=new DefaultHttpClient();
            httppost= new HttpPost("http://androidexample.com/media/webservice/getPage.php"); 
            //add your data
            nameValuePairs = new ArrayList<NameValuePair>(2);
            // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar, 
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            //Execute HTTP Post Request
            response=httpclient.execute(httppost);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            final String response = httpclient.execute(httppost, responseHandler);
            System.out.println("Response : " + response); 
            runOnUiThread(new Runnable() {
                public void run() {
                    String text = response;
                    tv.setText("Response from PHP : " + text);
                    dialog.dismiss();
                }
            });



        }catch(Exception e){
            dialog.dismiss();
            System.out.println("Exception : " + e.getMessage());
        }
    }
}

please help me I'm new in android

Kavindu
  • 11
  • 3

1 Answers1

1

Use AsyncTask:

Use the AsyncTask class (reference) to perform your background operation.

Why use AsyncTask:

It makes it incredibly easy to manage this sort of work, as it lets you perform the intensive (i.e. long, which consume a lot of resources) operations in the background thread (also called worker thread), and also lets you manipulate your UI from the UI thread (also called main thread).

If you perform intensive operations on UI thread, your app hangs and you get 'Application Not Responding' (called ANR) problems. If you try to manipulate UI from worker/background thread, you get an exception.

Using AsyncTask:

It works like this:

We call the long, intensive operation as the asynchronous task. In the AsyncTask model, the asynchronous task is executed in 4 steps - See them here.

Read comments in the following pseudocode. After this snippet, in the next one, I'll show you how to execute an AsyncTask and pass it the arguments (you can see in this snippet).

/*
 * PERFORM A LONG, INTENSIVE TASK USING AsyncTask
 * 
 * Notice the parameters of the class AsyncTask extended by AlarmClockTask. 
 * First represents what is passed by Android System to doInBackground() method when system calls it. This is originally passed by you when you execute the AlarmClockTask (see next snippet below to see how to do that), and then the system takes it and passes it to doInBackground()
 * Second represents what is passed to onProgressUpdate() by the system. (Also originally passed by you when you call a method `publishProgress()` from doInBackground(). onProgressUpdate() is called by system only when you call publishProgress())
 * Third represents what you return from doInBackground(); Then the system passes it to onPostExecute() as a parameter.
 */
public class AlarmClockTask extends AsyncTask<String, Integer, Boolean> {

    @Override
    protected void onPreExecute() {
        /*
         * 
         * FIRST STEP: (Optional)
         * 
         * This method runs on the UI thread.
         * 
         * You only set-up your task inside it, that is do what you need to do before running your long operation.
         * 
         * In your case, the long operation is perhaps loading data from the `php` file. SO HERE you might want to show
         * the progress dailog.
         */
    }

    @Override
    protected Boolean doInBackground(String... params) {
        /*
         * 
         * SECOND STEP: (Mandatory)
         * 
         * This method runs on the background thread (also called Worker thread).
         * 
         * So perform your long, intensive operation here.
         * 
         * So here you read your PHP file.
         * 
         * Return the result of this step. 
         * The Android system will pass the returned result to the next onPostExecute().
         */
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... string) {
        /*
         * Run while the background operation is running (Optional)
         * 
         * Runs on UI Thread
         * 
         * Used to display any form of progress in the user interface while the background computation is still
         * executing. 
         * 
         * For example, you can use it to animate a progress bar (for displaying progress of the background operation).
         */
    }


    protected void onPostExecute (String result) {
        /*
         * FOURTH STEP. Run when background operation is finished. (Optional)
         * 
         * Runs on UI thread.
         * 
         * The result of the background computation (what is returned by doInBackground()) 
         * is passed to this step as a parameter.
         * 
         */
    }

}

Here is how you would execute the AsyncTask:

new AlarmClockTask().execute(new String[] {"alpha", "beta", "gamma"});

The Android system will pass this String array you passed to execute(), to the doInBackground() method as the varargs parameter of doInBackground().

NXA
  • 440
  • 2
  • 10