Reputation:
When I use the project as public class HomeActivity extends Activity implements OnClickListener
and inside that I use getContentResolver
it show me the error
The method getContentResolver() is undefined for the type new View.OnClickListener(){}
But when I use public class HomeActivity extends ActionBarActivity
it works for me , but how I can handle it in public class HomeActivity extends Activity implements OnClickListener
Code :
public class HomeActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
btnEdit = (Button) findViewById(R.id.btn_edit);
btnEdit.setOnClickListener(this);
btnGallery = (Button) findViewById(R.id.btn_gallery);
btnGallery.setOnClickListener(this);
}
@Override
public void onClick(View view) {
Intent intent;
switch (view.getId()) {
case R.id.btn_edit:
intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, REQUEST_IMAGE);
// startActivityForResult(
// Intent.createChooser(intent, "Select Photo"),
// MyConstants.TAKE_PHOTO);
break;
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {return;}
if (requestCode == REQUEST_IMAGE) {
final Uri uri = data.getData();
Button button= (Button) findViewById(R.id.btn_camera);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try
{
InputStream is = this.getContentResolver().openInputStream(uri);
final Bitmap bmInImg = BitmapFactory.decodeStream(is);
}
catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
Upvotes: 1
Views: 669
Reputation: 2374
Because
getContentResolver()
is the method of the Context Class, not the method ofView.OnClickListener Interface
.
And when you are writing this line
InputStream is = this.getContentResolver().openInputStream(uri);
You are using this
to call the method from View.OnClickListener Interface, Which is not present in Interface, thats why Android is giving you error.
Declare a gloabal Context
Variable.
// Global Var
Context context;
// In onCreate
context = this;
Change this line to
InputStream is = this.getContentResolver().openInputStream(uri);
THIS:
InputStream is = context.getContentResolver().openInputStream(uri);
Upvotes: 1
Reputation: 971
In this line :
InputStream is = this.getContentResolver().openInputStream(uri);
"this" refers to the ClickListener you're creating. You need to use the "this" of the enclosing class like that :
InputStream is = HomeActivity.this.getContentResolver().openInputStream(uri);
Upvotes: 0