从图库中抓取图像并将该图像设置为RelativeLayout的背景时,我遇到了这些错误。因此,此代码将在OnClick()中打开Gallery,从库中抓取图像,并将其设置为RelativeLayout的背景。
logcat的: Gist
SettingsActivity:
MainActivity mainActivity;
RelativeLayout backgroundView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mainActivity = new MainActivity();
backgroundView = (RelativeLayout) findViewById(R.id.wallpaperView);
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {@link android.app.ActionBar}, if the API is available.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
public void setBackgroundClick(View v)
{
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
Uri targetUri = data.getData();
//textTargetUri.setText(targetUri.toString());
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
//imageView.setImageBitmap(bitmap);
backgroundView.setBackgroundDrawable(new BitmapDrawable(bitmap));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Toast.makeText(this, "Error", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
//NavUtils.navigateUpFromSameTask(this);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
由于
答案 0 :(得分:2)
从日志中可以看出backgroundView为null。你能检查findViewById(R.id.wallpaperView)是否找到了一个视图吗?
(看起来日志属于imageView没有评论,因为日志说:
Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
所以我认为位图检索很好,但在你的视图中设置是问题。