Put into shared preferences code:
PreferenceManager.getDefaultSharedPreferences(Bookmarks.this).edit()
.putString("togoto", link).apply();
String togoto = PreferenceManager.getDefaultSharedPreferences(Bookmarks.this)
.getString("togoto", "no");
Toast.makeText(Bookmarks.this, "Will go to "+togoto, Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_proxy_browser);
Intent myIntent = new Intent(Bookmarks.this, ProxyBrowserActivity.class);
startActivity(myIntent);
Get from shared prferences (In other context):
String togoto = PreferenceManager.getDefaultSharedPreferences(ProxyBrowserActivity.this).getString("togoto", "nogo");
Toast.makeText(ProxyBrowserActivity.this, "1 Going to "+togoto, Toast.LENGTH_SHORT).show();
if (togoto != "no") {
Toast.makeText(ProxyBrowserActivity.this, "Going to "+togoto, Toast.LENGTH_SHORT).show();
PreferenceManager.getDefaultSharedPreferences(ProxyBrowserActivity.this)
.edit().putString("togoto", "no").apply();
} else {
// no shared preferences
}
This does not appear to work and togoto returns no on the other context. How do I allow it to work over multiple contexts?
Please use
getSharedPreferences(KEY, MODE_PRIVATE) rather than
PreferenceManager.getDefaultSharedPreferenceManager.
Your code is fine when you replace this.
If u create a default SharedPreference, it' name is context.getPackageName() + "_preferences". And getDefaultSharedPreferences get that. When u set a name like "MyApp_preferences", getDefaultSharedPreferences will find nothing. Use getSharedPreferences.
Related
I have a problem like this and I could not find a solution. my problem is Now, besides the files I created in my application, I also need to access the files in the main directory. The code I use for this is as follows. When I press the back button it goes to the previous folder.
here is my code
public void DosyaGeri(View view) {
String yol = ((TextView) findViewById(
R.id.txtKmlDosyaKonumu)).getText().toString();
String android = "/storage/emulated/0/";
String atlama="/storage/emulated/0/Android/data/com.LiderBilgisayarYazilim.cepmap/files/";
// boolean defolt= yol == "/storage/emulated/0/";
if (File.separator.compareTo(yol) == File.separator.compareTo(android)) {
finish();
startActivity(new Intent(this, Harita.class));
return;
}
else if(File.separator.compareTo(yol) == File.separator.compareTo(atlama)){
yol = android;
DosyaListesiOlustur(yol);
}
else {
yol = yol.substring(0,
yol.substring(0, yol.length() - 2).lastIndexOf("/")) +
File.separator;
DosyaListesiOlustur(yol);
}
}
but this code does not work on xiaomi devices with android 10 or higher. The reason is that it uses a different directory instead of "storage / emulated / 0 /". and it gives access permission error to this directory. how can i solve this.
I am trying to create a pinned shortcut on the homescreen of my using ShortcutManager. I am able to create the pinned shortcut using the following code:
Intent i = new Intent();
i.setAction(Intent.ACTION_VIEW);
i.setData(Uri.parse("www.google.com"));
if (ShortcutManagerCompat.isRequestPinShortcutSupported(context)){
ShortcutInfoCompat shortcutInfo = new ShortcutInfoCompat.Builder(context, "#1")
.setIntent(i)
.setShortLabel("label")
.setIcon(IconCompat.createWithResource(context, R.drawable.ic_launcher))
.build();
ShortcutManagerCompat.requestPinShortcut(context, shortcutInfo, null);
}else{
L.v("Shortcut", "Pinned shortcuts are not supported!");
}
I am facing two issues:
There is no check to handle duplicate shortcuts. Every time I click on the button to create a shortcut, it creates a shortcut every single time and the home screen is getting filled by these shortcuts. Is there any way to check whether the shortcut already exists like:-
Intent i = new Intent();
i.setAction(Intent.ACTION_VIEW);
i.setData(Uri.parse("www.google.com"));
Intent installer = new Intent(); installer.putExtra("android.intent.extra.shortcut.INTENT", i); installer.putExtra("android.intent.extra.shortcut.NAME", "Shortcut name"); installer.putExtra("android.intent.extra.shortcut.ICON_RESOURCE", Intent.ShortcutIconResource.fromContext(getApplicationContext() , R.drawable.ic_launcher));
installer.putExtra("duplicate", false);
installer.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
sendBroadcast(installer);
The problem with this piece of code is that it is not working in android 8.0 and above but it handles duplication of shortcut correctly using the following code :-
installer.putExtra("duplicate", false);
I want to achieve the same using Shortcut Manager
When a shortcut is created using Shortcut Manager, the icon is duplicated like
I have looked at the solution provided here but no luck so far:-
Strange app icon duplication in pinned shortcut (Android O)
Any ideas??
You can get all current shortcuts by calling
List<ShortcutInfo> currPinned = shortcutManager.getPinnedShortcuts();
then add to Map or Set and iterate over them and if its already exist dont add it again
if (currPinned != null) {
for (ShortcutInfo shortcut: currPinned) {
currPinnedMap.put(shortcut.getId(), shortcut);
}
}
....
//iterate over you "new shortcuts" and check if the present already
if (currPinnedMap.containsKey(id)) {
continue;
}
// add really new ones
fun isPinnedShortcutsExits(context: Context, id: String): Boolean {
return when {
Build.VERSION.SDK_INT >= 30 -> {
context.getSystemService(ShortcutManager::class.java)
.getShortcuts(ShortcutManager.FLAG_MATCH_PINNED)
.any { it.id == id }
}
Build.VERSION.SDK_INT >= 25 -> {
context.getSystemService(ShortcutManager::class.java)
.pinnedShortcuts
.any { it.id == id }
}
else -> false
}
}
or
ShortcutManagerCompat.getShortcuts(this, ShortcutManagerCompat.FLAG_MATCH_PINNED)
.any { it.id == "xxx" }
I am making an app where the user keeps pressing a button to get in-app money, my problem is whenever the app is closed or paused when i return the app's Money counter resets to zero. So i tried to make a Shared Preferences code to save my variables when the app pauses or stops, However when i resume the app the Counter doesn't reset to zero but as soon as i click on the button to generate money it resets to zero? Any help would be appreciated.
The Code being executed when the button is pressed:
myBalance += 1;
TextView balanceShow = findViewById(R.id.balanceShow);
balanceShow.setText("Balance: " + myBalance + "Coin");
And this is the code executed on the application exit event (The code that saves the user balance):
TextView balanceShow = findViewById(R.id.balanceShow);
String balance = balanceShow.getText().toString();
SharedPreferences data = getSharedPreferences("MySavedData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = data.edit();
editor.putString("BALANCE", balance);
editor.commit();
Toast.makeText(this, "Saved!", Toast.LENGTH_SHORT).show();
And finally this is the code executed on the app's resume that loads the user's balance when he comes back:
TextView balanceShow = findViewById(R.id.balanceShow);
SharedPreferences data = getSharedPreferences("MySavedData", Context.MODE_PRIVATE);
String balance = data.getString("BALANCE", "No Data Found!");
balanceShow.setText(balance);
Toast.makeText(this, "Loaded!", Toast.LENGTH_SHORT).show();
To make things more clear:
1- The app starts with a "0" Coins balance.
2- I click on the button, to generate "1" Coin every time i press it which triggers the first code i posted.
3- Let's say i made "80" Coin.
4- Now i close the app.
5- I open the app, I find that my balance is "80" Coins. Great!
6- I press on the button, then the balance resets to "0" Coins and starts from scratch again!
Please help it's been hours since i am trying to figure what's happening, and i couldn't, What's wrong with the code? Also i tried numerous other saving codes and they all crash the app, this is the only Saving code that seems to work with me, Any help would be highly appreciated! Thanks!
TextView balanceShow = findViewById(R.id.balanceShow);
SharedPreferences data = getSharedPreferences("MySavedData", Context.MODE_PRIVATE);
String balance = data.getString("BALANCE", "No Data Found!");
balanceShow.setText(balance);
Toast.makeText(this, "Loaded!", Toast.LENGTH_SHORT).show();
Herein lies your problem. You are only updating the value of the TextField, whereas the value of the counter behind the TextField (here myBalance) is zero. Instead of saving the data stored in the TextField to SharedPreferences, you should instead store the integer data in the myBalance counter to the preferences and load that when you resume the app.
In short, in order to save coins:
private void saveCoinsToPreferences() {
SharedPreferences data = getSharedPreferences("MySavedData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = data.edit();
editor.putInt("BALANCE", myBalance);
editor.commit();
Toast.makeText(this, "Saved!", Toast.LENGTH_SHORT).show();
}
And in order to retrieve coins:
private int retrieveCoins() {
TextView balanceShow = findViewById(R.id.balanceShow);
SharedPreferences data = getSharedPreferences("MySavedData", Context.MODE_PRIVATE);
myBalance = data.getInt("BALANCE", -1);
balanceShow.setText("Balance: " + myBalance + "Coin");
Toast.makeText(this, "Loaded!", Toast.LENGTH_SHORT).show();
}
Try this
private void saveCoins(Context context, String coin) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor spe = sp.edit();
spe.putString(context.getString(R.string.pref_coin), coin);
spe.apply();
}
to retrieve the coins
private String getPaymentSelected(Context c) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(c);
return sp.getString(c.getString(R.string.pref_coin), "0");
}
create a string variable pref_coin in strings.xml (inside values folder)
I have created an add button. No data is entered in the EditText field and when the user press the button I am not able to Toast the message.
If(text1.getText( ).toString( ).matches(" ") || text2.getText( ).toString( ).matches(" "))
{
Toast.makeText(MainActivity.this,"input values",Toast.LENGTH_SHORT.show( );
}
you can try this
EditText usernameEditText = (EditText) findViewById(R.id.editUsername);
sUsername = usernameEditText.getText().toString();
if (sUsername.matches("")) {
Toast.makeText(MainActivity.this, "You did not enter a username", Toast.LENGTH_SHORT).show();
}
You are matching wrong string. Instead of .match(" ") use .match("") or it is better to use text1.getText().toString().isEmpty(). In fact your if block never reached.
Try changing your code and IF condition like this:
If (String.valueOf(text1.getText()).equals("") || String.valueOf(text2.getText()).equals(""))
{
Toast.makeText(MainActivity.this,"input values",Toast.LENGTH_SHORT).show();
}
That's all,
Hope it helps :)
Use trim() this function will remove spaces.
If(text1.getText( ).toString( ).trim().equals("") || text2.getText( ).toString.trim().equals(""))
{
Toast.makeText(MainActivity.this,"You did not enter a username and password",Toast.LENGTH_SHORT.show( );
}
I hope this will helpful.
I'm making a speech to text / text to speech extension for android with gamemaker: studio and altho the text to speech works perfect,( check my android apk out and you will see text to speech- perfect, speech to text- broken) getting speech to text doesn't work, it is not getting the results from the onActivityResult method, as shown by the absence of my Log.i entry that I put in the onActivityResult method in the debug window. Can any of you help me out as to why? I have tried the following in countless different ways but with no luck, I've looked at literally 100 threads in here having to do with onActivityResults and tried implementing their solutions (but java is either not to be set up the same when combined with gamemaker, or the runner library used by gm:s isn't compatible or something would have worked) what am I doing wrong? I've also looked at an extension that works with using onActivityResult fired by an intent with EXTRAs, (the extension was for picking media files from android device) and I tried setting it up exactly like they did except using my recognizerIntent, but it still doesn't work for speech recognition, Is this something that gamemakers runner library isn't set up to handle? is the on activity result somehow different for returning speech data than returning data from images selected? in this case they both require a request code, a result code and intent data with extras so I don't see what is going on here as to why it doesn't work. Also is there some technical documentation somewhere you can point me to that describes GM:S's runner library and how it works?
here's the relative codes to how I have it set up:
GAMEMAKER(gml)
left mouse press event:
getMic();
EXTENSION(Java)
get the microphone for listning:
public void getMic() {
Log.i("yoyo", "Listening for speech");
try {
j = new Intent();
j.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
j.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
j.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say something");
j.setAction(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
RunnerActivity.CurrentActivity.startActivityForResult(j, 100);
Log.i("yoyo", "send to onActivityResult, Data: " + String.valueOf(j));
} catch (ActivityNotFoundException a) {
Log.i("yoyo", "Your device doesn't support Speech Recognition");
}
}
The google speak now dialog pops up, i speak, it beeps confirming i spoke and disappears as it should
EXTENSION(java)
get our results from speaking and save them internally:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("yoyo", "onActivityResult, requestCode: " + requestCode + ", resultCode: " + resultCode);
(RunnerActivity.CurrentActivity).onActivityResult(requestCode, resultCode, data);
if(requestCode == 100){
if (resultCode == RESULT_OK && data != null) {
ArrayList<String> res = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
holdForGMS = String.valueOf(res.get(0));
editor.putString(GETMYSPEECH, holdForGMS).apply();
}
}
}
GAMEMAKER(gml)
retrieve the results from memory GMS side, in alarm event that fires after speaking:
if global.isSpeaking=1 findMySpeech();
global.isSpeaking=0;
EXTENSION(java)
findMySpeach method:
public void findMySpeech() {
String gmsar = preferences.getString(GETMYSPEECH,"");
Log.i("yoyo", "Spoken words- " + gmsar);
recognition(gmsar);
}
aaaaannnd it's gone. the log results show it got a result (got activity result -1) but never fired the onActivityResult, which of course didn't save the result in the preference editor either, here is the log and a flow chart: