Android: Store Photo that i too in app in SharedPreferences - android

I'm trying to store a photo in SharedPreferences that it took from inside my app.
but i cant find any code that will help me with that.
can you help me with it please ?
public class RegisterActivity extends Activity {
private final int REQUEST_IMAGE = 100;
EditText nameEditText;
EditText phoneEditText;
EditText emailEditText;
EditText bdayEditText;
ImageView photoImageView;
ImageButton cameraButton;
Button saveButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
// String nameEt = nameEditText.getText().toString();
// String phoneEt = phoneEditText.getText().toString();
// String emailEt = emailEditText.getText().toString();
// String bdayEt = bdayEditText.getText().toString();
photoImageView = (ImageView) findViewById(R.id.photoImageView);
cameraButton = (ImageButton) findViewById(R.id.cameraImageButton);
cameraButton.setOnClickListener(cameraButtonListener);
saveButton = (Button) findViewById(R.id.saveButton);
saveButton.setOnClickListener(saveButtonListener);
}
private OnClickListener cameraButtonListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE);
}
};
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK) {
Bitmap userImage = (Bitmap) data.getExtras().get("data");
photoImageView.setImageBitmap(userImage);
}
};
private OnClickListener saveButtonListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SharedPreferences sharedPreferences = getSharedPreferences(
"WaiterData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
nameEditText = (EditText) findViewById(R.id.nameEditText);
phoneEditText = (EditText) findViewById(R.id.phoneEditText);
emailEditText = (EditText) findViewById(R.id.emailEditText);
bdayEditText = (EditText) findViewById(R.id.bdayEditText);
if (nameEditText.getText().length() > 0
&& phoneEditText.getText().length() > 0
&& emailEditText.getText().length() > 0
&& bdayEditText.getText().length() > 0) {
editor.putString("name", nameEditText.getText().toString());
editor.putString("phone", phoneEditText.getText().toString());
editor.putString("email", emailEditText.getText().toString());
editor.putString("bday", bdayEditText.getText().toString());
// move back to MainActivity
Intent intent = new Intent(RegisterActivity.this,
MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(RegisterActivity.this,
"Please fill all The fields", Toast.LENGTH_SHORT)
.show();
}
}
};
}
and how can i can get the code out in other activity ?

The way I'm using to store images using SharedPreferences is to encode your image bitmap to a String then store that string, and then when needing the image retrieve that String and decode it again to a bitmap:
// declaring the sharedPreferences
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
// encoding image bitmap to String
int size = userImage.getWidth() * userImage.getHeight();
ByteArrayOutputStream stream = new ByteArrayOutputStream(
size);
userImage.compress(Bitmap.CompressFormat.JPEG, 50,
stream);
byte[] b = stream.toByteArray();
Editor editor = sharedPreferences.edit();
editor.putString("userImage", encodedImage);
editor.commit();
stream.close();
stream = null;
// then when needing that image again from the SharedPreferences
String decoded_image = sharedPreferences.getString("userImage", "default");
try{
byte[] decodedString = Base64.decode(decoded_image, Base64.DEFAULT);
Bitmap stored_userImage = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
// do whatever you want with it now
}catch(OutOfMemoryError oom){
}

Related

Saving current ImageView state for closing and reopening a app

I'm trying to make a app where i can take a picture of something and then set that picture to a ImageView and I have succeded with that. the next step is to be able the save the picture in the imageView so that the picture remains the same even when closing and reopening the app. I am using SharedPrefrences for storing some other values but i can't find a way to use it for images. Here is my code:
package com.example.pongrknare;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private ImageView imageView1;
private ImageView imageView2;
private ImageView imageView3;
private ImageView imageView4;
private ImageView imageView5;
private ImageView imageView6;
private TextView textView1;
private TextView textView2;
private TextView textView3;
private TextView textView4;
private TextView textView5;
private TextView textView6;
private Switch undoSwitch;
private int nr = 1;
private int p1 = 0;
private int p2 = 0;
private int p3 = 0;
private int p4 = 0;
private int p5 = 0;
private int p6 = 0;
public static final String SHARED_PREFS = "sharedPrefs";
public static final String P1 = "P1_value";
public static final String P2 = "P2_value";
public static final String P3 = "P3_value";
public static final String P4 = "P4_value";
public static final String P5 = "P5_value";
public static final String P6 = "P6_value";
private static final int REQUEST_IMAGE_CAPTURE = 101;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView1 = findViewById(R.id.imageView1);
imageView2 = findViewById(R.id.imageView2);
imageView3 = findViewById(R.id.imageView3);
imageView4 = findViewById(R.id.imageView4);
imageView5 = findViewById(R.id.imageView5);
imageView6 = findViewById(R.id.imageView6);
textView1 = findViewById(R.id.textView1);
textView2 = findViewById(R.id.textView2);
textView3 = findViewById(R.id.textView3);
textView4 = findViewById(R.id.textView4);
textView5 = findViewById(R.id.textView5);
textView6 = findViewById(R.id.textView6);
undoSwitch = findViewById(R.id.undoSwitch);
loadData();
update_text();
}
public void takePicture1(View view) {
Intent imageTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
nr = 1;
if(imageTakeIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(imageTakeIntent,REQUEST_IMAGE_CAPTURE);
}
}
public void takePicture2(View view) {
Intent imageTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
nr = 2;
if(imageTakeIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(imageTakeIntent,REQUEST_IMAGE_CAPTURE);
}
}
public void takePicture3(View view) {
Intent imageTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
nr = 3;
if(imageTakeIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(imageTakeIntent,REQUEST_IMAGE_CAPTURE);
}
}
public void takePicture4(View view) {
Intent imageTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
nr = 4;
if(imageTakeIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(imageTakeIntent,REQUEST_IMAGE_CAPTURE);
}
}
public void takePicture5(View view) {
Intent imageTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
nr = 5;
if(imageTakeIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(imageTakeIntent,REQUEST_IMAGE_CAPTURE);
}
}
public void takePicture6(View view) {
Intent imageTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
nr = 6;
if(imageTakeIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(imageTakeIntent,REQUEST_IMAGE_CAPTURE);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.reset_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.ja1:
p1 = 0;
p2 = 0;
p3 = 0;
p4 = 0;
p5 = 0;
p6 = 0;
update_text();
return true;
case R.id.ja2:
imageView1.setImageResource(R.color.colorImage);
imageView2.setImageResource(R.color.colorImage);
imageView3.setImageResource(R.color.colorImage);
imageView4.setImageResource(R.color.colorImage);
imageView5.setImageResource(R.color.colorImage);
imageView6.setImageResource(R.color.colorImage);
return true;
}
return super.onOptionsItemSelected(item);
}
private void update_text(){
textView1.setText("" + p1);
textView2.setText("" + p2);
textView3.setText("" + p3);
textView4.setText("" + p4);
textView5.setText("" + p5);
textView6.setText("" + p6);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (nr==1) {
Bundle extras = data.getExtras();
Bitmap imageBitmap1 = (Bitmap) extras.get("data");
imageView1.setImageBitmap(imageBitmap1);
saveData();
} else if(nr == 2){
Bundle extras = data.getExtras();
Bitmap imageBitmap2 = (Bitmap) extras.get("data");
imageView2.setImageBitmap(imageBitmap2);
saveData();
}else if(nr == 3){
Bundle extras = data.getExtras();
Bitmap imageBitmap3 = (Bitmap) extras.get("data");
imageView3.setImageBitmap(imageBitmap3);
saveData();
}else if(nr == 4){
Bundle extras = data.getExtras();
Bitmap imageBitmap4 = (Bitmap) extras.get("data");
imageView4.setImageBitmap(imageBitmap4);
saveData();
}else if(nr == 5){
Bundle extras = data.getExtras();
Bitmap imageBitmap5 = (Bitmap) extras.get("data");
imageView5.setImageBitmap(imageBitmap5);
saveData();
}else if(nr == 6){
Bundle extras = data.getExtras();
Bitmap imageBitmap6 = (Bitmap) extras.get("data");
imageView6.setImageBitmap(imageBitmap6);
saveData();
}else{
return;
}
}
public void count1(View view) {
if (undoSwitch.isChecked()== false) {
p1++;
}else if(p1> 0){
p1--;
}
textView1.setText(""+p1);
saveData();
}
public void count2(View view) {
if (undoSwitch.isChecked()== false) {
p2++;
}else if(p2>0){
p2--;
}
textView2.setText(""+p2);
saveData();
}
public void count3(View view) {
if (undoSwitch.isChecked()== false) {
p3++;
}else if(p3>0){
p3--;
}
textView3.setText(""+p3);
saveData();
}
public void count4(View view) {
if (undoSwitch.isChecked()== false) {
p4++;
}else if(p4>0){
p4--;
}
textView4.setText(""+p4);
saveData();
}
public void count5(View view) {
if (undoSwitch.isChecked()== false) {
p5++;
}else if(p5>0){
p5--;
}
textView5.setText(""+p5);
saveData();
}
public void count6(View view) {
if (undoSwitch.isChecked()== false) {
p6++;
}else if(p6>0){
p6--;
}
textView6.setText(""+p6);
saveData();
}
public void saveData(){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(P1, p1);
editor.putInt(P2, p2);
editor.putInt(P3, p3);
editor.putInt(P4, p4);
editor.putInt(P5, p5);
editor.putInt(P6, p6);
editor.apply();
}
public void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
p1 = sharedPreferences.getInt(P1, 0);
p2 = sharedPreferences.getInt(P2, 0);
p3 = sharedPreferences.getInt(P3, 0);
p4 = sharedPreferences.getInt(P4, 0);
p5 = sharedPreferences.getInt(P5, 0);
p6 = sharedPreferences.getInt(P6, 0);
}
}
You can save the photos to the app pictures directory as follows
1. Generate the image file:
private File createImageFile() throws IOException {
String timestamp = new SimpleDateFormat("yyyyMMdd_Hms").format(new Date());
String fileName = "JPEG_" + timestamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File photoImage = File.createTempFile(fileName, ".jpg", storageDir);
// Store this value in field to use later
picture1Path = photoImage.getAbsolutePath();
return photoImage;
}
Add the image file Uri to the IMAGE_CAPTURE intent:
private void takePicture1() {
Intent imageTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
Log.e(MainActivity.class.getSimpleName(), e.getMessage(), e);
}
// Add file Uri to intent
if (photoFile != null) {
Uri photoUri = FileProvider.getUriForFile(
this,"com.your_app_package.fileprovider", photoFile);
imageTakeIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
}
if(imageTakeIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(imageTakeIntent,REQUEST_IMAGE_CAPTURE);
}
}
Save image Uri to shared preferences if image capture successful:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE) {
if (resultCode == Activity.RESULT_OK) {
setPic();
// Save imageUri
preferences.edit().putString("image1Uri", currentPhotoPath).apply();
}
}
}
private void setPic() {
// load and display pic
Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath);
imageView1.setImageBitmap(bitmap);
}
4. Then set up the FileProvider:
In the app manifest.xml inside the tag:
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.your_app_package.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
Also include the WRITE_EXTERNAL_STORAGE permission.
The create the "file_paths.xml" and add:
<paths>
<external-files-path name="my_images" path="/"/>
</paths>
And then in onCreate load the image file Uri from preferences and display:
currentPhotoPath = preferences.getString("image1Uri", null);
if (currentPhotoPath != null) {
setPic();
}

Shared Preferences Deleting Data When App Is Reloaded

I am creating my first project using Android Studio, I am aiming to create an app where you can load photos in from the phones memory and display them so people can see.
I've managed to get it working sort of how I want it to, the pictures in the gallery stay where they should do when I close out of the app and then reopen it - however if I close the app restart it and then try and add a new photo it overwrites the gallery and deletes the pictures I orginally put in. Does anyone have any ideas on how I can fix this? I tried playing with when I create the images ArrayList but that didn't help.
Code:
Main Activity
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST = 0;
private static final int RESULT_LOAD_IMAAGE = 1;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
ImageView imageView;
Button uploadButton;
Button savedPhotos;
List<String> images;
String imageCreated;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST);
}
imageView = (ImageView) findViewById(R.id.imageView);
uploadButton = (Button) findViewById(R.id.button);
savedPhotos = (Button) findViewById(R.id.button2);
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
images = new ArrayList<>();
uploadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAAGE);
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(imageCreated, "Complete");
}
});
savedPhotos.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openPage2();
}
});
}
public void openPage2()
{
Intent intent = new Intent(this, SavedPhotos.class);
startActivity(intent);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch(requestCode)
{
case PERMISSION_REQUEST:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, "Permission Not Granted", Toast.LENGTH_SHORT).show();
finish();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
switch(requestCode)
{
case RESULT_LOAD_IMAAGE:
if(resultCode == RESULT_OK)
{
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.setImageBitmap(BitmapFactory.decodeFile(picturePath));
images.add(picturePath);
StringBuilder stringBuilder = new StringBuilder();
for(String i : images)
{
stringBuilder.append(i);
stringBuilder.append(",");
}
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("images", stringBuilder.toString() );
editor.commit();
}
}
}}
And SavedPhotos
public class SavedPhotos extends AppCompatActivity {
public static final String MyPREFERENCES = "MyPrefs" ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved_photos);
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
String wordsString = sharedpreferences.getString("images", "");
String[] itemWords = wordsString.split(",");
List<String> items = new ArrayList<String>();
LinearLayout layout = (LinearLayout) findViewById(R.id.linear);
for(int i = 0; i < itemWords.length; i++) {
ImageView imageView = new ImageView(this);
imageView.setId(i);
imageView.setPadding(2, 2, 2, 2);
imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
layout.addView(imageView);
items.add(itemWords[i]);
imageView.setImageBitmap(BitmapFactory.decodeFile(items.get(i)));
}
}}
Thank you for your help :)
I actually run to same issues before until i met a well made library and requires nothing and made my code much good looking, FastSave: https://github.com/yehiahd/FastSave-Android.

Getting Same Values For Two Different Keys in Shared Preferences

i am creating an app in which different payments modes are there so for card payments and cheque payments i have created two different activities in which i am getting details from user and save the data into shared Preferences and then app returns back to the activities where other details are also there and then user can save the data on a button click.This data gets saved into Sqlite Database.
My problem is when i am selecting card payment its getting stored properly but the same value also getting stored at cheque No aswell into the sqlite database.Inshort the value of card payment is getting copied into cheque no column by default.
below is my code for Card payment Activity :
public class CardNo extends Activity {
String bankname;
String cardno;
int chq;
TextView textView1, textView2;
EditText editText1, editText2;
Button btn;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.creditdebit);
textView1 = (TextView) findViewById(R.id.tv1);
textView2 = (TextView) findViewById(R.id.tv2);
editText1 = (EditText) findViewById(R.id.bankname);
editText2 = (EditText) findViewById(R.id.cardno);
btn = (Button) findViewById(R.id.btn1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveData();
Intent card = new Intent(CardNo.this, EnterAmount.class);
startActivity(card);
finish();
}
});
}
private void saveData() {
bankname = editText1.getText().toString();
cardno = editText2.getText().toString();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("Bank Name", bankname);
editor.putString("Card No", cardno);
editor.apply();
}
}
Now code for cheque payment Activity :
public class Cheque extends Activity {
String bankname1;
String chequeno;
int chq;
TextView textView1,textView2;
EditText editText1,editText2;
Button btn;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cheque);
textView1=(TextView)findViewById(R.id.tv11);
textView2=(TextView)findViewById(R.id.tv12);
editText1=(EditText)findViewById(R.id.bankname1);
editText2=(EditText)findViewById(R.id.chequeno);
btn=(Button)findViewById(R.id.btn11);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveData();
Intent cheque = new Intent(Cheque.this, EnterAmount.class);
startActivity(cheque);
finish();
}
});
}
private void saveData() {
bankname1 = editText1.getText().toString();
chequeno = editText2.getText().toString();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("Bank Name", bankname1);
editor.putString("Cheque No", chequeno);
editor.apply();
}
}
Now the code of the activity where i am retrieving the data from shared preferences and storing the data into sqlite.
public class EnterAmount extends Activity implements OnClickListener {
Intent intent;
Button save;
Spinner spinnerPayment, spinnerCategory;
EditText etamt, etbdgt, et_get_other;
String date, sBdgt, budget, bankname, cardno, chequeno;
String sAmt;
String spinnerItemSelectedPayment;
String spinnerItemSelectedCategory;
// String category;
int amt;
int date2;
TextView caategories, tv_cat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.enteramount);
save = (Button) findViewById(R.id.bsaveDb);
caategories = (TextView) findViewById(R.id.tvCaategories);
etamt = (EditText) findViewById(R.id.etAmount);
etbdgt = (EditText) findViewById(R.id.etbudget);
spinnerCategory = (Spinner) findViewById(R.id.spinnerCategory);
spinnerPayment = (Spinner) findViewById(R.id.payment_spinner);
List<String> sCategory = new ArrayList<String>();
String[] categories = {"Food", "Bills",
"Travel", "Entertainment", "Office Stationary",
"Medical Expenses", "Fuel"
};
sCategory.add("Food");
sCategory.add("Office Stationary");
sCategory.add("Bills");
sCategory.add("Travel");
sCategory.add("Entertainment");
sCategory.add("Medical Expenses");
sCategory.add("Fuel");
ArrayAdapter<String> sc = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, sCategory);
spinnerCategory.setAdapter(sc);
List<String> l = new ArrayList<String>();
String[] paymentMode = {"Cash", "Credit/Debit Card", "Cheque", "NetBanking"};
l.add("Cash");
l.add("Credit/Debit Card");
l.add("Cheque");
l.add("NetBanking");
ArrayAdapter<String> sp = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, l);
spinnerPayment.setAdapter(sp);
save.setOnClickListener(this);
spinnerCategory.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View selectedItemView, int pos, long id) {
spinnerItemSelectedCategory = parent.getItemAtPosition(pos)
.toString();
}
public void onNothingSelected(AdapterView<?> parentView) {
spinnerItemSelectedCategory = "Food";
}
});
spinnerPayment.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View selectedItemView, int pos, long id) {
spinnerItemSelectedPayment = parent.getItemAtPosition(pos).toString();
if (spinnerItemSelectedPayment.equals("Cheque")) {
Intent cheque = new Intent(EnterAmount.this, Cheque.class);
cheque.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(cheque);
} else if (spinnerItemSelectedPayment.equals("Credit/Debit Card")) {
Intent card = new Intent(EnterAmount.this, CardNo.class);
card.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(card);
}
}
public void onNothingSelected(AdapterView<?> parentView) {
spinnerItemSelectedPayment = "Cash";
}
});
final Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy-HH:mm:ss ");
date = sdf.format(c.getTime());
int yy = c.get(Calendar.YEAR);
int mm = c.get(Calendar.MONTH) + 1;
int dd = c.get(Calendar.DAY_OF_MONTH);
String s = yy + "" + (mm < 10 ? ("0" + mm) : (mm)) + ""
+ (dd < 10 ? ("0" + dd) : (dd));
Log.e("datechange", s);
date2 = Integer.parseInt(s);
Log.e("integer2", "hello" + date2);
}
#Override
public void onBackPressed () {
super.onBackPressed();
finish();
}
private void vibrate(int ms) {
((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).vibrate(ms);
}
private void loadSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
budget = sharedPreferences.getString("Budget", " ");
getSharedPreferences(mypreference,Context.MODE_PRIVATE);
bankname = sharedPreferences.getString("Bank Name", "Not Applicable");
cardno = sharedPreferences.getString("Card No", "Not Applicable");
chequeno = sharedPreferences.getString("Cheque No", "Not Applicable");
}
private void removeSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("Bank Name");
editor.remove("Cheque No");
editor.remove("Card No");
editor.apply();
}
private void savePreferences(String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bsaveDb: {
savePreferences("Budget", etbdgt.getText().toString());
loadSavedPreferences();
sAmt = etamt.getText().toString();
Log.e("category", "Hello" + sAmt);
try {
amt = Integer.parseInt(sAmt);
Log.e("amt is", "" + amt);
} catch (Exception e) {
}
DbClass dc = new DbClass(this);
dc.open();
if (amt == 0) {
Toast.makeText(getApplicationContext(),
"Please insert the amount", Toast.LENGTH_SHORT).show();
} else {
dc.categoryDetailsInsert(amt, spinnerItemSelectedCategory, date, spinnerItemSelectedPayment, date2, bankname, cardno, chequeno);
dc.close();
Toast.makeText(getApplicationContext(), "Saved successfully",
Toast.LENGTH_LONG).show();
amt = 0;
etamt.setText("");
etbdgt.setText(budget);
removeSavedPreferences();
}
break;
}
}
}
}
i am attching a screenshot of sqlite database and you can see bank name is getting stored properly but cardno and cheque no is always same with respect to payment.Screenshot Of Database
Attach your keys to the context tag to prevent override of values.
like:
String TAG = "ContextName or ActivityName";
then on saving do:
pref.put(TAG+key, "value");
Actually above code is Fine the Problem was in the code where i was retrieving code from the database i inserted the same index number for the two different columns. so i was getting same values for cheque no and debit card number.

How to get a Result from Image Capture and save it to Shared Preferences in Android

I am building an app in which I want when the user clicks the imageview, the device camera app to launch and take a picture and set it to the imageview. I have accomplished that!!! But when I exit the app and re-open it the image has been deleted. How can I do it so the image is permanent?
My code:
private SessionManager session;
private static final int REQ_CODE = 1152;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Uri file;
private String fileName = "ImageTaken";
private ImageView imagePhoto;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_data);
session = new SessionManager(getApplicationContext());
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
Toolbar tb = (Toolbar)findViewById(R.id.topBar);
setSupportActionBar(tb);
String name = user.get(SessionManager.KEY_NAME);
TextView watersName = (TextView)findViewById(R.id.waitersName);
TextView date = (TextView)findViewById(R.id.date);
TextView time = (TextView)findViewById(R.id.time);
watersName.setText(Html.fromHtml("<b>" + name + "</b>"));
Calendar c = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd" + "/" + "mm" + "/" + "yyyy");
String text = dateFormat.format(c.getTime());
date.setText(text);
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
String timeF = timeFormat.format(c.getTime());
time.setText(timeF);
Button btnnewworder = (Button)findViewById(R.id.btnnewworder);
btnnewworder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UserData.this, Tables.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);
}
});
Button payment = (Button)findViewById(R.id.btnpayment);
payment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogMessageDisplay.displayInfoMessage(UserData.this, "Payment Details", "There was no order made. \n Make an order and then tap the payment button.", AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
}
});
imagePhoto = (ImageView)findViewById(R.id.waiterPhoto);
imagePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
file = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//file = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, file);
startActivityForResult(intent, REQ_CODE);
}
});
}
OnActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQ_CODE){
if(resultCode == RESULT_OK){
imagePhoto.setImageURI(file);
editor.putString(fileName, file.toString());
editor.commit();
Toast.makeText(UserData.this, "Your file has been saved at " + file, Toast.LENGTH_SHORT).show();
}else if(resultCode == RESULT_CANCELED){
Toast.makeText(UserData.this, "Action Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
Thanks in advance!!!
Try this:
1) Initialize these:
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
2) Modify your onCreate() like:
sharedPreferences = getSharedPreferences(fileName, MODE_PRIVATE);
editor = sharedPreferences.edit();
imagePhoto = (ImageView)findViewById(R.id.waiterPhoto);
String commited = sharedPreferences.getString(fileName, null);
if(commited != null) {
imagePhoto.setImageURI(Uri.parse(commited));
}
3) Modify your onActivityResult() like:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQ_CODE){
if(resultCode == RESULT_OK){
imagePhoto.setImageURI(file);
editor.putString(fileName, file.toString());
editor.commit();
}else if(resultCode == RESULT_CANCELED){
Toast.makeText(UserData.this, "Action Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
And then you will have your desired effect. Hope it helps!!!
SharedPreferences are not meant for holding quantities of data such as imagery. They are meant for holding information about where an image is, or other small selections that the user has chosen.
If you want to save an image off, then you should do just that. Save the image within a local file within the application and then retrieve it later. You can save the location of that file in a SharedPreference object if you would like for you when you return. If it is only one, then you can replace it with the next one in the same file name the next time a picture is taken. This way you always have the latest image available since the last time that picture is taken; even after you shut down and restart the phone.

how update a textview

simple program: 2 buttons (previous/next) and a textview to show text.
by intent I created an Index (inside a method)
private void index(){
Intent i = new Intent(this, Index.class);
startActivityForResult(i, 1);
}
Index.class (with 3 buttons):
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String result = "1";
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();
}
});
Main.class
String value = "1";
final String prog1[] = new String[16];
final String prog2[] = new String[105];
final String prog3[] = new String[66];
int a;
int b;
int c=3;
int array1start = 0; int array1end = 15;
int array2start = 0; int array2end = 105;
int array3start = 0; int array3end = 65;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if (value.equals("1")){
a = array1start;
b = array1end;
prog=prog1;
}
else if (value.equals("2")){
a = array2start;
b = array2end;
prog=prog2;
textView1.setText(""+prog[a]);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
value=result;
Toast toast2=Toast.makeText(this,"value: "+value,Toast.LENGTH_LONG);
toast2.show();
}
if (resultCode == RESULT_CANCELED) {
//Write your code on no result return
}}
}//onAcrivityResult
at this point, choosen choice in index class should be change a result string to "value" string in main class
private void index(){
Intent i = new Intent(this, Index.class);
startActivityForResult(i, 1);
}
my textview take data from array1 or array2 by index class
so, I dont' understand how update textview (because index value is correct).
thanks for the help
Put you code into function onActivityResult
if (value.equals("1")){
a = array1start;
b = array1end;
prog=prog1;
}
else if (value.equals("2")){
a = array2start;
b = array2end;
prog=prog2;
textView1.setText(""+prog[a]);

Categories

Resources