I have problem with save current state in progress bar in SharedPreferences.
this is my code. Problem when go with this activity and next go out with activity agian ,progress bar don't count state with stay pervious.
private UpdateQrCode updateQrCode;
SharedPreferences sharedpreferences;
private static final String TIME = "Time";
method onCreate witch have
#Override
protected void onCreate(Bundle savedInstanceState) {
...
sharedpreferences = getSharedPreferences(mypreference, Context.MODE_PRIVATE);
if (sharedpreferences.contains(Time)) {
int currentInterval = sharedpreferences.getInt(TIME, 0);
progressBar.setMax(currentInterval);
progressBar.setProgress(currentInterval);
} else {
interval = Integer.parseInt(intervalTotpDecrypt);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
if (updateQrCode != null) {
updateQrCode.cancel(true);
}
}
//this class asyncTask with update progress bar
private class UpdateQrCode extends AsyncTask<Void, Integer, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setMax(interval);
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
secondTimeTextView.setText(String.valueOf(values[0]));
}
#Override
protected Integer doInBackground(Void... params) {
for (int i = interval; i >= 0; i--) {
publishProgress(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
try {
NewXorString = generateQrCodeString(otpDecrypt, path3Decrypt, intervalTotpDecrypt);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
generateNewString = Cryptography.xorHex(NewXorString);
UpdateQrCodeString(generateNewString);
updateQrCode.execute();
}
#Override
protected void onCancelled() {
super.onCancelled();
updateQrCode.cancel(true);
}
}
//method with save to sharedPreference
public void saveStateProgressBar() {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt(TIME, interval);
editor.commit();
}
are you using Editor to store values in shared preferences? e.g
SharedPreferences.Editor editor = prefs.edit();
editor.putString("progress", loadingProgress);
editor.commit();
Related
I found many subject about but I can't get a solution, I'm doing a soap request in doInBackground method of asyncTask, and I want to get an Integer to know if the process is done, here I call my asyncTask:
Simulation.AsyncSoapCall task = new Simulation.AsyncSoapCall();
try {
Integer taskResult = task.execute().get();
} catch (Exception e) {
e.printStackTrace();
}
My AsyncTask class:
private class AsyncSoapCall extends AsyncTask<Void, Void, Integer> {
Integer result;
Boolean isInternetPresent = false;
Boolean isUrlAvailable = false;
ConnectionDetector cd;
AsyncSoapCall(){
}
#Override
protected Integer doInBackground(Void... params) {
cd = new ConnectionDetector(getActivity().getApplicationContext());
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
String namespace = getResources().getString(R.string.NAMESPACE);
String url = getResources().getString(R.string.URL);
String soapaction = getResources().getString(R.string.SOAP_ACTION);
String login = getResources().getString(R.string.login);
String mdp = getResources().getString(R.string.mdp);
isUrlAvailable = cd.isUrlAvailable();
// check for Internet status
if (isUrlAvailable) {
String idApplication = Installation.id(getActivity());
SOAPContact soapContact = new SOAPContact(namespace, url, soapaction, login, mdp);
soapContact.saveParams(getResources().getString(R.string.origine), db);
result = 1;
} else {
result = 2;
}
} else {
result = 3;
}
return result;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
}
#Override
protected void onProgressUpdate(Void... values) {
Log.i(TAG, "onProgressUpdate");
}
}
I don't get error my app crasha at this line:
Integer taskResult = task.execute().get();
try to get the value from onPostExecute like
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
int yourNum = result;
}
that's it
Did you read the doc?
https://developer.android.com/reference/android/os/AsyncTask.html
AsyncTask has no "get" method.
You need to define a OnPostExecute method which will be called when your task is over with your Integer as a parameter.
public class MyActivity extends Activity
{
private Integer myInteger;
private void blabla(){
Simulation.AsyncSoapCall task = new Simulation.AsyncSoapCall() {
#Override
protected void onPostExecute(Integer result) {
//... Your code here ...
MyActivity.this.myInteger = result;
MyActivity.this.myMethod(result);
}
}
try {
task.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void myMethod(Integer integer){
}
}
Here is one method with the help of interfaces,
MainActivity.java
public class MainActivity extends AppCompatActivity {
static String TAG=MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AsyncSoapCall request = new AsyncSoapCall(new AsyncSoapCall.AsyncSoapInterface() {
#Override
public void callBack(String callBackValue) {
Log.d(TAG,callBackValue);
}
});
request.execute();
}
}
AsyncSoapCall.java
public class AsyncSoapCall extends AsyncTask<Void,Void,Void> {
interface AsyncSoapInterface{
void callBack(String callBackValue);
}
AsyncSoapInterface callbackObj;
AsyncSoapCall(AsyncSoapInterface callbackObj)
{
callbackObj = callbackObj;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
callbackObj.callBack("Your value");
}
}
I am trying to pull data from Microsoft Azure with this method. The problem is that it can sometimes be really slow, and I need these data in the shared preferences to do anything else in the application. How can I create a loading dialog that will wait for the data to be fetched? I tried putting this method in the AsyncTask doInBackground() method, but the dialog would just appear and then disappear after a millisecond. What is the right way to do this? I was reading similar topics on stackoverflow, but never found a solution.
Thank you!
private class LoadViewTask extends AsyncTask<String, Void, Boolean>
{
private ProgressDialog dialog;
private MainActivity activity;
public LoadViewTask(MainActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
private Context context;
#Override
protected void onPreExecute()
{
//Create a new progress dialog
dialog = ProgressDialog.show(MainActivity.this,"Loading...",
"", false, false);
}
//The code to be executed in a background thread.
#Override
protected Boolean doInBackground(final String... args)
{
try
{
mClient.invokeApi("getsettings", jObj, new ApiJsonOperationCallback() {
#Override
public void onCompleted(JsonElement result, Exception error,
ServiceFilterResponse response) {
SharedPreferences settings = getSharedPreferences("SettingsPrefs", 0);
SharedPreferences.Editor editor = settings.edit();
if (error != null) {
System.out.println("Error");
} else {
JsonObject res = result.getAsJsonObject();
try {
if(res.get("gender").toString().equals("null")){
userGender = res.get("gender").toString();
editor.putString("gender", userGender);
} else {
int index1 = res.get("gender").toString().indexOf("\"");
int index2 = res.get("gender").toString().lastIndexOf("\"");
editor.putString("gender", res.get("gender").toString().substring(index1+1, index2));
}
if(res.get("dob").toString().equals("null")){
userDob = res.get("dob").toString();
editor.putString("dob", userDob);
} else {
editor.putString("dob", res.get("dob").toString().substring(1, 11));
}
if (res.get("club").isJsonNull()) {
userClub = 0;
editor.putInt("userClub", userClub);
System.out.println("userclub is null in MA: "+userClub);
} else {
editor.putInt("userClub", res.get("club").getAsInt());
}
editor.commit();
} catch (Exception e) {
Log.e("Error: ", e.toString());
}
}
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final Boolean success)
{
//close the progress dialog
dialog.dismiss();
}
}
Just follow this steps
1) Create Method say loadDataFromServer() and put code inside
public void loadDataFromServer() {
dialog = ProgressDialog.show(MainActivity.this, "Loading...", "", false, false);
try {
mClient.invokeApi("getsettings", jObj, new ApiJsonOperationCallback() {
#Override
public void onCompleted(JsonElement result, Exception error, ServiceFilterResponse response) {
SharedPreferences settings = getSharedPreferences("SettingsPrefs", 0);
SharedPreferences.Editor editor = settings.edit();
if (error != null) {
System.out.println("Error");
} else {
JsonObject res = result.getAsJsonObject();
try {
if (res.get("gender").toString().equals("null")) {
userGender = res.get("gender").toString();
editor.putString("gender", userGender);
} else {
int index1 = res.get("gender").toString().indexOf("\"");
int index2 = res.get("gender").toString().lastIndexOf("\"");
editor.putString("gender", res.get("gender").toString().substring(index1 + 1, index2));
}
if (res.get("dob").toString().equals("null")) {
userDob = res.get("dob").toString();
editor.putString("dob", userDob);
} else {
editor.putString("dob", res.get("dob").toString().substring(1, 11));
}
if (res.get("club").isJsonNull()) {
userClub = 0;
editor.putInt("userClub", userClub);
System.out.println("userclub is null in MA: " + userClub);
} else {
editor.putInt("userClub", res.get("club").getAsInt());
}
editor.commit();
dialog.dismiss(); // / DISMISS DIALOG HERE
} catch (Exception e) {
Log.e("Error: ", e.toString());
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
2) Call this method like
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadDataFromServer();
}
3) dismiss dialog inside onCompleted() method. (I have added that line). just copy the method and call it.
Create a ProgressDialog and show() it before you call mClient.invokeApi and dismiss() it on onCompleted after you have done all the required processes
Try setting indeterminate to true,
//Create a new progress dialog
dialog = ProgressDialog.show(MainActivity.this,"Loading...",
"", true, false);
When I retrieve the value in results activity. I get nothing, I guess the the value is not being passed from doInBackground to onPostExecute. Any idea what's wrong? or am I passing it the wrong way
class calculateTask extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... params) {
Thread t= new Thread();
try {
t.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int pix=0;
int circ=0;
int width1=mBitmap.getWidth();
int height1=mBitmap.getHeight();
for(int i=0;i<width1;i++)
{
for(int j=0;j<height1;j++)
{
if(mBitmap.getPixel(i, j)==Color.WHITE)
{
pix++;
}
if(mBitmap.getPixel(i, j)==Color.LTGRAY)
{
circ++;
}
}
}
int percentage=100-((pix-circ))*100 ;
String p=intToChar(array,percentage);
return p;
}
#Override
protected void onPostExecute(String p) {
Intent i= new Intent(circle1.this,results.class);
i.putExtra("perc", p);
startActivity(i);
//super.onPostExecute(result);
}
}
public String intToChar(char[] array, int pix) {
// TODO Auto-generated method stub
String b="";
int i = array.length - 1;
while (pix > 0 && i >= 0) {
array[i--] = (char) (48 + pix % 10);
pix /= 10;
} b = new String(array);
return b;
}
I would use a global variable. Then assign value to the global variable in doInBackground, and then retrieve it in onPostExecute.
EDIT:
Many things are wrong.
Here is one of my examples from code
private class Load extends AsyncTask<Void, Void, Void>
{
private ProgressDialog progressDialog;
private Context context;
private boolean internet, refresh;
public Load(Context context, boolean internet, boolean refresh)
{
this.internet = internet;
this.refresh = refresh;
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = ProgressDialog.show(context, null, "Loading data ...");
}
#Override
protected Void doInBackground(Void... voids)
{
taskComplete = false;
while (!taskComplete)
{
getData(this.internet);
try
{
Thread.sleep( 1000 );
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
populateData();
progressDialog.dismiss();
}
}
Try imitating this. getData sets taskComplete to true once it is done.
i am trying to access saved preferences from within an asynctask but i always keep getting the error "preferences can not be resolved". Any ideas? Here is a part of the code:
public class Login extends SherlockActivity {
SharedPreferences preferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
new LongOperationLogin(this).execute();
}
}
class LongOperationLogin extends AsyncTask<String, Void, String> {
private Login longOperationContext = null;
public LongOperationLogin(Login context) {
longOperationContext = context;
}
#Override
protected String doInBackground(String... params) {
//THIS IS WHERE I NEED THE VALUE
String username = this.preferences.getString("username", "n/a");
try {
//JSON fetching
}
} catch (MalformedURLException e) {
e.printStackTrace();
Log.v("Error", "URL exc");
} catch (IOException e) {
e.printStackTrace();
Log.v("ERROR", "IOEXECPTOIn");
} catch (JSONException e) {
e.printStackTrace();
Log.v("Error", "JsonException");
}
return null;
}
#Override
protected void onPostExecute(String result) {
}
}
protected void onPreExecute() {
}
protected void onProgressUpdate(Void... values) {
}
}
Thanks in advance!
Robert
You should access your preferece variable with Login.this.preferences. Also make sure that your AsyncTask is an inner class (contained in Login).
Try this
String username = longOperationContext.preferences.getString("username", "n/a");
and make preferences field public
This is my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate");
setContentView(R.layout.list);
new GetBlockListAsyncTask().execute(BlockListActivity.this);
}
public void initializeDialog() {
dialog = ProgressDialog.show(BlockListActivity.this, "", "Loading data. Wait...", true);
dialog.show();
}
public void dismissDialog(){
dialog.dismiss();
}
The GetBlockListAsyncTask:
public class GetBlockListAsyncTask extends AsyncTask<Object, Boolean, String>{
private BlockListActivity callerActivity;
private String TAG = "GetBlockListAsyncTask";
private String stringCode = "";
#Override
protected String doInBackground(Object... params) {
callerActivity = (BlockListActivity)params[0];
try {
Log.d(TAG, "Start to sleep");
Thread.sleep(4000);
Log.d(TAG, "End sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
callerActivity.dismissDialog();
}
#Override
protected void onPreExecute() {
callerActivity.initializeDialog();
}
}
It will show error:
'Caused by: java.lang.NullPointerException'
onPreExecute(GetBlockListAsyncTask.java:101)
I find a solution is that if I move the initializeDialog out of the AsyncTask and put it before the line new GetBlockListAsyncTask().execute(BlockListActivity.this); in onCreate, it works.
The question is how to make it work if I want to put the initializeDialog in the AsyncTask .
Try adding a public constructor to your AsyncTask that accepts the Activity Context as the first argument:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create a new AsyncTask with the Activity Context
AsyncTask task = new GetBlockListAsyncTask(this);
// Execute the task
task.execute();
}
public class GetBlockListAsyncTask extends AsyncTask<Object, Boolean, String> {
private Context activityContext;
private String TAG = "GetBlockListAsyncTask";
private String stringCode = "";
//Constructor
public GetBlockListAsyncTask(Context c) {
// Store the activity context
activityContext = c;
}
#Override
protected String doInBackground(Object... params) {
try {
Log.d(TAG, "Start to sleep");
Thread.sleep(4000);
Log.d(TAG, "End sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
activityContext.dismissDialog();
}
#Override
protected void onPreExecute() {
activityContext.initializeDialog();
}
}