Android: Save image from Internal storage in SharedPreferences and display it - java

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();

Related

shared preference to save profile image

In my app I want to make a profile page with default image profile and allow to user to change it by take a picture from camera or choose image from gallery, I did that successfully and here's my code:
public class MainActivity extends AppCompatActivity {
private static final int pick = 1, capture = 2;
Uri imgeUri, touri;
ImageView imp;
SharedPreferences sh;
SharedPreferences.Editor editor;
String S;
boolean d=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("eee","in resume");
setContentView(R.layout.activity_main);
sh = getSharedPreferences("my" ,Context.MODE_PRIVATE);
editor=sh.edit();
imp = (ImageView) findViewById(R.id.profile_image);
if(d==false) {
imp.setImageResource(R.drawable.photo);
}
else{
imp.setImageURI(Uri.parse(sh.getString("link", null)));
}
}
public void changepic(View V) {
final String[] items = {"Take picture", "Choose Picture",
"cancle"};
AlertDialog.Builder build = new AlertDialog.Builder(this);
build.setTitle("Add Photo");
build.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (items[which].equals("Choose Picture")) {
Log.d("test","bh");
Intent i = new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivityForResult(i, pick);
} else if (items[which].equals("Take picture")) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, capture);
}
}
}).create().show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == pick && resultCode == RESULT_OK) {
imgeUri = data.getData();
Log.d("test","pick");
imp.setImageURI(imgeUri);
editor.putString("link",String.valueOf(imgeUri));
//Log.d("test",f);
editor.commit();
d=true;
} else if (requestCode == capture && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imp.setImageBitmap(imageBitmap);
}
}
But the problem is when selecting an image I save it in shared preference the image appears just fine when I'am in activity when go to another and return back this disappear and the activity show the default image, i know the reason it because every time i return to profile activity this was created again and the boolean variable d was false again.
How can i fix that when i must call the get preference.?
In the "onActivityResult()" method, save the imageUri (or imagePath) obtained to sharedPreferences.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor edit = preferences.edit();
edit.putString(key, value);
edit.apply();
Instead of using boolean, check if sharedPreference value is not a null string.If the sharedPreference value is not a null string, update the imageview with imageUri (or imagePath) from sharedPreference.
For loading image in imageView, i recommend you to use photo loading libraries like Picasso or Glide.

Error while transfer data from 2nd activity

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();
}
});

How to get the result from onActivityResult method for sharedpreferences

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();
}
}
}

ImageView not showing image selected from gallery

So I have a button that loads the gallery, and selects an image using this code...
public void getGalleryImage(View v){
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivityForResult(intent, 1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
galleryImage.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
But when it goes back to the original activity, the ImageView still doesn't show anything. It doesn't give me any errors, or anything like that. Here the XML for the ImageView...
<ImageView
android:id="#+id/galleryImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
How can I get it to show?
I ended up figuring something out. I just did...
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
galleryImage.setImageURI(selectedImage);
}
This worked for what I was trying to accomplish.
Try this:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
galleryImage.setImageBitmap(MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri));
}
}
public class MainActivity extends AppCompatActivity{
ImageView image;
Button pick;
int TAG_IMAGE = 100;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.imageView);
pick = (Button) findViewById(R.id.button);
pick.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent,"Select Image "),TAG_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == TAG_IMAGE && resultCode == RESULT_OK )
{
Uri selectedImage = data.getData();
try
{
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,filePath,null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePath[0]);
String images = cursor.getString(columnIndex);
image.setImageURI(selectedImage);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}

How to capture image and how to get image from gallery in android

I am integrating a code for how to capture image and how to get image from gallery.Here is my source code. its working fine for individual but it didn't show the imageview when upload image from gallery. please help me
private static int RESULT_LOAD_IMAGE = 1;
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView,imageView1;
private static final int SELECT_PICTURE = 1;
String selectedPath;
private String selectedImagePath;
Uri selectedImageUri;
//ADDED
private String filemanagerstring;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
//Log.d(TAG, "onShutter'd");
}
};
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
protected void onActivityResult1(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
Declare Global Variables just after your class declaration at the top:
private static int RESULT_LOAD_IMAGE = 1;
private static final int PICK_FROM_GALLERY = 2;
Bitmap thumbnail = null;
Call the intent like this: (Yourfunction)
public void YourFunction(){
Intent in = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(in, RESULT_LOAD_IMAGE);
}
Handle the result like this: Declare this outside of your onCreate anywhere in the class.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data){
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
thumbnail = (BitmapFactory.decodeFile(picturePath));
Thumbnail is your image, go play with it!

Categories

Resources