简体   繁体   中英

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;
}
  1. 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); }

    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM