I am having problems with a global variable in my Java code. Here is the thing: My Screen has 3 ImageButtons elements for picking 3 images when pressing on them; this works fine. I am using onActiviyResult in order to make it, but I have implemented just one onActiviyResult method for the 3 images, so I am using 3 if(){...} blocks in the method to know the pressed imagebutton, I mean this:
if(current_picture.equals("pic1"))}{
imagebutton1.setImageBitmap(bitmap);
}
if(current_picture.equals("pic2"))}{
imagebutton2.setImageBitmap(bitmap);
}
if(current_picture.equals("pic3"))}{
imagebutton3.setImageBitmap(bitmap);
}
Here, current_picture is a String, and it's declared outside the onCreate method, and its default value is set to: String current_picture = "";
I use this variable to save a value that was set on the setonclicklistener events of the 3 imagebuttons, I mean:
imagebutton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
current_picture = "pic1";
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose a
picture"), SELECT_PICTURE);
}
});
Same thing for imagebutton2 (current_picture = "pic2";) and imagebutton3 (current_picture = "pic3";). All these events are on onCreate method obviously.
So, the problem is that current_picture is losing its value set on the setonclicklistener methods when calling onActivityResult method, I mean, current_user value is still "" and not "pic1", "pic2" or "pic3" depending on the pressed imagebutton. I think its value is destroyed when calling the new activity onActivityResult, then onActivityResul just recognizes: String current_picture = "";
I have done many things to solve this but i am able to find a solution, I attached some code (not all, just important parts) below:
public class Publish_Event extends Activity{
private ImageButton imagebutton1;
private ImageButton imagebutton2;
private ImageButton imagebutton3;
private Bitmap bitmap;
private String current_picture="";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.publicar_eventos);
StrictMode.ThreadPolicy p = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(p);
imagebutton1 = (ImageButton)findViewById(R.id.pic1);
imagebutton2 = (ImageButton)findViewById(R.id.pic2);
imagebutton3 = (ImageButton)findViewById(R.id.pic3);
imagebutton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
current_picture = "pic1";
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose a
picture"), SELECT_PICTURE);
}
});
imagebutton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
current_picture = "pic2";
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose a
picture"), SELECT_PICTURE);
}
});
imagebutton3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
current_picture = "pic3";
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose a
picture"), SELECT_PICTURE);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
imagen_path = getRealPathFromURI(selectedImageUri);
bitmap = BitmapFactory.decodeFile(imagen_path);
if(current_picture.equals("pic1")){
imagebutton1.setImageBitmap(bitmap);
}
if(current_picture.equals("pic2")){
imagebutton2.setImageBitmap(bitmap);
}
if(current_picture.equals("pic3")){
imagebutton3.setImageBitmap(bitmap);
}
}
}
}
#TargetApi(Build.VERSION_CODES.KITKAT)
public String getRealPathFromURI(Uri contentUri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = null;
try {
if (Build.VERSION.SDK_INT > 19) {
// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(contentUri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
cursor = Publish_Event.this.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, sel, new String[] { id }, null);
} else {
cursor =
Publish_Event.this.getContentResolver().query(contentUri,
projection, null, null, null);
}
} catch (Exception e) {
e.printStackTrace();
}
String path = null;
try {
int column_index =
cursor.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index).toString();
cursor.close();
} catch (NullPointerException e) {
e.printStackTrace();
}
return path;
}
}
You can start activity with different request code.
public class Publish_Event extends Activity{
private static final int SELECT_PICTURE_1 = 1;
private static final int SELECT_PICTURE_2 = 2;
private static final int SELECT_PICTURE_3 = 3;
protected void onCreate(Bundle savedInstanceState) {
imagebutton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose a picture"), SELECT_PICTURE_1);
}
});
imagebutton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose a picture"), SELECT_PICTURE_2);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE_1) {
//change imagebutton1
}else if(requestCode == SELECT_PICTURE_2){
//change imagebutton2
}else if(requestCode == SELECT_PICTURE_3){
//change imagebutton3
}
}
}
}
Related
I have 3 different buttons: Upload Profile Picture, Upload Photo ID and Upload Criminal Record Photo, but after I call the openFileChooser() method which I created, I don't know how exactly I have to handle that to get 3 different URls.
I mean I did this
public class SignupCarrier extends AppCompatActivity {
EditText editfullname, editemail, editpassword, editconfirmpassword, editaddress, editcity, editstate, editzipcode, editcountry, editphone, editcardnumber, editexpiredate, editcvc;
Button upProfile, upIDPhoto, upCriminalRecord;
private Uri mProfilePic, mIdPhoto,mCriminalRecord;
FirebaseAuth mFirebaseAuth;
private StorageReference mStorageRef;
private StorageTask mUploadTask;
private static final int PICK_IMAGE_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup_carrier);
mFirebaseAuth = FirebaseAuth.getInstance();
upProfile = (Button) findViewById(R.id.profilePic);
upIDPhoto = (Button) findViewById(R.id.idphotoPic);
upCriminalRecord = (Button) findViewById(R.id.criminalRecord);
mStorageRef = FirebaseStorage.getInstance().getReference("carriersPictures");
upProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
upIDPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
upCriminalRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#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)
{
mProfilePic = data.getData();
}
}
}
But this would probably work only for upProfile Button, how can I modify the onActivityResult to get for each buttons the URLs?
Thank you! I'm new to Android.
Add Uri as parameter to your openFileChooser() method.
private void openFileChooser(Uri uri)
and call it like this:
upProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser(mProfilePic);
}
});
Update your openFileChooser() method to this:
private void openFileChooser(Uri uri) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
if (uri == mProfilePic) {
startActivityForResult(intent, PICK_IMAGE_REQUEST);
} else if (uri == mIdPhoto) {
startActivityForResult(intent, PICK_IMAGE_REQUEST_ID);
} else if (uri == mCriminalRecord) {
startActivityForResult(intent, PICK_IMAGE_REQUEST_CR);
}
}
You need to declare these constants: PICK_IMAGE_REQUEST_ID, PICK_IMAGE_REQUEST_CR
And in your onActivityResult() method check the requestCode to handle each case
My android app has three buttons On click all the button do the same work,
And the code is so long I don't want to copy the code 3 time.
So, how can I do this using a method?
This the code of one button
public void onClick(View v) {
switch (v.getId()) {
case R.id.Btn1:
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1); //Gallery acessing
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
super.setContentView(R.layout.activity_view);
selectedImage = (ImageView) findViewById(R.id.selectedImage); //Onresult redarct to anothr activity
}
Uri photoUri = data.getData();
if (photoUri != null) {
try {
currentImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri);
selectedImage.setImageBitmap(currentImage);
} catch (Exception e) {
e.printStackTrace();
Intent myIntent = new Intent(this, ViewActivity.class);
startActivity(myIntent); //switch activity
}
}}
}
You can try the below code. I have created a public method doSomething() which is called on each button click so it performs the same function whenever it is called.
public void onClick(View v) {
switch (v.getId()) {
case R.id.Btn1:
doSomething();
break;
case R.id.Btn2:
doSomething();
break;
}
}
public void doSomething(){
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1); //Gallery acessing
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
super.setContentView(R.layout.activity_view);
selectedImage = (ImageView) findViewById(R.id.selectedImage); //Onresult redarct to anothr activity
}
Uri photoUri = data.getData();
if (photoUri != null) {
try {
currentImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri);
selectedImage.setImageBitmap(currentImage);
} catch (Exception e) {
e.printStackTrace();
Intent myIntent = new Intent(this, ViewActivity.class);
startActivity(myIntent); //switch activity
}
}}
}
private View.OnClickListener myClickListener = new View.OnClickListener(){
public void onClick(View view){
//do all the work here
}
}
then set it in you Views
view1.setOnClickListener(myClickListener);
view2.setOnClickListener(myClickListener);
//... etc
You can Use performClick of first button in other views click.
Button button1 = findViewById(R.id.Btn1)
case R.id.Btn2:
button1.performClick()
In this MainActivity java class on Android Application Project I can't replace the original image given by the system with the one different selected from the photo gallery of smartphone.
When I select the one different photo I have always the original image.
public class MainActivity extends Activity implements OnClickListener {
Button uploadButton, btnselectpic;
ImageView imageview;
private ProgressDialog dialog = null;
private String imagepath = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uploadButton = (Button) findViewById(R.id.uploadButton);
btnselectpic = (Button) findViewById(R.id.btnselectpic);
imageview = (ImageView) findViewById(R.id.imageview);
btnselectpic.setOnClickListener(this);
uploadButton.setOnClickListener(this);
#Override
public void onClick(View arg0) {
if (arg0 == btnselectpic) {
selectImage();
} else if (arg0 == uploadButton) {
dialog = ProgressDialog.show(MainActivity.this, "",
"Uploading file...", true);
messageText.setText("uploading started.....");
new Thread(new Runnable() {
public void run() {
}
}).start();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && requestCode == 2 && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
imageview.setImageBitmap(bitmap);
messageText.setText("Uploading file path:" + imagepath);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null,
null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
} else if (options[item].equals("Choose from Gallery")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
The problem is that your onActivityResult() will never do anything.
You start this method off with:
if (requestCode == 1 && requestCode == 2 && resultCode == RESULT_OK) {
// ...
}
requestCode cannot be both 1 and 2, so this conditional will always be false.
You are likely looking for something more like this:
if ((requestCode == 1 && resultCode == RESULT_OK) ||
(requestCode == 2 && resultCode == RESULT_OK)) {
// ...
}
I am doing R&D in this topic.
I am getting image from gallery and able to view in image view.
And by long press over that image view i can able to share.
But the problem is i am not getting the attached image as output..
public class Facebookhome extends Activity {
Button share;
ImageView img;
Uri screenshotUri;
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_facebookhome);
share = (Button) findViewById(R.id.button1);
img = (ImageView) findViewById(R.id.imageView1);
share.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select
Picture"),
SELECT_PICTURE);
}
});
img.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
shareimage();
return true;
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public void shareitem() {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Here is the share content body";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
public void shareimage() {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
screenshotUri = Uri.parse(selectedImagePath);
sharingIntent.setType("image/jpg");
sharingIntent.putExtra(android.content.Intent.EXTRA_STREAM,
screenshotUri);
startActivity(Intent.createChooser(sharingIntent, "Share image using"));
// Toast.makeText(getBaseContext(), "FB Last",
// Toast.LENGTH_LONG).show();
}
}
private static int RESULT_LOAD_IMAGE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
Uri screenshotUri = Uri.parse(picturePath);
cursor.close();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("image/jpg"");
i.putExtra(Intent.EXTRA_EMAIL,
new String[] { "aa#gmail.com" });
i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
i.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(i, "Send mail..."));
}
}
I have an activity called CForm. I would like to call CGForm for result. After i get the result start another activity. The problem is that when i start the details_click method , it executes the CGFORM, but doesn't waits for setting the result in the form, it jumps to the CDFORM.
here is the code for CFORM:
////////////////////////////CForm/////////////////////////
public boolean details_click()
{
if(listview.getCheckedItemPosition()>=0)
{
ArrayList<ComandaClass> listcompos = CClass.C();
int gestiuneId = 0;
if ((configurare.bAlCom) && (listcompos.size() == 0))
{
StocClass.setComandaContextForDB(this);
listGest = StocClass.Gestiuni_Get();
if (listGest.size() > 1)
{
Intent intent = new Intent();
intent.setClass(CForm.this,CGForm.class);
startActivityForResult(intent,GET_CODE);//here i would like to get back the result from CGForm
dGeid=getGIdResult;
}
}
boolean tof = true;
if ((configurare.bGCom) && (gestiuneId == -1))
tof = false;
if (tof)
{
dCid=listCom.get(listview.getCheckedItemPosition()).getCId();
dClid=listCom.get(listview.getCheckedItemPosition()).getClId();
dF=listCom.get(listview.getCheckedItemPosition()).getF();
Intent intent = new Intent();
intent.setClass(CForm.this,CDForm.class);
startActivity(intent);
}
return true;
}
else
{
Toast.makeText(this, "X", 5000).show();
return false;
}
}
public static int getGIdResult=-1;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == GET_CODE)
{
if (resultCode == RESULT_OK)
{
getGIdResult=data.getIntExtra("GIdResult",-1);
}
else
{
getGIdResult=-1;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
CGFORM code:
////////////////////CGForm//////////////////
public class CGForm extends Activity
{
public static ArrayList<StocClass> listG=null;
public static int gid;
ListView listview=null;
Button btnOK=null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.comenzigestiuni);
Locale locale = new Locale("en");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics());
listview=(ListView)findViewById(R.id.listViewDG);
listG = CForm.listGest;
CG_Load();
}//oncreate
private void CG_Load()
{
//..adding data to listview
btnOK=(Button)findViewById(R.id.menuItemOk);
btnOK.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
if (listview.getCheckedItemPosition() >= 0)
{
gestiuneid = listG.get(listview.getCheckedItemPosition()).getGId();
Intent intent = new Intent();
intent.putExtra("GIdResult", gestiuneid);
setResult(RESULT_OK, intent);
finish();
}
}
});
}//CG_Load
#Override
protected void onStop()
{
gestiuneid=-1;
Intent intent = new Intent();
intent.putExtra("GIdResult", gestiuneid);
setResult(RESULT_OK, intent);
super.onStop();
}
}
thanks advanced !
Neither startActivity() nor startActivityForResult() are blocking calls. Anything that is supposed to be done after you receive the result needs to move to your onActivityResult() method.