Reading a file in AsyncTask Android

I am a novice programmer. I want to read data from a file and put them on the map. I want to read a txt file and do it in a background thread, here is my code

          MyTask mt;


           @Override
protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);           
          myFragmentManager = getSupportFragmentManager();    
          mySupportMapFragment  = (SupportMapFragment)myFragmentManager.findFragmentById(R.id.map);
          myMap = mySupportMapFragment.getMap();    
          mt = new MyTask();      
          }

      class MyTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
      super.onPreExecute();

    }

    @Override
    protected Void doInBackground(Void... params) {

                    StringBuffer sb = new StringBuffer();
                    BufferedReader br = null;
                    try {
                        br = new BufferedReader(new InputStreamReader(getAssets().open("example.txt")));
                        String temp;
                        while ((temp = br.readLine()) != null)
                            sb.append(temp);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            br.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    String myjsonstring = sb.toString();
                    try {

                        JSONObject jsonObjMain = new JSONObject(myjsonstring);
                        JSONArray jsonArray = jsonObjMain.getJSONArray("results");

                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObj = jsonArray.getJSONObject(i);
                            String name = jsonObj.getString("Adres");                               
                            JSONObject c = jsonArray.getJSONObject(i);
                            JSONObject phone = c.getJSONObject("location");
                            String lat = phone.getString("latitude");
                            String lon = phone.getString("longitude");

                            dLat=Double.parseDouble(lat);
                            dLon=Double.parseDouble(lon);                               
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
      return null;
    }

    @Override
    protected void onPostExecute(Void result) {
      super.onPostExecute(result);
      myMap.addMarker(new MarkerOptions().position(new LatLng(dLat, dLon)).title(name));
      dialog.dismiss();

    }
  }

With this code on a real device, nothing happens, no point is added. What is my fault?

Upvotes: 2

Views: 3611

Answers (2)

desseim
desseim

Reputation: 8248

Well, you instantiate a MyTask object (new MyTask()), assign it to what I think is a member variable in the whole context (mt =), but then that's it. This means that a MyTask object is referenced in the mt variable, but nothing more.

You need to execute (trigger) the task for it to run:

mt.execute();

Put this line at the place where you want the task to start.

See the Android documentation for details about AsyncTasks and how to use them, it's explained clearly:

Once created, a task is executed very simply:

new DownloadFilesTask().execute(url1, url2, url3);

As a general rule, always look there first, especially for basic usage of Android paradigms you're not accustomed to.


As for the <Void, Void, Void> part, I don't know how familiar you are with Java generics, if not you should first get introduced to the concept.

Here the AsyncTask can defined 3 things: the type of the parameters its doInBackGround() method accepts, the type of parameters its onProgressUpdate() method accepts, and lastly the type of the parameters its onProgressUpdate() method accepts and its doInBackground() method returns.

In your case, your AsyncTask doesn't take nor return any parameter, so you just specify these 3 types as the Void type (see this other SO question as for why). You have to specify the types because Java is a strongly (statically) typed language, if you don't it can't compile your code.

So where could this be useful ? Let's say you want to do the same thing (read data from a file asynchronously) in another Activity for example, then you could take the MyTask definition out in its own file, and reuse MyTask in both your activities. OK, but you want to load data from different files in each activity, so MyTask instances somehow have to take the file name to read from as a parameter. MyTask doInBackground() would then look like this:

protected Void doInBackground(String... params) {
    final String fileName = params[0];  // note: in real life you should check the arguments are valid first
    ...

Now you see that it takes parameters of type String. For the compiler to make sense out of this, and to allow code in your activities to pass parameters of type String to their MyTask instances when calling execute(), MyTask will have to be declared like this:

public class MyTask extends AsyncTask<String, Void, Void>

You'll have compile errors otherwise.

Again, check the Android doc for a slightly more extensive use of these type parameters.

Upvotes: 2

tpbapp
tpbapp

Reputation: 2506

As user "desseim" pointed out, you just need to execute the task:

mt.execute();

The parameters for the execute method are used for passing data to the doInBackground() method override and can be obtained with the "params" variable. Doing this is not necessary for you and is useful if you don't need to manipulate or access the Activity from within the background task and are using a separate class file for the task. As your task class is located within the Activity, passing parameters through execute is pointless because you can access the Activity data directly.

Upvotes: 0

Related Questions