jewstin
jewstin

Reputation: 87

Blinking screen when using AsyncTask

Hey guys I know this is a common problem, Im using a AsyncTaskActivity to have a JSON parser parse some json behind the scences of a app and pump a listview with an arrayadapter. This is my code code in my mainActivity.java. My screen flickers whenever I get to the belwo activity.

setContentView(R.layout.activity_see_schedule_activity);
        this.setTitle("Activity Schedule");
        //Log.e("ID see schedule#",getIntent().getExtras().getString("id#"));
        RequestQueue queue = Volley.newRequestQueue(see_schedule_activity.this);
        StringRequest request = new StringRequest(Request.Method.POST, httpUpdateRoutines, new Response.Listener<String>() {


            @Override
            public void onResponse(String response) {

                Toast.makeText(see_schedule_activity.this, "" + response, Toast.LENGTH_SHORT).show();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(see_schedule_activity.this, "Data Not Fetched " + error, Toast.LENGTH_SHORT).show();

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {


                Map<String, String> map = new HashMap<String, String>();

                //Log.e("ID see schedule#",getIntent().getExtras().getString("id#"));
                map.put("residentid", getIntent().getExtras().getString("id#"));
                return map;
            }
        };

        queue.add(request);

        new AsyncTaskParseJson(this).execute();




        ArrayList<String> schedulelist = getIntent().getExtras().getStringArrayList("tasks_filled");

        ArrayAdapter adapter = new ArrayAdapter<String>(this,
                R.layout.activity_listview, schedulelist);

        ListView listView = (ListView) findViewById(R.id.schedulelist);
        listView.setAdapter(adapter);
My AsyncTaskparseJson.java

public class AsyncTaskParseJson extends AsyncTask<String, String, String> {


    private Context c;

    String schedule;
    String activityid;
    String routine;
    String[] tasks;


    ArrayList<String> schedulelist = new ArrayList<String>();
    final String TAG = "AsyncTaskParseJson.java";
    // set your json string url here
    String yourJsonStringUrl = "http://www.wirelesshealth.wayne.edu/nhcheckup/getData(justin).php";
    // contacts JSONArray
    JSONArray dataJsonArr = null;

    public AsyncTaskParseJson(Context applicationContext) {
            this.c=applicationContext;
    }


    @Override
    protected void onPreExecute() {}

    @Override
    protected String doInBackground(String... arg0) {
        try {


            HashMap<Integer, String> hm = new HashMap<Integer, String>();
          -----------------------some hash -----------------

            // instantiate our json parser
            JsonParser jParser = new JsonParser();

            // get json string from url
            JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);

            // get the array of users
            dataJsonArr = json.getJSONArray("schedule");



            // loop through all users
            for (int i = 0; i < dataJsonArr.length(); i++) {
                Log.e("doInBackground","YOU GOT HERE");

                JSONObject c = dataJsonArr.getJSONObject(i);

                // Storing each json item in variable

                activityid = c.getString("activityid");
-------------------------------Pasres object c --------------
            }
            Intent intent = new Intent(c,see_schedule_activity.class);
           -- passes back arraylist -------------- intent.putStringArrayListExtra("tasks_filled",schedulelist);
            this.c.startActivity(intent);
            ((Activity)c).finish();


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

        return null;
    }


    @Override
    protected void onPostExecute(String strFromDoInBg) {
//        Intent intent = new Intent(see_schedule_activity.this,see_schedule_activity.class);
//        intent.putExtra("tasks_filled",tasks);
//        this.c.startActivity(intent);
//        ((Activity)c).finish();


    }



}

I did a bit of troubleshotting and found out the error has to do with the placement of the intent that's passed a array list. But here's the problem, if I put it in the doinBackground() the screen flashes rapidly (which is prolly becuase it keeeps calling the (setContentView(R.layout.activity_see_schedule_activity);) but if I keep it in onPostExcute nothing happens (hte arraylist isnt pumping the listview). So im a bit stumped, any help would be appreciated thanks!

Upvotes: 1

Views: 93

Answers (1)

user
user

Reputation: 87064

As I said in my comment, you enter a recursive call between the activity and the AsyncTask as you start the same activity again with an Intent. Instead, as you already pass the activity instance to the AsyncTask, simply create an update method in the activity and use that from the AsyncTask:

// field in see_schedule_activity
private ArrayAdapter<String> adapter;

// which you'll initialize in onCreate()
// with an empty list, as you don't yet have the data
...
adapter = new ArrayAdapter<String>(this,
            R.layout.activity_listview, new ArrayList<>());

ListView listView = (ListView) findViewById(R.id.schedulelist);
listView.setAdapter(adapter); 
... rest of onCreate()

public void update(List<String> results) {
    adapter.clear();
    adapter.addAll(results);
}

Then implement correctly the AsyncTask:

public class AsyncTaskParseJson extends AsyncTask<String, Void, List<String>> {    


private see_schedule_activity activity;
//... the rest

public AsyncTaskParseJson(see_schedule_activity activity) {
    this.activity = activity;
}

@Override
protected List<String> doInBackground(String... arg0) {
    // create scheduleList 
    return scheduleList;
}

@Override
protected void onPostExecute(List<String> results) {
    activity.update(results);
}
//...

This is not a good implementation of the AsyncTask but should get you going.

Upvotes: 1

Related Questions