8

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] https://i.stack.imgur.com/3kzmz.jpg

[2] : [Image of Add Activity Page] https://i.stack.imgur.com/lRo3V.jpg

mikepenz
  • 12,708
  • 14
  • 77
  • 117
宿命的な孤独
  • 325
  • 1
  • 4
  • 18

9 Answers9

4

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!

Community
  • 1
  • 1
MadScientist
  • 2,134
  • 14
  • 27
  • Hello for the if (resultCode== Activity.RESULT_OK && requestCode==123) what is the "Activity" referring to? Also, list.add(Parcels.unwrap(data.getParcelableArrayExtra(YOUR_KEY))); adapter.notifyDataSetChanged(); Why is the "list", "Parcels" and "adapter" all in red? Cannot resolve symbol. – 宿命的な孤独 Mar 04 '17 at 14:18
  • Do you have teamviewer to actually help me with it? :) – 宿命的な孤独 Mar 04 '17 at 14:55
  • list and other variables are red because that variables might not be defined, here the list will the final list which you`re using for showing things in the ListView (or RecyclerView) and Parcels is a library which you can optionally add to your project. Adapter is the class which will bind data to your RecyclerView if you have one. And Activty.RESULT_OK is static variable. you do not have to worry about what activity it is. – MadScientist Mar 04 '17 at 18:16
  • Sorry can help you with teamviewer, you might have to figure out stuff basic list and adapter stuff by yourself. [Here's a good guide](https://developer.android.com/training/material/lists-cards.html) – MadScientist Mar 04 '17 at 18:19
3

Use StartActivityForResult for AddActivity and return object from here and use in MainActivity. For example see here

Muneesh
  • 433
  • 10
  • 19
  • Hello could you help me to edit the codes and show me how do you do it because I really have no idea how to start with... – 宿命的な孤独 Feb 25 '17 at 10:02
  • see here [link](https://developer.android.com/training/basics/intents/result.html) – Muneesh Feb 25 '17 at 18:05
  • 1
    Link-only answers are generally [frowned upon](http://meta.stackexchange.com/a/8259/204922) on Stack Overflow. In time it is possible for links to atrophy and become unavailable, meaning that your answer is useless to users in the future. It would be best if you could provide the general details of your answer in your actual post, citing your link as a reference. – yennsarah Mar 02 '17 at 11:45
0

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.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
0

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.

Ivan
  • 782
  • 11
  • 23
0
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()}
Noorul
  • 3,386
  • 3
  • 32
  • 54
0

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.

Ali Nasir
  • 217
  • 2
  • 12
0

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
  1. 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) {

}
Jack_Zhang
  • 11
  • 3
0

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.

KKSINGLA
  • 1,284
  • 2
  • 10
  • 22
0

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()