【发布时间】:2013-11-28 02:46:46
【问题描述】:
我在这里有一个FileOutputstream:
public void SaveImage(Bitmap default_b) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 100000;
n = generator.nextInt(n);
String fname = "Image-" + n +".jpg";
File file = new File (myDir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = openFileOutput("file", Context.MODE_WORLD_WRITEABLE);
default_b.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
但是我在这一行得到一个错误:
FileOutputStream out = openFileOutput("file", Context.MODE_WORLD_WRITEABLE);
说 openFileOutput 是未定义的 *(请注意这是在基础适配器类中,当我尝试从上下文中执行此操作时,Context.getApplicationContext().openFileOutput 收到错误“无法对非静态方法进行静态引用getApplicationContext() from type Context") 我还收到警告说 Context.MODE_WORLD_WRITABLE 已被弃用。
然后我在这里有我的 FileInputstream(在另一个扩展 BaseAdapter 的类中):
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Try to reuse the views
ImageView view = (ImageView) convertView;
// if convert view is null then create a new instance else reuse it
if (view == null) {
view = new ImageView(mContextGV);
Log.d("GridViewAdapter", "new imageView added");
}
try {
FileInputStream in = new openFileInput("file");
BufferedInputStream buf = new BufferedInputStream(in);
byte[] bitMapA = new byte[buf.available()];
buf.read(bitMapA);
Bitmap bM = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
view.setImageBitmap(bM);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
e.printStackTrace();
}
view.setImageResource(drawables.get(position));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
view.setTag(String.valueOf(position));
return view;
}
这行有错误:
FileInputStream in = new openFileInput("file");
说 openFileInput 未定义,当我将其更改为:
FileInputStream in = new Context.getApplicationContext().openFileInput("file");
我收到一条错误消息,提示“Context.getApplicationContext() 无法解析为类型”
【问题讨论】:
-
您需要将您的活动上下文传递给您的适配器并使用它。作为旁注,你真的不应该让你的视图适配器打开文件,因为这会对性能造成巨大的影响。
-
好的,谢谢!我可以使用
FileOutputStream out = mContext.getApplicationContext().openFileOutput("file", Context.MODE_WORLD_WRITEABLE);修复 FOS 的错误,但我仍然在 FIS 上收到错误,并且我确保在适配器顶部有这个private Context Context; -
另外,您建议我怎么做才能不让视图适配器打开文件?
-
仅仅声明
private Context context;没有任何意义,它会是null。您需要传递一个实际的上下文(例如对调用活动的引用)并使用它。有一些库可以在列表中进行图像缓存和加载,并在很大程度上为您解决了这个问题。看看我之前的回答:stackoverflow.com/a/16859222/833647
标签: android fileinputstream fileoutputstream