I want to get the image from one activity to another activity. I tried converting the image to byte array in sender activity (PhotoActivity) and decoding the array to form original bitmap image on the receiver side (MainActivity) on the click of button 'btdn' but this isn't working. The image is visible in the sender activity's imageview but it stops when the button is clicked. This is my code:-
PhotoActivity.java
public class PhotoActivity extends Activity {
ImageView vitb;
Button btcm, btdn;
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int REQUEST_IMAGE_SELECT = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
vitb = findViewById(R.id.imageView);
btcm = findViewById(R.id.btn_cam);
btdn = findViewById(R.id.btn_back);
btcm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
btdn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Drawable drawable = vitb.getDrawable();
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
ByteArrayOutputStream bs = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 0, bs);
byte[] byteArray = bs.toByteArray();
Intent nIntent = new Intent();
nIntent.putExtra("PICTURE", byteArray);
setResult(RESULT_OK, nIntent);
finish();
}
});
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(PhotoActivity.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);
startActivityForResult(intent,REQUEST_IMAGE_CAPTURE);
}
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,REQUEST_IMAGE_SELECT);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
Bitmap bmp;
Bundle bundle = data.getExtras();
bmp = (Bitmap)bundle.get("data");
vitb.setImageBitmap(bmp);
}
else if (requestCode == 2) {
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);
cursor.close();
//ImageView imageView = findViewById(R.id.imageView);
vitb.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
}
MainActivity.java
public class MainActivity extends Activity{
private static final int REQUEST_CODE1 = 101;
private static final int REQUEST_CODE2 = 102;
Button btnLoc, btnPic;
Button btnSubmit;
TextView tvLoc;
ImageView image;
String phoneNumber = "9000000000";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSubmit = findViewById(R.id.btnSubmit);
btnLoc = findViewById(R.id.btnLoc);
btnPic = findViewById(R.id.btnPic);
tvLoc = findViewById(R.id.textView3);
image = findViewById(R.id.img);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
SmsManager.getDefault().sendTextMessage(phoneNumber, null, "Hello!", null, null);
}
catch (Exception e) {
AlertDialog.Builder alertDialogBuilder = new
AlertDialog.Builder(MainActivity.this);
AlertDialog dialog = alertDialogBuilder.create();
dialog.setMessage(e.getMessage());
dialog.show();
}
}
});
btnLoc.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,LocActivity.class);
startActivityForResult(intent,REQUEST_CODE1);
}
}
);
btnPic.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,PhotoActivity.class);
startActivityForResult(intent,REQUEST_CODE2);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
if(requestCode == REQUEST_CODE1 && data !=null) {
String strMessage = data.getStringExtra("loc");
tvLoc.setText(strMessage);
}
if(requestCode == REQUEST_CODE2 && data !=null) {
Bundle extras = getIntent().getExtras();
byte[] b = extras.getByteArray("PICTURE");
Bitmap bmp = BitmapFactory.decodeByteArray(b, 0, b.length);
image.setImageBitmap(bmp);
}
}
}
}
Related
I have 2 imageview with a certain image which send to the camera of the device and I want to validate, I want that when a photo is taken it changes image depending on the button from which the photo was taken.
I tried to do it this way but it didn't work.
ImageView imageV, imageV2;
static final int IMAGE_REQUEST = 1;
private static final int PERMISSION_REQUEST = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageV = findViewById(R.id.image_view);
imageV2 = findViewById(R.id.image_view_2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent camara = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (camara.resolveActivity(getPackageManager()) != null) {
startActivityForResult(camara, IMAGE_REQUEST);
}
}
});
btnIne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent camara = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (camara.resolveActivity(getPackageManager()) != null) {
startActivityForResult(camara, IMAGE_REQUEST);
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == IMAGE_REQUEST) {
if (resultCode == Activity.RESULT_OK) {
//Images to change
imageV.setImageResource(R.drawable.image_view_2do);
imageV2.setImageResource(R.drawable.image_view2_2do);
}
else {
//Default images
imageV.setImageResource(R.drawable.image_view_1er);
imageV2.setImageResource(getResources().getString(R.string.image_view2_1er));
}
}
}
You have to add different request code in startActivityForResult. Like you have used IMAGE_REQUEST for both button.
As Example :
ImageView imageV, imageV2;
static final int IMAGE_REQUEST = 1;
static final int IMAGE_REQUEST_2 = 2;
private static final int PERMISSION_REQUEST = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageV = findViewById(R.id.image_view);
imageV2 = findViewById(R.id.image_view_2);
btnStatementAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent camara = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (camara.resolveActivity(getPackageManager()) != null) {
startActivityForResult(camara, IMAGE_REQUEST);
}
}
});
btnIne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent camara = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (camara.resolveActivity(getPackageManager()) != null) {
startActivityForResult(camara, IMAGE_REQUEST_2);
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == IMAGE_REQUEST) {
if (resultCode == Activity.RESULT_OK) {
//Images to change
imageV.setImageResource(R.drawable.image_view_2do);
imageV2.setImageResource(R.drawable.image_view2_2do);
}
else if (requestCode == IMAGE_REQUEST_2) {
if (resultCode == Activity.RESULT_OK) {
//Images to change
imageV.setImageResource(R.drawable.image_view_2do);
imageV2.setImageResource(R.drawable.image_view2_2do);
}
else {
//Default images
imageV.setImageResource(R.drawable.image_view_1er);
imageV2.setImageResource(getResources().getString(R.string.image_view2_1er));
}
}
}
I have some problem as I mention in my question. I have two activity, Activity A and Activity B. When I Enter some data in Activity A, then I press next button, it will redirect to Activity B. At Activity B, I also enter some data. When I press back button, the data at Activity A is display as I entered before. When I press next button, the data that I entered at Activity B is missing. Below is my SharedPreferences code.
Activity A:
public class NewSuggestion extends AppCompatActivity {
private EditText etYear, etMonth, etTitle, etOwnValue;
private RadioGroup rgSuggestWill;
private RadioButton radioButton;
private Button btnNext;
ArrayAdapter<CharSequence> adapter;
private Spinner spReviewer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_suggestion);
final ActionBar abar = getSupportActionBar();
View viewActionBar = getLayoutInflater().inflate(R.layout.activity_new_suggestion, null);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(//Center the textview in the ActionBar !
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
TextView tvTitle = viewActionBar.findViewById(R.id.title);
tvTitle.setText("NEW SUGGESTION");
abar.setCustomView(viewActionBar, params);
abar.setDisplayShowCustomEnabled(true);
abar.setDisplayShowTitleEnabled(false);
//abar.setDisplayHomeAsUpEnabled(true);
abar.setHomeButtonEnabled(true);
etTitle = findViewById(R.id.etTitle);
etYear = findViewById(R.id.etYear);
etMonth = findViewById(R.id.etMonth);
rgSuggestWill =findViewById(R.id.rgSuggestWill);
final Calendar c = Calendar.getInstance();
String mm = c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.US);
int yy = c.get(Calendar.YEAR);
etYear.setText(new StringBuilder().append(yy));
etMonth.setText(new StringBuilder().append(mm));
spReviewer = findViewById(R.id.spReviewer);
adapter = ArrayAdapter.createFromResource(this,R.array.reviewer,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spReviewer.setAdapter(adapter);
spReviewer.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
btnNext = findViewById(R.id.btnNext);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPref = getSharedPreferences("MyData",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("title",etTitle.getText().toString());
editor.putString("year",etYear.getText().toString());
editor.putString("month",etMonth.getText().toString());
// get selected radio button from radioGroup
int selectedId = rgSuggestWill.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioButton = findViewById(selectedId);
editor.putString("suggestionwill",radioButton.getText().toString());
if (spReviewer.getSelectedItem().toString().equals("Please choose")){
AlertDialog alertDialog = new AlertDialog.Builder(NewSuggestion.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Please choose your reviewer");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}else{
editor.putString("reviewer",spReviewer.getSelectedItem().toString());
Intent intent = new Intent(NewSuggestion.this,NewSuggestion2.class);
startActivity(intent);
}
editor.apply();
}
});
}
#Override
public void onBackPressed() {
Intent intent = new Intent(NewSuggestion.this, DashboardApp.class);
startActivity(intent);
}
}
Activity B:
public class NewSuggestion2 extends AppCompatActivity {
private EditText etPresent, etDetails, etBenefit;
private ImageView imgAttach,btnCamera,btnGallery;
private Button btnNext,btnClear;
private Intent intent;
private Bitmap bitmap;
private int REQUEST_CODE = 1;
public static final int RequestPermissionCode = 1 ;
public static final String DEFAULT = "N/A";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_suggestion2);
final ActionBar abar = getSupportActionBar();
View viewActionBar = getLayoutInflater().inflate(R.layout.activity_new_suggestion, null);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(//Center the textview in the ActionBar !
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
TextView tvTitle = viewActionBar.findViewById(R.id.title);
tvTitle.setText("NEW SUGGESTION (Cont..)");
abar.setCustomView(viewActionBar, params);
abar.setDisplayShowCustomEnabled(true);
abar.setDisplayShowTitleEnabled(false);
//abar.setDisplayHomeAsUpEnabled(true);
abar.setHomeButtonEnabled(true);
etPresent = findViewById(R.id.etPresent);
etDetails = findViewById(R.id.etDetails);
etBenefit = findViewById(R.id.etBenefit);
imgAttach = findViewById(R.id.imgAttach);
btnCamera=findViewById(R.id.btnCamera);
EnableRuntimePermission();
btnCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 7);
}
});
btnGallery=findViewById(R.id.btnGallery);
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Photo"),REQUEST_CODE);
}
});
btnNext = findViewById(R.id.btnNext);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("present", etPresent.getText().toString());
editor.putString("details", etDetails.getText().toString());
editor.putString("benefit", etBenefit.getText().toString());
editor.apply();
Intent intent = new Intent(NewSuggestion2.this,ConfirmSuggestion.class);
startActivity(intent);
}
});
btnClear = findViewById(R.id.btnClear);
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imgAttach.setImageBitmap(null);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 7 && resultCode == RESULT_OK) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
imgAttach.setImageBitmap(bitmap);
}
if(requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null){
Uri uri = data.getData();
try{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
imgAttach.setImageBitmap(bitmap);
}catch (IOException e){
e.printStackTrace();
}
}
}
public void EnableRuntimePermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(NewSuggestion2.this,
Manifest.permission.CAMERA))
{
Toast.makeText(NewSuggestion2.this,"CAMERA permission allows us to Access CAMERA app", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(NewSuggestion2.this,new String[]{
Manifest.permission.CAMERA}, RequestPermissionCode);
}
}
#Override
public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {
switch (RC) {
case RequestPermissionCode:
if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(NewSuggestion2.this,"Permission Granted, Now your application can access CAMERA.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(NewSuggestion2.this,"Permission Canceled, Now your application cannot access CAMERA.", Toast.LENGTH_LONG).show();
}
break;
}
}
#Override
public void onBackPressed() {
}
}
Assign value to present,details,benefit from sharedpref
SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
etPresent = findViewById(R.id.etPresent);
etDetails = findViewById(R.id.etDetails);
etBenefit = findViewById(R.id.etBenefit);
etPresent.setText(sharedPref.getString("present", ""));
etDetails.setText(sharedPref.getString("details", ""));
etBenefit.setText(sharedPref.getString("benefit", ""));
In Activity B make sure you save data in onBackPressed()
#Override
public void onBackPressed() {
editor.putString("present", etPresent.getText().toString());
editor.putString("details", etDetails.getText().toString());
editor.putString("benefit", etBenefit.getText().toString());
editor.apply();
super.onBackPressed();
}
You have to override the onBackPress() method.In Activity B it is necessary to put data in to SharedPreferences.
#Override
public void onBackPressed() {
SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("present", etPresent.getText().toString());
editor.putString("details", etDetails.getText().toString());
editor.putString("benefit", etBenefit.getText().toString());
editor.commit();
}
How i can choose image from gallery and them put it on parse.com ?
There i open GALLERY:
#Override
public void onClick(View arg0) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
i.setType("image/*");
i.setAction(Intent.ACTION_VIEW);
///// - here must be code tat can choose file that i must upload to parse
////
There is code that can upload image to parse.com :
I think it will be something like this
ParseObject image = new ParseObject("guestList");
image.put("photo", image);
image.saveInBackground();
UPD
public class SendGuestPhoto extends Activity {
ImageView imageView;
private static final int PICK_IMAGE = 100;
String path;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send_guest_photo);
imageView = (ImageView) findViewById(R.id.image_view);
Button button_choose_guest_photo = (Button)findViewById(R.id.button_choose_guest_photo);
button_choose_guest_photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openGallery();
}
});
}
private void openGallery() {
Intent gallery =
new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
Uri imageUri = data.getData();
imageView.setImageURI(imageUri);
}
}
public void SendPhoto(){
Button button_send_guest_photo = (Button)findViewById(R.id.button_send_guest_photo);
button_send_guest_photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ParseObject photos = new ParseObject("guestsImages");
photos.put("photos", ????????????????);
photos.saveInBackground();
}
});
}
}
I have a button in Claims.java. When button is pressed, it will show Alert Dialog Window with radio buttons.If the radio button is checked, it will goes to specific activity. In the activity, it has an editText and a save button. I want the value on the editText display on the button(Claims.java) when the save button in the activity is clicked.
Claims.java >> AlertDialog Window in Claims.java >> AlertDialogRadio.java
I use startActivityForResult() to receive a result back from AlertRadioDialog.java. But the problem now is it will display AlertDialogRadio which is not what I want and the text does not display on the textView. How can I do to achieve this?
Claims.java
public class Claims extends Fragment {
private TextView c;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View claims = inflater.inflate(R.layout.claims, container, false);
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
AlertDialogRadio();
}
};
Button button1 = (Button) claims.findViewById(R.id.button10);
Button button = (Button) claims.findViewById(R.id.button8);
button1.setOnClickListener(listener);
c=(TextView)claims.findViewById(R.id.textView49);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(getActivity().getApplicationContext(), CameraMain.class);
startActivity(intent);
}
});
return claims;
}
public void AlertDialogRadio() {
final CharSequence[] ClaimsModel = {"Project", "Petrol", "Car Maintenance"
, "Medical", "Other"};
AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
alt_bld.setTitle("Select a Claims");
alt_bld.setSingleChoiceItems(ClaimsModel, -1, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(), Project1.class);
startActivity(intent);
} else if (item == 1) {
Intent intent = new Intent(getActivity().getApplicationContext(), Petrol.class);
startActivity(intent);
} else if (item == 2) {
Intent intent = new Intent(getActivity().getApplicationContext(), CarMainten.class);
startActivity(intent);
} else if (item == 3) {
Intent intent = new Intent(getActivity().getApplicationContext(), Medical.class);
startActivity(intent);
} else if (item == 4) {
Intent intent = new Intent(getActivity().getApplicationContext(), Other.class);
startActivity(intent);
}
}
});
AlertDialog alert = alt_bld.create();
alert.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("text");
c.setText(result);
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}//onActivityResult
}
Assume the user choose Project.
Project1.java
public class Project1 extends AppCompatActivity {
private static String text;
private static EditText txt;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project);
txt= (EditText)findViewById(R.id.editText36);
Button b=(Button)findViewById(R.id.button17);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent returnIntent = new Intent();
text = txt.getText().toString();
returnIntent.putExtra("text", text);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
}
First of all, you're not using startActivityForResult at all.
Here's how you should proceed:
Claims.java
public static final int PROJECT_REQUEST_CODE = 1;
public static final int CAMERA_REQUEST_CODE = 2;
public static .....
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(), Project1.class);
startActivityForResult(intent, PROJECT_REQUEST_CODE);
}
else if .....
And in OnActivityResult :
if (requestCode == PROJECT_REQUEST_CODE) {
...
}
else if(requestCode == CAMERA_REQUEST_CODE) {
...
}
else if ...
I have the same code in 2 Classes of my android-project. I´m just begin to learn java / android, so pls could you give me some tips? Do I have set a new class? Thank you for your help!
Main.java
public class Main extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnGallery = (Button) findViewById(R.id.btnGallery);
btnGallery.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);
Intent uploadActivity = new Intent(Main.this, Upload.class);
uploadActivity.putExtra("picturePath", picturePath);
startActivity(uploadActivity);
cursor.close();
}
}
}
And Upload.java
public class Upload extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
Bundle extras = getIntent().getExtras();
String picturePathView = extras.getString("picturePath");
ImageView imageView = (ImageView) findViewById(R.id.imgView);
findViewById(R.id.imgView).setScrollBarStyle(
View.SCROLLBARS_INSIDE_INSET);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePathView));
Button btnGallery = (Button) findViewById(R.id.btnGallery);
btnGallery.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);
ImageView imageView = (ImageView) findViewById(R.id.imgView);
findViewById(R.id.imgView).setScrollBarStyle(
View.SCROLLBARS_INSIDE_INSET);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
cursor.close();
}
}
}
This is actually what hasanghaforian said, but a little bit more conrect.
Your abstract Activity which enables holds the properties which are the same for Upload and Main could be the following
public abstract class AbstractMediaPickerActivity extends Activity {
protected static int RESULT_LOAD_IMAGE = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected void startMediaPicker() {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
protected abstract void onImagePicked(String picturePath);
#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);
cursor.close();
onImagePicked(picturePath);
}
}
}
Your both other classes are inherited by the AbstractMediaPickerActivity
public class MainActivity extends AbstractMediaPickerActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnGallery = (Button) findViewById(R.id.btnGallery);
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
startMediaPicker();
}
});
}
protected void onImagePicked(String picturePath) {
Intent uploadActivity = new Intent(Main.this, Upload.class);
uploadActivity.putExtra("picturePath", picturePath);
startActivity(uploadActivity);
}
}
public class Upload extends AbstractMediaPickerActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
Bundle extras = getIntent().getExtras();
String picturePathView = extras.getString("picturePath");
ImageView imageView = (ImageView) findViewById(R.id.imgView);
findViewById(R.id.imgView).setScrollBarStyle(
View.SCROLLBARS_INSIDE_INSET);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePathView));
Button btnGallery = (Button) findViewById(R.id.btnGallery);
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
startMediaPicker();
}
});
}
#Override
protected void onImagePicked(String picturePath) {
ImageView imageView = (ImageView) findViewById(R.id.imgView);
findViewById(R.id.imgView).setScrollBarStyle(
View.SCROLLBARS_INSIDE_INSET);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
Create a Class(for example SuperActivity) that extends Activity and add duplicated code to it.Then create Activities A,B that extend SuperActivity.
Sure you can put all the code in one class. I'm not gonna write all the code but you will get the idea how to gain refactoring in your code.
For onClickListner, you can do the following:
#Override
public void onClick(View clickedView) {
int clickedViewId = clickedView.getId();
switch(clickedViewId) {
case R.id.firstItem:
// code when first view is clicked
case R.id.secondItem:
// code when second view is clicked
default:
// optional
}
}
And then setting the same onClickListner for both views.
The same kind of switch statement you can use in onActivityResult method. I hope now you can merge the two classes in one.