In qr scanner reader, after clicking a button it will open the camera and it will scan result. Then it will display result using onactivityresult method.
How to get that result from onActivityResult method, and use it in sharedpreferences? Below is my code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
String scanContent = result.getContents();
customerSno.setText(" " + scanContent);
} else {
Toast.makeText(getApplicationContext(),"Cancelled", Toast.LENGTH_LONG).show();
To save the result in SharedPreference
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("result", scanContent);
editor.commit();
To retrieve from SharedPreference
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String result = prefs.getString("result", "No saved result");
context is your activity context. If this code is in any activity just use this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==IntentIntegrator.REQUEST_CODE){
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
String scanContent = result.getContents();
customerSno.setText(" " + scanContent);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("result", scanContent);
editor.commit();
} else {
Toast.makeText(getApplicationContext(),"Cancelled", Toast.LENGTH_LONG).show();
}
}
}
Related
I'm trying to load a image from my phone and apply it to an ImageView. I need this image when I re-open the app to be kept in the ImageView.
I'm trying to do something like that with shared preferences. But I get the following log error:
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'android.content.SharedPreferences$Editor android.content.SharedPreferences$Editor.putString(java.lang.String, java.lang.String)' on a null object reference
private static final int PICK_IMAGE = 100;
static SharedPreferences sharedPref;
static SharedPreferences.Editor editor;
private static final String PREFS_NAME = "preferenceName";
Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
PROFILE_IMG = (ImageView)findViewById(R.id.profile_image);
PHOTObutton = (Button)findViewById(R.id.photo_btn);
// Get from the SharedPreferences
sharedPref = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
String imageUriString = sharedPref.getString("imageURI", null);
Uri imageUri = Uri.parse(imageUriString);
PROFILE_IMG.setImageURI(imageUri);
//open gallery-- select profile photo
PHOTObutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openGallery();
}
});
}
private void openGallery() {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){
imageUri = data.getData();
sharedPref = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
editor.putString("imageURI", imageUri.toString());
editor.commit();
PROFILE_IMG.setImageURI(imageUri);
}
}
What am I doing wrong?
This error is because your editor is null. Try this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){
imageUri = data.getData();
SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("imageURI", imageUri.toString());
editor.commit();
PROFILE_IMG.setImageURI(imageUri);
}
}
you forgot to inizile the editor add this into your onactivity result
editor=sharedPref.edit()
editor.putString("imageURI", imageUri.toString());
editor.commit();
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
I have an app where you upload images to my company server
So The user enters their login details, Email, Password and clientID(4 digit code)(in LoginActivity.java) and then this information must be passed to all the other activities, this passed information is then used to build a URL. Now the issue I am having is the Sharedprefrences doesn't share correctly...they either come up as NULL on the url or as just "email" or "password"
The Information is saved correctly in login activity but when i try to pass it to other activities it fails
Login activity here I save the prefrences
public class LoginActivity extends AppCompatActivity implements TextWatcher {
SharedPreferences MyPrefs;
Intent intent;
SharedPreferences.Editor editor;
public static final String PREF_NAME= "MYPREFS";
public static final String ID = "ClientID" ;
public static final String EMAIL = "username" ;
public static final String PASS = "password";
EditText email, password, id;
#SuppressLint("CommitPrefEdits")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button buttonOne=findViewById(R.id.button);
buttonOne.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent activity2Intent=new Intent(getApplicationContext(), MainActivity.class);
startActivity(activity2Intent);
}
});
MyPrefs= getSharedPreferences(PREF_NAME, 0);
editor = MyPrefs.edit();
email=findViewById(R.id.emailtext);
password=findViewById(R.id.pwdtext);
id=findViewById(R.id.clientid);
email.setText(MyPrefs.getString(EMAIL,"username"));
password.setText(MyPrefs.getString(PASS,"password"));
id.setText(MyPrefs.getString(ID, "id"));
email.addTextChangedListener(this);
password.addTextChangedListener(this);
id.addTextChangedListener(this);
MyPrefs =getSharedPreferences(EMAIL,0);
MyPrefs =getSharedPreferences(ID,0);
MyPrefs =getSharedPreferences(PASS,0);
intent = new Intent(LoginActivity.this,CameraActivity.class);
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
managePrefs();
}
#Override
public void afterTextChanged(Editable editable) {
managePrefs();
}
private void managePrefs(){
SharedPreferences.Editor editor =MyPrefs.edit();
editor.putString(EMAIL, email.getText().toString().trim());
editor.putString(PASS, password.getText().toString().trim());
editor.putString(ID, id.getText().toString().trim());
editor.apply();
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
Camera Activity this is where the shared prefrences must be passed to
public class CameraActivity extends AppCompatActivity implements View.OnClickListener {
private final int PICK_IMAGE=12345;
private final int REQUEST_CAMERA=6352;
private static final int REQUEST_CAMERA_ACCESS_PERMISSION=5674;
private Bitmap bitmap;
String myURL;
String email;
String clientId;
String pwd;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
My code for calling sharedprefrences
SharedPreferences sharedPreferences = getSharedPreferences(LoginActivity.PREF_NAME, 0);
email = sharedPreferences.getString(LoginActivity.EMAIL, "username");
clientId = sharedPreferences.getString(LoginActivity.ID, "id");
pwd = sharedPreferences.getString(LoginActivity.PASS, "password");
imageView=findViewById(R.id.imageView);
Button fromCamera=findViewById(R.id.fromCamera);
Button fromGallery=findViewById(R.id.fromGallery);
Button upload=findViewById(R.id.upload);
upload.setOnClickListener(this);
fromCamera.setOnClickListener(this);
fromGallery.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.fromCamera:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_ACCESS_PERMISSION);
} else {
getImageFromCamera();
}
break;
case R.id.fromGallery:
getImageFromGallery();
break;
case R.id.upload:
if (bitmap != null)
uploadImageToServer();
break;
}
}
private void uploadImageToServer() {
#SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
String currentTimeStamp = dateFormat.format(new Date());
final ProgressDialog pd=new ProgressDialog(CameraActivity.this);
pd.setMessage("Uploading, Please Wait....");
pd.show();
Intent intent = getIntent();
String Item= intent.getStringExtra("Spinner");
String Item2= intent.getStringExtra("Spinner2");
Uri.Builder builder=new Uri.Builder();
builder.scheme("https")
.authority("www.smartpractice.co.za")
.appendPath("files-upload-ruben.asp")
.appendQueryParameter("MyForm", "Yes")
.appendQueryParameter("ClientID",clientId)
.appendQueryParameter("Username", email)
.appendQueryParameter("Pwd", pwd)
.appendQueryParameter("category",Item )
.appendQueryParameter("client",Item2 );
myURL=builder.build().toString();
Toast toast = Toast.makeText(CameraActivity.this, myURL , Toast.LENGTH_LONG);
toast.show();
File imageFile=persistImage(bitmap,currentTimeStamp);
Ion.with(this)
.load(myURL)
.uploadProgressDialog(pd)
.setMultipartFile("SP-LOG", "image/jpeg", imageFile)
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
pd.cancel();
Toast.makeText(getApplicationContext(),"Uploaded",Toast.LENGTH_SHORT).show();
}
});
}
private File persistImage(Bitmap bitmap, String name) {
File filesDir=getApplicationContext().getFilesDir();
File imageFile=new File(filesDir, name + ".jpg");
OutputStream os;
try {
os=new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.flush();
os.close();
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
}
return imageFile;
}
private void getImageFromCamera() {
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
private void getImageFromGallery() {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
try {
InputStream inputStream=getContentResolver().openInputStream(data.getData());
bitmap=BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} else if (requestCode == REQUEST_CAMERA) {
if (resultCode == Activity.RESULT_OK) {
Bundle extras=data.getExtras();
bitmap=(Bitmap) extras.get("data");
imageView.setImageBitmap(bitmap);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA_ACCESS_PERMISSION) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getImageFromCamera();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
To store data in shared preference do something like this:
private SharedPreferences.Editor editor = getSharedPreferences(PREF_NAME, MODE_PRIVATE).edit();
editor.putString("email", email);
editor.putString("ID", id);
editor.putString("Pass", password);
editor.apply();
so I'll give you bit of explanation, when you write editor.putString("email", email); it tells editor to put your email against key "email".
Now, if you want to read these values back do it like this:
String email = getSharedPreferences(PREF_NAME, MODE_PRIVATE).getString("email", "");
String ID= getSharedPreferences(PREF_NAME, MODE_PRIVATE).getString("ID", "");
String password= getSharedPreferences(PREF_NAME, MODE_PRIVATE).getString("Pass", "");
Leme know if you don't understand anything.
getSharedPrerencences(String name, int mode) returns a reference to a shared preferences file name. That is, after the lines
MyPrefs =getSharedPreferences(EMAIL,0);
MyPrefs =getSharedPreferences(ID,0);
MyPrefs =getSharedPreferences(PASS,0);
your variable MyPrefs points to shared preferences file named password, which is probably not what you intended, since later you read from a file named MYPREFS.
Also, you don't need to call editor = MyPrefs.edit(); if you are just reading from the preferences, like you are doing in onCreate. That is why you get the warning that you have suppressed using #SuppressLint("CommitPrefEdits")
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();
}
});
I'm trying to saves Facebook id and facebook usrname in my SharedPreferences on my android app to use it whenever and wherever i want, but logcat returns me "empty"
here is my "Oncomplete" Facebook method:
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
String result = response.toString();
SharedPreferences pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putString("result", result);
edt.commit();
Log.i("string","PROVAAAAAA");
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link");
request.setParameters(parameters);
request.executeAsync();
}
i noticed that logcat doesn't writes "PROVAAAAAAA"
And here is my callback method:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
CallbackManager callbackManager = CallbackManager.Factory.create();
callbackManager.onActivityResult(requestCode, resultCode, data);
SharedPreferences pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
String id = pref.getString("facebook_id", "empty");
Log.i("RESULT", id );
Log.i("RESULT", "***************");
edt.commit();
}
You're using the Activity#getPreferences method when what you really want is PreferenceManager#getDefaultSharedPreferences. The former is described as being "Activity persistent state", which may be why you're having trouble accessing it.
Try replacing all occurrences of getActivity().getPreferences(0) with PreferenceManager.getDefaultSharedPreferences(getActivity()).