I want to define callback for a Notebook program that way after note saved in EditActivity,in Main Activity Update list of notes,But This does not happen.
EditActivity:
public interface OnClickDoneListener{
void onClickDone();
}
public void setOnClickDoneListener(OnClickDoneListener onClickDoneListener){
this.onClickDoneListener=onClickDoneListener;
}
btnDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (extras != null) {
myDatabase.updateRow(id, txtTitle.getText().toString(), txtDesc.getText().toString());
NoteModel noteModel = new NoteModel();
noteModel.setTitle(txtTitle.getText().toString());
noteModel.setDesc(txtDesc.getText().toString());
Intent intent = new Intent(EditActivity.this, MainActivity.class);
startActivity(intent);
onClickDoneListener.onClickDone();
} else {
Done();
}
}
});
Main Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setupViews();
getDataFromDB();
recyclerView.setAdapter(new NoteAdapter(MainActivity.this,dataList));
noteAdapter = new NoteAdapter(MainActivity.this,dataList);
recyclerView.setAdapter(noteAdapter);
fabAdd = (FloatingActionButton)findViewById(R.id.fab_main_add) ;
EditActivity editActivity = new EditActivity();
editActivity.setOnClickDoneListener(new EditActivity.OnClickDoneListener() {
#Override
public void onClickDone() {
noteAdapter.notifyDataSetChanged();
}
});
please help me.
My English is poor,sorry for it.
You want your data to be updated when the MainActivity is shown, right ?
You just have to call your getDataFromDB part in onResume() instead of onCreate()
EditActivity editActivity = new EditActivity();
editActivity.setOnClickDoneListener(new EditActivity.OnClickDoneListener() {
#Override
public void onClickDone() {
noteAdapter.notifyDataSetChanged();
}
});
What you are doing here is setting the value of OnClickDoneListener in a new instance of EditActivity that you will never use. Because when you use new Intent(MainActivity.this, EditActivity.class) to start the EditActivity it will create a new instance of EditActivity and your interface would be null.
I suggest you use android's Broadcast Receiver instead of a callback in this case. All you have to do is:
In MainActivity: You will need to instantiate a broadcast receiver. You need to register it onCreate or onStart and unregister it onStop or onDestory.
In EditAcitivity: You send a broadcast whenever you want to notify your MainActivity to update the list.
Check out this example:
https://riptutorial.com/android/example/18305/communicate-two-activities-through-custom-broadcast-receiver
Related
I have a MainActivity with some cards which have different names. onClick, the title is passed as an intent via the adapter to the secondActivity and displayed as the header. From there, I can go to other activities. If I come back from one of these other activities (via the back button created by establishing second activity as the parent activity) the header is gone. How do I keep the header that was originally passed on as an intent or should I go about this completely different?
I have tried using onResume() and onStart() in the secondActivity to reassign the intent from a global variable.
The adapter class, where the card onClick method is written:
#Override
public void onBindViewHolder(final TripHolder tripHolder, final int position) {
Trip trip = trips.get(position);
tripHolder.setDetails(trip);
tripHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, SecondActivity.class);
TextView card_title = v.findViewById(R.id.TripNamecl);
intent.putExtra("card_title", card_title.getText().toString());
context.startActivity(intent);
}
});
}
The secondActivity where the header should be displayed:
public class SecondActivity extends AppCompatActivity {
String name;
TextView header;
static final String STATE_HEADER = "header";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
name = getIntent().getStringExtra("card_title");
header = findViewById(R.id.TripsHeader);
header.setText(name);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString(STATE_HEADER, name);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
name = savedInstanceState.getString(STATE_HEADER);
header.setText(name);
}
public void launchMapsActivity(View view) {
Uri gmmIntentUri = Uri.parse("geo:48.8566°,2.3522");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
if (mapIntent.resolveActivity(getPackageManager()) != null) {
startActivity(mapIntent);
}
}
public void launchTravelActivity(View view) {
Intent intent = new Intent(this, TravelActivity.class);
startActivity(intent);
}
public void launchPlansActivity(View view) {
Intent intent = new Intent(this, PlansActivity.class);
startActivity(intent);
}
}
SOLUTION:
The solution was to put android:launchMode="singleTop" into the manifest file for the secondactivity. It's described in more detail here: How can I return to a parent activity correctly?
In order to do it you should override onSavedInstanceState in your SecondActivity.
You can use something like that, obv adapt it to your needs:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
//here you can save your variables
savedInstanceState.putString("myHeader", name);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//here you can retrieve your variables
name = savedInstanceState.getString("myHeader");
}
Let me know if this worked! good luck
remove header.setText(name); from onResume and onStart methods
If you want to save data in first activity between lifecicle method calls you have to save your data in Bundle object.
Override method onSaveInstanceState(Bundle bundle) of your activity:
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("AStringKey", variableData);
outState.putString("AStringKey2", variableData2);
}
And also override Activity method onRestoreInstanceState(Bundle savedInstanceState):
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
variableData = savedInstanceState.getInt("AStringKey");
variableData2 = savedInstanceState.getString("AStringKey2");
setYourHeaderMethodExample(variableData2)
}
When coming back from third activity to second activity onStart() and onResume() method call executes. Try not using onStart() and onResume() for setting the header and use onCreate method for setting the header.
onCreate() method executes only once in its lifetime, but onStart() and onResume() will execute whenever the activity comes to screen. So when coming back from third activity we don't have any values in the intent.
In your second activity's onCreate method add:
getSupportActionBar().setHomeButtonEnabled(true);
and override the onOptionsItemSelected() method in the class and add the following code:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
You don't need to override the onStart() and onResume() methods.
I have Act_01 (where I put value) and Act_02 (where I get value) but have declared these methods in a Extras class, getting value from Act_02 returns null value:
Act_01: (Where I want to pass the value Name to Act_02)
public class Act_01 extends Activity {
Extras cc_Extras;
Button btn1;
Intent intent;
String str_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_01);
cc_Extras = new Extras();
str_Name = "Buck";
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
cc_Extras.putExtras();
startActivity(intent);
}
});
}
}
Act_02: (Where I want ot receive value Name from Act_01 but the app crashes with null value)
public class Act_02 extends Activity {
Extras cc_Extras;
String str_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_02);
cc_Extras = new Extras();
if(getIntent() != null && getIntent().getExtras() != null)
{
cc_Extras.getExtras();
}
Toast.makeText(getApplicationContext(), "Name: "+str_Name, Toast.LENGTH_SHORT).show();
}
}
Extras: (Where I define the methods to put and get Extras)
public class Extras extends Activity {
String str_Name;
Intent intent;
public void putExtras() {
// TODO Auto-generated method stub
intent.putExtra("KEY_Name", str_Name);
}
public void getExtras() {
// TODO Auto-generated method stub
str_Name = getIntent().getExtras().getString("KEY_Name");
}
}
EDIT: I do not want to pass and get data directly between activities, I want to use the 3rd class (Extras.java) because I have too many activities having too many values between each other and want to sort of define them globally in Extras so that all my other activities can just call one method instead of getting and putting too many values in my activities.
Your app crashes not with a null value, but a null pointer reference because you created a new Activity manually
cc_Extras = new Extras();
Then called a lifecycle method on it
cc_Extras.getExtras()
Which calls getIntent(), but the Intent was never setup by the Android framework, and cc_Extras.getExtras() wouldn't have any of the data you wanted anyway in the second Activity because it was just created there, not from the first Activity.
Briefly, you should never make a new Activity, and your Extras class does not need to be an Activity in the first place (nor does it provide much benefit).
Just use the Intent object provided by the first Activity to start the second Activity, and get extras like normal. Don't overcomplicate your code. Regarding the title of the question, Intent and Bundle are already "another class" designed by Android for you to transfer data.
On both activities you are creating a new instances of Extras class means they dont hold the same value you can do this to transfer data from A to B
public class Act_01 extends Activity {
Button btn1;
Intent intent;
String str_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_01);
str_Name = "Buck";
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
intent = new Intent(Act_01.this, Act_02.class);
intent.putExtra("data", str_Name)
startActivity(intent);
}
});
}
}
And receieve data like this
public class Act_02 extends Activity {
String str_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_02);
// cc_Extras = new Extras();
if(getIntent() != null)
{
if (getIntent().getStringExtra("data") != null) {
Toast.makeText(Act_02.this, "Name: "+getIntent.getStringExtra("data"), Toast.LENGTH_SHORT).show();
}
}
}
}
Also you should consider using Activity Context instead of the application context
Ok! so here are the few things I might wanna suggest you to correct.
Changes needs to be done in the code.
You are not assigning anything to "intent" object , and you have passed a intent without assigning anything to it.
Your instance cc_Extra isn't doing anything in the activity1. You might wanna pass the "intent" object in your constructor of class like cc_Extras= new Extras(intent); and in the Extras class do the following- Intent intent;
Extras(Intent i)
{
this.intent=i;
}
In the activity2 you are creating the new Instance of Extras(). So according to your code it is going to be NULL by default. If you have done the changes from the previous step, you can create new instance by doing cc_Extras(getIntent());
Corrections in the code
1) In Extras class getExtras() method instead of str=getIntent() use str=intent.getExtras.getString().
2) In the activity2 you are not assigning anything to your String str_Name, so you need to return the string you got in getExtras() method. You can do it by changing the return type to String. Below is the sample code.
public String getExtras()
{
str_Name=intent.getExtras().getString("KEY_Name");
//OR
//str_Name=intent.getStringExtra("KEY_Name");
return str_Name;
}
3) By the doing this you need to catch this string in the activity2 by doing `
if(getIntent() != null && getIntent().getExtras() != null)
{
str_Name=cc_Extras.getExtras();
}`
4) Another thing is you must create intent like this-
Intent intent=new Intent(currentActivityName.this,anotherActivity2.class);
//then use the intent object
EDIT- Your code must look like this in the end...
Act1
public class Act_01 extends Activity {
Extras cc_Extras=null;
Button btn1;
String str_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_01);
str_Name = "Buck";
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//changes to do
Intent intent= new Intent(Act01.this,Act02.class);
cc_Extras= new Extras(intent);
cc_Extras.putExtras(str_Name);
//end
startActivity(intent);
}
});
}
}
Act02
public class Act_02 extends Activity {
Extras cc_Extras;
String str_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_02);
cc_Extras = new Extras(getIntent());
if(getIntent() != null && getIntent().getExtras() != null)
{
str_Name=cc_Extras.getExtras();
}
Toast.makeText(getApplicationContext(), "Name: "+str_Name, Toast.LENGTH_SHORT).show();
}
}
Extras class
public class Extras { //remove "extends Activity" because it is a class not a activity
String str_Name;
Intent intent;
Extras(Intent i)
{
this.intent=i;
}
public void putExtras(String str) {
// TODO Auto-generated method stub
str_Name=str;
intent.putExtra("KEY_Name", str_Name);
}
public String getExtras() {
// TODO Auto-generated method stub
str_Name = intent.getExtras().getString("KEY_Name");
return str_Name;
}
}
Above code will work just on String. You can extend the functionality if you want.
I hope this must work to get your code working!
I have three Activities. MainActivity,ActivityB and ActivityC. In activity A and B there are two buttons source and destination in both activities. in Activity C there is a list of data. when button is clicked (either Source or destination) from activity A and B. both Activities are calling Activity C
code for Activity A is following
public class MainActivity extends Activity {
TextView source,destination;
Button sendSource,sendDestination,btnTob;
String src,des,activity,checksrc,checkdes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
source=(TextView)findViewById(R.id.tv_rcvDataA);
destination=(TextView)findViewById(R.id.tv_rcvDataAa);
sendSource=(Button)findViewById(R.id.btn_sendA);
sendDestination=(Button)findViewById(R.id.btn_sendAa);
btnTob=(Button)findViewById(R.id.btn_toB);
sendSource.setText("source");
sendDestination.setText("destination");
src=sendSource.getText().toString();
des=sendDestination.getText().toString();
activity=getClass().getSimpleName();
sendSource.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent send= new Intent(MainActivity.this,ActivityC.class);
send.putExtra("source",src);
send.putExtra("Activity",activity);
startActivity(send);
}
});
sendDestination.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent senda= new Intent(MainActivity.this,ActivityC.class);
senda.putExtra("destination",des);
senda.putExtra("Activity",activity);
startActivity(senda);
}
});
btnTob.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent movetoB= new Intent(MainActivity.this,ActivityB.class);
startActivity(movetoB);
finish();
}
}); }}
and code for Activity B is
public class ActivityB extends Activity {
TextView sourceB,destinationB;
Button sendSourceB,sendDestinationB;
String src,des,activity,checksrc,checkdes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
sourceB=(TextView)findViewById(R.id.tv_rcvDataB);
destinationB=(TextView)findViewById(R.id.tv_rcvDataBa);
sendSourceB=(Button)findViewById(R.id.btn_sendB);
sendDestinationB=(Button)findViewById(R.id.btn_sendDataBa);
activity=getClass().getSimpleName();
sendDestinationB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent senda= new Intent(ActivityB.this,ActivityC.class);
senda.putExtra("destination",src);
senda.putExtra("Activity",activity);
startActivity(senda);
}
});
sendSourceB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent send= new Intent(ActivityB.this,ActivityC.class);
send.putExtra("source",src);
send.putExtra("Activity",activity);
startActivity(send);
}
});}}
now how to check in activityC which activity is calling this activity and which buttonclicklistener is calling the intent
You need to send the value for determine what value and what activity via Intent.putExtra(). Please be remember that you need to set the key as the first parameter for Intent.putExtra(), like
intent.putExtra(THIS_IS_THE_KEY, THIS_IS_YOUR_VALUE);
You need to create something like this:
// This is the key for your putExtra
// you need to create this as global variable.
public static final String FROM_KEY = "FROM";
public static final String ACTIVITY_KEY = "ACTIVITY";
public static final boolean IS_FROM_SOURCE = true;
// This is a sample to send data to Activity C
// where the activity caller is B and from source
Intent senda= new Intent(ActivityB.this,ActivityC.class);
senda.putExtra(FROM_KEY, IS_FROM_SOURCE);
senda.putExtra(ACTIVITY_KEY,"activity_a");
Then in your Activity C, you need to receive the Intent Extra.
You can get the value in Activity onCreate(), something like this:
Bundle extras = getIntent().getExtras();
boolean from = extras.getBoolean(FROM_KEY);
String act = extras.getString(ACTIVITY_KEY);
// do something here if from activity a
if(act.equals("activity_a")) {
if(IS_FROM_SOURCE) {
// do something if from source
} else {
// do something if from destination.
}
} else { // if from activity a
if(IS_FROM_SOURCE) {
// do something if from source
} else {
// do something if from destination.
}
}
In onCreate or anytime after that method is called in Activity-C, you should do the following:
Intent intent = getIntent();
if (intent != null) {
String activity = intent.getStringExtra("Activity");
String src = intent.getStringExtra("source");
// Do something with those values
}
I am working on a budget app and am having trouble getting my expenses to the class that will create a graph. The user will be able to input an expense along with a check box indicating what they spent money on. When I send the value to MainActivity, it reads the expense and shows the updated budget, however, when I try to read it in my class that will make a graph, the graph shows up empty and is not reading the values. Here is my Expense Activity (Screen 2):
public class ExpensesActivity extends AppCompatActivity {
EditText editTextExpense;
Expenses expenses;
String selectedCheckBox;
CheckBox personalCheckBox;
CheckBox commuteCheckBox;
CheckBox billsCheckBox;
CheckBox funCheckBox;
CheckBox workCheckBox;
CheckBox foodCheckBox;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_expenses);
editTextExpense = (EditText)findViewById(R.id.moneySpent);
personalCheckBox = (CheckBox)findViewById(R.id.personalCheckBox);
commuteCheckBox = (CheckBox)findViewById(R.id.commuteCheckBox);
billsCheckBox = (CheckBox)findViewById(R.id.billsCheckBox);
funCheckBox = (CheckBox)findViewById(R.id.funCheckBox);
workCheckBox = (CheckBox)findViewById(R.id.workCheckBox);
foodCheckBox = (CheckBox)findViewById(R.id.foodCheckBox);
backToMainMenu();
}
public void backToMainMenu() {
final Button expenseButton = (Button)findViewById(R.id.addExpenseSecondScreen);
expenseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (personalCheckBox.isChecked()) {
selectedCheckBox = personalCheckBox.getText().toString();
}
if (commuteCheckBox.isChecked()) {
selectedCheckBox = commuteCheckBox.getText().toString();
}
if (billsCheckBox.isChecked()) {
selectedCheckBox = billsCheckBox.getText().toString();
}
if (funCheckBox.isChecked()) {
selectedCheckBox = funCheckBox.getText().toString();
}
if (workCheckBox.isChecked()) {
selectedCheckBox = workCheckBox.getText().toString();
}
if (foodCheckBox.isChecked()) {
selectedCheckBox = foodCheckBox.getText().toString();
}
float expense = Float.parseFloat(editTextExpense.getText().toString());
Intent intent = getIntent();
intent.putExtra("expense", expense);
intent.putExtra("checkBoxText", selectedCheckBox);
setResult(RESULT_OK, intent);
finish();
}
});
}
}
I am not sure what you are expecting here but onActivityResult is used to get the result from starting an Activity using startActivityForResult and will only be called in the activity which called startActivityForResult.
Since activities are only active one at a time (unless you are targeting the N preview) you would have to pass the result data using the start intent to the other activity.
Use BroadcastReceiver register the BroadcastReceiver to both activity and fire the BroadcastReceiver when you want to send the data. Use LocalBroadcastManager
sample code to create BroadcastReceiver
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}
}
registerReceiver(receiver, filter);
and unregister in onDestroy()
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
I don't know exactly what you want,are you tried "static" for expense and
selectedCheckBox variables.Then you easily get the values from any where or use
shared preference.
I have three classActivity created. One is super class and other sub class and third is HomeActivity.
Code for super class is :
public class MyActivity extends Activity {
Button btnHome = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onHomeClick(View view) {
String LOG_TAG = "Akshar";
System.out.println("Hello11111");
btnHome = (Button) view;
Log.v(LOG_TAG, "index=" + btnHome);
}
}
and my subclass code is :
public class ChooseIsland extends MyActivity {
Button btn_home = null;
MyActivity ob1 = new MyActivity();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chooseiland);
addListenerOnButton();
}
private void addListenerOnButton() {
// TODO Auto-generated method stub
ob1.onHomeClick(btn_home);
}
}
Now I want to go on Home page when click so when I write ?
Intent intent = new Intent(this, HomeActivity.class);
There is no close operation as such in android. You should make sure you do not save anything in stack so whenever you are traversing from one activity to other, make sure you use intent flags to clear history or top of stack and then call finish.
finish() will close the current activity and the previous activity will come to foreground.
Generally to we write finish() method to close activity.