Can not resolve symbol REQUEST_CODE - java

I am trying to select an image from gallery using this code placed in my UploadActivity class
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
private void selectImage(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
startActivityForResult(Intent.createChooser(intent,"Select Picture"),REQUEST_CODE);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode,resultCode,data);
if(requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null ){
Uri uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
ImageHolder.setImageBitmap(bitmap);
}
catch (IOException e){
e.printStackTrace();
}
}
}
But it keep giving me the above error. Is there what I need to import and if yes what is it because the IDE - android studio does not show me when I click on options.
If there is nothing to be imported, what can I edit to solve the error?
I'll appreciate your support.

Just define a constant value holding your request code.
Like so private static final Int REQUEST_CODE = 12
The value of the REQUEST_CODE can be any number, but it should be unique in the sense that if your onActivityResult gets called by different sources, each of those sources must have a different request code. Otherwise you will end up in the wrong condition.

The error is clear. The variable REQUEST_CODE has not been declared yet.
Simply declare it as private and initialize it to 1 like this:
private int REQUEST_CODE = 1;
I hope that works

Related

Custom Gallery Image Picker

I would like to allow the user to pock only one image that can be referenced via a uri, I've successfully done this through the following code:
private static final int PICK_IMAGE_REQUEST = 1;
private Uri imageUri;
// Choose file extended from BottomTabView, opens all images on device
public static void openFileChooser(Context context) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
((Activity) context).startActivityForResult(intent, PICK_IMAGE_REQUEST);
// Slide Animation
((Activity) context).overridePendingTransition(R.anim.slide_in_up, R.anim.nothing);
}
// TODO: Is it better to use bitmap or URI
// Check if user has selected file and describe next step
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
// Retrieve image as a URI
imageUri = data.getData();
// Pass image URI to an intent and start activity
Intent intent = new Intent(this, UploadImageActivity.class);
intent.putExtra("imageUri", imageUri.toString());
startActivity(intent);
// Slide Animation
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
this.finish();
}
}
The above code opens the following:
However, I would like to have something like the following:
Question: How can I achieve something more like the "Custom Gallery"?
if you want to custom layout pick image, you need:
create a screen and using recyclerView to make the layout as you want
get all picture gallery (https://stackoverflow.com/a/25957752/10153377)

I cannot get a taken picture just pictures from screenshot

I can't get the normal taken picture by my phone in java. Everything is working while I choose picture from the gallery which is screenshot but when It's normal taken picture it's not returning anything. I will give you some parts of the code where u can see how I'm getting picture.
#Override
public void onActivityResult(int reqCode, int resultCode, final Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (reqCode == PICK_IMAGE && resultCode == Activity.RESULT_OK) {
final Uri imageUri = data.getData();
final String path = getPath(getActivity(), imageUri);
if (path != null) {
try {
File f1 = new File(path);
final AsyncHttpClient client = new AsyncHttpClient(true, 80, 443);
client.addHeader("accept", "application/json");
final RequestParams params = new RequestParams();
params.put("id", id);
params.put("token", token);
params.put("avatar", f1);
And also this
add_avatar.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
// filePickUtils.requestImageGallery(STORAGE_PERMISSION_IMAGE, true, true);
if (getActivity().checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
1);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant that should be quite unique
return;
}
if (getActivity().checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
1);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant that should be quite unique
return;
}
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
photoPickerIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, PICK_IMAGE);
}
});
What would you suggest?
Thanks for your help
Given that you only need to read the image, and upload the data to your backend server, I'd suggest if you use Intent.ACTION_GET_CONTENT instead of Intent.ACTION_PICK.
Why
Your problem might related to what Intent.ACTION_PICK needs to have. The documentation stated:
Input: getData() is URI containing a directory of data (vnd.android.cursor.dir/*) from which to pick an item.
So it means, if you want to use Intent.ACTION_PICK, you need to provide the directory of the data.
Meanwhile if you use Intent.ACTION_GET_CONTENT, you can just set the MIME type of the file that you want to search (just as what you are doing now), and use Context.startActivity(intent).
Additional note from the documentation that you might want to read:
Input: getType() is the desired MIME type to retrieve. Note that no URI is supplied in the intent, as there are no constraints on where the returned data originally comes from. You may also include the CATEGORY_OPENABLE if you can only accept data that can be opened as a stream. You may use EXTRA_LOCAL_ONLY to limit content selection to local data. You may use EXTRA_ALLOW_MULTIPLE to allow the user to select multiple items.
Output: The URI of the item that was picked. This must be a content: URI so that any receiver can access it.
Add a comment here, if you need further information.
Sample Code:
In your activity
private searchImageFile() {
Intent intent = new Intent(Intent.GET_CONTENT);
// Filter to only show results that can be "opened"
intent.addCategory(Intent.CATEGORY_OPENABLE);
// Filter to show only images, using the image MIME data type.
// it would be "*/*".
intent.setType("image/*");
startActivityForResult(intent, READ_REQUEST_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
final Uri imageUri = resultData.getData();
//Do something with your Uri.
}
}

Android - getIntExtra results in default value in onActivityResult

I'm trying to allow a user to select an image from their gallery to replace an existing one in my activity (which was programatically added based on DB values). Here's the portion of my code that's causing some issues:
public void requestImage(int imageID){
Intent intent = new Intent();
intent.putExtra("imageID",imageID);
intent.setType("image/*");
Log.v("requestImage",Integer.toString(intent.getIntExtra("imageID",0)));
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
int imageID = data.getIntExtra("imageID",0);
Log.v("onactivityresult",Integer.toString(imageID));
} catch (IOException e) {
e.printStackTrace();
}
}
}
The goal is to get the ID of the image that was selected for this function, which I'm passing in to requestImage, through to onActivityResult. onActivityResult contains the code for setting the image's bitmap based on the image selected by the user (omitted from code sample for conciseness).
Note the two logging statements, which result in:
05-27 15:51:31.756 7769-7769/com.praytoday.app.praytoday V/requestImage: 12
05-27 15:45:55.511 2037-2037/com.praytoday.app.praytoday V/onactivityresult: 0
As you'll notice in the logging statements, the first log is actually getting the int from the intent itself, so I am certain it's being set correctly (and there aren't any type issues here).
It seems to me that data must not be the same intent (please excuse my lack of knowledge on the subject of intents - this is pretty new to me).
Things that I have tried:
Using getIntent() instead of data
Not using the createChooser, and instead just using the plain intent
Looking at every question/answer about this I could find
Any help in determining why this extra value is not in the data argument would be much appreciated! Thanks in advance.
I went ahead and just set a global variable to store which image is currently set for replacement. requestImage sets it to the current image ID, and then onActivityResult uses that variable. Not very elegant, but it works!

File upload with Android 4.4.4 in webview

I am trying to upload images via a WebView in Android. The problem is the missing content type. Seems like it`s a known issue in Android 4.4.4. What can be done in this situation? I found this answer on similar question, but I can't figure out how to implement this solution. I have access to server side.
Thanks.
In the answer you found, they call
startActivityForResult( Intent.createChooser( i, "File Chooser" ), MainActivity.FILECHOOSER_RESULTCODE)
What means, you should get the results of this in this method
protected void onActivityResult( int requestCode, int resultCode, Intent data )
{
if(requestCode == MainActivity.FILECHOOSER_RESULTCODE)
{
if(resultCode == RESULT_OK)
// TODO: Check Results of data-intent
}
}
in this method you can handle the results from the file chooser and do a upload by yourself (e.g. with URLConnection or ApacheHttpClient).
UPDATE 2016-10-19
Here is a Example where the ValueCallback is stored and the result of the ChooserIntent is passed back to the callback.
I didn`t try this example, but I think it should trigger a own upload methode from the webview.
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageURI = null;
protected void onActivityResult( int requestCode, int resultCode, Intent data )
{
if(requestCode == MainActivity.FILECHOOSER_RESULTCODE)
{
if(resultCode == RESULT_OK) {
result = intent == null ? mCapturedImageURI : intent.getData();
mUploadMessage.onReceiveValue(result);
}
}
}
onReceiveValue(result);
Source: http://androidexample.com/Open_File_Chooser_With_Camera_Option_In_Webview_File_Option/index.php?view=article_discription&aid=128
Check this thread for more examples https://stackoverflow.com/a/7857102/2377961

Returning Image Resource ID

I'm trying to get a program to let the user to import a custom background.
Here's where I'm at:
I have the getDrawable function taking another function as an argument:
mDrawableBg = getResources().getDrawable(getImage());
getImage() is suppose to return a integer referencing the selected image, here is the code (so far) for that function:
public int getImage(){
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 10);
}
This is suppose to open the gallery and let the user select an image. I would then use mDrawableBg to set the background. I'm not sure how to return a reference ID to that selected image though. Any suggestions?
Try this:
String pathName = "selected Image path";
Resources res = getResources();
Bitmap bitmap = BitmapFactory.decodeFile(pathName);
BitmapDrawable bd = new BitmapDrawable(res, bitmap);
View view = findViewById(R.id.container);
view.setBackgroundDrawable(bd);
The way you're attempting to do it is not possible, I'm afraid. One of the things you'll want to learn as a new Android developer is how the cycle between activities works. In your case, you're running an Activity that calls upon an Intent to get data from it. However, in the Android API, an Intent can only be referenced on its own time. This means you can't use your getImage() method the way you had tried.
There is hope, though!
What you first need to do is call the Intent. You will do this through the code you have now in getImage():
public void getImage() { // This has to be a void!
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 10);
}
This method will now start the Image Picker that you want users to select from. Next, you have to catch what is returned. This cannot be returned from your getImage() method, but instead must be collected from elsewhere.
You must implement the below method:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
final int SELECT_PICTURE = 1; // Hardcoded from API
if (requestCode == SELECT_PICTURE) {
String pathToImage = data.getData().getPath(); // Get path to image, returned by the image picker Intent
mDrawableBg = Drawable.createFromPath(pathToImage); // Get a Drawable from the path
}
}
}
Lastly, instead of calling mDrawableBg = getResources().getDrawable(getImage());, just call getImage();. This will initialize the Image Picker.
Some reading:
Android Activity (notably stuff about Intents and getting a result back)
Android Drawable
Getting a Drawable from a path
More on the Image Picker Intent
Good luck!
I'm not sure, but if you mean you don't know how to receive results from that intent, you can use :
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK)
{
if (requestCode == 10)
{
// DoSomething
}
}
}

Categories