Share data between two app using SharedPreferences - java

I am sharing data between two my app, this is my code for get the data from the shared pref in app A
try {
final Context mContext = createPackageContext("com.example.demo", Context.MODE_PRIVATE);
final String val = mContext.getSharedPreferences("pref_name",Context.MODE_PRIVATE).getString(MY_KEY,"");
Log.e("sharedtest",val);
finish();
} catch (Exception e) {
e.printStackTrace();
}
this code is inside the onCreate() method, I don't have any more code anywhere. My problem is that, if I save the some value in my app B and than start my app A the saved data were correctly retrieved at first time, after retrieving the data my activity were finishing (I have only one activity), and if I start my launcher icon and start my app A, there is no updated data(it is the same), which where changed from app B.
also if I kill my app from system app settings and launch it like first time launch updated data is here, every data change needs my app killing from settings, how can I fix that? what I'm missing?

I found solution it may be a trick but it works fine for me,
after my app A finishes its job, I'm calling the system exit method.
System.exit(1);
it makes app "A" to be exit and finish job completely
After that I had the latest updated data in my preferences

Related

How to detect whether MainActivity was launched by the app starting, or by an intent by another activity?

So I'm using Java in Android Studio and have come across a problem.
Essentially I have a value in my MainActivity, and when the user is in the EditActivity, they can edit this value. I do this by using putExtra for myValue when transferring from the MainActivity to the EditActivity, and when transferring back, the newly updated variable is named myNewValue. Essentially what I want is:
if(MainActivity is started via app launching){
textView.setText(myValue)
}else if(MainActivity is started via intent from EditActivity){
textView.setText(myNewValue)
}
In your First Screen (splash screen) . start your intent like this
intent.putextra("check_this","mainactivity");
intent.putextra(""your_value","abcd");
in your EditActivity.
intent.putextra("check_this","editactivity");
intent.putextra(""your_new_value","abcdefg");
So in your CurrentScreen.
Bundle b = getIntent.getExtra();
if(b.getString("check_this").equals("mainactivity")){
textView.setText(myValue). // this screen is opened from splash
}else{
textView.setText(myNewValue). // this is from editactivity
}

Clear Data Of All the Applications from Your Application (Launcher)

I have created an application which is working as a launcher. In that application I have opening various other apps. In that app I want to clear all the data(i.e login details, search history) of other application to be removed on click of a button.
PackageManager pm = getPackageManager();
Method[] methods = pm.getClass().getDeclaredMethods();
for (Method m:methods){
if(m.getName().equals("freeStorage")){
try{
long desiredFreeStorage = Long.MAX_VALUE;
m.invoke(pm,desiredFreeStorage,null);
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
Using the above code, I am able to delete the cache but not able to delete the data of other apps.
Please provide me a solution for that.
Sorry for my bad english.
Its normal behavior. you can't delete data that belongs to other Apps via your app. Files that contain data are private and only accessible by Apps that own them or shared by App.
For example, most of the Apps use SharedPreference as private files to save data for later use. So, its senseless if other Apps are allowed to delete that data.

Application or activity takes time to load some times

I have created a startup activity from where I am calling another activity which has a view pager and shows some introductory pages.
This app was taking time to load so I thought to display a progress dialog till the activity loads, but that progress dialog also appears few seconds later.
startup activity:
public class StartUpActivity extends AppCompatActivity {
boolean isUserFirstTime, login;
public static String PREF_USER_FIRST_TIME;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isUserFirstTime = Boolean.valueOf(Utils.readSharedSetting(StartUpActivity.this, PREF_USER_FIRST_TIME, "true"));
Intent introIntent = new Intent(StartUpActivity.this, SlidingActivity.class);
introIntent.putExtra(PREF_USER_FIRST_TIME, isUserFirstTime);
ProgressDialog dialog = new ProgressDialog(StartUpActivity.this);
dialog.setMessage("Welcome to Mea Vita, please wait till the app loads.");
dialog.setCancelable(false);
dialog.setInverseBackgroundForced(false);
dialog.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//Here you can send the extras.
startActivity(new Intent(StartUpActivity.this,SlidingActivity.class));
// close this activity
finish();
}
}, 4000);
}
}
This doesn't happen every time,only sometimes. What can be the possible reason for this? how can I stop this?
Any solution? Thank you..
There is a strange issue with newly released Android Studio 2.0 (same issue in 2.1) first time of launching application take longer than usual (e.g. 2, 3 seconds or sometimes screen blinks or goes black) this issue happens only in debug mode and not effect your released APK.
A temporary solution to fix this is disabling instant run:
Settings → Build, Execution, Deployment → Instant Run and uncheck Enable Instant Run
First of all, make as rule to make all data loading in async tasks, you must check activity that you want to start where you load data.
The problem is in your second activity.
oncreate method should be used only to make findviews or start async tasks, don't load any in oncreate or in onstart or in onresume.
Probably you are loading high res images in sliding layout or you loading data in it.
There is another way, load all data in async task on first activity, then with ready data start second activity with already data loaded.
There are a few things that can load slowly.
Android need to read your code from storage and load the classes into ram.
I assume Utils.readSharedSetting(StartUpActivity.this, PREF_USER_FIRST_TIME, "true") reads from preferences. That's a file that you're reading from synchronously.
Actually launching the dialog takes a very small amount of time.
I'd suggest showing your loading inside the activity itself to minimize the work needed to render it.
Also, you can store PREF_USER_FIRST_TIME as a boolean instead of a String.

How to host widgets and how to update them always reliably?

I'm hosting widgets in my app. They can be picked from a list of all installed widgets and are added to a view. I save their IDs to database and restore them from these saved IDs again after restart of the app.
This works most of the times, but not always. Widgets are not always updated properly. One scenario where that happens for sure is:
"rebooting phone and starting app before boot-process of device has finished."
(if i wait until booting is completed, it works!!!)
There must be another scenario, but i couldnt reproduce that. I restart my app and they are not updated. So i wonder if i am missing something important.
I have basically used this tutorial:
http://leonardofischer.com/hosting-android-widgets-my-appwidgethost-tutorial/#comment-14678
My Code:
onCreate:
mAppWidgetManager = AppWidgetManager.getInstance(this);
mAWH_AppWidgetHost = new MyAppWidgetHost(MyApp.getContext(), R.string.APPWIDGET_HOST_ID);
onStart:
mAWH_AppWidgetHost.startListening();
onStop:
mAWH_AppWidgetHost.stopListening();
restore from id (saved in database):
AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
MyAppWidgetHostView hostView = (MyAppWidgetHostView) mAWH_AppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
hostView.setAppWidget(appWidgetId, appWidgetInfo);
mLL_innerLayout.addView((MyAppWidgetHostView) hostView);
I cannot find any sites in the web that make this clear. Neither does looking at source code of different launcher apps make it more clear to me.
I had the same problem, but then I moved
mAWH_AppWidgetHost.startListening();
in onCreate method and
mAWH_AppWidgetHost.stopListening();
in onDestroy method. This is suggested here

Refresh running activity with new data from AsyncTask result

I have a class, that executes some command in background. Class method is executed asynchronously (by using AsyncTask) and when command finishes, it posts event with command result. Then, new activity is started. To do this, I added inside OnCreate method to MainActitity:
ssh = new SshSupport();
ssh.Connect();
ssh.ExecuteCommand(commandType);
//..................................
ssh.eventHandler = new ISshEvents()
{
#Override
public void SshCommandExecuted(SshCommandsEnum commandType, String result)
{
if (progressDialogExecuting.isShowing()) progressDialogExecuting.dismiss();
Intent intent = new Intent(MainActivity.this, ResultListActivity.class);
intent.putExtra("result", result);
intent.putExtra("commandType", commandType);
startActivity(intent);
}
So it works as should. My commands starts in background and when finished, my event fires and displays new activity with results (all results are received via getIntent().getExtras() and then formatted to be displayed as should).
Problem: on result activity I have "Refresh" button. When pressed, all data should be refreshed. So I need to execute ssh.ExecuteCommand(commandType); again to get refreshed data. Note that I don't want to open new ssh connection for this. Instead, I want to use already opened connection and simply execute my command again.
So I made my 'ssh' static and I used MainActivity.ssh.ExecuteCommand(commandType); on refresh button press. It works, but obviously, it causes to create second instance of ResultListActivity, instead of refreshing data on existing one.
I can even avoid to creating result activity again by checking if it's already exists (for example by adding 'active' boolean static variable to it). However, it won't help me because I still have no any possibility to refresh data inside my existing activity.
So, how can I do it?
No responses, so I'm answering to my own question. My solution was:
- Change my activity launchMode to singleTop
- Override method onNewIntent
In this case each time I start this activity: if activity already exists it won't be created again. Instead, onNewIntent method will be called.
http://developer.android.com/guide/topics/manifest/activity-element.html#lmode
http://developer.android.com/reference/android/app/Activity.html#onNewIntent%28android.content.Intent%29
However, I'm not sure if approach like this is good. How do you think?

Categories

Resources