Skip to content Skip to sidebar Skip to footer

Arraylist Populating Listview In Separate Class Not Working

I'm trying to add an item to arraylist/adapter on a Button click in my class MyMaxes.java: Date currentDate = new Date(); ArrayAdapter records = new ArrayAdapter<

Solution 1:

Why can't you have one view with a Button and a ListView that you add to?

Your first problem - you can't reference the local variable records from anywhere outside the click listener. This is a compilation error.

Second problem - you would be creating a brand new, empty adapter each time you clicked the button, then only adding one Record to it.


activitymain.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listViewRecord"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btnTest"/>

</LinearLayout>

Let's call this RecordActivity because it displays and adds records to a ListView.

I would suggest using an AlertDialog to show a popup View when you click the button to get a Record object.

public class RecordActivity extends AppCompatActivity {

    Button mButton;
    ArrayAdapter<Record> mAdapter;
    ListView listViewRec;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButton= (Button) findViewById(R.id.btnTest);
        mAdapter = new ArrayAdapter<Record>(getApplicationContext(), R.layout.custom_record);
        listViewRec = (ListView) findViewById(R.id.listViewRecord);
        listViewRec.setAdapter(mAdapter);

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAdapter.add(getRecord());
            }
        });
    }

    private Record getRecord() {
        Date currentDate = new Date();
        // TODO: Get your max values from somewhere
        int maxSquat = 1;  // TODO: From input field
        int maxBench = 1; // TODO: From input field
        int maxDead = 1; // TODO: From input field

        return new Record(currentDate ,maxSquat, maxBench, maxDead);
    }
}

Remove maxTotal from the parameters. You can calculate that inside the constructor of a Record.

public Record(Date date,int squat, int bench, int dead) {
    this.bench = bench;
    this.dateTime = date;
    this.dead = dead;
    this.squat = squat;
    this.total = bench + dead + squat;
}

Post a Comment for "Arraylist Populating Listview In Separate Class Not Working"