'ListView shows only 1 item
I'm creating an app where you can choose a workout exercise and add it to a specific day of the week. You can then view any day of the week and see all the exercises that you have added. However, I am having an issue where when I add an exercise to a given day, it replaces the exercise that was previously there instead of adding it to the list. I am using an ArrayList to store the Strings, and an ArrayAdapter to display the String in the ListView. I've looked around for other questions that have had this problem but none of the solutions fixed it for me.
This is the code I am using to add an exercise to a specific day of the week:
package com.example.workoutplanner;
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MondayWorkout extends AppCompatActivity {
ListView listView;
ArrayList<String> listElements = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_week_workout);
listView = findViewById(R.id.listValue);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MondayWorkout.this);
String message = prefs.getString("monday", "");
listElements.add(message);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listElements);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
initToolbar();
}
private void initToolbar() {
getSupportActionBar().setTitle("Monday Workouts");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case android.R.id.home: {
onBackPressed();
}
}
return super.onOptionsItemSelected(item);
}
}
This is my XML file for the ListView:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SundayWorkout">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:background="@color/design_default_color_on_primary"
android:id="@+id/ToolbarSundayWorkout">
</androidx.appcompat.widget.Toolbar>
<ListView
android:id="@+id/listValue"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:text="value"
android:textSize="30sp" />
</RelativeLayout>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
