Queue_Flush Not flushing Text and speaking updated - java

I read many blogs but still facing issue with speaking of updated text string after calling shutdown. Next time clicking on play, will speak old string and new one after other. Here is the code:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.batful);
try {
editor = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit();
// editor.putBoolean("b", true).apply();
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
value = sharedPreferences.getString("personalmessage", null);
Log.e("Voice Message create: ", value);
value = sharedPreferences.getString("personalmessage", null);
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
if (i != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.ENGLISH);
/* textToSpeech.setLanguage(Locale.getDefault());*/
final Handler h = new Handler();
h.postDelayed(new Runnable() {
public void run() {
if (Build.VERSION.SDK_INT >= 21) {
textToSpeech.speak(value, TextToSpeech.QUEUE_FLUSH, null, null);
} else {
textToSpeech.speak(value, TextToSpeech.QUEUE_FLUSH, null);
}
h.postDelayed(this, delay);
}
}, delay);
}
}
});
stopvol = (TextView)
findViewById(R.id.stop);
stopvol.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
turnoffbeep(getApplicationContext());
finish();
}
});
} catch (
Exception e)
{
e.printStackTrace();
}
}
static void turnoffbeep(Context contextforstat) {
Log.i(TAG, "Turn Off beep");
if ((textToSpeech != null)) {
// textToSpeech.stop();
textToSpeech.shutdown();
}
}
If u see QUEUE_FLUSH is added but results are not achieved. Looking at Android documentation, I believe I m following correct. Still If someone help me in looking for correct reason for not dropping old text, pls
Just got other fact if I change input from shared preference to edit text , it is speaking latest text not old.

after R&D got issue, it was handler which are creating mess and picking old text. As shutdown do not cancel handler and replay was adding another handler to existing.

Related

Android Studio - How can I trigger an intent when an 'if' is fulfilled

I've managed to get a qr scanner powered by google vision working and placing the qrcode into a text view on the same activity.
The end goal is to have the url in the qrcode open up in a webview in another activity (QRWebActivity) as soon as a qrcode is detected.
At this stage I was able to move the qrcode into a string and push across and open in the webview using intents activated by sendMessage2 on button click.
But I really want to find a way to have it just automatically open the QRWebActivity and send the webview to the qrCode on 'if(qrCodes.size()!=0).
Any help would be amazing.
Really sorry if I'm not using the right terminology, I just don't know what I'm doing but really keen to finish this app by the end of the week for release and I'm so close.
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrCodes = detections.getDetectedItems();
if(qrCodes.size()!=0)
{
textView.post(new Runnable() {
#Override
public void run() {
Vibrator vibrator = (Vibrator)getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
textView.setText(qrCodes.valueAt(0).displayValue);
}
});
}
}
});
}
public void sendMessage2 (View view)
{
String qrmessage = textView.getText().toString();
Intent intent2 = new Intent(view.getContext(),QRWebActivity.class);
intent2.putExtra("EXTRA_QRMESSAGE",qrmessage);
startActivity(intent2);
}
}
If I could just simulate pressing the button and triggering 'sendMessage2' when qrCodes !=0 that would do me... even though I'm sure there's a more elegant way.
From your code, here is my solution:
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrCodes = detections.getDetectedItems();
if (qrCodes.size() != 0) {
textView.post(new Runnable() {
#Override
public void run() {
Vibrator vibrator = (Vibrator)getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
textView.setText(qrCodes.valueAt(0).displayValue);
sendMessage2(textView);
}
});
}
}
All the code is already there, just dont split it up:
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrCodes = detections.getDetectedItems();
if(qrCodes.size()!=0)
{
Intent intent2 = new Intent(view.getContext(),QRWebActivity.class);
intent2.putExtra("EXTRA_QRMESSAGE",qrCodes.valueAt(0).displayValue);
startActivity(intent2);
textView.post(new Runnable() {
#Override
public void run() {
Vibrator vibrator = (Vibrator)getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
textView.setText(qrCodes.valueAt(0).displayValue);
}
});
}
}

Save Boolean state while restarting the application

I have 6 boolean variables which I have initialized as false. There are 6 different imageviews which are associated with these 6 boolean false variables. When the user clicks any of these image, there respective boolean variable is switched to true and when the user again clicks the same image, it will turn to false like on and off. After being satisfied with the selected options, the user can click the done button and the data will be save in the firebase accordingly to whether which options are true and which are false.
My problem is that whenever the application is restarted, all boolean variables are again initialized to false, I understand the fact that, the application restarts for OnCreate class due to which the variables are again false. How can I write a certain code which can save the state of these variables even after application restarts?
Below is my Code:
boolean checkcar = false, checkPickUp = false, checkTruck = false, checkCycle = false, checkBike = false, checkMen = false;
private FirebaseAuth firebaseAuth;
private String currentUserID;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
myTransport = inflater.inflate(R.layout.fragment_transport, container, false);
firebaseAuth = FirebaseAuth.getInstance();
currentUserID = firebaseAuth.getCurrentUser().getUid();
carImage = myTransport.findViewById(R.id.carTransport);
pickUpImage = myTransport.findViewById(R.id.pickUpTransport);
truckImage = myTransport.findViewById(R.id.truckTransport);
cycleImage = myTransport.findViewById(R.id.cyclerTransport);
bikeImage = myTransport.findViewById(R.id.bikeTransport);
menImage = myTransport.findViewById(R.id.menTransport);
done = myTransport.findViewById(R.id.selectUserTransportBtn);
transport = FirebaseDatabase.getInstance().getReference().child("UserProfileDetails").child(currentUserID).child("Transport");
MarkUserRegisteredTransport();
carImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!checkcar) {
carImage.setColorFilter(carImage.getContext().getResources().getColor(R.color.TransportAfterClicked), PorterDuff.Mode.SRC_ATOP);
checkcar = true;
} else {
carImage.setColorFilter(carImage.getContext().getResources().getColor(R.color.colorAccent), PorterDuff.Mode.SRC_ATOP);
checkcar = false;
}
}
});
pickUpImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!checkPickUp) {
pickUpImage.setColorFilter(pickUpImage.getContext().getResources().getColor(R.color.TransportAfterClicked), PorterDuff.Mode.SRC_ATOP);
checkPickUp = true;
} else {
pickUpImage.setColorFilter(pickUpImage.getContext().getResources().getColor(R.color.colorAccent), PorterDuff.Mode.SRC_ATOP);
checkPickUp = false;
}
}
});
truckImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!checkTruck) {
truckImage.setColorFilter(truckImage.getContext().getResources().getColor(R.color.TransportAfterClicked), PorterDuff.Mode.SRC_ATOP);
checkTruck = true;
} else {
truckImage.setColorFilter(truckImage.getContext().getResources().getColor(R.color.colorAccent), PorterDuff.Mode.SRC_ATOP);
checkTruck = false;
}
}
});
cycleImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!checkCycle) {
cycleImage.setColorFilter(cycleImage.getContext().getResources().getColor(R.color.TransportAfterClicked), PorterDuff.Mode.SRC_ATOP);
checkCycle = true;
} else {
cycleImage.setColorFilter(cycleImage.getContext().getResources().getColor(R.color.colorAccent), PorterDuff.Mode.SRC_ATOP);
checkCycle = false;
}
}
});
bikeImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
menImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!checkMen) {
menImage.setColorFilter(menImage.getContext().getResources().getColor(R.color.TransportAfterClicked), PorterDuff.Mode.SRC_ATOP);
checkMen = true;
} else {
menImage.setColorFilter(menImage.getContext().getResources().getColor(R.color.colorAccent), PorterDuff.Mode.SRC_ATOP);
checkMen = false;
}
}
});
here is when user can click done and the information is updated in the firebase with true or false with their res
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HashMap userTransport = new HashMap();
userTransport.put("check Car", checkcar);
userTransport.put("check PickUp", checkPickUp);
userTransport.put("check Truck", checkTruck);
userTransport.put("check Cycle", checkCycle);
userTransport.put("check bike", checkBike);
userTransport.put("check Men", checkMen);
transport.updateChildren(userTransport).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Toast.makeText(getContext(), "Transportation information updated", Toast.LENGTH_LONG).show();
} else {
String message = task.getException().getMessage();
Toast.makeText(getContext(), "Error Occured: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
});
return myTransport;
}
According to your comment:
well i needed the data to be stored even after the user deletes the application just like instagram and facebook
I would like to tell you that either SharedPreferences nor Bundle won't help in this case. Both tehniques when used, do not persist across application uninstalls. If you reinstall the app, your SharedPreferences or your Bundle will be empty and you will not be able to use any data at all.
To solve this, I recommend you add that data to database and everytime the user wants to update his preferences, change the data in database accordingly. So create six new properties of type boolean under your transport object and set/update them accordingly with user's choice.
You can use onSaveInstanceState to save the boolean values, and fetch the values in onCreate or onRestoreInstanceState.
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("boolean1", booleanValue1);
outState.putString("boolean2", booleanValue2); //and so on
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if(savedInstanceState!=null){
if(getString("boolean1") != null){
booleanValue1 = savedInstanceState.getString("boolean1");
}
}
}
Use SharedPreferences, if the application is killed the values saved will not be deleted or reset.
PreferenceManager mManager = PreferenceManager.getDefaultSharedPreferences(context);
//example methods
public static boolean getBool(String resName, boolean defValue) {
return mManager.getBoolean(resName, defValue);
}
public static void setBool(String resName, boolean value) {
mManager.edit()
.putBoolean(resName, value)
.apply();
}
PS: Well, if you uninstall the app or delete the app data (in "Settings", for example) datas will be destroyed

Chrome Custom Tabs pre-load webpages while browsing?

I'm testing the Chrome Custom Tabs. It is supposed to preload webpages a user is likely to click in the background. This happens through calling
session.mayLaunchUrl(uri, null, null);
While the MainActivity is active, the webpage is preloaded nicely and when launching the URL, the webpage loads quickly as expected.
However I would like to serve other webpages automatically to the user while he is already browsing (and the activity therefore is in background). Then, preloading the webpages does not seem to speed up the loading process anymore and even though the new served webpages are loading, this happens slowly.
I wrote a small app demonstrating this behavior. Preloading and launching an URL manually works nicely (as the activity is active, I suppose), serving new webpages in a loop automatically is slow (as the activity is not active and the mayLaunchUrl method does not work as expected then).
Is it possible to make use of the pre-loading mechanism while the user is browsing already? If yes, how?
I added the MainActivity code as example below:
public class MainActivity extends AppCompatActivity {
private CustomTabsSession mCustomTabsSession;
private CustomTabsClient mClient;
private CustomTabsServiceConnection mConnection;
private EditText urlET;
private String TAG = "MainActivity";
private ArrayList<String> urlList;
private Thread cycleThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v("MainActivity", "onCreate");
urlList = new ArrayList<>();
urlList.add("http://www.google.com");
urlList.add("https://github.com");
urlList.add("http://stackoverflow.com");
urlList.add("http://www.heise.de");
// pre launch the chrome browser, bind services etc
warmup();
urlET = (EditText) findViewById(R.id.urlID);
// pre load a webpage manually
Button prepareBt = (Button) findViewById(R.id.prepareBt);
assert prepareBt != null;
prepareBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mayLaunch(null);
}
});
//launch webpage manually
Button launchBt = (Button) findViewById(R.id.launchBt);
assert launchBt != null;
launchBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launch(null);
}
});
//start a loop that serves webpages every 10 seconds
Button cycleBt = (Button) findViewById(R.id.cycleBt);
assert cycleBt != null;
cycleBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(cycleThread !=null)
cycleThread.interrupt();
cycleThread = new Thread(cycle);
cycleThread.start();
}
});
}
private Runnable cycle = new Runnable() {
#Override
public void run() {
int i = 0;
mayLaunch(Uri.parse(urlList.get(i)));
try {
Thread.sleep(5000);
while (true){
try {
Log.d(TAG, "launch: "+urlList.get(i));
launch(Uri.parse(urlList.get(i)));
i++;
if(i>=urlList.size())
i=0;
Thread.sleep(5000);
Log.d(TAG, "prepare: "+urlList.get(i));
mayLaunch(Uri.parse(urlList.get(i)));
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
private void mayLaunch(Uri uri){
if(uri ==null)
uri = Uri.parse(urlET.getText().toString());
CustomTabsSession session = getSession();
session.mayLaunchUrl(uri, null, null);
}
private void launch(Uri uri){
if(uri ==null)
uri = Uri.parse(urlET.getText().toString());
CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder(getSession())
.setToolbarColor(ContextCompat.getColor(this, R.color.colorPrimaryDark))
.setShowTitle(true)
.setStartAnimations(this, android.R.anim.slide_in_left, android.R.anim.slide_out_right)
.setExitAnimations(this, android.R.anim.slide_in_left, android.R.anim.slide_out_right)
.build();
customTabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
customTabsIntent.launchUrl(this,uri);
}
public CustomTabsSession getSession() {
if (mClient == null) {
mCustomTabsSession = null;
} else if (mCustomTabsSession == null) {
mCustomTabsSession = mClient.newSession(null);
Log.d(TAG, "getSession: created new session");
}
return mCustomTabsSession;
}
private void warmup(){
if (mClient != null) return;
String packageName = "com.android.chrome";
if (packageName == null) return;
mConnection = new CustomTabsServiceConnection() {
#Override
public void onCustomTabsServiceConnected(ComponentName componentName, CustomTabsClient customTabsClient) {
mClient = customTabsClient;
mClient.warmup(0L);
}
#Override
public void onServiceDisconnected(ComponentName name) {
mClient = null;
mCustomTabsSession = null;
}
};
CustomTabsClient.bindCustomTabsService(this, packageName, mConnection);
}
private void coolDown(){
if (mConnection == null) return;
unbindService(mConnection);
mClient = null;
mCustomTabsSession = null;
mConnection = null;
}
public void onDestroy() {
Log.v("MainActivity", "onDestroy");
super.onDestroy();
coolDown();
}
#Override
public void onBackPressed(){
}
}
Thanks!
CustomTabs ignores mayLaunchUrl() sent from the background. This is for 2 reasons:
Simple measure to avoid wasted bandwidth (it is easy to check that a custom tab from the same session is not the foreground, just did not do it yet)
Pages loaded through mayLaunchUrl() currently do not preserve Window.sessionStorage(), which is not a problem for App -> CustomTab transition, but for navigating within a single CustomTab this may break assumptions for users with navigation patterns like:
SiteA -> SiteB -> SiteA
(the second visit to SiteA does not see what is in the session). Teaching mayLaunchUrl() to choose the right sessionStorage() is complex, no plans for this yet.

Update GUI after purchase of an IAP is complete, IAPv3 - Android

I finally figured out how to consume an IAP in v3 of the InAppBilling API. The user can now constantly consume as many products as they please.
Now I want the GUI for the user to be updated once the purchase is confirmed complete. I have put Toasts all over the below code to try and find out where to update the GUI at but I have yet to have a Toast appear yet. But remember that the consuming of the IAPs work.
I have identified in my code below the snippet that updates the GUI for the user. That snippet of code is what I want run AFTER a successful purchase is complete.
So my question is where to put that snippet of code so that the GUI is updated for the user after a successful purchase.
public class Levels extends SwarmActivity {
//static final String SKU_BUYLIVES = "buy5lives";
static final String SKU_BUYLIVES = "android.test.purchased";
IabHelper mHelper;
IInAppBillingService mService;
#Override
public void onCreate(Bundle savedInstanceState) {
moreLives = (Button)findViewById(R.id.moreLives);
moreLives.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
buyLives();
}
});
}
public void buyLives() {
final Dialog dialog = new Dialog(c);
dialog.setContentView(R.layout.buylives);
String base64EncodedPublicKey = a + b + d + e + f + g + h + i + j + k;
TextView title = (TextView)dialog.findViewById(R.id.question);
Button no = (Button)dialog.findViewById(R.id.no);
Button yes = (Button)dialog.findViewById(R.id.yes);
title.setText(c.getResources().getString(R.string.buyLivesQuestion));
no.setText(c.getResources().getString(R.string.maybelater));
yes.setText(c.getResources().getString(R.string.buy));
// Create the helper, passing it our context and the public key to verify signatures with
mHelper = new IabHelper(Levels.this, base64EncodedPublicKey);
// start setup. this is asynchronous and the specified listener will be called once setup completes.
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
// there was a problem.
complain("An error has occurred. We apologize for the inconvenience. " + c.getResources().getString(R.string.problem1) + " " + result);
return;
}
// IAB is fully set up. Now, let's get an inventory of stuff we own.
mHelper.queryInventoryAsync(mGotInventoryListener);
}
});
yes.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
mHelper.launchPurchaseFlow(Levels.this, SKU_BUYLIVES, 10001, mPurchaseFinishedListener, "payload");
dialog.dismiss();
// the below ~14 lines is the code that I want to call to update the GUI for the user. this block of code has been all over the place. this is just the last spot I tested it at.
SharedPreferences settings = getSharedPreferences("level_SP", 0);
livesCount = settings.getInt("livesTotal1", 0);
remainderTimeStamp = settings.getLong("remainderTimeStamp1", 0);
livesCount = 5;
remainderTimeStamp = 0;
SharedPreferences.Editor editor = settings.edit();
editor.putInt("livesTotal1", livesCount);
editor.putLong("remainderTimeStamp1", remainderTimeStamp);
editor.commit();
livesCountTV.setText(c.getResources().getString(R.string.livesCount) + " " + livesCount);
livesCounterTV.setText(c.getResources().getString(R.string.livesCounter) + " FULL!");
}
});
no.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
dialog.dismiss();
}
});
dialog.show();
}
// listener that's called when we finish querying the items and subscriptions we own.
IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
if(result.isFailure()) {
complain(c.getResources().getString(R.string.sorryerror) + c.getResources().getString(R.string.failedtoquery) + " " + result);
return;
} else if(inventory.hasPurchase(SKU_BUYLIVES)) {
mHelper.consumeAsync(inventory.getPurchase(SKU_BUYLIVES), null);
}
}
};
// callback for when a purchase is finished
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
// this appears to the user immediately after purchasing.
if(result.isFailure()) {
complain(c.getResources().getString(R.string.sorryerror) + result);
} else if(purchase.getSku().equals(SKU_BUYLIVES)) {
alert(c.getResources().getString(R.string.livesbought));
try {
Bundle ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null);
int response = ownedItems.getInt("RESPONSE_CODE");
if (response == 0) {
// success
Toast.makeText(Levels.this, "SUCCESS", Toast.LENGTH_LONG).show();
try {
mService.consumePurchase(3, getPackageName(), SKU_BUYLIVES);
// this Toast is never seen.
Toast t = Toast.makeText(Levels.this, "PURCHASE CONSUMED", Toast.LENGTH_LONG);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
// error
// this Toast is never seen.
Toast.makeText(Levels.this, "ERROR", Toast.LENGTH_LONG).show();
}
} catch (RemoteException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return;
}
};
void complain(String message) {
alert("Error: " + message);
}
void alert(String message) {
AlertDialog.Builder bld = new AlertDialog.Builder(this);
bld.setMessage(message);
bld.setNeutralButton("OK", null);
bld.create().show();
}
#Override
public void onDestroy() {
super.onDestroy();
if(mHelper != null) mHelper.dispose();
mHelper = null;
}
}
To open Google Play purchase dialog you should have used startIntentSenderForResult() method with your purchase intent. Once user is done with this dialog, onActivityResult() gets called on your activity. This is the place where you should verify the purchase and update GUI if needed.
This is an example of how you open purchase dialog.
public void buyProduct() {
PendingIntent buyIntent = ... // create your intent here
IntentSender sender = buyIntent.getIntentSender();
try {
startIntentSenderForResult(sender, REQ_BUY_PRODUCT, new Intent(), 0, 0, 0);
} catch (SendIntentException e) {
Log.e(TAG, "", e);
}
}
This is example of how to handle purchase intent
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQ_BUY_PRODUCT && resultCode == Activity.RESULT_OK) {
// here you verify data intent and update your GUI
...
return;
}
}
Both methods belong to your activity.

problem setting progress bar before alert dialog which has a spinner

public class classified extends Activity
{
private ArrayAdapter<String> aaagency ;
String strdata="";
String strerrormess="";
public void onCreate(Bundle savedInstanceState)
{
setTitle("Classified Ad. Booking");
super.onCreate(savedInstanceState);
this.setContentView(R.layout.classified);
}
public void srcAgency(View view) throws IOException
{
Log.i("Classified Ad","srcAgency");
new srcAgency().execute();
srcAgency srcagen = new srcAgency();
strdata = srcagen.strtempdata;
Log.i("AgencyData2", strdata);
Log.i("AgencyData3", strerrmess);
if(strerrmess.equals(""))
{
strarr= fun1.split(strdata, "^");
aaagency = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item , strarr);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Agency");
builder.setAdapter(aaagency, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
txtAgency.setText(strarr[item]);
}
});
builder.show();
}
}
class srcAgency extends AsyncTask<Void, String, Void>
{
String strtempdata="";
ProgressDialog dialog;
#Override
protected void onPreExecute()
{
strerrmess="";
super.onPreExecute();
dialog = ProgressDialog.show(classified.this, "", "Please wait...", true);
dialog.show();
}
#Override
protected Void doInBackground(Void... unused)
{
try
{
stragency = txtAgency.getText().toString().trim();
intagencyBrac1= stragency.lastIndexOf('(');
intagencyBrac2= stragency.lastIndexOf(')');
if (stragency.length() < 3)
{strerrmess="Please Enter atleast 3 Characters for Agency Searching";}
else if(intagencyBrac1>=0||intagencyBrac2>=0)
{strerrmess="Please Enter Characters for Agency Searching";}
else
{
if(stragency.indexOf(' ')!=-1)
{stragency = stragency.replace(' ', '!');}
Log.i("AgencyUrl",strurl);
strdata = "Client1^Client2^Client3^Client4^Client5^Client6^Client1";
Log.i("AgencyData",strdata);
strtempdata = strdata;
if(!strdata.equals(""))
{
}
else
{strerrmess ="No Data Available";}
}
}
catch(Exception e)
{
}
return null;
}
#Override
protected void onPostExecute(Void unused)
{
dialog.dismiss();
if (strerrmess.equals("Please Enter atleast 3 Characters for Agency Searching"))
{Toast(strerrmess);intflag=1;}
else if(strerrmess.equals("Please Enter Characters for Agency Searching"))
{Toast(strerrmess);intflag=1;}
else if(strerrmess.equals("Your Session Got Expired. Please login again."))
{
Intent intent = new Intent(classified.this, loginscreen.class);
startActivity(intent);
Toast(strerrmess);
intflag=1;
}
else
{intflag=0;}
}
}
}
I am unable to get the value of strdata which i have initialized in asynctask function in the srcagency function. What should I do? Even though strdata is a global variable.
I have also tried this but I think you can't initialize array adapter in onpostexecute function...
#Override
protected void onPostExecute(Void unused)
{
dialog.dismiss();
if (strerrmess.equals("Please Enter atleast 3 Characters for Agency Searching"))
{Toast(strerrmess);intflag=1;}
else if(strerrmess.equals("Please Enter Characters for Agency Searching"))
{Toast(strerrmess);intflag=1;}
else if(strerrmess.equals("Your Session Got Expired. Please login again."))
{
Intent intent = new Intent(classified.this, loginscreen.class);
startActivity(intent);
Toast(strerrmess);
intflag=1;
}
else
{strarr= fun1.split(strdata, "^");
aaagency = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item , strarr);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Agency");
builder.setAdapter(aaagency, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
txtAgency.setText(strarr[item]);
}
});
builder.show();}
}
Any help or comments would be appreciated.
Thanks
Log.i("Classified Ad","srcAgency");
new srcAgency().execute();
srcAgency srcagen = new srcAgency();
strdata = srcagen.strtempdata;
This does not work. You are saying, start an AsyncTask that will set your strdata at some point in the future but also immediately return and after creating a new AsyncTask have it know what the last AsyncTask did.
Try this:
void srcAgency(View v){
//We only want to start the AsyncTask here, nothing else.
// Whatever you did before and whatever triggered the srcAgency(View) method
srcAgency srcagen = new srcAgency();
srcagen.execute();
return;
}
public void realSrcAgency(View v) {
... // The rest of original srcAgency(View)
}
// Inside of asyncTask srcAgency ...
public void postExecute() {
// Call the new method we just had, but after our asyncTask is done.
realSrcAgency(null);
}
Basically you can't expect all these things to happen simultaneously. It would be easy to help you if you trimmed down the specifics of your code. It looks like you just want a button or some click to start an async task that fills a strings. However after that string is filled do something else with it. Also I don't believe you need an async task for any of this.

Categories

Resources