Storing a high score in Android app - java

I have an app which displays the score on the main screen but this sets to zero every time a new game is started. What I want it to do is store that score and only change if the next score is higher, hence it being the highest score.
At the moment a hitCount method is deployed which a finish() method utilises to show the score from the game activity to the main activity.
The finish() method is below:
public void finish(){
Intent returnIntent = new Intent();
returnIntent.putExtra("GAME_SCORE", gameView.getHitCount());
setResult(RESULT_OK, returnIntent);
super.finish();
}
In the MainMenu class, the following onActivityResult() method is used to get the score to display on the main screen:
protected void onActivityResult(int requestCode, int resultCode, Intent retIntent) {
// Check which request we're responding to
if (requestCode == SCORE_REQUEST_CODE) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
if (retIntent.hasExtra("GAME_SCORE")) {
int scoreFromGame = retIntent.getExtras().getInt("GAME_SCORE");
tvScore.setText(Integer.toString(scoreFromGame));
//highScore.setText(Integer.toString(scoreFromGame));
}
}
}
}
Now, I know I must use something like shared preference to have any chance of storing the score and replacing it with a higher number when achieved but I can't figure out how and where.
As always, any help greatly appreciated.
Thanks

Put the following into your onCreate method to read the high score.
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
// Read the high score from Shared Preference
int mHighScore = sharedPref.getInt(getString(R.string.high_score), 0);
Update your high score using Shared Preference:
protected void onActivityResult(int requestCode, int resultCode, Intent retIntent) {
// Check which request we're responding to
if (requestCode == SCORE_REQUEST_CODE) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
if (retIntent.hasExtra("GAME_SCORE")) {
int scoreFromGame = retIntent.getExtras().getInt("GAME_SCORE");
tvScore.setText(Integer.toString(scoreFromGame));
//highScore.setText(Integer.toString(scoreFromGame));
// Write the new high score to Shared Preference
SharedPreferences.Editor editor = sharedPref.edit();
if (scoreFromGame > mHighScore) {
editor.putInt(getString(R.string.high_score), scoreFromGame);
editor.commit();
}
}
}
}
}

You should definitively read about SharedPreferences and look at the link given in the comments. If you want a quick solution for now:
MainActivity.java
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Set highscore text on start
prefs = PreferenceManager.getDefaultSharedPreferences(this);
int highscore = prefs.getInt(PreferenceHelper.KEY_HIGHSCORE, 0);
tvHighScore.setText(Integer.toString(highscore));
}
protected void onActivityResult(int requestCode, int resultCode, Intent retIntent) {
// Check which request we're responding to
if (requestCode == SCORE_REQUEST_CODE) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
if (retIntent.hasExtra("GAME_SCORE")) {
int scoreFromGame = retIntent.getExtras().getInt("GAME_SCORE");
tvScore.setText(Integer.toString(scoreFromGame));
int highscore = prefs.getInt(PreferenceHelper.KEY_HIGHSCORE, 0); // Get highscore stored in prefs
if (scoreFromGame > highscore) {
// Update text and save new highscore
tvHighScore.setText(Integer.toString(scoreFromGame));
prefs.edit().putInt(PreferenceHelper.KEY_HIGHSCORE, scoreFromGame).apply();
}
}
}
}
}
PreferenceHelper.java
public final class PreferenceHelper {
public static final String KEY_HIGHSCORE = "highscore";
}
You don't have to use the PreferenceHelper class, but it's a good practice.

Related

Android how to set and retrieve data from Preference object

I am working on a preference fragment, one preference is to select an external image file as the app background.
I try to save the file path string to the correspond preference, so that I can load that path data from SharedPreferences when the app is launched.
My problem is when using Preference class instead of EditTextPreference, there is no setText() method to save the path value, and I cannot figure out how to store the data onto a Preference object and then retrieve through SharedPreferences.getString("key", "") in my activity.
If I use a EditTextPreference instead, indeed it works but I have to disable or customize the dialog component of EditTextPreference, since I need to start a new activity to pick a image when tapping this preference.
I notice in the official documentation they use Preference when using intent together. Is there any way to save data to a Preference object and then retrieve that data in an activity?
// In preference fragment
private Preference bgPref;
#Override
public void onActivityResult(
int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && data != null) {
Uri imageUri = data.getData();
final String path = getFilePath(requireContext(), imageUri);
if (path != null) {
bgPref.setText(path); // how to set a string value for a Preference?
Drawable d = Drawable.createFromPath(path);
if (containerView != null) {
containerView.setBackground(d);
}
}
} else {
Toast.makeText(requireContext(), "You haven't picked Image", Toast.LENGTH_LONG).show();
}
}
// In Main activity
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String bgPath = sharedPrefs.getString("bgPath", "");
Drawable d = Drawable.createFromPath(bgPath);
if (!bgPath.isEmpty()) findViewById(R.id.nav_host_fragment).setBackground(d);
//...
You can edit this preference directly. In onActivityResult():
#Override
public void onActivityResult(
int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && data != null) {
Uri imageUri = data.getData();
final String path = getFilePath(requireContext(), imageUri);
if (path != null) {
// Save preference here
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("bgPath", path);
editor.apply();
// Now recreate activity to refresh the UI
requireActivity().recreate();
// In onCreateView, you can use this preference to set background
}
} else {
Toast.makeText(requireContext(), "You haven't picked Image", Toast.LENGTH_LONG).show();
}
}
}

How to pass a callback method between Xamarin Android activites [duplicate]

In my activity, I'm calling a second activity from the main activity by startActivityForResult. In my second activity, there are some methods that finish this activity (maybe without a result), however, just one of them returns a result.
For example, from the main activity, I call a second one. In this activity, I'm checking some features of a handset, such as does it have a camera. If it doesn't have then I'll close this activity. Also, during the preparation of MediaRecorder or MediaPlayer if a problem happens then I'll close this activity.
If its device has a camera and recording is done completely, then after recording a video if a user clicks on the done button then I'll send the result (address of the recorded video) back to the main activity.
How do I check the result from the main activity?
From your FirstActivity, call the SecondActivity using the startActivityForResult() method.
For example:
int LAUNCH_SECOND_ACTIVITY = 1
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, LAUNCH_SECOND_ACTIVITY);
In your SecondActivity, set the data which you want to return back to FirstActivity. If you don't want to return back, don't set any.
For example: In SecondActivity if you want to send back data:
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();
If you don't want to return data:
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();
Now in your FirstActivity class, write the following code for the onActivityResult() method.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LAUNCH_SECOND_ACTIVITY) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
}
if (resultCode == Activity.RESULT_CANCELED) {
// Write your code if there's no result
}
}
} //onActivityResult
To implement passing data between two activities in a much better way in Kotlin, please go through 'A better way to pass data between Activities'.
How to check the result from the main activity?
You need to override Activity.onActivityResult() and then check its parameters:
requestCode identifies which app returned these results. This is defined by you when you call startActivityForResult().
resultCode informs you whether this app succeeded, failed, or something different
data holds any information returned by this app. This may be null.
Example
To see the entire process in context, here is a supplemental answer. See my fuller answer for more explanation.
MainActivity.java
public class MainActivity extends AppCompatActivity {
// Add a different request code for every activity you are starting from here
private static final int SECOND_ACTIVITY_REQUEST_CODE = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// "Go to Second Activity" button click
public void onButtonClick(View view) {
// Start the SecondActivity
Intent intent = new Intent(this, SecondActivity.class);
startActivityForResult(intent, SECOND_ACTIVITY_REQUEST_CODE);
}
// This method is called when the second activity finishes
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check that it is the SecondActivity with an OK result
if (requestCode == SECOND_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) { // Activity.RESULT_OK
// get String data from Intent
String returnString = data.getStringExtra("keyName");
// set text view with string
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(returnString);
}
}
}
}
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
// "Send text back" button click
public void onButtonClick(View view) {
// get the text from the EditText
EditText editText = (EditText) findViewById(R.id.editText);
String stringToPassBack = editText.getText().toString();
// put the String to pass back into an Intent and close this activity
Intent intent = new Intent();
intent.putExtra("keyName", stringToPassBack);
setResult(RESULT_OK, intent);
finish();
}
}
Complementing the answer from Nishant, the best way to return the activity result is:
Intent returnIntent = getIntent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();
I was having a problem with
new Intent();
Then I found out that the correct way is using
getIntent();
to get the current intent.
startActivityForResult: Deprecated in Android X
For the new way we have registerForActivityResult.
In Java :
// You need to create a launcher variable inside onAttach or onCreate or global, i.e, before the activity is displayed
ActivityResultLauncher<Intent> launchSomeActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
Intent data = result.getData();
// your operation....
}
}
});
public void openYourActivity() {
Intent intent = new Intent(this, SomeActivity.class);
launchSomeActivity.launch(intent);
}
In Kotlin :
var resultLauncher = registerForActivityResult(StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val data: Intent? = result.data
// your operation...
}
}
fun openYourActivity() {
val intent = Intent(this, SomeActivity::class.java)
resultLauncher.launch(intent)
}
Advantage:
The new way is reduce complexity which we faced when we call the activity from a fragment or from another activity
Easily ask for any permission and get callback
For those who have problem with wrong requestCode in onActivityResult
If you are calling startActivityForResult() from your Fragment, the requestCode is changed by the Activity that owns the Fragment.
If you want to get the correct resultCode in your activity try this:
Change:
startActivityForResult(intent, 1); To:
getActivity().startActivityForResult(intent, 1);
The ActivityResultRegistry is the recommended approach
ComponentActivity now provides an ActivityResultRegistry that lets you handle the startActivityForResult()+onActivityResult() as well as requestPermissions()+onRequestPermissionsResult() flows without overriding methods in your Activity or Fragment, brings increased type safety via ActivityResultContract, and provides hooks for testing these flows.
It is strongly recommended to use the Activity Result APIs introduced in Android 10 Activity 1.2.0-alpha02 and Fragment 1.3.0-alpha02.
Add this to your build.gradle
def activity_version = "1.2.0-beta01"
// Java language implementation
implementation "androidx.activity:activity:$activity_version"
// Kotlin
implementation "androidx.activity:activity-ktx:$activity_version"
How to use the pre-built contract
This new API has the following pre-built functionalities
TakeVideo
PickContact
GetContent
GetContents
OpenDocument
OpenDocuments
OpenDocumentTree
CreateDocument
Dial
TakePicture
RequestPermission
RequestPermissions
An example that uses the takePicture contract:
private val takePicture = prepareCall(ActivityResultContracts.TakePicture()) { bitmap: Bitmap? ->
// Do something with the Bitmap, if present
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener { takePicture() }
}
So what’s going on here? Let’s break it down slightly. takePicture is just a callback which returns a nullable Bitmap - whether or not it’s null depends on whether or not the onActivityResult process was successful. prepareCall then registers this call into a new feature on ComponentActivity called the ActivityResultRegistry - we’ll come back to this later. ActivityResultContracts.TakePicture() is one of the built-in helpers which Google have created for us, and finally invoking takePicture actually triggers the Intent in the same way that you would previously with Activity.startActivityForResult(intent, REQUEST_CODE).
How to write a custom contract
A simple contract that takes an Int as an input and returns a string that the requested Activity returns in the result Intent.
class MyContract : ActivityResultContract<Int, String>() {
companion object {
const val ACTION = "com.myapp.action.MY_ACTION"
const val INPUT_INT = "input_int"
const val OUTPUT_STRING = "output_string"
}
override fun createIntent(input: Int): Intent {
return Intent(ACTION)
.apply { putExtra(INPUT_INT, input) }
}
override fun parseResult(resultCode: Int, intent: Intent?): String? {
return when (resultCode) {
Activity.RESULT_OK -> intent?.getStringExtra(OUTPUT_STRING)
else -> null
}
}
}
class MyActivity : AppCompatActivity() {
private val myActionCall = prepareCall(MyContract()) { result ->
Log.i("MyActivity", "Obtained result: $result")
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
...
button.setOnClickListener {
myActionCall(500)
}
}
}
Check this official documentation for more information.
If you want to update the user interface with the activity result, you can't to use this.runOnUiThread(new Runnable() {}. Doing this, the UI won't refresh with the new value. Instead, you can do this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) {
return;
}
global_lat = data.getDoubleExtra("LATITUDE", 0);
global_lng = data.getDoubleExtra("LONGITUDE", 0);
new_latlng = true;
}
#Override
protected void onResume() {
super.onResume();
if(new_latlng)
{
PhysicalTagProperties.this.setLocation(global_lat, global_lng);
new_latlng=false;
}
}
This seems silly, but it works pretty well.
In Kotlin
Suppose A & B are activities the navigation is from A -> B
We need the result back from A <- B
in A
// calling the Activity B
resultLauncher.launch(Intent(requireContext(), B::class.java))
// we get data in here from B
private var resultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
when (result.resultCode) {
Activity.RESULT_OK -> {
result.data?.getStringExtra("VALUE")?.let {
// data received here
}
}
Activity.RESULT_CANCELED -> {
// cancel or failure
}
}
}
In B
// Sending result value back to A
if (success) {
setResult(RESULT_OK, Intent().putExtra("VALUE", value))
} else {
setResult(RESULT_CANCELED)
}
It is a very common problem on Android
It can be broken down into three pieces
Start Activity B (happens in Activity A)
Set requested data (happens in activity B)
Receive requested data (happens in activity A)
startActivity B
Intent i = new Intent(A.this, B.class);
startActivity(i);
Set requested data
In this part, you decide whether you want to send data back or not when a particular event occurs.
E.g.: In activity B there is an EditText and two buttons b1, b2.
Clicking on Button b1 sends data back to activity A.
Clicking on Button b2 does not send any data.
Sending data
b1......clickListener
{
Intent resultIntent = new Intent();
resultIntent.putExtra("Your_key", "Your_value");
setResult(RES_CODE_A, resultIntent);
finish();
}
Not sending data
b2......clickListener
{
setResult(RES_CODE_B, new Intent());
finish();
}
The user clicks the back button
By default, the result is set with Activity.RESULT_CANCEL response code
Retrieve result
For that override onActivityResult method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RES_CODE_A) {
// b1 was clicked
String x = data.getStringExtra("RES_CODE_A");
}
else if(resultCode == RES_CODE_B){
// b2 was clicked
}
else{
// The back button was clicked
}
}
I will post the new "way" with Android X in a short answer (because in some case you does not need custom registry or contract). If you want more information, see: Getting a result from an activity
Important: there is actually a bug with the backward compatibility of Android X so you have to add fragment_version in your Gradle file. Otherwise you will get an exception "New result API error : Can only use lower 16 bits for requestCode".
dependencies {
def activity_version = "1.2.0-beta01"
// Java language implementation
implementation "androidx.activity:activity:$activity_version"
// Kotlin
implementation "androidx.activity:activity-ktx:$activity_version"
def fragment_version = "1.3.0-beta02"
// Java language implementation
implementation "androidx.fragment:fragment:$fragment_version"
// Kotlin
implementation "androidx.fragment:fragment-ktx:$fragment_version"
// Testing Fragments in Isolation
debugImplementation "androidx.fragment:fragment-testing:$fragment_version"
}
Now you just have to add this member variable of your activity. This use a predefined registry and generic contract.
public class MyActivity extends AppCompatActivity{
...
/**
* Activity callback API.
*/
// https://developer.android.com/training/basics/intents/result
private ActivityResultLauncher<Intent> mStartForResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
switch (result.getResultCode()) {
case Activity.RESULT_OK:
Intent intent = result.getData();
// Handle the Intent
Toast.makeText(MyActivity.this, "Activity returned ok", Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(MyActivity.this, "Activity canceled", Toast.LENGTH_SHORT).show();
break;
}
}
});
Before new API you had :
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MyActivity .this, EditActivity.class);
startActivityForResult(intent, Constants.INTENT_EDIT_REQUEST_CODE);
}
});
You may notice that the request code is now generated (and hold) by the Google framework.
Your code becomes:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MyActivity .this, EditActivity.class);
mStartForResult.launch(intent);
}
});
First you use startActivityForResult() with parameters in the first Activity and if you want to send data from the second Activity to first Activity then pass the value using Intent with the setResult() method and get that data inside the onActivityResult() method in the first Activity.
In your Main Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.takeCam).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(getApplicationContext(),TakePhotoActivity.class);
intent.putExtra("Mode","Take");
startActivity(intent);
}
});
findViewById(R.id.selectGal).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(getApplicationContext(),TakePhotoActivity.class);
intent.putExtra("Mode","Gallery");
startActivity(intent);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
In Second Activity to Display
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
private static final int PICK_PHOTO_FOR_AVATAR = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_take_photo);
imageView=findViewById(R.id.imageView);
if(getIntent().getStringExtra("Mode").equals("Gallery"))
{
pickImage();
}
else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
} else {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
}
}
public void pickImage() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, PICK_PHOTO_FOR_AVATAR);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_PERMISSION_CODE)
{
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
else
{
Toast.makeText(this, "Camera Permission Denied..", Toast.LENGTH_LONG).show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
if (requestCode == PICK_PHOTO_FOR_AVATAR && resultCode == Activity.RESULT_OK) {
if (data == null) {
Log.d("ABC","No Such Image Selected");
return;
}
try {
Uri selectedData=data.getData();
Log.d("ABC","Image Pick-Up");
imageView.setImageURI(selectedData);
InputStream inputStream = getApplicationContext().getContentResolver().openInputStream(selectedData);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
Bitmap bmp=MediaStore.Images.Media.getBitmap(getContentResolver(),selectedData);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e){
}
}
}
You need to override Activity.onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CODE_ONE) {
String a = data.getStringExtra("RESULT_CODE_ONE");
}
else if(resultCode == RESULT_CODE_TWO){
// b was clicked
}
else{
}
}

Multiple images upload code not working. What am I missing?

I'm developing an Android app in which the user will be asked to upload 2 images from his phone gallery.
My activity has one "Upload" button + 2 ImageViews to show the selected images before proceeding to the next activity.
Everything seems to work fine but both ImageViews are filled with just one of the images I select and I don't know why.
I searched on Google and on this website finding a lot of similar questions, but none of them helped me. Since I'm not an expert I could be missing something stupid and easy, but I'm quite lost at this point and decided to create a post.
Here is my Java code from the activity:
public class UploadActivity extends AppCompatActivity {
//Button and ImageViews have the same names for layout IDs
Button uploadBtn;
ImageView imgOne;
ImageView imgTwo;
public static final int PICK_IMAGE = 100;
public static Uri imgUri1;
public static Uri imgUri2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
uploadBtn = (Button)findViewById(R.id.uploadBtn);
imgOne = (ImageView)findViewById(R.id.imgOne);
imgTwo = (ImageView)findViewById(R.id.imgTwo);
uploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openGallery();
}
});
}
private void openGallery() {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
gallery.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(gallery, PICK_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
imgUri1 = data.getData();
imgOne.setImageURI(imgUri1);
imgUri2 = data.getData();
imgTwo.setImageURI(imgUri2);
}
}
}
This code works but shows just one selected image for BOTH ImageViews.
Looks like it's skipping the second image and assigns its ImageView to the first one more time.
Your Problem is this piece of code:
imgUri1 = data.getData();
imgOne.setImageURI(imgUri1);
imgUri2 = data.getData();
imgTwo.setImageURI(imgUri2);
You set imgUri1 AND imgUri2 to data.getData(). So imgUri1 and imgUri2 are exact the same. So you set the same Uri to both imageViews.
Maybe should set data to array data[0]=data1fromimg1 and data[1]=data2fromimg1
in your code like this
<br>
imgUri1 = data[0].getData();<br>
imgOne.setImageURI(imgUri1);<br>
imgUri2 = data[1].getData();<br>
imgTwo.setImageURI(imgUri2);
make sure that receive data
Solved by myself after many tries.
The solution was to use a for like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE && resultCode == RESULT_OK && data.getClipData() != null) {
int count = data.getClipData().getItemCount();
for(int i = 0; i < count; i++) {
Uri screen = data.getClipData().getItemAt(i).getUri();
imgUri1 = data.getClipData().getItemAt(0).getUri();
imgOne.setImageURI(imgUri1);
imgUri2 = data.getClipData().getItemAt(1).getUri();
imgTwo.setImageURI(imgUri2);
}
}
}

Meaning of a code related to GALLERY_REQUEST

I have used the following code to get a picture from the gallery in an app on clicking a button. It works fine but I just wanted to know the meaning of the codes used. Could someone help me in it?
private ImageButton mSelectImage;
public static final int GALLERY_REQUEST =1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
mSelectImage = (ImageButton)findViewById(R.id.imageSelect);
mSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){
Uri imageUri = data.getData();
mSelectImage.setImageURI(imageUri);
}
}
This is the requestCode. It helps you to identify from which Intent you came back. For example if you have two or more intent for camera request and for the Contact request.Whenever the subsequently called finish and need to pass data back to Acivity, now you need to identify in your onActivityResult from which intent call you are returning from and put your handling logic accordingly.
public static final int CAMERA_REQUEST = 101;
public static final int CONTACT_VIEW = 202;
#Override
public void onCreate(Bundle savedState)
{
super.onCreate(savedState);
// For CameraRequest you would most likely do
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
// For ContactReqeuest you would most likely do
Intent contactIntent = new Intent(ACTION_VIEW, Uri.parse("content://contacts/people/1"));
startActivityForResult(contactIntent, CONTACT_VIEW);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == Activity.RESULT_CANCELED) {
// code to handle cancelled state
}
else if (requestCode == CAMERA_REQUEST) {
// code to handle data from CAMERA_REQUEST
}
else if (requestCode == CONTACT_VIEW) {
// code to handle data from CONTACT_VIEW
}
}
GALLERY_REQUEST is a request code which is used like token, imagine you go into mall with bag, but they can't let you in with the bag so you have to put your bag outside the mall and guy will gives you a token, so when you will come back you give him that token and he will give your bag.
This token is managed just because you are not the only one who came with the bag there may be more, as the rule all person have to put their bag outside mall, but how to identify which bag belongs to which person,they used token.
Just like that request code is used, you may going to several other apps via implicit intent from your activity but when you came back, one method called for all intent: onActivityResult now you have request code to identify that from which activity is user coming from.

Call method when intent closes

I am making a music player application, and I am trying to implement playlists. I have a file chooser in another intent, and I would like the ListView in the mainActivity to update when the file chooser intent closes. how can I call my UpdateListView method when it closes?
start intent:
Intent intent = new Intent(this, FileChooser.class);
startActivity(intent);
Closing intent
public void closeButton(View view){
finish();
}
Any help would be appreciated! thanks!
I assume you are using your own FileChoser class, not a standard Android one:
private static final int FileChooserRequestCode = 666;
Intent intent = new Intent(this, FileChooser.class);
startActivityForResult(intent, FileChooserRequestCode);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == FillChooserRequestCode) {
if (resultCode == Activity.RESULT_OK) {
// ... file is chosen
String fileName = data.getStringExtra("FileName");
} else {
... dialog is closed
}
}
}
in FileChoser you do
Intent intent = new Intent();
intent.putStringExtra("FileName", fileName);
SetResult(Activity.RESULT_OK, intent);
finish();
and
SetResult(Activity.RESULT_CANCELED);
finish();
You can use startActivityForResult() please refer the link Getting Results From Activity
static final int FILE_CHOOSER_INTENT = 1; // The request code
...
private void chooseFile() {
Intent intent = new Intent(this, FileChooser.class);
startActivityForResult(intent, FILE_CHOOSER_INTENT);
}
Call setResult pass your result data as Intent. for details refer link SetResult function
Override this in your calling activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == FILE_CHOOSER_INTENT) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a contact.
// The Intent's data Uri identifies which contact was selected.
// Do something with the contact here (bigger example below)
}
}
}

Categories

Resources