Data from Google Drive's Appdata folder is disappearing - java

I'm trying to create Spreadsheet file in Google Drive's Appdata folder for my aplication, to use it as a remote database.
Just at the beggining and I'm stuck already. Files are created properly(?), but they seems to be dissapearing after a moment.
I'm doing it like this:
First, on onCreate method I log into my Google Account:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_APPFOLDER)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.addApi(Drive.API)
.addConnectionCallbacks(this)
.build();
signIn();
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
onActivityResult handles updating UI(displaying user's name and profile pic, all works great on the login/logout side)
Then, in onConnected(Bundle bundle) method, I try to find out if user already has existing database in AppFolder, if not, I'm asking him to create one.
#Override
public void onConnected(Bundle bundle) {
queryDrive();
}
public void queryDrive() {
Query query = new Query.Builder().addFilter(Filters.eq(SearchableField.TITLE, DreamDbSchema.NAME_REMOTE)).build();
Drive.DriveApi.query(mGoogleApiClient, query).setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() {
#Override
public void onResult(DriveApi.MetadataBufferResult metadataBufferResult) {
MetadataBuffer buffer = metadataBufferResult.getMetadataBuffer();
if (buffer != null) {
if (buffer.getCount() == 0) {
new AlertDialog.Builder(ListActivity.this).setTitle(R.string.no_database_on_gdrive)
.setMessage(R.string.no_database_on_gdrive_message)
.setCancelable(false)
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(driveContentsCallback);
}
})
.setNeutralButton(R.string.cancel_and_disconnect, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
signOut();
}
})
.show();
} else {
for (int i = 0; i < buffer.getCount(); i++) {
Log.d("DRIVE_FILES: ", buffer.get(i).getTitle());
}
}
} else {
Log.d("DRIVE_BUFFER: ", "null");
}
}
});
}
final private ResultCallback<DriveApi.DriveContentsResult> driveContentsCallback =
new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Toast.makeText(ListActivity.this, R.string.error_while_creating_GDrive_file, Toast.LENGTH_SHORT).show();
return;
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(DreamDbSchema.NAME_REMOTE)
.setMimeType("vnd.google-apps.spreadsheet")
.build();
Drive.DriveApi.getAppFolder(mGoogleApiClient)
.createFile(mGoogleApiClient, changeSet, result.getDriveContents())
.setResultCallback(fileCallback);
}
};
final private ResultCallback<DriveFolder.DriveFileResult> fileCallback = new
ResultCallback<DriveFolder.DriveFileResult>() {
#Override
public void onResult(DriveFolder.DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
Toast.makeText(ListActivity.this, R.string.error_while_creating_GDrive_file, Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(ListActivity.this, getString(R.string.database_created_GD), Toast.LENGTH_SHORT).show();
}
};
Everything seems to be working good for about 10 minutes. In another activity I can successfully remove this file like this:
#Override
public void onClick(View v) {
if (!mGoogleApiClient.isConnected()) {
Toast.makeText(SettingsActivity.this, R.string.not_loged_in, Toast.LENGTH_SHORT).show();
} else {
Drive.DriveApi.getAppFolder(mGoogleApiClient).listChildren(mGoogleApiClient).setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() {
#Override
public void onResult(final DriveApi.MetadataBufferResult metadataBufferResult) {
Log.d("DRIVE_FILES: ", String.valueOf(metadataBufferResult.getMetadataBuffer().getCount()));
for (int i = 0; i < metadataBufferResult.getMetadataBuffer().getCount(); i++) {
final int j = i;
DriveId fileId = metadataBufferResult.getMetadataBuffer().get(i).getDriveId();
Drive.DriveApi.getFile(mGoogleApiClient, fileId).delete(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
Toast.makeText(SettingsActivity.this, R.string.database_removed_GD, Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}
}
and it also prints in log "1" for a while. But give it a ten minutes or so, and I'm once again prompted to create database, because it finds Appdata folder to be empty.

Related

Google billing API automatically refunding in-app purchases even after being aknowledged

I tried looking at previous questions and answers but with no luck finding a real solution. I'm acknowledging purchases once they are processed although my users are still automatically refunded. Below is my whole purchase activity. It's a simple activity with a big button to purchase the app's full version. Anoter button to restore previous purchases. A third button to show some advice if users were not able to restore their purchase.
Any help would be appreciated!
public class BuyActivity extends AppCompatActivity {
Button unlock_button;
Button restore_purchase;
static final String PRODUCT_ID = "full_version";
private BillingClient billingClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buy);
unlock_button = findViewById(R.id.unlock_button);
restore_purchase = findViewById(R.id.restore_purchase);
billingClient = BillingClient.newBuilder(getApplicationContext())
.setListener((billingResult, list) -> {
// responds to all purchases that were already made
if (billingResult.getResponseCode()==BillingClient.BillingResponseCode.OK && list!= null) {
for (Purchase purchase:list){
if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED) {
acknowledge_purchase(purchase);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
features_unlocked();
}
},500);
} else {
Toast.makeText(getApplicationContext(), "ERROR OCCURRED", Toast.LENGTH_SHORT).show();
}
}
} else if (billingResult.getResponseCode()==BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED && list!=null) {
features_unlocked();
} else {
Toast.makeText(getApplicationContext(), "ERROR OCCURRED", Toast.LENGTH_SHORT).show();
}
})
.enablePendingPurchases()
.build();
connect_to_google();
restore_purchase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
restore_purchase();
}
});
unlock_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//launch_purchase_flow(productDetailsList.get(0));
Toast.makeText(getApplicationContext(), "CAN'T START THE PURCHASE PROCESS", Toast.LENGTH_SHORT).show();
}
});
}
void features_unlocked(){
App.get().MyTheme = 1;
Intent i = new Intent(BuyActivity.this, Unlocked_celebration.class);
startActivity(i);
finish();
}
void connect_to_google(){
billingClient.startConnection(new BillingClientStateListener() {
#Override
public void onBillingSetupFinished(BillingResult billingResult) {
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
// The BillingClient is ready. You can query purchases here.
get_product_details(); // download all details to different variables as you want
Log.i( "appName", String.format( "billing setup response code %s", billingResult.toString() ) );
}
}
#Override
public void onBillingServiceDisconnected() {
connect_to_google();
// Try to restart the connection on the next request to
// Google Play by calling the startConnection() method.
}
});
}
//show products available to buy
void get_product_details(){
List<String> productIds = new ArrayList<>();
productIds.add("full_version");
SkuDetailsParams params = SkuDetailsParams
.newBuilder()
.setSkusList(productIds)
.setType(BillingClient.SkuType.INAPP)
.build();
billingClient.querySkuDetailsAsync(
params,
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(#NonNull BillingResult billingResult, #Nullable List<SkuDetails> list) {
if (billingResult.getResponseCode()==BillingClient.BillingResponseCode.OK && list!=null){
if (list.size()>0) {
Log.println(Log.DEBUG,"TAG", "onSkuDetailsResponse: " + list.get(0).getPrice());
unlock_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
billingClient.launchBillingFlow(
BuyActivity.this,
BillingFlowParams.newBuilder().setSkuDetails(list.get(0)).build()
);
}
});
}
}
}
}
);
}
void acknowledge_purchase(Purchase purchase){
AcknowledgePurchaseParams acknowledgePurchaseParams = AcknowledgePurchaseParams
.newBuilder()
.setPurchaseToken(purchase.getPurchaseToken())
.build();
billingClient.acknowledgePurchase(acknowledgePurchaseParams, new AcknowledgePurchaseResponseListener() {
#Override
public void onAcknowledgePurchaseResponse(#NonNull BillingResult billingResult) {
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
}
}
});
}
void restore_purchase(){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
connect_to_google();
new Handler().post(new Runnable() {
#Override
public void run() {
billingClient.queryPurchasesAsync(
BillingClient.SkuType.INAPP,
new PurchasesResponseListener() {
#Override
public void onQueryPurchasesResponse(#NonNull BillingResult billingResult, #NonNull List<Purchase> list) {
if (billingResult.getResponseCode()==BillingClient.BillingResponseCode.OK) {
for (Purchase purchase: list){
if (purchase.getPurchaseState()==Purchase.PurchaseState.PURCHASED
&& !purchase.isAcknowledged()) {
acknowledge_purchase(purchase);
features_unlocked();
} else if (purchase.getPurchaseState()==Purchase.PurchaseState.PURCHASED) {
features_unlocked();
}
}
} else if (billingResult.getResponseCode()==BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED) {
features_unlocked();
}
}
}
);
}
});
}
},300);
}
protected void onResume() {
super.onResume();
restore_purchase();
}
#Override
protected void onStop() {
super.onStop();
if (billingClient != null) billingClient.endConnection();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
public void onDestroy() {
if (billingClient != null) billingClient.endConnection();
billingClient=null;
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
if (billingClient != null) billingClient.endConnection();
}
public void cantRestore(View v){
Intent i = new Intent(BuyActivity.this, RestorePurchase.class);
startActivity(i);
}
}

I want to proceed to next action after scanning QR Code? Where should I add Intent?

I need to implement a QR Code scanner on an android project. I implemented the QR Code, however, I do not know how to switch to another action after QR is read.
I want to create an Intent to move to new action but I do not know where to add it.
I need the app to switch to another action as soon as it detects and reads QR Code.
code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_test);
CodeScannerView scannerViewTest = findViewById(R.id.scanner_view_test);
codeScannerTest = new CodeScanner(this, scannerViewTest);
askPermission();
if(CameraPermission) {
scannerViewTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
codeScannerTest.startPreview();
}
});
codeScannerTest.setDecodeCallback(new DecodeCallback() {
#Override
public void onDecoded(#NonNull Result result) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ScanTest.this, result.getText(), Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
private void askPermission(){
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(ScanTest.this, new String[]{Manifest.permission.CAMERA}, CAMERA_PERM);
}else {
codeScannerTest.startPreview();
CameraPermission = true;
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == CAMERA_PERM){
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
codeScannerTest.startPreview();
CameraPermission = true;
}else{
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)){
new AlertDialog.Builder(this)
.setTitle("Permission")
.setMessage("Please provide the camera permission for using all the features of the app")
.setPositiveButton("Proceed", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(ScanTest.this, new String[]{ Manifest.permission.CAMERA}, CAMERA_PERM);
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
} else {
new AlertDialog.Builder(this)
.setTitle("Permission")
.setMessage("You have denied some permissions. Allow all permissions at [Settings] > [Permissions]")
.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Intent settings_intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", getPackageName(), null));
settings_intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(settings_intent);
finish();
}
}).setNegativeButton("No, Exit app", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
}).create().show();
}
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
protected void onPause() {
if(CameraPermission){
codeScannerTest.releaseResources();
}
super.onPause();
}
You need to add it at the onDecoded method
codeScannerTest.setDecodeCallback(new DecodeCallback() {
#Override
public void onDecoded(#NonNull Result result) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Intent intent = Intent(this, YouNextActivity.class);
intent.putExtra("barcode", result.getText());
startActivity(intent);
//Toast.makeText(ScanTest.this, result.getText(), Toast.LENGTH_SHORT).show();
}
});
}
});
You can use the Intent.getExtra("barcode") and can get the value in your next Activity.

The SMS Code is expired. How to get pass this exception been stuck on this for days

I keep on getting the error of sms code has been expiraed please resend it even though it just came in my phone. This for android studio firebase authentication by phone number by the way. Can we solve this error?
Below are the codes:
The Send OTP Code:
public void sendOTP(){
final String Mobile = getMobileNo();
//Looks if the mobile number is already signed
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
if(currentUser!=null){
Toast.makeText(this,"User with mobile no"+Mobile+" already exists",Toast.LENGTH_LONG).show();
Intent in = new Intent(OTPActivity.this,LoginActivity.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(in);
}
//if not a current user then send otp.
else {
PhoneAuthOptions options = PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber(Mobile)
.setTimeout(120L, TimeUnit.SECONDS)
.setActivity(this)
.setCallbacks(mCallBack)
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
}
The mCallBacks Code:
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId = s;
setVerificationId(verificationId);
setToken(forceResendingToken);
}
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
final String code = phoneAuthCredential.getSmsCode();
if(code!=null){
OTP.setText(code);
verifyCode(getVerificationId(),code);
}
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Toast.makeText(OTPActivity.this,e.getMessage(),Toast.LENGTH_LONG).show();
}
};
The Verify Code:
public void verifyCode(String verificationId,String code){
if(code!=null) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
FirebaseAuth.getInstance().signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
FirebaseUser user = task.getResult().getUser();
AlertDialog.Builder builder = new AlertDialog.Builder(OTPActivity.this);
builder.setMessage("Congratulations!!You are Registered. Do You Want To Login?");
builder.setCancelable(true);
builder.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent in = new Intent(OTPActivity.this, LoginActivity.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(in);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(OTPActivity.this, "Exiting the app.", Toast.LENGTH_SHORT).show();
System.exit(0);
}
});
}
else
{
if(task.getException() instanceof FirebaseAuthInvalidCredentialsException){
Toast.makeText(OTPActivity.this,task.getException().getMessage(),Toast.LENGTH_SHORT).show();
}
}
}
});
}
else
{
Toast.makeText(this,"Code Field is Empty.Please Enter OTP.",Toast.LENGTH_LONG).show();
}
}
Please Help. Been stuck on this for days.
The Exception I am getting is that:
The sms Code has expired(even though I have got the otp code like seconds ago.).Please resend the code.

How to insert Scanned data in FireBase Realtime DataBase from QR/Barcode?

This is my code it is working fine it scans Qr/Barcode, but I want scanned data to insert in fire-base database. This app is connected with fire-base and using ML kit for barcode scanning. This app also has login signup connected with fire-base auth and scanner app. but I don't know how to push scanned data in fire-base realtime database in android studio.
public class MainActivity extends AppCompatActivity {
View view;
CameraView camera_view;
boolean isDetected= false;
Button btn_start_again;
private static final String TAG = "MainActivity";
FirebaseVisionBarcodeDetectorOptions options;
FirebaseVisionBarcodeDetector detector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseVisionBarcodeDetector detector = FirebaseVision.getInstance()
.getVisionBarcodeDetector();
Dexter.withActivity(this)
.withPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO})
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
setupCamera();
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
}
}).check();
}
public void logout(View view) {
FirebaseAuth.getInstance().signOut();//logout
startActivity(new Intent(getApplicationContext(),login.class));
finish();
}
private void setupCamera()
{
btn_start_again= (Button)findViewById(R.id.btn_again);
btn_start_again.setEnabled(isDetected);
btn_start_again.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isDetected = !isDetected;
}
});
camera_view = (CameraView)findViewById(R.id.cameraView);
camera_view.setLifecycleOwner(this);
camera_view.addFrameProcessor(new FrameProcessor() {
#Override
public void process(#NonNull Frame frame)
{
processImage(getVisionImageFromFrame(frame));
}
});
options = new FirebaseVisionBarcodeDetectorOptions.Builder()
.setBarcodeFormats(FirebaseVisionBarcode.FORMAT_QR_CODE)
.build();
detector = FirebaseVision.getInstance().getVisionBarcodeDetector(options);
}
private void processImage(FirebaseVisionImage image){
if(!isDetected)
{
detector.detectInImage(image)
.addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionBarcode>>() {
#Override
public void onSuccess(List<FirebaseVisionBarcode> firebaseVisionBarcodes) {
processResult(firebaseVisionBarcodes);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, ""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}
private void processResult(List<FirebaseVisionBarcode> firebaseVisionBarcodes){
if (firebaseVisionBarcodes.size()>0)
{
isDetected = true;
btn_start_again.setEnabled(isDetected);
for(FirebaseVisionBarcode item: firebaseVisionBarcodes)
{
int value_type = item.getValueType();
switch (value_type)
{
case FirebaseVisionBarcode.TYPE_TEXT:
{
createDialog(item.getRawValue());
}
break;
case FirebaseVisionBarcode.TYPE_URL:
{
//start browser intent
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(item.getRawValue()));
startActivity(intent);
}
break;
case FirebaseVisionBarcode.TYPE_CONTACT_INFO:
{
String info = new StringBuilder("Name: ")
.append(item.getContactInfo().getName().getFormattedName())
.append("\n")
.append("Address: ")
.append(item.getContactInfo().getAddresses().get(0).getAddressLines())
.append("\n")
.append("Email: ")
.append(item.getContactInfo().getEmails().get(0).getAddress())
.toString();
createDialog(info);
}
break;
default:
break;
}
}
}
}
private void createDialog(String text)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(text)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
private FirebaseVisionImage getVisionImageFromFrame(Frame frame){
byte[] data= frame.getData();
FirebaseVisionImageMetadata metadata = new FirebaseVisionImageMetadata.Builder()
.setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21)
.setHeight(frame.getSize() .getHeight())
.setWidth(frame.getSize() .getWidth())
//.setRotation(frame.getRotation())
.build();
return FirebaseVisionImage.fromByteArray(data,metadata);
}
}

How to clear app cache on exit pressed button?

I just want to clear app cache on exit when pressed, tried many answers out there but got errors and didn't work, so here is my code:
if (Config.ENABLE_EXIT_DIALOG) {
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setIcon(R.mipmap.ic_launcher);
dialog.setTitle(R.string.app_name);
dialog.setMessage(R.string.dialog_close_msg);
dialog.setPositiveButton(R.string.dialog_option_yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MainActivity.this.finish();
}
});
dialog.setNegativeButton(R.string.dialog_option_rate_us, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
final String appName = getPackageName();
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appName)));
}
MainActivity.this.finish();
}
});
dialog.setNeutralButton(R.string.dialog_option_more, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.play_more_apps))));
MainActivity.this.finish();
}
});
dialog.show();
} else {
super.onBackPressed();
}
got solved, i think it's old way but it's working fine found it here
i actually used his question code at the end of the my mainActivity file and it worked like a charm, though i guess it's an old way but it's ok.
and here is the code
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
clearApplicationData();
}
public void clearApplicationData() {
File cache = getCacheDir();
File appDir = new File(cache.getParent());
if (appDir.exists()) {
String[] children = appDir.list();
for (String s : children) {
if (!s.equals("lib")) {
deleteDir(new File(appDir, s));
Log.i("EEEEEERRRRRRROOOOOOORRRR", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
}
}
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}

Categories