Json Element returns null in AsyncTask - android

When I call only wpCategories = JsonToElement.getllAllCategory(); in the buttons onClick methood it works fine. (wpCategories get filled with data). But when I put this in a asynctask, wpCategories returns null. (is the doInBackground not being called?)
Here is my buttons on click methood:
public void onImageGridClick(View view) {
new GetJsonElementTask().execute();
Intent intent = new Intent(this, CategoryGridActivity.class);
intent.putParcelableArrayListExtra(Extra.IMAGES, wpCategories);
startActivity(intent);
}
And the asyncTask:
private class GetJsonElementTask extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(HomeActivity.this, "",
"Loading...");
}
#Override
protected String doInBackground(Void... arg0) {
wpCategories = JsonToElement.getllAllCategory();
return null;
}
#Override
protected void onPostExecute(String value) {
progressDialog.dismiss();
}
#Override
protected void onProgressUpdate(Integer... progress) {
Log.v("DEBUG_LOG", "In onProgressUpdate");
}
}

Start your Activity inside onPostExecute because this method execute after doInBackground execution complete :
#Override
protected String doInBackground(Void... arg0) {
wpCategories = JsonToElement.getllAllCategory();
return wpCategories; //<<< return value from here
}
#Override
protected void onPostExecute(String value) {
progressDialog.dismiss();
Intent intent = new Intent(this, CategoryGridActivity.class);
intent.putParcelableArrayListExtra(Extra.IMAGES, value);
startActivity(intent);
}

Try following
public void onImageGridClick(View view) {
new GetJsonElementTask().execute();
}
public void startCategoryGridActivity(){
Intent intent = new Intent(this, CategoryGridActivity.class);
intent.putParcelableArrayListExtra(Extra.IMAGES, wpCategories);
startActivity(intent);
}
And the asyncTask:
private class GetJsonElementTask extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(HomeActivity.this, "",
"Loading...");
}
#Override
protected String doInBackground(Void... arg0) {
wpCategories = JsonToElement.getllAllCategory();
return null;
}
#Override
protected void onPostExecute(String value) {
progressDialog.dismiss();
startCategoryGridActivity();
}
#Override
protected void onProgressUpdate(Integer... progress) {
Log.v("DEBUG_LOG", "In onProgressUpdate");
}
}

Related

AsyncTask Thread with Intent

I run loading screen which should show current status "scanning packages, etc" . So that my activity wouldn't freeze I must use thread, but then I can't update status (TextField). I tried using AsyncTask but that didn't helped me at all, still after running I see text field unchanged.
public class LoadingScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loadingscreen_layout);
try {
startLoadingScreen();
}catch (Exception e){
Log.e("Scanner","Scanner",e);
}
}
public void startLoadingScreen(){
try{
new Thread(new Runnable() {
#Override
public void run() {
new ScanningOperation().execute("Scanning");
//loadingScreen.setStatus("Scanning");
final PackageManager pm = getPackageManager();
//get a list of installed apps.
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
//changeIntent();
//finish();
}
});
} catch (Exception e){
Log.e("Thread","Thread");
}
}
private class ScanningOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
return params[0];
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
TextView txt = findViewById(R.id.statusView);
txt.setText(result);
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
}

Android, kill/remove Asynctask at it's onPostExecute()

I'm developing an app that when user clicks on a Button it executes an Asynctask that this class calls a method at it's onPostExecute method that calls another Asynctask! It works when user clicks once, but at the second time it crashes and says Cannot execute task: the task has already been executed (a task can be executed only once)
.
public class Test extends Activity {
A a;
B b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
a = new A();
a.execute();
}
});
}
class A extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
// doing st
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
runB();
a.cancel(true);
}
}
public void runB() {
b = new B();
b.execute();
}
class B extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
// doing st
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//doing st
b.cancel(true);
}
}
Use AsyncTask.Status for checking status of AsyncTask before calling AsyncTask.execute() method on Button onClick:
#Override
public void onClick(View arg0) {
if(a ==null){
a = new A();
a.execute();
}
}
And in onPostExecute of B class assign null to a :
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//doing st
b.cancel(true);
a=null;
}

Adding ProgressDialog as Async Task is slowing down the performance

This is my code for Login.
public void Login_Click(View view) {
HashMap<String, String> op_Config = XMLParser
.parse(LoginActivity.this);
}
It takes around 4 Sec to finish executing. So I added progress dialog like this.
public void Login_Click(View view) {
new IsLogedIn().execute();
}
class IsLogedIn extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... value) {
try
{
HashMap<String,String> op_Config = XMLParser.parse(LoginActivity.this);
finish();
Intent intent=new Intent(LoginActivity.this,MainMenuActivity.class);
startActivity(intent);
}
catch (Exception e) {
}
}
#Override
protected void onPostExecute(String file_url) {
dismissDialog(progress_bar_type);
}
}
But now it is taking more than 1 min to finish.
Try doing like this
class IsLogedIn extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... value) {
try
{
HashMap<String,String> op_Config = XMLParser.parse(LoginActivity.this);
}
catch (Exception e) {
}
}
#Override
protected void onPostExecute(String file_url) {
if(dilog.isShowing()){
dismissDialog(progress_bar_type);
}
finish();
startActivity(new Intent(LoginActivity.this,MainMenuActivity.class));
}
}

Android splash screen and server communication

I am developing an application in android, where i need to display a splash screen and at the same time there will be server communication. The problem here is when i launch the app, first application is communicating with the server and then it is displaying the splash screen. I want to both server communication and splash screen at the same time.
The following is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
try {
Thread thread = new Thread(this);
thread.start();
thread.join();
//Attractions
CommonMethods.getSystemOutput("Response Json Array String Attractions:::"+jArrayMobileAttractions);
attractionsDate = JsonParsing.getLatestDate(jArrayMobileAttractions);
attractionsDate = getDate(attractionsDate);
CommonMethods.getSystemOutput("Attractions Date:::::"+attractionsDate);
//Categories
CommonMethods.getSystemOutput("Response Json Array String Categories:::"+jArrayCategories);
categoryDate = JsonParsing.getLatestDate(jArrayCategories);
categoryDate = getDate(categoryDate);
CommonMethods.getSystemOutput("Category date:::"+categoryDate);
//Contacts
CommonMethods.getSystemOutput("Response Json Array String Contacts:::"+jArrayContacts);
contactsDate = JsonParsing.getLatestDate(jArrayContacts);
contactsDate = getDate(contactsDate);
CommonMethods.getSystemOutput("Contacts Date:::"+contactsDate);
} catch (Exception e) {
CommonMethods.getSystemOutput("Exception in Splash screen thread:::"+e);
}
}
public void run() {
// if (attractionsDate == null) {
jArrayMobileAttractions = RequestHandler.getJSONfromURL(Constants.MOBILE_ATTRACTIONS_URL);
jArrayCategories = RequestHandler.getJSONfromURL(Constants.CATEGORY_URL);
jArrayContacts = RequestHandler.getJSONfromURL(Constants.CONTACTS_URL);
// } else {
// jArrayMobileAttractions = RequestHandler.getJSONfromURL(Constants.MOBILE_ATTRACTIONS_URL+"?lastupdateddate="+attractionsDate);
// }
}
You can use the AsynchTask Manager in which it has a method
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// Do Server Interaction Here
return response;
}
#Override
protected void onPreExecute(String result) {
//Show your Splash Screen
}
#Override
protected void onPostExecute(String result) {
//Gone the Splash Screen view
}
}
For this purpose it will be better start from "SplashActivity" - in onCreate() start new Thread for communication with server, and when all communication finished - call startActivityForResult(mainActivityIntent). For correct behavior back button finish splash activity on finish main activity. Approximate code:
public class SplashActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setup view for activity
new Thread(new Runnable() {
public void run() {
// do here some long operation
startActivityForResult(new Intent(SplashActivity.this, MainActivity.class), 0);
}
}).start();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
finish();
}
}
I had the same thing to do and I did it this way and it works just fine. I had to show the splashscreen and download some file from the server, unzip it, move files insto proper directories and then start the apps main screen. Here is the code, I used AsyncTask.
So, you have three AsyncTask classes, one for each task and in the onPostExecute() I call the next AsyncTask. I can't say if this is the best way but it works for me.
I removed unneccessary code but for clarity I left a call to a dialog where I ask a user ih he wants to proceed with downloading as it may take a while. Also I check if FIRST_RUN is true just so I know if I should download the package since for my app I need to do it only the first time, so if it is true I do the spashscreen activities and if it is false I proceed to MAINAPP activity.
Hope it helps.
public class SplashScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen);
SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
boolean firstRun = settings.getBoolean("FIRST_RUN", true);
if (firstRun) {
showDialog(INITIAL_DLG);
} else {
startActivity(new Intent(appContext, MAINAPP.class));
}
}
/***
* First entry after YES on Dialog!
*/
protected void initialize() {
messageTV.setVisibility(TextView.VISIBLE);
progressBar.setVisibility(ProgressBar.VISIBLE);
downloadThread = new DownloadFiles();
downloadThread.execute();
}
protected void rollback() {
}
#Override
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder builder;
switch (id) {
case INITIAL_DLG:
builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.app_setup)
.setCancelable(false)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
initialize();
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDlg = builder.create();
return alertDlg;
default:
return null;
}
}
protected class DownloadFiles extends AsyncTask<String, Integer, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
//file download
} catch (Exception e) {
result = false;
}
return true;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
unzipThread = new DecompressZipFile();
unzipThread.execute();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
messageTV.setText("Step 1/4:Downloading data...");
progressBar.setProgress(0);
progressBar.setMax(100);
super.onPreExecute();
}
}
protected class DecompressZipFile extends AsyncTask<String, Integer, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
//unzip files
return true;
} catch(Exception e) {
return false;
}
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (values[0]<0) progressBar.setMax(values[0]*-1);
else progressBar.setProgress(values[0]);
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
moveDBThread = new MoveDBFile();
moveDBThread.execute();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
messageTV.setText("Step 2/4:Decompressing data...");
progressBar.setProgress(0);
progressBar.setMax(100);
super.onPreExecute();
}
}
protected class MoveDBFile extends AsyncTask<String, Integer, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
//moving files
return true;
} catch (Exception e) {
globalE = e;
finish();
return false;
}
}
#Override
protected void onPreExecute() {
messageTV.setText("Step 3/4:Shufflin'...");
progressBar.setProgress(0);
progressBar.setMax(100);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (result) {
getSharedPreferences(PREFS_NAME,0).edit().putBoolean("FIRST_RUN", false).commit();
startActivity(new Intent(appContext, MAINAPP.class));
} else {
rollback();
}
}
}
}

Android AsyncTask problem

I have a string that I want to update using AsyncTask class
here is my code:
public class MainActivity extends Activity{
private String str = "oldString";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getString();
}
private void getString(){
new CustomTask().execute();
}
private class CustomTask extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
Log.i("Lesson3", "doInBackground method");
str = "newString";
return "someString";
}
protected void onPostExecute(String s){
Log.i("Lesson3", "onPostExecute method");
}
}
onPostExecute method is not called, thats the problem??
Thanks
Answer is simple,
#Override
protected void onPostExecute(String s){
Log.i("Lesson3", "onPostExecute method");
}
You forgot your #Override the execute calls onPostExecute of the super class since it has not been overridden as yet.
public class MainActivity extends Activity {
private String str = "oldString";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getString();
}
private void getString() {
new CustomTask().execute();
}
private void postExecuteCallback() {
Log.i("Lesson3", "String after callback: " + str );
}
private class CustomTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
Log.i("Lesson3", "doInBackground method");
str = "newString";
return "someString";
}
protected void onPostExecute(String s) {
Log.i("Lesson3", "onPostExecute method");
postExecuteCallback();
}
}
}
Why have you decided it doesn't run? Following code works just fine (fixed syntax errors in yours):
package com.stackoverflow;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
public class Test extends Activity {
private String str = "oldString";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getString();
}
private void getString() {
new CustomTask().execute();
}
private class CustomTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
Log.i("Lesson3", "doInBackground method");
str = "newString";
return "someString";
}
protected void onPostExecute(String s) {
Log.i("Lesson3", "onPostExecute method");
}
}
}
How about having our own AsyncTask ?
Please have a look.
public abstract class CustomAsyncTask<Params, Progress, Result> {
private boolean isFinished = false;
private Result res;
protected void onPreExecute() {
}
protected void onPostExecute(Result result) {
}
protected void onProgressUpdate(Progress progress) {
}
protected abstract Result doInBackground(Params...params);
private void CheckAndUpdateUI()
{
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if(isFinished)
{
onPostExecute(res);
}
else
CheckAndUpdateUI();
}
},500);
}
public void execute(final Params...params)
{
onPreExecute();
//
CheckAndUpdateUI();
isFinished = false;
//
new Thread(new Runnable() {
#Override
public void run() {
res = doInBackground(params);
isFinished = true;
}
}).start();
}
}

Categories

Resources