onPreExexute method is not called - java

I'm trying to display a Toast when I call the AsyncTask class with new saveWithStickers(BaseActivity.this).execute(); to notify the user that the save process being started, when I run the code below the onPreExecute() method for some logical reason is not called so the Toast does not appear as well,is runOnUiThread the reason for this behavior?
#SuppressLint("StaticFieldLeak")
public class saveWithStickers extends AsyncTask<Void, File, File> {
File fileSaved;
Context mContext;
saveWithStickers(Context context) {
mContext = context;
}
#Override
protected File doInBackground(Void... voids) {
fileSaved = FileUtil.getNewFile(BaseActivity.this, "VAPOGRAM");
if (fileSaved != null)
runOnUiThread(() -> {
stickerView.save(fileSaved, true);
});
return fileSaved;
}
#SuppressLint("SetTextI18n")
#Override
protected void onPreExecute() {
super.onPreExecute();
content.setVisibility(View.GONE);
Toast.makeText(mContext, "saving ...", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(File file) {
super.onPostExecute(file);
}
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckPermissionUtil checkPermissionUtil = new CheckPermissionUtil(BaseActivity.this);
if (Build.VERSION.SDK_INT >= 23) {
if (checkPermissionUtil.checkPermission(1812)) {
new saveWithStickers(BaseActivity.this).execute();
} else
checkPermissionUtil.requestPermission(1812);
} else {
new saveWithStickers(BaseActivity.this).execute();
}
}
});

Replace your code with this
#SuppressLint("StaticFieldLeak")
public class saveWithStickers extends AsyncTask<Void, File, File> {
File fileSaved;
Context mContext;
saveWithStickers(Context context) {
mContext = context;
}
#Override
protected File doInBackground(Void... voids) {
fileSaved = FileUtil.getNewFile(BaseActivity.this, "PHOTO EDITOR");
if (fileSaved != null)
runOnUiThread(() -> stickerView.save(fileSaved, true));
return fileSaved;
}
#SuppressLint("SetTextI18n")
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(mContext, "Saving ...", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(File file) {
super.onPostExecute(file);
}
}
To access to the context you need to pass it or use WeakRerefence to your parent activity

Related

void android.view.View.setVisibility(int) on a null object reference

i searched every directory and i dont see problem, please help me.
BlockquoteProcess:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setVisibility(int)' on a null object reference
at com.example.projectmanagement.wallet.CreateCashActivity.setViewOrUpdateWallet(CreateCashActivity.java:58)
at com.example.projectmanagement.wallet.CreateCashActivity.onCreate(CreateCashActivity.java:46) 
And my code:
public class CreateCashActivity extends AppCompatActivity {
private EditText inputWalletTitle, inputWalletSubtitle, inputWalletText;
private Wallet alreadyAvailableWallet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_wallet);
ImageView imageBack = findViewById(R.id.imageBack);
imageBack.setOnClickListener(v -> onBackPressed());
inputWalletTitle = findViewById(R.id.inputWalletTitle);
inputWalletSubtitle = findViewById(R.id.inputWalletSubtitle);
inputWalletText = findViewById(R.id.inputWalletText);
Button save_btn = findViewById(R.id.save_btn);
save_btn.setOnClickListener(v -> saveWallet());
ImageView imageSave = findViewById(R.id.imageSave);
imageSave.setOnClickListener(v -> saveWallet());
if (getIntent().getBooleanExtra("isViewOrUpdate", false)) {
alreadyAvailableWallet = (Wallet) getIntent().getSerializableExtra("wallet");
setViewOrUpdateWallet();
}
}
private void setViewOrUpdateWallet() {
inputWalletTitle.setText(alreadyAvailableWallet.getTitle());
inputWalletSubtitle.setText(alreadyAvailableWallet.getSubtitle());
inputWalletText.setText(alreadyAvailableWallet.getWalletText());
if (alreadyAvailableWallet != null) {
this.findViewById(R.id.layoutDeleteWallet).setVisibility(View.VISIBLE);
}
}
private void saveWallet() {
if (inputWalletTitle.getText().toString().trim().isEmpty()) {
Toast.makeText(this, "Uzupełnij kwotę oraz walutę!", Toast.LENGTH_SHORT).show();
return;
}
if (inputWalletSubtitle.getText().toString().trim().isEmpty()) {
Toast.makeText(this, "Brak zlecenia!", Toast.LENGTH_SHORT).show();
return;
}
if (inputWalletText.getText().toString().trim().isEmpty()) {
Toast.makeText(this, "Brak opisu wydatku!", Toast.LENGTH_SHORT).show();
return;
}
final Wallet wallet = new Wallet();
wallet.setTitle(inputWalletTitle.getText().toString());
wallet.setSubtitle(inputWalletSubtitle.getText().toString());
wallet.setWalletText(inputWalletText.getText().toString());
if (alreadyAvailableWallet != null) {
wallet.setId(alreadyAvailableWallet.getId());
}
#SuppressLint("StaticFieldLeak")
class SaveWalletTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
WalletDatabase.getDatebase(getApplicationContext()).walletDao().insertWallet(wallet);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
}
new SaveWalletTask().execute();
}
public void deleteText(View view) {
final LinearLayout layoutMiscellcash = findViewById(R.id.layoutDeleteWallet);
layoutMiscellcash.findViewById(R.id.layoutDeleteWallet).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
#SuppressLint("StaticFieldLeak")
class DeleteWalletTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
WalletDatabase.getDatebase(getApplicationContext()).walletDao()
.deleteWallet(alreadyAvailableWallet);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Intent intent = new Intent();
intent.putExtra("isWalletDeleted", true);
setResult(RESULT_OK, intent);
finish();
}
}
new DeleteWalletTask().execute();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (data != null) {
}
}
}
}
Logcat show line 58 and 46, this is:
this.findViewById(R.id.layoutDeleteWallet).setVisibility(View.VISIBLE);
and:
if (getIntent().getBooleanExtra("isViewOrUpdate", false)) { alreadyAvailableWallet = (Wallet) getIntent().getSerializableExtra("wallet"); setViewOrUpdateWallet(); }
I dont see problem in this. Please help.

Progress Dialog: android.view.WindowLeaked: has leaked window DecorView#6995336[] that was originally added here

I tried to change the orientation of my device on recycler view but it always crashes when progress dialog shows up.
How to solve this?
Here is my code:
private class LoadOrdersListAgent extends AsyncTask {
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(OrdersActivity.this);
ordersList = new ArrayList<>();
rvor = findViewById(R.id.recycler_view_orders_agent);
emptytv = findViewById(R.id.empty_view_orders_agent);
emptytv.setVisibility(View.GONE);
rvor.setHasFixedSize(true);
rvor.setLayoutManager(new LinearLayoutManager(OrdersActivity.this));
rvor.setItemAnimator(new DefaultItemAnimator());
dialog.setMessage("Loading....");
dialog.show();
}
#Override
protected void onPostExecute(Void aVoid) {
final OrdersAdapter adapter = new OrdersAdapter(getApplicationContext(), ordersList);
rvor.setAdapter(adapter);
rvor.setLayoutManager(new LinearLayoutManager(OrdersActivity.this));
srl.setRefreshing(false);
if (dialog.isShowing()) {
dialog.dismiss();
}
if (ordersList.isEmpty()) {
Log.d("TESTING.....", "LIST OF ORDERS ----->" + ordersList);
rvor.setVisibility(View.GONE);
srl.setVisibility(View.GONE);
emptytv.setVisibility(View.VISIBLE);
} else {
rvor.setVisibility(View.VISIBLE);
srl.setVisibility(View.VISIBLE);
emptytv.setVisibility(View.GONE);
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected Void doInBackground(Void... voids) {
ordersList = OrdersApi.getOrders(url, key);
return null;
}
}
private void swipeOrderLayout() {
srl = findViewById(R.id.swipe);
srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
if (new CheckNetworkUtil(OrdersActivity.this).isNetworkAvailable()) {
new LoadOrdersListAgent().execute();
// new LoadOrdersListAdmin().execute();
} else
Toast.makeText(OrdersActivity.this, "No Internet Connection!", Toast.LENGTH_SHORT).show();
srl.setRefreshing(false);
}
});
}
I got this error when i was Finishing/Destroying the activity without Dismissing progress Dialogue.
Solution use dialog.dismiss(); to dismiss the progress dialogue before destroying or pausing the activity
in your case remove the if condition and just call dialog.dismiss(); in postExecute method
Declare your ProgressDialog in Global using :
Add this code above onCreate() :
private ProgressDialog dialog;
Add this code within a onCreate():
dialog = new ProgressDialog(OrdersActivity.this);
dialog.setMessage("Loading....");
dialog.show();
Add this code within as onPreExecute method ,
if (!dialog.isShowing()) {
dialog.show();
}

How to show ProgressDialog when AsyncTask start gathering data from the server till when it gets all the data

I would like to make an app which displays some data from the server. When I log in as an admin, I would like there to be a progress dialog until the application gets all the data from the server.
I have 3 Classes. Main Activity(login screen), SecondActivity(displays data) and BackgroundWorker(which extends AsyncTask).
I know that in on postExecute I have to close ProgressBar
Override
protected void onPreExecute() {
if(activity.getClass() == MainActivity.class) {
this.progressDialog.setMessage("Please wait for a while.");
this.progressDialog.setTitle("Login");
this.progressDialog.show();
}
else
super.onPreExecute();
}
#Override
protected void onPostExecute(final String result) {
if(activity.getClass() == MainActivity.class) {
new CountDownTimer(1000, 500) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
System.out.println(result);
if (result.equals("Username or password is not correct")) {
alertDialog.setMessage(result);
alertDialog.show();
} else if(result.equals("is Admin")) {
Intent intent = new Intent(activity,Admin.class);
intent.putExtra("username",user);
activity.startActivity(intent);
activity.finish();
}
progressDialog.dismiss();
}
}.start();
}
I have made like this for login Screen but I don't think it is wise to delay the application on purpose. And also my implementation doesn't work if I call AsyncTask class twice in one activity. Any suggestion?
You can use this code:
class MyTask extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("loading");
pd.show();
}
#Override
protected Void doInBackground(Void... params) {
// Do your request
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pd != null)
{
pd.dismiss();
}
}
}
Take a look at this link, if you want!
Good luck with your android development!

ProgressDialog new Activity Asynctask is not showing, why?

I made a AsyncTask class with the following code
public class removeDialog extends AsyncTask<Void, Void, Void> {
Context c;
ProgressDialog asyncDialog;
String page;
public removeDialog(Context c, String page) {
this.c = c;
this.page = page;
asyncDialog = new ProgressDialog(c);
}
#Override
protected void onPreExecute() {
//set message of the dialog
asyncDialog.setTitle("Please wait");
asyncDialog.setMessage("Loading...");
asyncDialog.setCancelable(false);
//show dialog
asyncDialog.show();
if (page == "algemeneVoorwaarden") {
Intent intent = new Intent(c, algemeneVoorwaarden.class);
c.startActivity(intent);
}
if (page == "contact") {
Intent intent = new Intent(c, contactTest.class);
c.startActivity(intent);
}
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
//don't touch dialog here it'll break the application
//do some lengthy stuff like calling login webservice
return null;
}
#Override
protected void onPostExecute(Void result) {
//hide the dialog
asyncDialog.dismiss();
super.onPostExecute(result);
}
}
First time I tried:
on the first time I see an ProgressDialog, but the second time I want to open the activity I get nothing.
Second time I tried:
I get no ProgressDialog even the first time I try.
I execute my code in an AsyncTask class, code:
voorwaarden.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new removeDialog(c, "algemeneVoorwaarden").execute();
}
});
Does someone know why it isn't working? Please help me.
Your dialog will be dismissed as soon as it's shown, because your doInBackground is empty. Try adding a Thread.sleep() with a few seconds, just to simulate a delay.
Also, I suspect that the new activities you're starting will leave your dialog behind. So I would suggest you to test the code without these new activities for now.
public class RemoveDialog extends AsyncTask<Void, Void, Void> {
ProgressDialog asyncDialog;
public RemoveDialog(Context c) {
asyncDialog = new ProgressDialog(c);
}
#Override
protected void onPreExecute() {
//set message of the dialog
asyncDialog.setTitle("Please wait");
asyncDialog.setMessage("Loading...");
asyncDialog.setCancelable(false);
//show dialog
asyncDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
Thread.sleep(3000);
}
catch (InterruptedException ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
//hide the dialog
asyncDialog.dismiss();
super.onPostExecute(result);
}
}

Android AsyncTask runs multiple times

In my app ,there is an one button which get input from database.When I press it more than one in a short time it crashes.
How can i avoid this error with using asynctask?
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showinf();
}
});
}
private String[] columns={"name","surname"};
private void showinf(){
SQLiteDatabase db=v1.getReadableDatabase();
Cursor c=db.query("infos",columns,null,null, null,null,null);
Random mn2=new Random();
int count=c.getCount();
String mn=String.valueOf(count);
int i1=mn2.nextInt(count+1);
c.move(i1);
t1.setText(c.getString(c.getColumnIndex("name")));
t2.setText(c.getString(c.getColumnIndex("surname")));
}
thanks...
You can create a boolean flag (let's say bDiscardButtonAction), and set it to true in onPreExecute() and set it to false in onPostExecute(), something like:
public class FooTask extends AsyncTask<Foo, Foo, Foo>
{
private static boolean bDiscardButtonAction = false;
private boolean isDiscareded = false;
#Override
public void onPreExecute()
{
if(bDiscardButtonAction)
{
isDiscareded = true;
return;
}
bDiscardButtonAction = true;
}
#Override
public Foo doInBackground(Foo... params)
{
if(isDiscareded) return;
// ...
}
#Override
public void onPostExecute(Void result)
{
if(!isDiscareded) bDiscardButtonAction = false;
}
#Override
public void onCancelled(Foo result)
{
if(!isDiscareded) bDiscardButtonAction = false;
}
}
disable the show button in onPreExecute() and enable it back onPostExecute().
public class getAsyncDataTask extends AsyncTask<Void, Void, Void>
{
#Override
public void onPreExecute()
{
show.setAlpha(0.5);
show.setEnable(false);
}
#Override
public void doInBackground(Void... params)
{
//retrieve the data from db;
}
#Override
public void onPostExecute()
{
show.setAlpha(1.0);
show.setEnable(true);
}
}
I hope this code will help u out.
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
new AsynchTaskManualLocation().execute();
});
public class AsynchTaskGetData extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... url) {
//showinf(); this method contains operation of getting data from //database OR ur logic to getdata
return showinf();
}
#Override
protected void onPostExecute(String result) {
//here u get result in resul var and process the result here
}
}
}

Categories