我是android / java编程的新手,我遇到一个错误,说明符号getContext
无法解析,我正试图从我的应用程序中获取图片保存到照片库在手机主外部存储。如果有人能帮助我解决这个错误,我将非常感谢任何输入:
public void saveImage(){
String fileName="Site" + System.currentTimeMillis();
ContentValues values=new ContentValues();
values.put(MediaStore.Images.Media.TITLE,fileName);
values.put(MediaStore.Images.Media.DATE_ADDED,System.currentTimeMillis());
values.put(MediaStore.Images.Media.MIME_TYPE,"image/jpg");
Uri uri=getContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
try {
OutputStream outStream=getContext().getContentResolver().openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,outStream);
outStream.flush();
outStream.close();
Toast message=Toast.makeText(getContext(),R.string.message_saved,Toast.LENGTH_SHORT);
message.setGravity(Gravity.CENTER,message.getXOffset() / 2,message.getYOffset() / 2);
message.show();
}
catch ( IOException ex) {
Toast message=Toast.makeText(getContext(),R.string.message_error_saving,Toast.LENGTH_SHORT);
message.setGravity(Gravity.CENTER,message.getXOffset() / 2,message.getYOffset() / 2);
message.show();
}
答案 0 :(得分:2)
我建议你创建类似这样的东西:
public class ContextGetter extends Application {
private static Context context;
public void onCreate(){
super.onCreate();
context = getApplicationContext();
}
public static Context getAppContext() {
return context;
}
}
每当您需要Context
时,只需使用getAppContext()
方法。
顺便说一句,您需要在清单中进行一些更改:
<application
android:name=".ContextGetter"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
并在application
标记