I can put the Stringset inside the SharedPreferences. But When I try to get the back I cant.
I am getting the set size 0
This is my code for saving ====>
public class DefineProduct extends AppCompatActivity {
EditText productName, barcode,cost,price,size,color,notes;
Button saveBtn;
SharedPreferences sharedPref;
SharedPreferences.Editor editor ;
Set<String> set = new HashSet<>();
#SuppressLint("CommitPrefEdits")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_define_product);
sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor = sharedPref.edit();
productName = findViewById(R.id.productNameText);
barcode = findViewById(R.id.barcodeEditText);
cost = findViewById(R.id.costText);
price = findViewById(R.id.priceText);
size = findViewById(R.id.sizeText);
color = findViewById(R.id.colorText);
notes = findViewById(R.id.notesText);
saveBtn = findViewById(R.id.saveBtn);
}
public void Save(View view){
set.add(productName.getText().toString());
set.add(barcode.getText().toString());
set.add(cost.getText().toString());
set.add(price.getText().toString());
set.add(size.getText().toString());
set.add(color.getText().toString());
set.add(notes.getText().toString());
editor.putStringSet(barcode.getText().toString(),set);
editor.commit();
Toast.makeText(getApplicationContext(),"Saved", Toast.LENGTH_LONG).show();
productName.setText("");
barcode.setText("");
cost.setText("");
price.setText("");
size.setText("");
color.setText("");
notes.setText("");
set.clear();
}
}
This is my code for getting the StringSet from an other activity =====>
public void onActivityResult(int requestCode,int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode,resultCode,data);
if(islem == 1 && resultCode == RESULT_OK && data != null){
Uri uri = data.getData();
try {
if(Build.VERSION.SDK_INT >= 28){
ImageDecoder.Source source = ImageDecoder.createSource(this.getContentResolver(), uri);
productImage = ImageDecoder.decodeBitmap(source);
productImageVeawer.setImageBitmap(productImage);
productImage.compress(Bitmap.CompressFormat.PNG, 10, byteArrayOutputStream);
}
else {
productImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
productImageVeawer.setImageBitmap(productImage);
}
} catch (IOException e) {
e.printStackTrace();
}
}
if(islem == 0 && resultCode == RESULT_OK && data != null){
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
productImageVeawer.setImageBitmap(bitmap);
bitmap.compress(Bitmap.CompressFormat.PNG, 10, byteArrayOutputStream);
}
if(islem == 2){
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
System.out.println("Scan result : " + result.getContents().toString());
Set<String> set = pref.getStringSet(result.getContents().toString(), new HashSet<String>());
System.out.println("***************************** Set size : " + set.size());
ArrayList<String> arrayList = new ArrayList<>();
arrayList.addAll(set);
// barcodeText.setText(arrayList.get(0).toString());
// productNameText.setText(arrayList.get(1).toString());
}
super.onActivityResult(requestCode,resultCode, data);
}
use this
SharedPreferences sharedPref;
SharedPreferences.Editor editor ;
Set<String> set = new HashSet<>();
#SuppressLint("CommitPrefEdits")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_define_product);
sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor = sharedPref.edit();
}
public void Save(View view){
editor.putStringSet(barcode.getText().toString(),set);
editor.apply();
Toast.makeText(getApplicationContext(),"Saved", Toast.LENGTH_LONG).show();
set.clear();
}
and to fetch data in another activity
public NameActivity extands AppCompactActivity{
SharedPreferences sharedPref;
SharedPreferences.Editor editor ;
#SuppressLint("CommitPrefEdits")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_define_product);
sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Set<String> fetch = sharePref.getStringSet(barcode.getText().toString(), null);
}
}
Don't use the PreferenceManager, use
SharedPreferences prefs = getApplicationContext.getSharedPreferences(FILENAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
To keep the filename easy to remember, I use the package name. Also, make sure you use "" around the filename.
You are putting empty Set to preference, you should add some value to the Set and save like following
set.add("Test");
editor.putStringSet(barcode.getText().toString(),set);
editor.apply(); // must apply the change
Related
I want to allow users to upload a profile picture in my app so far I have achieved this, but the problem is when I exit the app the profile picture disappears, so I was asking is there a way to store the picture in cache I'm using glide but don't know how to go about it
changing load defaults on my oncreate method but still does not work.
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
public static final int REQUEST_IMAGE = 100;
#BindView(R.id.img_profile)
ImageView imgProfile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(null);
loadProfileDefault();
}
private void loadProfile(String url) {
Log.d(TAG, "Image cache path: " + url);
GlideApp.with(this).load(url)
.into(imgProfile);
imgProfile.setColorFilter(ContextCompat.getColor(this, android.R.color.transparent));
}
private void loadProfileDefault() {
GlideApp.with(this).load(R.drawable.baseline_account_circle_black_48)
.into(imgProfile);
imgProfile.setColorFilter(ContextCompat.getColor(this, R.color.profile_default_tint));
}
#OnClick({R.id.img_plus, R.id.img_profile})
void onProfileImageClick() {
Dexter.withActivity(this)
.withPermissions(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
if (report.areAllPermissionsGranted()) {
showImagePickerOptions();
}
if (report.isAnyPermissionPermanentlyDenied()) {
showSettingsDialog();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
private void showImagePickerOptions() {
ImagePickerActivity.showImagePickerOptions(this, new ImagePickerActivity.PickerOptionListener() {
#Override
public void onTakeCameraSelected() {
launchCameraIntent();
}
#Override
public void onChooseGallerySelected() {
launchGalleryIntent();
}
});
}
private void launchCameraIntent() {
Intent intent = new Intent(MainActivity.this, ImagePickerActivity.class);
intent.putExtra(ImagePickerActivity.INTENT_IMAGE_PICKER_OPTION, ImagePickerActivity.REQUEST_IMAGE_CAPTURE);
// setting aspect ratio
intent.putExtra(ImagePickerActivity.INTENT_LOCK_ASPECT_RATIO, true);
intent.putExtra(ImagePickerActivity.INTENT_ASPECT_RATIO_X, 1); // 16x9, 1x1, 3:4, 3:2
intent.putExtra(ImagePickerActivity.INTENT_ASPECT_RATIO_Y, 1);
// setting maximum bitmap width and height
intent.putExtra(ImagePickerActivity.INTENT_SET_BITMAP_MAX_WIDTH_HEIGHT, true);
intent.putExtra(ImagePickerActivity.INTENT_BITMAP_MAX_WIDTH, 1000);
intent.putExtra(ImagePickerActivity.INTENT_BITMAP_MAX_HEIGHT, 1000);
startActivityForResult(intent, REQUEST_IMAGE);
}
private void launchGalleryIntent() {
Intent intent = new Intent(MainActivity.this, ImagePickerActivity.class);
intent.putExtra(ImagePickerActivity.INTENT_IMAGE_PICKER_OPTION, ImagePickerActivity.REQUEST_GALLERY_IMAGE);
// setting aspect ratio
intent.putExtra(ImagePickerActivity.INTENT_LOCK_ASPECT_RATIO, true);
intent.putExtra(ImagePickerActivity.INTENT_ASPECT_RATIO_X, 1); // 16x9, 1x1, 3:4, 3:2
intent.putExtra(ImagePickerActivity.INTENT_ASPECT_RATIO_Y, 1);
startActivityForResult(intent, REQUEST_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == REQUEST_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = data.getParcelableExtra("path");
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
loadProfile(uri.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I want the selected image to remain even after closing the app how do I go about it please enter
There are 2 ways to achieve your result.
Using Shared Preferences. You can save your variable uri to shared preference and fetch data from it next time. For this, you can check if uri is available in Shared Preference or not.
Using Room database library.
Below is the code using Shared Preference :
Your onCreate() will be like :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(null);
loadImageFromSharedPrefernce();
}
private void loadImageFromSharedPrefernce() {
SharedPreferences prefs = getSharedPreferences("PREF_NAME", MODE_PRIVATE);
if (prefs.contains("imageUrl")){
String imageUrl = prefs.getString("imageUrl", "");
loadProfile(imageUrl); //your method
}
else {
loadProfileDefault(); //your method
}
}
Your onActivityResult() will be like :
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == REQUEST_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = data.getParcelableExtra("path");
try {
saveImageToSharedPreference(uri);
loadImageFromSharedPrefernce();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void saveImageToSharedPreference(Uri uri) {
SharedPreferences.Editor editor = getSharedPreferences("PREF_NAME", MODE_PRIVATE).edit();
editor.putString("imageUrl", String.valueOf(uri));
editor.apply();
}
You should save profile pic URI in SharedPreference which is being received in onActivityResult() method. Adding the sample code below, have a look.
private void saveProfilePicLocal(String uri){
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
editor.putString("profile_uri", uri); // Storing string
editor.commit(); // commit changes
}
Now you have to call above function in onActivityResult() method like below.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == REQUEST_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = data.getParcelableExtra("path");
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
saveProfilePicLocal(uri.toString())
loadProfile(uri.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
After that, you should check whether you have any profile locally saved or not if there is any URI exists in SharedPreference read it and load otherwise load default one. Check the sample code below.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(null);
//Check whether profile pic URI exists in Local SharedPreference
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
if (prefs.contains("profile_uri")){
String uri = pref.getString("profile_uri", null);
if(TextUtils.isEmpty(uri.trim())
loadProfileDefault();
else
loadProfile(uri);
}
}
Happy coding!.
I have 2 Activity.
FirstActivity with 1 textView and 1 button, and
MainActivity with 4 checkBoxes, 1 textView and 1 button.
First Activity is the first activity which app show to user.
Layouts of my activities
On the FirstActivity i want to check how many checboxes are checked in the textView.
On the MainActivity all working fine, we can select checkboxes and textView show how many is checked. Adittionaly, state of checkboxes and state of textView is save into SharedPreference.
Now i describe my problem, i dont know how to show currently numbers of checked boxes in 1st activity in my app after launch.
I tried to use onActivityResult but i think i do this wrong, and this my button2 with double intent must be also wrong.
What i should fix here and how ?
I paste here code of my 2 Activities:
FirstActivity :
public class FirstActivity extends AppCompatActivity {
private static final String SHARED_PREFS_NAME = "abc";
private Button b1;
private TextView tv2;
private int number;
public static final int REQUEST_CODE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
b1 = (Button)findViewById(R.id.b1);
tv2 = (TextView)findViewById(R.id.tv2) ;
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(FirstActivity.this, MainActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
});
SharedPreferences preferences = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE);
number = preferences.getInt("NUMBER", 0);
tv2.setText(""+number);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CODE) {
int number = data.getExtras().getInt("number");
tv2.setText(""+number);
number = getIntent().getExtras().getInt("number");
saveNumberToSharedPrefs(number);
}
}
}
private void saveNumberToSharedPrefs(int num){
SharedPreferences preferences = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE); //Create and store this instance in onCreate method of activity, or use it like this.
preferences.edit().putInt("NUMBER", num).apply(); // Use constant value for key
}
}
MainActivity :
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
private int numberOfTrue;
private TextView tv1;
private CheckBox cb1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CheckBox cb2,cb3,cb4;
Button b2;
b2 = (Button)findViewById(R.id.b2);
tv1 = (TextView)findViewById(R.id.tv1);
cb1 = (CheckBox)findViewById(R.id.cb1);
cb1.setChecked(getFromSP("cb1"));
cb1.setOnCheckedChangeListener(this);
cb2 = (CheckBox)findViewById(R.id.cb2);
cb2.setChecked(getFromSP("cb2"));
cb2.setOnCheckedChangeListener(this);
cb3 = (CheckBox)findViewById(R.id.cb3);
cb3.setChecked(getFromSP("cb3"));
cb3.setOnCheckedChangeListener(this);
cb4 = (CheckBox)findViewById(R.id.cb4);
cb4.setChecked(getFromSP("cb4"));
cb4.setOnCheckedChangeListener(this);
loadVariable();
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent output = new Intent();
output.putExtra("number", numberOfTrue);
setResult(Activity.RESULT_OK, output);
finish();
}
});
}
private boolean getFromSP(String key){
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}
private void saveInSp(String key,boolean value) {
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
private void saveVariable(int numberOfTrue){
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("key2", numberOfTrue);
editor.commit();
}
private void loadVariable(){
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
int number = sharedPref.getInt("key2", 0);
tv1.setText(""+number);
numberOfTrue=number;
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch(buttonView.getId()){
case R.id.cb1:
saveInSp("cb1",isChecked);
if (isChecked == true){
numberOfTrue++;
}
else
{
numberOfTrue--;
}
break;
case R.id.cb2:
saveInSp("cb2",isChecked);
if (isChecked == true){
numberOfTrue++;
}
else
{
numberOfTrue--;
}
break;
case R.id.cb3:
saveInSp("cb3",isChecked);
if (isChecked == true){
numberOfTrue++;
}
else
{
numberOfTrue--;
}
break;
case R.id.cb4:
saveInSp("cb4",isChecked);
if (isChecked == true){
numberOfTrue++;
}
else
{
numberOfTrue--;
}
break;
}
saveVariable(numberOfTrue);
loadVariable();
}
}
This one if definitely wrong.
Intent intent = new Intent(MainActivity.this, FirstActivity.class);
intent.putExtra("number", numberOfTrue);
startActivityForResult(intent,1);
Intent output = new Intent();
output.putExtra("number", numberOfTrue);
setResult(Activity.RESULT_OK, output);
finish();
You need to left only second part of code. Like this:
Intent output = new Intent();
output.putExtra("number", numberOfTrue);
setResult(Activity.RESULT_OK, output);
finish();
And start your MainActivity like this:
Intent intent = new Intent(FirstActivity.this, MainActivity.class);
startActivityForResult(intent, REQUEST_CODE); // This change is important.
And then do this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
number = getIntent().getExtras().getInt("number");
}
}
This way you'll receive number from MainActivity when it'll be closed. But if you want to read this value on FirstActivity start (without going to MainActivity, you need to store checked number in shared preferences and then get value in onCreate() method of FirstActivity.
Write into SharedPreferences in onActivityResult to insure that only "saved" checks will be saved.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
number = getIntent().getExtras().getInt("number");
saveNumberToSharedPrefs(number);
}
}
private void saveNumberToSharedPrefs(int num){
SharedPreferences preferences = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE); //Create and store this instance in onCreate method of activity, or use it like this.
preferences.edit().putInt("NUMBER", num).apply(); // Use constant value for key
}
And then you can load your checked number in onCreate method of FirstActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
....
SharedPreferences preferences = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE);
number = preferences.getInt("NUMBER", 0);
}
Update
Here you'r trying to get number from intent in onActivityResult. That's wrong, this way you'll always have number = 0 (default value). On activity result doesn't fill data into intent. All your data is in data variable passed in method.
number = getIntent().getExtras().getInt("number");
saveNumberToSharedPrefs(number);
You need to leave only this:
if (requestCode == REQUEST_CODE) { //also you need to check if result is RESULT_OK
number = data.getExtras().getInt("number");
tv2.setText(""+number);
saveNumberToSharedPrefs(number);
}
FirstActivity
Store values :
Intent intent = new Intent(getBaseContext(), Activity.class);
intent.putExtra("ID", sessionId);
startActivity(intent);
SecondActivity
Fetching Values:
String s = getIntent().getStringExtra("ID");
public static final int REQUEST_CODE = 100;
change on FirstActivity.java
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(FirstActivity.this, MainActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
});
add onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CODE) {
Log.d("TAG","------"+data.getExtras().getInt("number"));
int number = data.getExtras().getInt("number");
tv2.setText(""+number);
}
}
}
change on MainActivity.java
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Log.d("TAG","------"+numberOfTrue);
Intent output = new Intent();
output.putExtra("number", numberOfTrue);
setResult(Activity.RESULT_OK, output);
finish();
}
});
Hi I'm trying to detect whether my app has been opened for the first time. If it has, I need to run an activity and once it's opened for the second time it should not show it again.
This is my code:
fragment:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Intent intent = new Intent(getActivity(), TutorialFeaturedActivity.class);
//startActivity(intent);
SharedPreferences settings = this.getActivity().getSharedPreferences(PREFS_NAME, 0); // Get preferences file (0 = no option flags set)
boolean firstRun = settings.getBoolean("firstRun", true); // Is it first run? If not specified, use "true"
if(firstRun) {
Log.w("onCreate: ","first time" );
Intent intent = new Intent(getActivity(), TutorialFeaturedActivity.class);
startActivity(intent);
SharedPreferences.Editor editor = settings.edit(); // Open the editor for our settings
editor.putBoolean("firstRun", false); // It is no longer the first run
editor.apply(); // Save all changed settings
} else {
Log.w("onCreate: ","second time");
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
getSpecials();
}
But all it does is start the activity and when I start it again it freezes in a white screen but checking the logs it shows like the else statement is constantly running over and over. I'm fairly new to Android so some help or advice would be greatly appreciated
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SharedPreferences pref = YourActivityName.this.getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor= pref.edit();
boolean firstRun = pref.getBoolean("firstRun", true);
if(firstRun)
{
Log.i("onCreate: ","first time" );
editor.putBoolean("firstRun",false);
editor.commit();
Intent intent = new Intent(getActivity(), TutorialFeaturedActivity.class);
startActivity(intent);
}
else
{
Log.i("onCreate: ","second time");
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
// getSpecials();
}
It looks like your activity is looping because within your else statement, you tell it to restart the activity which lands again in the else statement and so on and so on.
Try using editor.commit if editor.apply not working
editor.putBoolean("firstRun", false);
editor.apply(); // Save all changed settings
editor.commit(); // Save all changed settings
In else case your starting "MainActivity.class".
Why your loading MainActivity from the oncreate of MainActivity ?
it will make a loop.
Remove the start activity from else case.
Try this approach:
public class MainActivity extends Activity {
SharedPreferences prefs = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
}
#Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firstRun", true)) {
Intent intent = new Intent(MainActivity.this, TutorialFeaturedActivity.class);
startActivity(intent);
prefs.edit().putBoolean("firstRun", false).commit();
}
else
{
//do nothing
}
getSpecials();
}
}
Please Try this my friend
public class SessionManager {
private static String TAG = SessionManager.class.getSimpleName();
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "ManageRun";
private static final String KEY_IS_RUN = "isRun";
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setLatest(boolean isRun) {
editor.putBoolean(KEY_IS_RUN, isRun);
// commit changes
editor.commit();
Log.d(TAG, "Manage Version session modified!");
}
public boolean isLatest() {
return pref.getBoolean(KEY_IS_RUN, true);
}
}
**In first Activity Check **
private SessionManager session;
session = new SessionManager(getApplicationContext());
if (session.isLatest()) {
session.setLatest(false);
Log.w("onCreate: ","first time" );
Intent intent = new Intent(getActivity(), TutorialFeaturedActivity.class);
startActivity(intent);
}
else
{
Log.w("onCreate: ","second time");
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
private boolean isFirstTime() {
if (firstTime == null) {
SharedPreferences mPreferences = this.getSharedPreferences("first_time", Context.MODE_PRIVATE);
firstTime = mPreferences.getBoolean("firstTime", true);
if (firstTime) {
SharedPreferences.Editor editor = mPreferences.edit();
editor.putBoolean("firstTime", false);
editor.commit();
}
}
return firstTime;
}
if (isFirstTime()) {
Intent i = new Intent(SplashActivity.this, Intro_slider.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
} else {
final UserFunctions uf = new UserFunctions();
if (uf.isUserLoggedIn(SplashActivity.this)) {
Intent i = new Intent(SplashActivity.this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
} else {
Intent i = new Intent(SplashActivity.this, Social_Login_Activity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
}
Try this code.
In my application I have 2 buttons.
The first button in start game and the second button in continue game.
I want to disable my second button for the first time when my application runs.
It means just for the first time my second button is disabled to onClick. How to handle this?
How can I make it understand it is the first time?
public class Menu extends Activity implements View.OnClickListener {
SharedPreferences prefs;
Editor edit;
TextView best;
private boolean flag;
public static ImageView btn1, conti, but3, but4;
static Noti_Queue noti_queue;
static Splash splash;
public static AppList applist;
public static int userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.home_activity);
flag = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("flag", false);
if (applist == null) {
applist = new AppList(this);
applist.set_identity("1");
}
if (splash == null) {
splash = new Splash(this);
splash.set_identity("1");
}
if (noti_queue == null) {
noti_queue = new Noti_Queue(this);
noti_queue.set_identity("1");
}
btn1 = (ImageView) findViewById(R.id.button1);
conti = (ImageView) findViewById(R.id.btn2);
but3 = (ImageView) findViewById(R.id.button3);
but4 = (ImageView) findViewById(R.id.button4);
btn1.setOnClickListener(this);
conti.setOnClickListener(this);
conti.setBackgroundResource(R.drawable.cont);
if (!flag) {
flag = true;
conti.setBackgroundResource(R.drawable.cont_press);}
conti.setEnabled(flag);
but3.setOnClickListener(this);
but4.setOnClickListener(this);
// giving question id
final int que_id = getIntent().getIntExtra("integer", 0);
Log.e("mhs", que_id + "");
//now lets save the que_id(now it is save to SharedPreferences
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
userId = myPrefs.getInt("userId", 0);
//let get it to show
Log.e("saved", que_id + "");
setsize();
best = (TextView) findViewById(R.id.textView1);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");
best.setTypeface(tf, Typeface.BOLD);
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
edit = prefs.edit();
if (prefs.getInt("Best", 0) <= 0) {
edit.putInt("Best", 0);
edit.commit();
}
best.setText("بیشترین امتیاز : " + prefs.getInt("Best", 0));
}
#Override
public void onBackPressed() {
splash.Display();
splash = null;
super.onBackPressed();
}
#Override
protected void onResume() {
best.setText("بیشترین امتیاز : " + prefs.getInt("Best", 0));
super.onResume();
}
private void setsize() {
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int h = dm.heightPixels;
int w = dm.widthPixels;
h = h / 6;
w = w - ((w * 30) / 100);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(w, h);
but4.setLayoutParams(params);
but3.setLayoutParams(params);
btn1.setLayoutParams(params);
conti.setLayoutParams(params);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
if (!flag) {
flag = true;
PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("flag", flag).commit();
conti.setEnabled(flag);
conti.setBackgroundResource(R.drawable.cont_press);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
//finishing this activity is important to exit from app
Menu.this.finish();
}
break;
case R.id.btn2:
Toast.makeText(getApplicationContext(), userId + "", Toast.LENGTH_LONG).show();
Intent intent1 = new Intent(Menu.this, ContinueActivity.class);
intent1.putExtra("integer2", userId);
startActivity(intent1);
Menu.this.finish();
break;
case R.id.button3:
Toast.makeText(getApplicationContext(), "help", Toast.LENGTH_LONG).show();
break;
case R.id.button4:
applist.Display();
break;
}
}
With the help of sharedprefrence you can achieve this for example.
SharedPreferences sharedPreferences = getSharedPreferences("myPref", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("enableButton", true);
editor.commit();
put this code for enabling Button.
SharedPreferences sharedPreferences = getSharedPreferences("myPref", MODE_PRIVATE);
flag = sharedPreferences.getBoolean("enableButton", false);
if (flag) {
conti.setEnabled(true); ;
}
I am trying to have SharedPreferences once and control it to different methods rather than having different SharedPreferences in different methods. I have SharedPreferences in the onCreate, LoadPreferences, SavePreferences and ClearTextViews methods. I want to make it so that I have preferences saved to the TextViews from entered text in the EditText and then be able to clear them all with a button. Please help me if you can. Here is the relevant code:
public class notesActivity extends Activity implements OnClickListener
{
Button saveNote;
Button clearText;
EditText note;
TextView textSavedNote1, textSavedNote2, textSavedNote3, textSavedNote4, textSavedNote5, textSavedNote6;
SharedPreferences spNote;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
saveNote = (Button)this.findViewById(R.id.saveNotes);
saveNote.setOnClickListener(this);
clearText = (Button)this.findViewById(R.id.clearAllText);
clearText.setOnClickListener(this);
textSavedNote1 = (TextView)findViewById(R.id.stringSavedNote1);
textSavedNote2 = (TextView)findViewById(R.id.stringSavedNote2);
textSavedNote3 = (TextView)findViewById(R.id.stringSavedNote3);
textSavedNote4 = (TextView)findViewById(R.id.stringSavedNote4);
textSavedNote5 = (TextView)findViewById(R.id.stringSavedNote5);
textSavedNote6 = (TextView)findViewById(R.id.stringSavedNote6);
note = (EditText)this.findViewById(R.id.notes);
spNote = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = spNote.edit();
edit.putString("note"+saveNote,note.getText().toString());
edit.commit();
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Goes back to the home screen
case R.id.item1: Intent i = new Intent(notesActivity.this, UserSettingActivity.class);
startActivity(i);
case R.id.item2:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
// Refreshes the page.
case R.id.item3:
finish();
startActivity(getIntent());
default:
return super.onOptionsItemSelected(item);
}
}
public void onClick (View v){
if(v==saveNote){
SavePreferences("NOTE1", note.getText().toString());
LoadPreferences();
note.setText("");
if(textSavedNote1.getText().toString().length()>0){
SavePreferences("NOTE2", note.getText().toString());
LoadPreferences();
note.setText("");
}
else{
}
}
else if(v==clearText){
ClearTextViews();
}
}
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedNote1 = sharedPreferences.getString("NOTE1", "");
String strSavedNote2 = sharedPreferences.getString("NOTE2", "");
String strSavedNote3 = sharedPreferences.getString("NOTE3", "");
String strSavedNote4 = sharedPreferences.getString("NOTE4", "");
String strSavedNote5 = sharedPreferences.getString("NOTE5", "");
String strSavedNote6 = sharedPreferences.getString("NOTE6", "");
textSavedNote1.setText(strSavedNote1);
textSavedNote2.setText(strSavedNote2);
textSavedNote3.setText(strSavedNote3);
textSavedNote4.setText(strSavedNote4);
textSavedNote5.setText(strSavedNote5);
textSavedNote6.setText(strSavedNote6);
}
private void ClearTextViews(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
}
}
There are some links that can be helpfull
How to use SharedPreferences in Android to store, fetch and edit values
http://developer.android.com/reference/android/content/SharedPreferences.html
Examples
How to use SharedPreferences
http://android-er.blogspot.com.br/2011/01/example-of-using-sharedpreferencesedito.html
Try the code below.
/*I have added one more button, on click on that button i have set call clearText function and set all text empty, each time before clicking on save button you click first clear button then next value will be inserted in next textview.*/
public class SharedPreferenceJustOneSetOfPreferencesActivity extends Activity implements OnClickListener{
private Button saveNote,clearText,ClearAll;
static TextView textSavedNote1, textSavedNote2, textSavedNote3, textSavedNote4, textSavedNote5, textSavedNote6;
private EditText note;
private SharedPreferences spNote;
private static final String TAG = SharedPreferenceJustOneSetOfPreferencesActivity.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();
saveInPreference();
}
private void initView() {
textSavedNote1 = (TextView)findViewById(R.id.textSavedNote1);
textSavedNote2 = (TextView)findViewById(R.id.textSavedNote2);
textSavedNote3 = (TextView)findViewById(R.id.textSavedNote3);
textSavedNote4 = (TextView)findViewById(R.id.textSavedNote4);
textSavedNote5 = (TextView)findViewById(R.id.textSavedNote5);
textSavedNote6 = (TextView)findViewById(R.id.textSavedNote6);
note = (EditText)findViewById(R.id.note);
saveNote = (Button)findViewById(R.id.saveNote);
clearText = (Button)findViewById(R.id.clearText);
ClearAll = (Button)findViewById(R.id.ClearAll);
saveNote.setOnClickListener(this);
clearText.setOnClickListener(this);
ClearAll.setOnClickListener(this);
}
private void saveInPreference() {
spNote = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = spNote.edit();
edit.putString("note"+saveNote,note.getText().toString());
edit.commit();
}
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.layout.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.item1: Intent i = new Intent(SharedPreferenceJustOneSetOfPreferencesActivity.this, UserSettingActivity.class);
startActivity(i);
case R.id.item2:
Intent intent = new Intent(SharedPreferenceJustOneSetOfPreferencesActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
case R.id.item3:
finish();
startActivity(getIntent());
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View view) {
if (view == saveNote) {
String textvedNote1 =textSavedNote1.getText().toString();
String textvedNote2= textSavedNote2.getText().toString();
String textvedNote3 =textSavedNote3.getText().toString();
String textvedNote4= textSavedNote4.getText().toString();
String textvedNote5 =textSavedNote5.getText().toString();
String textvedNote6= textSavedNote6.getText().toString();
if (textvedNote1.equals("")) {
SavePreferences("NOTE1", note.getText().toString());
Log.e(TAG,"textvedNote1: Inside "+textvedNote1.length());
LoadPreferences();
note.setText("");
}else if (textvedNote2.equals("")&& !textvedNote1.equals("")) {
SavePreferences("NOTE2", note.getText().toString());
Log.e(TAG,"textvedNote2: Inside "+textvedNote1.length());
LoadPreferences();
note.setText("");
} else if (textvedNote3.equals("")&& !textvedNote2.equals("")) {
Log.e(TAG,"textvedNote3: Inside "+textvedNote2.length());
SavePreferences("NOTE3", note.getText().toString());
LoadPreferences();
note.setText("");
} else if (textvedNote4.equals("")&& !textvedNote3.equals("")) {
Log.e(TAG,"textvedNote4: Inside "+textvedNote3.length());
SavePreferences("NOTE4", note.getText().toString());
LoadPreferences();
note.setText("");
} else if (textvedNote5.equals("")&& !textvedNote4.equals("")) {
Log.e(TAG,"textvedNote5: Inside "+textvedNote4.length());
SavePreferences("NOTE5", note.getText().toString());
LoadPreferences();
note.setText("");
} else if (textvedNote6.equals("")&& !textvedNote5.equals("")) {
SavePreferences("NOTE6", note.getText().toString());
Log.e(TAG,"textvedNote6: Inside "+textvedNote5.length());
LoadPreferences();
note.setText("");
}
} else if (view == clearText) {
ClearTextViews();
}else if (view == ClearAll){
ClearTextViews();
textSavedNote1.setText("");
textSavedNote2.setText("");
textSavedNote3.setText("");
textSavedNote4.setText("");
textSavedNote5.setText("");
textSavedNote6.setText("");
}
}
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedNote1 = sharedPreferences.getString("NOTE1", "");
String strSavedNote2 = sharedPreferences.getString("NOTE2", "");
String strSavedNote3 = sharedPreferences.getString("NOTE3", "");
String strSavedNote4 = sharedPreferences.getString("NOTE4", "");
String strSavedNote5 = sharedPreferences.getString("NOTE5", "");
String strSavedNote6 = sharedPreferences.getString("NOTE6", "");
if (!strSavedNote1.equals("")) {
Log.e(TAG,"LoadPreferences1: "+strSavedNote1);
textSavedNote1.setText(strSavedNote1);
} else if (!strSavedNote2.equals("")) {
Log.e(TAG,"LoadPreferences2: "+strSavedNote2);
textSavedNote2.setText(strSavedNote2);
} else if (!strSavedNote3.equals("")) {
Log.e(TAG,"LoadPreferences3: "+strSavedNote3);
textSavedNote3.setText(strSavedNote3);
} else if (!strSavedNote4.equals("")) {
textSavedNote4.setText(strSavedNote4);
} else if (!strSavedNote5.equals("")) {
textSavedNote5.setText(strSavedNote5);
} else if (!strSavedNote6.equals("")) {
textSavedNote6.setText(strSavedNote6);
}
}
private void ClearTextViews(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
}
}