can write OnClickListener into parceable? - java

Hello I have a trouble with OnClickListener
View.OnClickListener listener= new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Toast.makeText(Conversations.this, "click on MSG",
Toast.LENGTH_SHORT).show();
}
};
========================================================================
I Need put this listener into Fragment which will parceable.
I not parceableing listener but after readvalue is null and when click app crasher because it's reference on null object.
now I need find some methods which can use for save and read object (View.OnClickListener) if parceable or something similar.
Without this I need rebuild my project :(
Please Help me.
Thanks
_______________________________________________________--
I haven't have fragment in fragment I want all fragment put into "extra" and in other activity read from extra..
Intent i= new Intent(Conversations.this,MessagesSingleFragmentActivity.cla‌​ss); i.putExtra("Fragment1", (Parcelable) recycleMessage); startActivity(i);
and in other activity have
Intent extras = getIntent(); Fragment fragment = (Fragment) extras.getParcelableExtra("Fragment1"); fm.beginTransaction().replace(R.id.fragment_container, fragment).commit();

No you cannot pass OnClickListener as Parcelable but , if you want to observe click from one fragment to another , then you have to implement the onclick in second fragment.
FragA.java:// who have onClickListener
Runnable run;
public void setClick(Runnable run){
this.run = run;
}
view.setOnClickListener(new OnClickListener(){
public void onClick(View v){
// do something in onclick
if(run!=null){run.run();}
}
});
FragB.java:
((FragA)getParentFragment()).setClick(
new Runnable() {
#Override
public void run() {
// do something in other fragment
}
}
)
Updated:
If you want to perform something onClick of ActivityA on ActivityB , then EventBus are best options for that use Otto or EventBus by GreenBot

It is recommended to interact between fragments via Activity.. or more generally by interface which Activity conforms to.
One more thing: If you have common functionality in both fragments, maybe it is better to extract it to Activity?

Related

How to switch to another activity using imageview in reycleview?

So, I am basically building an expense tracker app. I have successfully implemented Recycleview which contains Transactions' history. Now, what I am trying to achieve is to use an arrow imageview in the recycleview which will forward me to another activity when it is clicked. Any help will be appreciated on it.
in your adapter class inside onBindViewHolder method add
holder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, OtherActivity.class);
context.startActivity(intent);
}
});

Crashing when an Intent is called inside a Recycler View Adapter

public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.parentCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context,DetailedView.class);
context.startActivity(intent);
}
});
The Intent is not passing to the other activity when the cardView is clicked.
Recycler view doesnt have current activity context, so while recycler adapter initial time you need to pass current activity of context.
check context is null or not
check DetailedView activity registered manifest or not
another war to achieve intent interface concept is there
refer this tutorial better https://www.geeksforgeeks.org/android-recyclerview/
There are multiple reasons to this crash since you have not provided the Crash logs/stacktrace.
The context provided is not an Activity context in which case you need to add the Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK to your Intent's flags.
It is possible the crash is in the DetailedView Activity due to probably a NullPointerException or it is not added to AndroidManifest.xml
This is not the right way.
First of all crate interface callback
public interface ItemClick {
void onItemClick(int position);
}
Then calling this interface method inside adapter class and passing through the constructor and finally
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (settingsItemClick!=null)
{
int pos=getAdapterPosition();
if(pos!=RecyclerView.NO_POSITION)
{
settingsItemClick.onItemClick(pos);
}
}
}
});
3.Then inside activity implements interface method.

How do I pass a boolean value from a DialogFragment to another Fragment in Android?

I'm trying to make it so a clear button will open up an alert dialog which has a yes or no. When clicking the yes button, it should pass a bool value from the dialog frag to the other frag. If the value is true, which it should be when yes is clicked, it will call methods which will clear a database. Here is the dialog frag and the part of the frag where I'm trying to implement it. I can't get the dialog box to appear, but so far it does make the screen darker which I assume means I'm not hooking it up right.
Dialog frag:
public class DialogClear extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.clear_dialog, null);
final Button yes = dialogView.findViewById(R.id.yes);
final Button no = dialogView.findViewById(R.id.no);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
return builder.create();
}
}
Here is how I'm trying to call it from my frag
clearButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialogClear = new DialogClear();
dialogClear.setTargetFragment(BloodPressureFragment.this, 1);
dialogClear.show(getFragmentManager(),"");
dataManager.clearDatabase();
dataManager.createDatabase();
dataText.setText("");
dataText.setBackgroundResource(R.drawable.no_border);
updateList();
}
});
welcome to code party
you have many choices to do this job, but i will show you best way for using fragments.
As you know, all fragments changes in one activity and extend from it.
So the easy way is this:
1.build public fields in your activity
2.build a getInstant method on activity
3.fill and get values of that activity from any fragments that you want show on this
see this example:
public boolean isLocationOn;
this field is build in activity
now:
in any fragment:
MainActivity.getInstance().isLocationOn = true;
in other fragment:
if(MainActivity.getInstance().isLocationOn){
//todo show map or ...
}
in this way you can use anything in fragments
update me in comments
You should read and try using 3 thing's to solve this.
1. Navigation Component
easy to navigate to fragment's and DialogFragment
2. View Model
Share same View Model between different fragment's of an activity
Data is not lost on Orientation change's
All business logic at one place and easy to unit test
3. Live Data
recommended for responsive ui
Easy to understand Api's

Passing data between activities in onPause

i am facing trouble in passing data in activity's onpause() method.when user clicks a button in one activity, 2nd activity starts.in 1st activity's onPasue method i want to pass some data to other activity.i use intent.putExtra() to save data in onpause().in 2nd activity i use bundle.getString() to retrieve data.below is my code
public class FirstActivity extends Activity {
Intent intent;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tola_calculation);
b = (Button) findViewById(R.id.button);
intent = new Intent(Tola_calculation.this, Kaat_calculation.class);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(intent);
}
});
}
#Override
public void onPause() {
super.onPause();
intent.putExtra("key", "i am value");
}}
and
public class secondActivity extends Activity {
int value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kaat_calculation);
Bundle extras=new Bundle();
Intent intent=getIntent();
extras=intent.getExtras();
if (extras!=null) {
String value = extras.getString("key");
Toast.makeText(Kaat_calculation.this,value,Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(Kaat_calculation.this,"null problem",Toast.LENGTH_SHORT).show();
}
}}
problem is in 2nd activity intent.getExtras() returns null first time.i press back button 1st activity resumes.then i click again to go to 2nd activity.this time data is retrieved and intent.getextras() does not return null.can somebody explain this strange behaviour.or i am doing something strange as i am new to android programming.i hope i am able to clearly explain problem
This happens because your 2nd Activity is created before the 1st Activity calls onPause().
Solution: put your extra inside the onClick() callback. In other words (as the other answers suggest) you need to attach data to the Intent before calling startActivity() with that Intent.
In 1st Activity's onPause() method I want to pass some data to
other Activity
There's absolutely no need to do so because your 1st Activity is guaranteed to call onPause() as soon as your 2nd Activity becomes visible. So you already know at this point that your 1st Activity has called onPause().
Consult the official docs on Activity lifecycle for more details.
You should add data to Intent before you start the new activity. So this row
intent.putExtra("key", "i am value");
Should go before
startActivity(intent);
All in all, right code
public class FirstActivity extends Activity {
Intent intent;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tola_calculation);
b = (Button) findViewById(R.id.button);
intent = new Intent(Tola_calculation.this, Kaat_calculation.class);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent.putExtra("key", "i am value");
startActivity(intent);
}
});
}
#Override
public void onPause() {
super.onPause();
}
}
onPause method does not mean that your Activity is finishing, merely that it is pausing. If the user is pressing the back-button for example it will Pause, but not finish the Activity. better see the Activity lifecycle documentation
and also see this http://developer.android.com/reference/android/app/Activity.html#finish%28%29
It's NOT working the first time because when you are calling startActivity the extra is not set yet. Activity #2 starts before onPause is called.
It is working the second time because you made the intent variable an instance variable and you are not calling finish() after startActivity() call. That makes your first activity instance stay alive. The second time you launch the activity #2 the intent instance is already there and it already has the extra in it.
Solution: you should put the extra right before calling startActivity() and it'll work fine.
There is a great 7 step explanation on how this all works on Android Docs page

How do I get a button to open another activity?

I've added a button to my activity XML file and I can't get it to open my other activity. Can some please tell me step by step on how to do this?
A. Make sure your other activity is declared in manifest:
<activity
android:name="MyOtherActivity"
android:label="#string/app_name">
</activity>
All activities must be declared in manifest, even if they do not have an intent filter assigned to them.
B. In your MainActivity do something like this:
Button btn = (Button)findViewById(R.id.open_activity_button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, MyOtherActivity.class));
}
});
Using an OnClickListener
Inside your Activity instance's onCreate() method you need to first find your Button by it's id using findViewById() and then set an OnClickListener for your button and implement the onClick() method so that it starts your new Activity.
Button yourButton = (Button) findViewById(R.id.your_buttons_id);
yourButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
startActivity(new Intent(YourCurrentActivity.this, YourNewActivity.class));
}
});
This is probably most developers preferred method. However, there is a common alternative.
Using onClick in XML
Alternatively you can use the android:onClick="yourMethodName" to declare the method name in your Activity which is called when you click your Button, and then declare your method like so;
public void yourMethodName(View v){
startActivity(new Intent(YourCurrentActivity.this, YourNewActivity.class));
}
Also, don't forget to declare your new Activity in your manifest.xml. I hope this helps.
References;
Starting Another Activity (Official API Guide)
If you declared your button in the xml file similar to this:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="next activity"
android:onClick="goToActivity2"
/>
then you can use it to change the activity by putting this at the java file:
public void goToActivity2 (View view){
Intent intent = new Intent (this, Main2Activity.class);
startActivity(intent);
}
Note that my second activity is called "Main2Activity"
Button T=(Button)findViewById(R.id.button_timer);
T.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(getApplicationContext(),YOURACTIVITY.class);
startActivity(i);
}
});
Write code on xml file.
<Button android:width="wrap_content"
android:height="wrap_content"
android:id="#+id/button"
android:text="Click"/>
Write Code in your java file
Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
startActivity(new Intent(getApplicationContext(),Secondclass.class));
/* if you want to finish the first activity then just call
finish(); */
}
});
use the following code to have a button, in android studio, open an already existing activity.
Button StartButton = (Button) findViewById(R.id.YOUR BUTTONS ID GOES HERE);
StartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, YOUR ACTIVITY'S ID GOES HERE.class));
}
});
I did the same that user9876226 answered.
The only differemce is, that I don't usually use the onClickListener. Instead I write following in the xml-file: android:onClick="open"
open is the function, that is bound to the button.
Then just create the function open() in your activity class. When you click on the button, this function will be called :)
Also, I think this way is more confortable than using the listener.
Apply the following steps:
insert new layout xml in folder layout
rename window2
add new button and add this line: android:onClick="window2"
mainactivity.java
public void openWindow2(View v) {
//call window2
setContentView(R.layout.window2);
}
}
Use following steps to add the new activity (Manifest file will be automatically update)
File > New > Activity > Empty Activity
In your MainActivity.java file add the following code inside protected void onCreate(Bundle savedInstanceState).
Make sure you call finish(); function at the end. So when you tap the Back button, it will not go back to the previous activity.
Button btn = (Button)findViewById(R.id.open_activity_button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, MyOtherActivity.class));
finish();
}
});

Categories