I have a problem with updates my recyclerView. When I get unswer (it`s ArrayList with objects) in method onActivityResult I call the custom update method, where I update my ArrayList, but nothing happens...
I try to do it like in this topic how to update RecyclerView element from OnActivityResult
It`s my code :
Parent`s activity :
ArrayList<Unswer> unswerFromMain;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
if (data==null){
Log.d("LOGO", "no unswer" );
return;
} else {
unswerFromMain = (ArrayList<Unswer>) data.getSerializableExtra("aboutGROUPS");
recyclerAdapter.updateAdapter(unswerFromMain);
}
}
}
RecyclerAdapter class :
private ArrayList<Unswer> getUnswer = new ArrayList<>();
public void updateAdapter (ArrayList<Unswer> updateUnswer){
getUnswer = updateUnswer;
notifyDataSetChanged();
}
Try
getUnswer.clear()
getUnswer.addAll(updateUnswer);
instead of
getUnswer = updateUnswer;
Related
This question already has answers here:
How to manage startActivityForResult on Android
(14 answers)
Closed 3 years ago.
I am using both an ImagePicker and a barcode reader in a single activity. The main problem is that both of these require onActivityResult() to display the result. As we know a single activity can only have a single onActivityResult() method in it. How can I display both of them?
I have tried using switch cases to assign multiple requestCodes in the onActivityResult() but can't seem to figure out the solution.
Here's the method I tried.
public class MainActivity extends AppCompatActivity{
private TextView mIdentificationNumber;
private IntentIntegrator scanQR;
//Authentication For Firebase.
private FirebaseAuth mAuth;
//Toolbar
private Toolbar mToolBar;
private DatabaseReference mUserRef;
private ImageView mAssetImg;
private EditText massetName, massetModel, massetBarcode, massetArea, massetDescription;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting the Present instance of the FireBase Authentication
mAuth = FirebaseAuth.getInstance();
//Finding The Toolbar with it's unique Id.
mToolBar = (Toolbar) findViewById(R.id.main_page_toolbar);
//Setting Up the ToolBar in The ActionBar.
setSupportActionBar(mToolBar);
if (mAuth.getCurrentUser() != null){
mUserRef = FirebaseDatabase.getInstance().getReference().child("Users")
.child(mAuth.getCurrentUser().getUid());
mUserRef.keepSynced(true);
}
massetBarcode = (EditText) findViewById(R.id.BarcodeAsset);
scanQR = new IntentIntegrator(this);
massetBarcode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanQR.initiateScan();
}
});
mAssetImg = (ImageView) findViewById(R.id.asset_img);
mAssetImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getImage();
}
});
}
//OnStart Method is started when the Authentication Starts.
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null).
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null){
startUser();
} else {
mUserRef.child("online").setValue("true");
Log.d("STARTING THE ACTIVITY" , "TRUE");
}
}
#Override
protected void onPause() {
super.onPause();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null){
mUserRef.child("online").setValue(ServerValue.TIMESTAMP);
Log.d("STOPPING THE ACTIVITY" , "TRUE");
}
}
private void startUser() {
//Sending the user in the StartActivity If the User Is Not Logged In.
Intent startIntent = new Intent(MainActivity.this , AuthenticationActivity.class);
startActivity(startIntent);
//Finishing Up The Intent So the User Can't Go Back To MainActivity Without LoggingIn.
finish();
}
//Setting The Menu Options In The AppBarLayout.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//Inflating the Menu with the Unique R.menu.Id.
getMenuInflater().inflate(R.menu.main_menu , menu);
return true;
}
//Setting the Individual Item In The Menu.(Logout Button)
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.main_logout_btn){
FirebaseAuth.getInstance().signOut();
startUser();
}
return true;
}
private void getImage() {
ImagePicker.Companion.with(this)
.crop() //Crop image(Optional), Check Customization for more option
.compress(1024) //Final image size will be less than 1 MB(Optional)
.maxResultSize(1080, 1080) //Final image resolution will be less than 1080 x 1080(Optional)
.start();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 0:
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
massetBarcode.setText(result.getContents());
Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
}
}
break;
case 1:
if (resultCode == Activity.RESULT_OK) {
assert data != null;
Uri imageURI = data.getData();
mAssetImg.setImageURI(imageURI);
}
break;
}
}
}
The rest of the answers told to use startActivityForResult() but that method requires Intent to go from one activity to another but I don't want to do this.
In both cases, the libraries you're using provide a way to specify a request code so you can distinguish the results in onActivityResult.
Your scanQR object should set a request code, per the source code:
massetBarcode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanQR.setRequestCode(123).initiateScan();
}
});
You getImage() method should also specify a request code, again, per the library's source code.
private void getImage() {
ImagePicker.Companion.with(this)
.crop() //Crop image(Optional), Check Customization for more option
.compress(1024) //Final image size will be less than 1 MB(Optional)
.maxResultSize(1080, 1080) //Final image resolution will be less than 1080 x 1080(Optional)
.start(456); // Start with request code
}
Now, you can handle each request code as needed:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 123:
// HANDLE BARCODE
break;
case 456:
// HANDLE IMAGE
break;
}
}
Closing thought: I've never used either library. I found the solution by 1) assuming any library that provides an Activity you're supposed to invoke for a result would allow you to specify a request code for it and 2) looking through their documentation and source code for how to do that.
I'd encourage you to thoroughly study the documentation and source code for any open source library you intend to use since as soon as you do their code become your code and their bugs become your bugs, so you better know how to fix or workaround them.
Hope that helps!
In order to get results from fragments to your Activity, you can use an Interface to enable communication between them.
StartActivityForResult is used to start an activity and get a result back from it.
Please read more about it from here.
The startActivityForResult methos can use a second argument, a number so you can distinguish the resul
startActivityForResul(intent, 8)
You dont need to set the code back in the other activity, that is handled under the hood. So you probabbly want to add the number as a contant
private static final CAMERA_INTENT = 2
And then use it like this
startActivityForResul(intent, CAMERA_INTENT)
Finally in the onActivityResult implements the case basis
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
if (CAMERA_INTENT == requestCode) {
//DO PHOTO STUFF
}
}
The argument you need to eval is requestCode
Hello fellow programmers,
I'm experiencing some issues regarding my Android App, i'm currently
working on. For this purpose, I only need to mention that I have two
Activities (One is called MainActivity.class and the second is called
FilterActivity.class).
The purpose of my MainActiviy class is to display a movie (Genres,
year, rating etc) + a trailer of the specifik video.
In the OnCreate method for MainActiviy, im initializing the
YouTubePlayerView (since I want a random movie to pop up as soon as
you open the application).
The purpose of my FilterActivity class is to choose some specfik
search criterias for a movie.
I'm opening FilterActivity from MainActivity like this:
public void openFilter(){
Intent askIntent = new Intent(this, FilterActivity.class);
startActivityForResult(askIntent, 1); }
And in my FilterActivity im sending the information from a newly
created movie like this:
movieIntent.putExtra("url", a.getUrl());
movieIntent.putExtra("title", a.getTitle());
movieIntent.putExtra("rating", (String.valueOf(a.getRating())));
movieIntent.putExtra("plot", a.getDesc());
movieIntent.putExtra("year", (String.valueOf(a.getYear())));
movieIntent.putExtra("genre", a.getGenres());
setResult(RESULT_OK, movieIntent);
finish();
And this is how I fetch data from MainActivity:
protected void onActivityResult(int requestCode, int resultCode, final Intent data){
if(resultCode == RESULT_OK){
titleView.setText(data.getStringExtra("title"));
ratingView.setText(data.getStringExtra("rating"));
plotView.setText(data.getStringExtra("plot"));
yearView.setText(data.getStringExtra("year"));
genreView.setText(data.getStringExtra("genre"));
url = data.getStringExtra("url"); }
This is basically what I need to show. (This is all works by the way):
I'm getting a newly created movie and the criterias match.
However, in the OnActivityResult, I can't get my YoutubePlayerView to
re-load the video with the specific URL. The old video is still there,
and playable. I have checked and I am indeed getting a new URL from
the FilterActivity.
The only way I'm coming around this issue is by basically reloading
the activity, and then (since im creating a random movie in my
OnCreate method), the criteria don't match.
Any suggestions would be appreciated!
Sincerely
In onActivityResult, release current player and re-initialize YoutubePlayerView :
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
if (resultCode == RESULT_OK) {
mVideoId = getVideoId(data.getStringExtra("url"));
mPlayer.release();
mYoutubeplayerView.initialize(mApiKey, this);
}
}
A complete example of MainActivity is :
public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
String mVideoId = "5xVh-7ywKpE";
String mApiKey = "YOUR_API_KEY";
YouTubePlayerView mYoutubeplayerView;
YouTubePlayer mPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mYoutubeplayerView = (YouTubePlayerView) findViewById(R.id.player);
mYoutubeplayerView.initialize(mApiKey, this);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFilter();
}
});
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
YouTubePlayer youTubePlayer, boolean b) {
mPlayer = youTubePlayer;
mPlayer.loadVideo(mVideoId);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult youTubeInitializationResult) {
}
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
if (resultCode == RESULT_OK) {
mVideoId = getVideoId(data.getStringExtra("url"));
mPlayer.release();
mYoutubeplayerView.initialize(mApiKey, this);
}
}
private String getVideoId(String url) {
String pattern = "(?<=watch\\?v=|/videos/|embed\\/)[^#\\&\\?]*";
Pattern compiledPattern = Pattern.compile(pattern);
Matcher matcher = compiledPattern.matcher(url);
if (matcher.find()) {
return matcher.group();
}
return "";
}
public void openFilter() {
Intent askIntent = new Intent(this, FilterActivity.class);
startActivityForResult(askIntent, 1);
}
}
Note that I've used this post to extract Youtube videoId from url path
What I am aiming to do here is to change the picture of "ibChamp" from the default one to "ahri". Note that the names inside the ***s are the names of the activity.
***CreateBuilds.java***
ibChamp.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent champs = new Intent(CreateBuilds.this, Champions.class);
//creates the Intent champs for startActivityForResult()
startActivityForResult(champs, 0);
//opens up Champions.class layout
}
});
protected void onActivityResult(int requestCode, int resultCode, int data){
//starts when this.finish() from Champions is ran
ImageButton ibChamp = (ImageButton) findViewById(R.id.ibChamp);
//creates the ImageButton ibChamp
ibChamp.setImageResource(R.drawable.ahri);
//sets the picture of ibChamp to "ahri"
};
***Champions.java****
private myapplicationtest mytestInst = new myapplicationtest();
public void changePicture(final int champion){
mytestInst.setInt(champion);
//runs "setInt" from the myapplicationtest class
this.finish();
//closes this current layout to run onActivityResult
}
In this code, the onActivityResult() does not seem to run, since after "Champions.java" is finished, "ibChamp"'s picture did not change. If there is something extremely obvious, please state it, and any questions are welcomed.
finish() will terminate the Activity. IMHO, it does not make sense to call finish() and then do layout changes (I ssume on the view in the Activity to be finished).
Change "int data" into "Intent data":
protected void onActivityResult(int requestCode, int resultCode, int data)
---->
protected void onActivityResult(int requestCode, int resultCode, Intent data)
I have two Activities A and B. B has a method searchDevices. I want to access that method from A 's onCreate method. How can I do it with Intent?
I tried this :
public void onCreate(Bundle savedInstanceState)
{
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MY_UUID= UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//Function enbling Bluetooth
enableBluetooth();
///Function to initialize components
init();
//Calling AvailableDevices class's method searchDevice to get AvailableDevices
Intent intent=new Intent(this,AvailableDevices.class);
int x=10;
intent.putExtra("A", x);
}catch(Exception e){Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();}
}
You can also create a base activity that both ActivityA and ActivityB extends and put searchDevices() method in it.
For ex:
public class BaseActivity extends Activity{
public void searchDevices(){
}
}
public class ActivityB extends BaseActivity{
onCreate..
{
...
searchDevices();
}
}
public class ActivityA extends BaseActivity{
onCreate..
{
...
searchDevices();
}
}
if ActivityA is in a class called class1 make a method in class1 like this
public static void method1(){
}
then in activity 2 call the method by doing this ActivityA.method1()
Why don't use StartActivityForResult.
As per my understanding You can start AvailableDevices Activity for result with Intent having extra data and call searchDevice to get AvailableDevices and return the result to calling Activity.
[Edit]
In Class A
//Calling AvailableDevices class's method searchDevice to get AvailableDevices
Intent intent=new Intent(this,AvailableDevices.class);
int x=10;
intent.putExtra("A", x);
startActivityForResult(intent , searchDevicesRequestCode); //searchDevicesRequestCode = 100
Also override onActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == searchDevicesRequestCode) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// Manipulate searchDevicesResult from Intent data
}
}
}
In Class B
#override
onCreate()
{
//call searchDevices()
String result = searchDevices(); // save result to send in any form
// Create intent to deliver some kind of result data
Intent intentResult = new Intent("RESULT_ACTION");
intentResult.putExtra("key",result);
setResult(Activity.RESULT_OK, intentResult);
finish();
}
onActivityResult() is a standard Android function that is called after a child Activity closes. However, it doesn't seem to close all the way.
After my child activity finishes, onActivityResult() is called in the parent. At this point, my action is to inject a context (through a provider, non-assisted) in a new class the parent is creating, using the parcelable information that the child has just given back to me for an #Assisted parameter in that new class.
However, despite finish() being called on the child, the context that is injected is not the parent--it is the child! This kills the program.
How do I get around this?
Here's some code that gives you an idea of what I'm doing.
In the parent:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_NEW_EXERCISE)
{
if (resultCode == RESULT_OK)
{
EntityExercise exercise = (EntityExercise)data.getExtras().get("exercise");
addNewRoutineExerciseDetail(exercise);
//Toast.makeText(this, exercise.getName(), Toast.LENGTH_LONG).show();
}
}
}
public RoutineExerciseDetail addNewRoutineExerciseDetail(EntityExercise exercise)
{
RoutineExerciseDetail detail = detailFactory.create(exercise);
detail.setOnClickRelativeLayoutListener(mEditParamsOnClickListener);
return detail;
}
In the child:
View.OnClickListener mListenerReturnExercise = new View.OnClickListener()
{
#Override
public void onClick(View v) {
Intent resultIntent = new Intent();
resultIntent.putExtra("exercise", (EntityExercise)v.getTag()); //Assuming it's the tag
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
};
RoutineExerciseDetail's constructor's parameters:
#Inject
public RoutineExerciseDetail(ActivityBaseRoboOrm<DatabaseHelper> context, List<RoutineExerciseDetail> list,
#AddEditExercise TableLayout layout, #Assisted EntityExercise exercise)
Yes, this will fail on RoboGuice 1.1. Activity.onActivityResult() is a somewhat unusual method in that it executes before the activity's onResume() is called, thus RoboGuice doesn't know to switch the context back to the caller activity.
One of the main changes in RoboGuice 1.2 is to fix this behavior. If you switch to 1.2 and replace any providers with ContextScopedProviders per these instructions, you should be good to go.
If you need to stay with RoboGuice 1.1, you should be able to scope your context manually the following way:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
scope.enter(this);
try {
...
} finally {
scope.exit(this);
}
}
In ActivityForResult method in Android your requestcode should be same in both the Activity.then and only then your code will work. I hope it will help you.