保存数据(4)利用session进行图片与对象存储共享

图片存储

try
		{   
			SharedPreferences sharedPreferences = getSharedPreferences(
					"base64", Activity.MODE_PRIVATE);
			Editor editor = sharedPreferences.edit();
			ByteArrayOutputStream baos = new ByteArrayOutputStream();			
			BitmapFactory.decodeResource(getResources(), R.drawable.flower)
					.compress(CompressFormat.JPEG, 50, baos);
			String imageBase64 = new String(Base64.encode(baos.toByteArray(),
					Base64.DEFAULT));			
			editor.putString("image", imageBase64);
			editor.commit();
			baos.close();
		}
		catch (Exception e)
		{
			// TODO: handle exception
		}

图片读取

try
		{
			Product product = new Product();

			product.name = "Android手机";
			product.price = 2800;
			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			ObjectOutputStream oos = new ObjectOutputStream(baos);
			oos.writeObject(product);

			SharedPreferences sharedPreferences = getSharedPreferences(
					"base64", Activity.MODE_PRIVATE);
			Editor editor = sharedPreferences.edit();
			sharedPreferences = getSharedPreferences("base64",
					Activity.MODE_PRIVATE);

			String productBase64 = new String(Base64.encode(baos.toByteArray(),
					Base64.DEFAULT));

			editor.putString("product", productBase64);
			editor.commit();
			oos.close();
		}
		catch (Exception e)
		{
			// TODO: handle exception
		}

对象存储

try
		{
			Product product = new Product();

			product.name = "Android手机";
			product.price = 2800;
			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			ObjectOutputStream oos = new ObjectOutputStream(baos);
			oos.writeObject(product);

			SharedPreferences sharedPreferences = getSharedPreferences(
					"base64", Activity.MODE_PRIVATE);
			Editor editor = sharedPreferences.edit();
			sharedPreferences = getSharedPreferences("base64",
					Activity.MODE_PRIVATE);

			String productBase64 = new String(Base64.encode(baos.toByteArray(),
					Base64.DEFAULT));

			editor.putString("product", productBase64);
			editor.commit();
			oos.close();
		}
		catch (Exception e)
		{
			// TODO: handle exception
		}


对象读取

		try
		{
			SharedPreferences sharedPreferences = getSharedPreferences(
					"base64", Activity.MODE_PRIVATE);

			String base64Product = sharedPreferences.getString("product", "");

			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			byte[] productBytes = Base64.decode(base64Product.getBytes(),
					Base64.DEFAULT);
			ByteArrayInputStream bais = new ByteArrayInputStream(productBytes);
			ObjectInputStream ois = new ObjectInputStream(bais);
			Product product = (Product) ois.readObject();
			Toast.makeText(this,
					"name:" + product.name + "\nprice:" + product.price,
					Toast.LENGTH_LONG).show();
			ois.close();

		}
		catch (Exception e)
		{
			// TODO: handle exception
		}





阅读更多
个人分类: android
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭