0

I am doing a project in android studio where I have 4 activities. The first one is a list view which has an add button at the bottom. When you click the add button a new page opens, that's the second activity that is the adding form when I click on a specific item on the list it shows its details, that's the 3rd activity. In that activity, I have at the bottom an edit button that when I click it, it opens the last activity.

Now, I managed to do all of that, my only problem is at the 4th activity when I edit the text there and I want to save I don't know how to implement the edited item to the list, and how to implement a delete item from that activity that will delete and edit the list on the main activity would love to get some help.

Main activity code-

package com.example.studentrecyclerview;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

public class MainActivity extends AppCompatActivity {

    FloatingActionButton floatingBtn;
    ListView lv_studentsList;

    StudentAdapter adapter;
    MyStudents myStudents;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setTitle("Student List");
        setContentView(R.layout.activity_main);

        floatingBtn = findViewById(R.id.main_floatingbtn);
        myStudents = ((MyApplication) this.getApplication()).getMyStudents();

        lv_studentsList = findViewById(R.id.lv_listofnames);

        adapter = new StudentAdapter(MainActivity.this , myStudents);
        lv_studentsList.setAdapter(adapter);

        Bundle incomingMessages = getIntent().getExtras();
        if(incomingMessages != null){

            String name = incomingMessages.getString("name");
            int id = Integer.parseInt( incomingMessages.getString("id"));
            int picturenumber = Integer.parseInt(incomingMessages.getString("picturenumber"));
            boolean flag = incomingMessages.getBoolean("checkbox");



            Student s = new Student(name, id, picturenumber, flag);


            myStudents.getMyStudentList().add(s);
            adapter.notifyDataSetChanged();

        }


        floatingBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(v.getContext(),NewStudentForm.class);
                startActivity(i);
            }
        });

        lv_studentsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                displayForm(position);
            }
        });


    }

    public void displayForm(int position){

        Intent i = new Intent(getApplicationContext(), DisplayForm.class);
        Student s = myStudents.getMyStudentList().get(position);

        i.putExtra("name",s.getName());
        i.putExtra("id",s.getId());
        i.putExtra("checkbox", s.isFlag());

        //i.putExtra("picturenumber",s.getPictureNumber());

        startActivity(i);

    }


}

adapter code

package com.example.studentrecyclerview;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

public class StudentAdapter extends BaseAdapter {

    Activity mActivity;
    MyStudents myStudents;

    public StudentAdapter(Activity mActivity, MyStudents myStudents) {
        this.mActivity = mActivity;
        this.myStudents = myStudents;
    }

    @Override
    public int getCount() {
        return myStudents.getMyStudentList().size();
    }

    @Override
    public Student getItem(int position) {
        return myStudents.getMyStudentList().get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View oneStudentLine;

        LayoutInflater inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        oneStudentLine = inflater.inflate(R.layout.student_one_line, parent, false);

        TextView tv_name = oneStudentLine.findViewById(R.id.tv_name);
        TextView tv_id = oneStudentLine.findViewById(R.id.tv_id_label);
        ImageView iv_icon = oneStudentLine.findViewById(R.id.iv_icon);
        CheckBox cb = oneStudentLine.findViewById(R.id.row_cb);

        Student s = this.getItem(position);

        tv_name.setText(s.getName());
        tv_id.setText(Integer.toString(s.getId()));
        cb.setChecked(s.isFlag());


        int icon_resource_numbers [] = {
                R.drawable.icon01_02,
                R.drawable.icon01_31,
                R.drawable.icon01_03,
                R.drawable.icon01_04,
                R.drawable.icon01_05,
                R.drawable.icon01_06,
                R.drawable.icon01_07,
                R.drawable.icon01_08,
                R.drawable.icon01_09,
                R.drawable.icon01_10,
                R.drawable.icon01_11,
                R.drawable.icon01_12,
                R.drawable.icon01_13,
                R.drawable.icon01_14,
                R.drawable.icon01_15,
                R.drawable.icon01_16,
                R.drawable.icon01_17

        };
        iv_icon.setImageResource(R.drawable.icon01_02);
        iv_icon.setImageResource((icon_resource_numbers[position]));




        return oneStudentLine;
    }
}

second activity code

package com.example.studentrecyclerview;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class NewStudentForm extends AppCompatActivity {

    Button btn_add , btn_cancel;
    EditText et_name ,et_id, et_picturenumber;
    CheckBox cb;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setTitle("New Student");
        setContentView(R.layout.activity_new_student_form);

        btn_cancel = findViewById(R.id.btn_cancel);
        btn_add = findViewById(R.id.btn_add);
        et_name = findViewById(R.id.add_stud_et_name);
        et_id = findViewById(R.id.add_stud_et_id);
        et_picturenumber = findViewById(R.id.add_stud_picnum);
        cb = (CheckBox) findViewById(R.id.form_cb);


        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent i = new Intent(v.getContext(), MainActivity.class);
                startActivity(i);

            }
        });

        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String newName = et_name.getText().toString();
                String newId = et_id.getText().toString();
                String newPictureNumber= et_picturenumber.getText().toString();
                boolean flag = cb.isChecked();



                Intent i = new Intent(v.getContext(), MainActivity.class);

                i.putExtra("name", newName);
                i.putExtra("id", newId);
                i.putExtra("picturenumber", newPictureNumber);
                i.putExtra("checkbox", flag);
                startActivity(i);
            }
        });


    }
}

third acitvity code

package com.example.studentrecyclerview;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

public class DisplayForm extends AppCompatActivity {

    TextView tv_name;
    TextView tv_id;
    CheckBox cb;
    ImageView img;
    Button btn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setTitle("Student Details");
        setContentView(R.layout.activity_display_form);
        btn = findViewById(R.id.displayform_edit);
        tv_name = (TextView) findViewById(R.id.displayform_et_name);
        tv_id = (TextView) findViewById(R.id.displayform_et_id);
        cb = (CheckBox) findViewById(R.id.displayform_cb);
        img = (ImageView) findViewById(R.id.displayform_icn);

        Bundle incomingIntent = getIntent().getExtras();
        if (incomingIntent != null){
            String name = incomingIntent.getString("name");
            int id = incomingIntent.getInt("id");
            boolean flag = incomingIntent.getBoolean("checkbox");


            // picture missing
            tv_name.setText(name);
            tv_id.setText(Integer.toString(id));
            cb.setChecked(flag);

            //picture missing
        }

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editStudent();
            }
        });

    }

    public void editStudent() {

        Intent i = new Intent(getApplicationContext(), EditStudents.class);
        boolean flag = cb.isChecked();
        String name = tv_name.getText().toString();
        String id = tv_id.getText().toString();


        i.putExtra("name_edit", name);
        i.putExtra("id_edit", id);
        i.putExtra("checkbox_edit",flag);
        startActivity(i);


    }
}

the forth one the edit one where i want to implement the save after edited

package com.example.studentrecyclerview;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class EditStudents extends AppCompatActivity {

    EditText et_name;
    EditText et_id;
    CheckBox cb;
    Button save;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setTitle("Edit Students");
        setContentView(R.layout.activity_edit_students);
        et_name = findViewById(R.id.editStud_et_name);
        et_id = findViewById(R.id.editStud_et_id);
        cb = (CheckBox) findViewById(R.id.editStud_cb);
        save = findViewById(R.id.editStud_saveBtn);


        Bundle incomeInt = getIntent().getExtras();

        if(incomeInt != null){
          String name = incomeInt.getString("name_edit");
          String id = incomeInt.getString("id_edit");
          boolean flag = incomeInt.getBoolean("checkbox_edit");


          et_name.setText(name);
          et_id.setText(id);
          cb.setChecked(flag);

        }
save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
**// what to do here**
            }
        });


// 7:02


    }
}

Some pics-

first activitysecond activity

third activty

forth activity

this is my student class

package com.example.studentrecyclerview;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class MyStudents {

    List<Student> myStudentList;

    public MyStudents(List<Student> myStudentList) {
        this.myStudentList = myStudentList;
    }

    public MyStudents(){
       String[] startingNames = {"Alon"};
       this.myStudentList = new ArrayList<>();
       Random rng = new Random();
       for(int i=0; i<startingNames.length; i++){
           Student s = new Student(startingNames[i], rng.nextInt(50)+ 15, 2, true );
           myStudentList.add(s);
       }

    }

    public List<Student> getMyStudentList() {
        return myStudentList;
    }

    public void setMyStudentList(List<Student> myStudentList) {
        this.myStudentList = myStudentList;
    }
}

this is student class

package com.example.studentrecyclerview;

public class Student {
    String name;
    int id;
    int pictureNumber;
    boolean flag;

    public Student(String name, int id, int pictureNumber, boolean flag) {
        this.name = name;
        this.id = id;
        this.pictureNumber = pictureNumber;
        this.flag = flag;
    }

    public boolean isFlag() {
        return flag;
    }


    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getPictureNumber() {
        return pictureNumber;
    }

    public void setPictureNumber(int pictureNumber) {
        this.pictureNumber = pictureNumber;
    }
}

my application class

package com.example.studentrecyclerview;

import android.app.Application;

public class MyApplication extends Application {


    private MyStudents myStudents = new MyStudents();

    public MyStudents getMyStudents() {
        return myStudents;
    }

    public void setMyStudents(MyStudents myStudents) {
        this.myStudents = myStudents;
    }
}


where can can i implement it correctly i cant accsess it from the editstudent class i wanna make the save button save the edited details of the student

Dan
  • 3,647
  • 5
  • 20
  • 26
  • My advice is to save your list of students using [sharedcontentPreferences](https://stackoverflow.com/a/7057858/16653700) and use it to replace passing data using intents. You can access the student list from anywhere in your code by loading from the `sharedContentPreferences`. At the start of every activity you can load the list of students from `sharedContentPreferences`. Apply the code in your save button `onclick`. – Alias Cartellano Nov 19 '21 at 18:41
  • Another possibility is to pass your list of students as a [static list](https://medium.com/@kenny_io/passing-data-between-activities-2d0ef122f19d) that will be accessible to all activities, however, should you exit the app the data will be lost. – Alias Cartellano Nov 19 '21 at 18:49
  • Declare `static List myStudentList;` and you can use a static getter to return the list to any activity. – Alias Cartellano Nov 19 '21 at 18:52
  • What progress have you made on this? – Alias Cartellano Nov 27 '21 at 20:50

1 Answers1

0

This is one of the few times I would recommend using a singleton. https://www.baeldung.com/java-singleton

Inside your singleton will sit your List of objects and you'll access it by:

ClassSingleton.getInstance.getMyStudents

But First, I want to mention something. I'm not sure what your 'MyStudents' class looks like. But ideally, your class should represent a single object. And then you make a Array/List of that object.

class Student

String name;
int id;
int photoId;
boolean checkBox;

Public Student(String name, int id, int photoId, boolean checkBox) {
    this.name = name;
    this.id = id;
    this.photoId = photoId;
    this.checkBox = checkBox
}

Setter and getters....

Now create an empty ArrayList of Students.

ArrayList<Student> allStudents = new ArrayList<>;

Now you can create students one at a time and add those students to your arraylist

Student jim = new Student("Jim", 1, 21, false)
Student mary = new Student("Mary", 1, 22, false)

allStudents.add(jim);
allStudents.add(mary);

Your singleton will have this arraylist in it and you will have methods that allow you to interact with it. Such as 'getStudentById', 'addNewStudent', 'deleteStudent', 'getAllStudent', etc...

public Student getStudentById(Student student) {
    for (Student s: allStudents) {
        if (s.getId == student.getId) {
        return s;
        }
    }
return null;
}

public void addNewStudent(Student newStudent) {
    for(Student s: allStudents) {
       if(s.getId == newStudent.getId) {
       return;
       }
    }
allStudents.add(newStudent);
return;
}

And to call thses methods from one of your activities would look something like this:

ClassSingleton.getInstance.addNewStudent(newStudent)

Now you can go to another activity call ClassSingleton.getInstance.getAllStudents() and your newStudent will be in the arraylist.

REPLY TO COMMENT

In your save/edit activities your button will need to create a new student object from the information in the fields and than add that student object to your arrayList of students. Because your RecyclerView adapter is using that arrayList, you then call notifyDataChange();

In your MyStudents class we need to be able to add students to the arrayList. Create a method call addNewStudent()

public void addNewStudent(Student newStudent) {
    for(Student s: allStudents) {//Check if student already is exists
       if(s.getId == newStudent.getId) {//if found
       allStudent.remove(s);//Remove old student data
       allStudent.add(newStudent);//add new student data
       return;
       }
    }
allStudents.add(newStudent); //if student isn't found add them
return;
}

Now that we are able to add a student to your arraylist, we can then use a button to call addNewStudent().

save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//Lets create a student object from the fields in the activity
//First we need to gather any field that needs to be an int and convert them from strings to integers. Because all text in EditText are strings.
String sId = et_id.getText().toString; //get string value of field
int iId = Integer.parseInt(sId) //Convert string to int

String sPicId = et_picturenumber.getText(); // and again
int iPicId = Integer.parseInt(sPicId)

Student newStudent = new Student( //based on your Student class constructor we can create a new student like so.
                         et_name.getText().toString(),
                         iId,
                         iPicId,
                         cb.isChecked()
                         );

//Now that we have a new student we can now add them to the arrayList
//This next line of code will be different depending on how you have instantiated your ArrayList. But it might be something like this.
myStudentList.add(newStudent)

            }
        });
JonR85
  • 700
  • 4
  • 12
  • hey edited the post so u can see the 2 other classes i made how can i fix the save button so it could access it and save the edited information – dezlight Nov 19 '21 at 12:46
  • what do i need to change in my code so the save button in the last activity will edit the specific person details and resave them in the list please help i am sitting hours on this – dezlight Nov 19 '21 at 14:32
  • It dosent change anything =\ sometimes it just take me back to third acitivty the display form and sometimes it crashes ``` MyStudents.addNewStudent(com.example.studentrecyclerview.Student)' on a null object reference at com.example.studentrecyclerview.EditStudents$1.onClick(EditStudents.java:70) ``` – dezlight Nov 19 '21 at 16:18
  • This is the point I was trying to make at the top of my answer. You need to create a singleton class to hold your myStudent Arraylist. If you don't know what a singleton is, I provided a link on how to create one. But you should fully understand what one is before continuing. Basically a Singleton class is a class that gets initialized once and that instance can then can be used anywhere in your app. So if your singleton class holds an ArrayList of Students. You can call, use, modify that same arraylist anywhere in your app with confidence that you won't be working with multiple instances. – JonR85 Nov 19 '21 at 17:53