user2082987
user2082987

Reputation: 1731

AsyncTask for sending data to server

I am writing an AsyncTask that is expected to send the data to the server continuously in background. I have called it in onCreate() of MainActivity. But it is not working. The toast in onPreExecute() is displayed then nothing happens.

private class MyAsync extends AsyncTask<Void, Void, Void>
 {
      @Override
      protected void onPreExecute() 
      {
          Toast.makeText(getApplicationContext(),"1", Toast.LENGTH_LONG).show();
            // update the UI immediately after the task is executed
            super.onPreExecute();
      }

          @Override
          protected Void doInBackground(Void... params)
          {
             // Toast.makeText(getApplicationContext(),"2", Toast.LENGTH_LONG).show();
              File file = new File(Environment.getExternalStorageDirectory(),"/BPCLTracker/gpsdata.txt");
              int i=0;

              RandomAccessFile in = null;

              try
              {
                  in = new RandomAccessFile(file, "rw");
              } 
              catch (FileNotFoundException e) 
              {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
              //String line =null;
              while (true) 
              {
                HttpEntity entity=null;
                try 
                {
                    if (new GPSLoggerService().isInternetOn()) 
                    {
                            while ((line = in.readLine()) != null)
                            {

                                HttpClient client = new DefaultHttpClient();
                                String url = "http://67.23.166.35:80/android/insert.php";
                                HttpPost request = new HttpPost(url);
                                StringEntity se = new StringEntity(line);
                                se.setContentEncoding("UTF-8");
                                se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                                entity = se;
                                request.setEntity(entity);
                                HttpResponse response = client.execute(request);
                                entity = response.getEntity();
                                i++;
                            }
                            if((line = in.readLine()) == null && entity!=null)
                            {
                                file.delete();
                                new MyAsync().execute();
                            }


                    }// end of if
                    else
                    {
                        Thread.sleep(60000);

                    } // end of else
                }// end of try
                catch (NullPointerException e1)
                {
                    e1.printStackTrace();
                } 
                catch (InterruptedException e2) 
                {
                    e2.printStackTrace();
                }
                catch (IOException e1) 
                {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }// end of while

      }//doinbackground

      @Override
      protected void onProgressUpdate(Void... values) {
         // Toast.makeText(getApplicationContext(),"3", Toast.LENGTH_LONG).show();
      }

      @Override
      protected void onPostExecute(Void result) {
          Toast.makeText(getApplicationContext(),"4", Toast.LENGTH_LONG).show();
      }

     }//AsyncTask

Please help. Thank you.

Upvotes: 0

Views: 5601

Answers (4)

Lexo
Lexo

Reputation: 437

Verify that your device has internet access and also that you have granted internet access permission in your AndroidManiest.xml file.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Upvotes: 0

Carlo Baltazar
Carlo Baltazar

Reputation: 1

i noticed that your parameters in asyncTask is all void try changing the first one as a String of course change also the parameter of do in background as a String then invoke your class to your onCreate. follow this as a reference

public class reqDataREST extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... arg0) {
    // TODO Auto-generated method stub

    HttpClient client = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(
            "http://icommute-ph.com/api/v1/todos/");

    try {
    // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("Name", tstData.getText().toString()));
                postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        BasicHttpContext httpContext = new BasicHttpContext();
            httpContext.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore());

    // Execute HTTP Post Request
        HttpResponse response = client.execute(postRequest, httpContext);
        //int statusCode = response.getStatusLine().getStatusCode();
    }
    catch (ClientProtocolException e) {
        e.printStackTrace();
        // TODO Auto-generated catch block
    }
    catch (IOException e) {
        e.printStackTrace();
        // TODO Auto-generated catch block
    }
    return null;
}

}

Upvotes: 0

Sanjeev Badoni
Sanjeev Badoni

Reputation: 95

You can upload data continuously by using using service. I Provide the code that run in background and uplaod data on server continuously .

you just call this service :

startService(new Intent(this, BackgroundService.class));

Also Add entry in Android Manifest File

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class BackgroundService extends IntentService
{
    private static final String TAG = "BackgroundService";
    Context mContext = null;

    final static int SERVICE_NAME = 1;
    int WORK_TYPE;

    public BackgroundService()
    {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(Intent intent)
    {

        mContext = getBaseContext();
        WORK_TYPE = SETTING;
        new BackgroundTask(mContext).execute();
    }

    public class BackgroundTask extends AsyncTask<String, String, Void>
    {
        Context mContext = null;

        public BackgroundTask(Context context)
        {
            mContext = context;
        }

        protected void onPreExecute()
        {
        }

        protected Void doInBackground(final String... args)
        {
            switch (WORK_TYPE)
            {
                case SETTING:
                String input = "what ever text data post on server";
                response = sendDataToServer(input);
                JsonUtils.parseServerData(response, hashMapObj);
                break;
            }
            return null;
        }

        protected void onPostExecute(final Void unused)
        {
            switch (WORK_TYPE)
            {
                case SETTING:
                    if (!"".equalsIgnoreCase(response) && response != null)
                    {
                        DeviceUtils.deviceRegistration(hashMapObj, mContext);   
                    }
                    callService(SERVICE_NAME);
                    break;
            }
        }
    }

    public void callService(int work)
    {
        WORK_TYPE = work;
        new BackgroundTask(mContext).execute();
    }


    public String sendDataToServer(String data)
    {
        StringBuffer sb = new StringBuffer("");
        String serverUrl = "http://67.23.166.35:80/android/insert.php" ;
        try
        {
            URL url = new URL();
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setConnectTimeout(6 * 10 * 1000);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            conn.setRequestMethod("POST");

            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String line = "";
            while ((line = rd.readLine()) != null)
            {
                // Process line...
                sb.append(line);
            }

            wr.close();
            rd.close();
            return sb.toString();
        }
        catch (Exception e)
        {
            Log.d("Exception : ", e.getStackTrace().toString());
        }

        return sb.toString();
    }}

Upvotes: 1

codeMagic
codeMagic

Reputation: 44571

For a question, you need to be a little more specific on what is happening. However, you don't want to do it this way. AsyncTask is for short lived operations/ According to the Docs

AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.

You have an infinite loop with while(true) which is rarely a good idea. I suggest you rethink how you do this. You could set up a Timer, AlarmManager, or a Service but I suggest you don't use AsyncTask for this

Upvotes: 3

Related Questions