如何在Gridview上保留图像?请有人

时间:2014-05-13 18:33:58

标签: android android-intent android-gridview android-gallery android-external-storage

我在下面的代码中列出了从Gallery中选取的图像列表到GridView布局中。 这些图片在GridView布局中显示得很好,但问题是当我关闭应用程序或从图库中选择不同的图片时这些图片会消失。

有人请指出我正确的方向吗?

非常感谢任何帮助。

代码:

public class MainActivity extends Activity {

   GridView gridGallery;
   Handler handler;
   Gallery_Adapter_Activity adapter;

   Button btnGalleryPick;
   Button btnGalleryPickMul;

   String action;
   ViewSwitcher viewSwitcher;
   ImageLoader imageLoader;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);

    initImageLoader();
    init();
}

private void initImageLoader() {
    @SuppressWarnings("deprecation")
    DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
            .cacheOnDisc().imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
            .bitmapConfig(Bitmap.Config.RGB_565).build();
    ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
            this).defaultDisplayImageOptions(defaultOptions).memoryCache(
            new WeakMemoryCache());

    ImageLoaderConfiguration config = builder.build();
    imageLoader = ImageLoader.getInstance();
    imageLoader.init(config);
}

private void init() {

    handler = new Handler();
    gridGallery = (GridView) findViewById(R.id.gridGallery);
    gridGallery.setFastScrollEnabled(true);                     
    adapter = new Gallery_Adapter_Activity(getApplicationContext(), imageLoader);
    adapter.setMultiplePick(false);
    gridGallery.setAdapter(adapter);

    viewSwitcher = (ViewSwitcher) findViewById(R.id.viewSwitcher);
    viewSwitcher.setDisplayedChild(1);


    Button done_button = (Button) findViewById(R.id.done);      
    done_button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {       
            finish();                           
        }                       
    });


    btnGalleryPickMul = (Button) findViewById(R.id.btnGalleryPickMul);
    btnGalleryPickMul.setOnClickListener(new View.OnClickListener() {                               

        @Override
        public void onClick(View v) {       //Add Images Button OnClickListener
            Intent i = new Intent(Multiple_Pick_Activity.ACTION_MULTIPLE_PICK);
            startActivityForResult(i, 12345);           
        }                           
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == result_requestcode && resultCode == Activity.RESULT_OK)

{       

SDcardPath_Activity SDcardPath_Class = new SDcardPath_Activity();

String[] ALL_Paths = data.getStringArrayExtra("all_path");

for (String single_path : ALL_Paths) 
{      

    SQ_LITE_DATABASE.addImageFile(single_path);           

}

try { 


ArrayList<SDcardPath_Activity> SQLite_Databse_Data = SQ_LITE_DATABASE.readImageFiles();
SQLite_Databse_Data.add(SDcardPath_Class);

viewSwitcher.setDisplayedChild(0);
adapter.addAll(SQLite_Databse_Data);        

Intent intent = new Intent (Image_MainActivity.this, Image_MainActivity.class);
startActivity(intent);
finish();

  } catch (Exception e) 
  {
   e.printStackTrace();
   return;

  }
 }       
}

编辑:发布上面的工作代码

3 个答案:

答案 0 :(得分:1)

我建议您使用SQlite database来存储图片路径 拍照时,请将它们保存在SD卡中,并将其路径记录在数据库中 每次开始活动时都会迭代数据库,获取所有内容并填充GridView 如果您不打算保存大量图像,SharedPreferences会很好。

答案 1 :(得分:1)

将这些放入你的onActivityResult:

  @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == result_requestcode && resultCode == Activity.RESULT_OK)

    {       

    SDcardPath_Activity SDcardPath_Class = new SDcardPath_Activity();

    String[] ALL_Paths = data.getStringArrayExtra("all_path");

    for (String single_path : ALL_Paths) 
    {      

        SQ_LITE_DATABASE.addImageFile(single_path);           

    }

 try { 


    ArrayList<SDcardPath_Activity> SQLite_Databse_Data = SQ_LITE_DATABASE.readImageFiles();
    SQLite_Databse_Data.add(SDcardPath_Class);

    viewSwitcher.setDisplayedChild(0);
    adapter.addAll(SQLite_Databse_Data);        

    Intent intent = new Intent (Image_MainActivity.this, Image_MainActivity.class);
    startActivity(intent);
    finish();

   } catch (Exception e) 
   {
    e.printStackTrace();
    return;

   }
  }       
 }

答案 2 :(得分:0)

如果您需要在关闭应用时保留列表,则需要将列表存储到 SharedPreferences,数据库或文件。

方法I:使用SharedPreferences。

将所选文件保存到SharedPreferences

 // selectedFiles is Set<String> with all your selected files
 Set<String> selectedFiles = new HashSet<String>();

 // TODO put your selected file names into selectedFiles set

 SharedPreferences prefs = getSharedPreferences("prefs_selection", 0);
 SharedPreferences.Editor editor = prefs.edit();

 editor.putStringSet("selection", selectedFiles);

 // save
 editor.commit();

从SharedPreferences中恢复所选文件

SharedPreferences prefs = getSharedPreferences("prefs_selection", 0);

Set<String> selectedFiles = prefs.getStringSet("selection", null);
if (selectedFiles != null) {
    // TODO put elements of selectedFiles into appropriate your elements
}

方法II:使用SQLLiteDatabase。

定义派生自SQLiteOpenHelper的类。

public class ImagesOpenHelper extends SQLiteOpenHelper {

    private static final String KEY_IMAGE = "image_file";
    private static final String DATABASE_NAME = "imagesdb";
    private static final int DATABASE_VERSION = 1;
    private static final String IMAGES_TABLE_NAME = "images";
    private static final String IMAGES_TABLE_CREATE =
            "CREATE TABLE " + IMAGES_TABLE_NAME + " (" +
            KEY_IMAGE + " TEXT);";

    public ImagesOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(IMAGES_TABLE_CREATE);
    }

    public void addImageFile(String file) {
        ContentValues values = new ContentValues();
        values.put(KEY_IMAGE, file);

        getWritableDatabase().insert(IMAGES_TABLE_NAME, null, values);
    }

    public void readImageFiles() {
        Cursor cursor = getReadableDatabase().query(IMAGES_TABLE_NAME, new String[] { KEY_IMAGE }, null, null, null, null, null, null);

        try {
            if (!cursor.moveToFirst())
                return ; 

            ArrayList<SDcardPath_Activity> Picture_List = new ArrayList<SDcardPath_Activity>();

            do {
                String file = cursor.getString(0);

                SDcardPath_Activity PICTURE = new SDcardPath_Activity();
                PICTURE.sdcardPath = file;
                Picture_List.add(PICTURE);

            } while (cursor.moveToNext());

            viewSwitcher.setDisplayedChild(0);
            adapter.addAll(Picture_List);
        }
        finally {
            cursor.close();
        }
    }
}

在活动的onCreate中创建此类的对象。 调用readImageFiles()来读取图像文件路径。 调用addImageFile(String file)将图像文件路径添加到数据库中。

在ImageLoader imageLoader行之后添加以下行:

ImagesOpenHelper imagesOpenHelper;

添加到onCreate

imagesOpenHelper = new ImagesOpenHelper(this);
imagesOpenHelper.readImageFiles();

在onActivityResult中,将以下行添加到for循环:

imagesOpenHelper.addImageFile(string);