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

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent" ><ListViewandroid:layout_width="match_parent"android:layout_height="match_parent"android:id="@+id/listViewRecord"/><Buttonandroid: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.

publicclassRecordActivityextendsAppCompatActivity {

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

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

        mButton.setOnClickListener(newView.OnClickListener() {
            @OverridepublicvoidonClick(View v) {
                mAdapter.add(getRecord());
            }
        });
    }

    private Record getRecord() {
        DatecurrentDate=newDate();
        // TODO: Get your max values from somewhereintmaxSquat=1;  // TODO: From input fieldintmaxBench=1; // TODO: From input fieldintmaxDead=1; // TODO: From input fieldreturnnewRecord(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"