I have a remote call that I make and I am wondering where it is better to put this processing code:
if ( result == null )
{
Toast.makeText(getApplicationContext(), "Some error message", Toast.LENGTH_LONG).show();
}
else
if ( result.equals( "all_problems_db_error" ))
{
Log.d( "AllBusinessesActivity" , "result: " + result )
}
else
{
// Unwrap the stuff from the JSON string
String problem_title = null;
String problem_id = null;
try
{
JSONArray obj = new JSONArray(result);
if ( obj != null )
{
problems.clear();
for ( int i = 0; i < obj.length(); i++ )
{
JSONObject o = obj.getJSONObject(i);
problem_title = o.getString("problem_title");
problem_id = o.getString("problem_id");
Problem p = new Problem ( );
p.setProblemId(problem_id);
p.setProblemName(problem_title);
problems.add( p );
}
adapter.notifyDataSetChanged();
}
}
catch ( Exception e )
{
// Do something :)
}
}
Is it better to have it in the onPostExecute() or at the end or doInBackground() ?
I now do it in onPostExecute() but every once in a while I experience some slowness, and I have been reading that it might be better to do this in the doInBackground.
Could someone please explain to me the difference? And if I do this in the doInBackground() then what is the purpose of having the onPostExecute method?
Is it better to have it in the onPostExecute()Since in your case there is no manipulation of any UI component, you can have the code in
doInBackground(). But since you are showing atoastwhen the result isnullyou can check the result indoInBackground()and if the result is not null you can do the remaining processing on thatresultin the same function or else you can pass on toonPostExecute()where you can show thetoast.at the end or doInBackground()Yes. You can have this code at the end of
doInBackground()since this method runs on a non-UI thread and this will definitely reduce the slowness you experience.The difference between both these method
doInBackground()andonPostExecute()is simply that the former runs on a non-UI thread and the later on the UI-Thread.And if I do this in the doInBackground() then what is the purpose of having the onPostExecute methodUsually the
doInBackground()is used to perform time consuming operations. These operations may include activities like calling a webservice or fetching images from servers. In such cases (like fetching images from servers) you want that images to be displayed on your screen (which is your UI). After you fetch these resource you pass on the data to theonPostExecute()where you can update your UI since it runs on your UI thread.Hope this explanation clears your doubt.