Below are the 3 java classes which I am using for my android application development. I would like to add the student data (name and phone number) from the AddActivity to be stored in MainActivity page after clicking "Add". I have researched on this and tried using an array. But I am quite confused on how the logic must be for the code to send the data keyed in AddActivity into the MainActivity page. Can anyone give me a guidance on how to work this out and would really be grateful if you could show me another way rather the way I am trying. I want the data to be stored in a ListView format in the MainActivity after each "Add" I have clicked in the AddActivity page. I do hope that someone will be able to guide me in doing this. Thank you.
MainActivity.java -
https://jsfiddle.net/eb1fprnn/
public class MainActivity extends AppCompatActivity {
ListView listView;
Button addStudent;
ArrayList<Student> students = new ArrayList<Student>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add();
}
public void add() {
Student student;
addStudent = (Button) findViewById(R.id.add);
addStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
}
}
AddActivity.java -
https://jsfiddle.net/40k5mas2/
public class AddActivity extends AppCompatActivity {
EditText name, phone;
Button add;
int FphoneNumber;
String Fname;
ArrayList<Student> students;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
students = (ArrayList<Student>) getIntent().getSerializableExtra("AddNewStudent");
setContentView(R.layout.activity_add);
edit();
addStudent();
}
public void edit() {
name = (EditText) findViewById(R.id.StudentName);
phone = (EditText) findViewById(R.id.phone);
final Button addStudent = (Button) findViewById(R.id.AddStudent);
name.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
addStudent.setEnabled(!name.getText().toString().trim().isEmpty());
Fname = name.getText().toString();
String phoneNumber = phone.getText().toString();
FphoneNumber = Integer.parseInt(phoneNumber);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void addStudent() {
add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this, MainActivity.class);
intent.putExtra("studentName",name.getText().toString() );
intent.putExtra("phoneNumber",phone.getText().toString());
startActivity(intent);
Student student = new Student(Fname, FphoneNumber);
students.add(student);
}
});
}
public void addStudent(){
add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this,Record.class);
startActivity(intent);
}
});
}
Student.java -
https://jsfiddle.net/gy0g7b0s/
public class Student {
String mName;
int mPhoneNumber;
public Student (String name, int number){
mName = name;
mPhoneNumber = number;
};
public String getmName() {
return mName;
}
public String getmName(String newName) {
return (this.mName = newName);
}
public int getmPhoneNumber() {
return this.mPhoneNumber;
}
public int getmPhoneNumber(int newPhoneNumber) {
return (this.mPhoneNumber = newPhoneNumber);
}
#Override
public String toString() {
return String.format("%s\t%f",this.mName, this.mPhoneNumber);
}
[1] : [Image of Main Activity Page] http://imgur.com/a/pMWt4
[2] : [Image of Add Activity Page] http://imgur.com/a/8YvVc
as mentioned above, the correct way would be to use the startActivityForResult method. Check this.
And how to go about it, Damn easy!
Modifying your code:
public void add() {
Student student;
addStudent = (Button) findViewById(R.id.add);
addStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivityForResult(intent,123);
}
});
}
}
and in the same activity (MainActivity) listen for the result
Also would recommend you to use the parceler.org lib for sending objects
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode== Activity.RESULT_OK && requestCode==123){
// perform your list addition operation here and notify the adapter for change
// the returned data comes in 'data' parameter and would recommend you to use parcels.org lib
// for sending parcelable pojo across activities and fragments.
list.add(Parcels.unwrap(data.getParcelableArrayExtra(YOUR_KEY)));
adapter.notifyDataSetChanged();
}
}
And in your AddActivity, when you add just do this.
public void addStudent() {
// add the 'add' button view to the oncreatemethod
// add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do not restart the activity that opened this activty
// this activity is anyways on top of the MainActivity. Just finish this activty setting the result
// Intent intent = new Intent(AddActivity.this, MainActivity.class);
// intent.putExtra("studentName",name.getText().toString() );
// intent.putExtra("phoneNumber",phone.getText().toString());
// startActivity(intent);
// How to do that?
Student student = new Student(Fname, FphoneNumber);
Intent intent = new Intent();
intent.putExtra(YOUR_KEY, Parcels.wrap(student));
// you can also do it without the parcels lib
// intent.putExtra("studentName",name.getText().toString() );
// intent.putExtra("phoneNumber",phone.getText().toString());
setResult(123,intent); // set the result code. it should be the same one as the one your listening on in MainAcitivty
// then just finish this activity.
finish();
// this calls the onActivtyResultMethod in MainActivity which furtther does the logic
// students.add(student);
}
});
}
That should work! Cheers!
Use StartActivityForResult for AddActivity and return object from here and use in MainActivity. For example see here
Since you store the data in a file, the add activity should just write the data to the file. Then the main activity should always read the file to refresh the list.
I will suggest using a static class if you don't want to use a Database.
Or if you should use a file is just very simple to write into a file when you add and read from it in the next activity.
Just create a Static class like this.
public static class MyStaticClass{
private static ArrayList <Student> mStudents = new ArrayList<Student>()
public static void addStudent(Student theNewStudent){
mSudents.add(theNewStudent);
}
public static List<Student> getStudents(){
return mStudents;
}
}
or with a file:
public static class MyFileClass{
private static String pathFile = "Your path";
public static void addStudent(Student theNewStudent){
File file = new OutputStreamWriter(new FileOutputStream(pathFile,true)); //the true is to append to the file
file.write(/*parse your student as a string*/);
file.close();
}
public static List<Student> getStudents(){
ArrayList<Student> students = new ArrayList<>()
File file = new File(pathFile);
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
//parse your line to a student object
students.add(yourNewStudent);
}
sc.close();
return students;
}
}
Just call the add student and the get students in the proper class as follows.
MyStaticClass.addStudent(student);
or
MyFileClass.addStudent(student);
Hope it helps.
In your onclick listener:
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this, MainActivity.class);
Student student = new Student(Fname, FphoneNumber);
MyStaticClass.addStudent(student); // or the FileClass
startActivity(intent);
}
and i cant see where do you retrieve the list. but just use the getStudents of the class.
Intent yourFirstAct= new Intent(firstAct.this,second.class);
yourFirstAct.putExtra("","");
startActivitForResult(yourFirstAct);
in first Activity,
#Override
public void onAcitivityResult(....){
super();
}
in your second activity when you done,
do your stuff whatever you want in second activity. and pass it to mainActivity
Intent yoursecAct= new Intent();
yourSecAct.putExtra("","");
setResult(yourSecAct);
finish();
IF YOU ARE USING IN FRAGMENT
if you do startActivityResult() in fragment means,
your fragment mainActivity must return super() in
public void onAcitivityResult(...){super()}
After getting the details from the student, put the respective details in a bundle and just use intent to go back to the main activity. Then use bundles to extract the data in the main activity.
You can use startActivityForResult for the same. if you haven't found the answer yet then please let me know. I will provide you the code.
Many above answers already defined this thing in a very good way.
This is about communication between Activities. You can use event bus to realize this.
https://github.com/JackZhangqj/EventBus
Then 1. Add event bus dependency to the App's build.grade
compile "de.greenrobot:eventbus:3.0.0
Register and unregister your subscribe in the MainActivity.java
#Override
protected void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
protected void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
3.Post event in the AddActivity.java
EventBus.getDefault().post(new Student(name.getText().toString(), phone.getText().toString()));
4.Implement event handling method in MainActivity
//The student is the added student in the AddActivity.java
public void onEventMainThread(Student student) {
}
To kind of expand a little bit on MadScientist's answer, ListView's need adapters in order set the data in it's view. You'll need to define an ArrayAdapter for your list view to communicate with. This will need to go in your MainActivity and will be initialized in the onCreate method. Assuming you want to display both types of information, you'll need to construct your adapter with the built in layout for showing two items via android.R.layout.simple_list_item_2. If you would like to create your own layout, however, you can look up how to do that here.
public class MainActivity extends AppCompatActivity {
Button addStudent;
ArrayAdapter<Student> adapter;
ArrayList<Student> students = new ArrayList<Student>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_2, students);
ListView listView = (ListView) findViewById(R.id.listView);
listView.addAdapter(adapter);
add();
}
Call the startActivityForResult(intent, 123) in your Listener to start the new activity. Then, once you have typed in your data, add your items to the intent and call finish() in your AddActivity. Override the onActivityResult in your MainActivity to pull the items off your intent and add them to your list. Finally, notify the adapter of the changes via adapter.notifyDataSetChanged()
So basically my question is just explained in the title. How can I send data between activities without having to start that activity which receive the data. Here's my code: This is the main activity sending the data :
public class MainActivity extends Activity {
private EditText mainedit1;
private TextView maintext1;
private Button mainadd1;
private Button maindone1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
maindone1=(Button) findViewById(R.id.maindone);
mainedit1=(EditText)findViewById(R.id.mainedit1);
maintext1=(TextView)findViewById(R.id.maintext1);
mainadd1=(Button)findViewById(R.id.mainadd);
mainadd1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String test1= mainedit1.getText().toString();
Intent intent = new Intent(MainActivity.this,test.class);
intent.putExtra("word",test1);
startActivity(intent);
}
});
And this is the activity receiving the data :
public class test extends Activity {
TextView testtext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fortest);
testtext=(TextView)findViewById(R.id.testtext);
Intent intent = getIntent();
String Word = intent.getStringExtra("word");
testtext.setText(Word);
}
So what I did in here is to send the data but also starting the activity, and this is not what I want to share. Please show me how do I fix my code?
It seems you're just looking to save a string for later use. In your MainActivity, just do the following to save the string:
getSharedPreferences("my_prefs", Context.MODE_PRIVATE).edit().putString("word", test1).commit();
Then when you're ready to retrieve it in your test activity, just do so like this:
String Word = getSharedPreferences("my_prefs", Context.MODE_PRIVATE).getString("word", null);
testtext.setText(Word);
You can use sharedprefrence of android following code you can implement
In your MainActivity, just do the following to save the string:
getSharedPreferences("my_prefs", Context.MODE_PRIVATE).edit().putString("word", test1).commit();
Then when you're ready to retrieve it in your test activity, just do so like this:
String Word = getSharedPreferences("my_prefs", Context.MODE_PRIVATE).getString("word", null);
testtext.setText(Word);
OR
Sending data without having to start a new Acitivity, by create static variable
ex.
public class First_Activity extends Activity {
public static String USER_FORMATED_NUMBER = null;
USER_FORMATED_NUMBER="Data you want to pass";
}
public class Second_Activity extends Activity {
String data=First_Activity.USER_FORMATED_NUMBER;
}
I have the first class named iHave
public class iHave extends ActionBarActivity
{
//below is the instance for calling the method from the other activity.
(The name of the other activity is **iThank**)
**iThank thankYou = new iThank();**
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_i_have);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
**//this is the method I want to access from iThank class** **strong text**
thankYou.display();
}
});
}
//The Next class is "iThank"
public class iThank extends ActionBarActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_i_thank);
txtThank = (TextView) findViewById(R.id.textView3);
//this is the method I want to access/use from iHave Activity
public void display()
{
txtThank.setText ("Shine");
}
}
How can I use the method "public void display()" of iThank activity to the "iHave" activity? It always gives me an error of NullPointerException. Please help. Thank you very much!
How can I access a method from an activity and use it into another
activity in Android?
By creating object for other to access method from Activity is right way.
Use LocalBroadcastManager for communicating between application components.
1. Send broadcast from iHave on Button click:
#Override
public void onClick(View v)
{
Intent intent = new Intent("DISPLAY_EVENT");
LocalBroadcastManager.getInstance(v.getContext()).sendBroadcast(intent);
}
2. Register LocalBroadcastManager in iThank Activity:
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(ReceiveMessage,
new IntentFilter("DISPLAY_EVENT"));
}
3. Create BroadcastReceiver object and call display() method in iThank Activity:
private BroadcastReceiver ReceiveMessage = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
display();
}
};
Also add null check in display method for TextView:
public void display()
{
if(txtThank !=null)
txtThank.setText ("Shine");
}
Please don't to this, it is not how activities are intended to work. You might want to have a look over the Activities Developer Guide to get started. If you want to launch a new activity (e.g. iThank) from the current foreground activity (e.g. iHave), you never instantiate the class yourself directly and always launch it using an intent. If you have data to pass along (such as a message to display), it needs to be bundled along with the intent as an extra (see same link).
Activities should never call methods on each other directly, because this requires them to have references to each other. The framework manages the life cycle of each activity independently, and those references can lead to leaks.
I have a Main activity and after click on button I start thread (but the thread is hidden in library and I have only callback in Main activity.
Now I want to start another activity (call A) where I want to put results from the thread.
Below is simplified code:
public class Main extends Activity {
XManager.ResultsCallback xResultsCallback = new XManager.ResultsCallback() {
// the method is called every 10 sec.
#Override
public void onResult(ArrayList<String> texts) {
}
};
XManager xManager = new xManager(xResultsCallback);
View.OnClickListener onClick = new View.OnClickListener() {
#Override
public void onClick(View arg0) {
XManager.start();
Intent i = new Intent(Main.this, A.class);
startActivity(i);
}
};
}
I want to update the content of A activity each time when onResult() method is called. How to do that?
Use LocalBroadcastManager,
In your Main Activity create function :
private void sendResult() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "This is my result!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
and add BroadcastReceiver in your A Activity
private BroadcastReceiver onResult= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("jazzy","onReceive called");
}
};
add on OnCreate
#Override
public void onCreate(Bundle savedInstanceState) {
// Register to receive messages.
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("custom-event-name"));
}
add onDestroy
#Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
I have a suggestion that you should do as follows:
Start Your Activity A on button click
Inside Activity A declare your XManager instance with a callback present in A itself
Then start your XManager as XManager.start(); that way you would be getting all the callbacks in your desired activity.
Have a great day!
I think if you want to decouple the logic, beside you can use the Android BroadcastReceiver, the another flexible choice is to use the Bus
And you can integrate it with gradle easily
dependencies {
compile 'com.squareup:otto:+'
}
Can i define an activity in parent class of all activities that that can open new activity like this method that working:
public class ActivityBase extends Activity{
public <T extends Activity,U extends Activity> void openActivity()
{
Intent myIntent = new Intent(T.this, U.class);
T.this.startActivity(myIntent);
}
}
public class ActivityChield extends ActivityBase{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_warning_unregistered_shipping);
// Set widgets reference
btnOpenActivity = (Button)findViewById(R.id.btn_wus_select_violation);
// Set widgets event listener
setListeners();
}
private void setListeners()
{
btnOpenActivity.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick(View view)
{
openActivity<ActivityChield , OtherActivity>();
}
});
}
}
This code is not working . Please help me how can i define a method that can open all activities with one method.
I don't think this way is a perfect solution. Better is to write the calling code when you need.
By the way here is a solution for your question
public void openActivity(Class<?> calledActivity) {
Intent myIntent = new Intent(this, calledActivity);
this.startActivity(myIntent);
}
And you can call it as
openActivity(OtherActivity.class);