6
public class MyWorkout extends AppCompatActivity {
    Button addExercise
    // Record how many clicks
    int clickCounter=0;
    private ListView mListView;
    ArrayList<String> listItems = new ArrayList<String>()
    ArrayAdapter<String> adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SetContentView(R.layout.activity_my_workout);
        Toolbar MyWorkouttoolbar = (Toolbar) findViewById(R.id.MyWorkouttoolbar);
        setSupportActionBar(MyWorkouttoolbar);
        listItems.add("Power Clean");
        listItems.add("Dead Lift");
        listItems.add("Hang Clean");
        listItems.add("Military Press");
        listItems.add("Leg Press");
        listItems.add("Squat");
        listItems.add("Bench MAX");
        listItems.add("Squat MAX");
        listItems.add("Stair Stepper");
        listItems.add("Treadmill");
        listItems.add("Bike");
        listItems.add("Elliptical");
        listItems.add("Bicep Curls");
        listItems.add("Dumb Bell Squats");
        listItems.add("Goblet Squats");
        listItems.add("Bar Bell Curls");
        listItems.add("Bar Bell Bench Press");
        listItems.add("Dumb Bell Bench Press");
        listItems.add("Incline Bar Bell Bench Press");
        listItems.add("Incline Dumb Bell Bench Press");
        listItems.add("Decline Dumb Bell Bench Press");
        listItems.add("Decline Bar Bell Bench Press");
        listItems.add("Dumb Bell Lunges");
        listItems.add("Bar Bell Lunges");
        listItems.add("Dumb Bell Flys");
        listItems.add("Tricep Push Downs");

        if (mListView == null) {
            mListView = (ListView) findViewById(R.id.MyWorkoutlistView);
        }
        adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,listItems);
        setListAdapter(adapter);
        addExercise = (Button) findViewById(R.id.addExercise);
        addExercise.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Collections.shuffle(listItems);
                adapter.getItem(4);
                adapter.notifyDataSetChanged();
            }
        });
     }

     private void updateListView(){
         ListView listView = (ListView)findViewById(R.id.MyWorkoutlistView);
     }

     // method which will handle dynamic insertion
     public void addItems(View v) {
        listItems.add("Clicked : "+clickCounter++);
        adapter.notifyDataSetChanged();
     }

     protected ListView getListView(){
         if (mListView==null){
             mListView = (ListView) findViewById(R.id.MyWorkoutlistView);
         }
         return mListView;
     }

     protected void setListAdapter(ListAdapter adapter){
         getListView().setAdapter(adapter);
     }

     protected ListAdapter getListAdapter(){
         ListAdapter adapter = getListView().getAdapter();
         if (adapter instanceof HeaderViewListAdapter){
            return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
        } else {
            return adapter;
        }
    }

I have a list view populated with exercises. I would like to randomly select an element in an array and add that random element to another list view.

Also is it possible to change the original exercise list view to display only the random element?

I am new to android studio, so if I am unclear let me know and I will explain better. Thank you

Gil Vegliach
  • 3,542
  • 2
  • 25
  • 37
Lukeriggz
  • 167
  • 4
  • 17

3 Answers3

1

Add/Remove items to custom ListView programmatically.This example show how to add/remove items to/from custom ListView, using Java code at run-time. Refer to this Link : http://android-er.blogspot.in/2015/01/add-remove-items-to-custom-listview.html

EDIT 1 : MainActivity.java

package com.example.androidimageviewlist;

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

import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

  public class Item {
  Drawable ItemDrawable;
  String ItemString;
  Item(Drawable drawable, String t){
  ItemDrawable = drawable;
   ItemString = t;
    }
 }

 static class ViewHolder {
  ImageView icon;
  TextView text; 
  }

  public class ItemsListAdapter extends BaseAdapter {

  private Context context;
  private List<Item> list;

  ItemsListAdapter(Context c, List<Item> l){
   context = c;
   list = l;
  }

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

   @Override
   public Object getItem(int position) {
   return list.get(position);
  }

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

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

   // reuse views
  if (rowView == null) {
   LayoutInflater inflater = ((Activity) context).getLayoutInflater();
   rowView = inflater.inflate(R.layout.row, null);

   ViewHolder viewHolder = new ViewHolder();
   viewHolder.icon = (ImageView) rowView.findViewById(R.id.rowImageView);
   viewHolder.text = (TextView) rowView.findViewById(R.id.rowTextView);
   rowView.setTag(viewHolder); 
  }

  ViewHolder holder = (ViewHolder) rowView.getTag();
  holder.icon.setImageDrawable(list.get(position).ItemDrawable);
  holder.text.setText(list.get(position).ItemString);

  return rowView;
  }

  public List<Item> getList(){
   return list;
  }
 }

 List<Item> items1, items2;
 ListView listView1, listView2;
 ItemsListAdapter myItemsListAdapter1, myItemsListAdapter2;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  listView1 = (ListView)findViewById(R.id.listview1);
  listView2 = (ListView)findViewById(R.id.listview2);

  initItems();
  myItemsListAdapter1 = new ItemsListAdapter(this, items1);
  myItemsListAdapter2 = new ItemsListAdapter(this, items2);
  listView1.setAdapter(myItemsListAdapter1);
  listView2.setAdapter(myItemsListAdapter2);

  listView1.setOnItemClickListener(listOnItemClickListener);
  listView2.setOnItemClickListener(listOnItemClickListener);

    listView1.setOnItemLongClickListener(new OnItemLongClickListener(){

   @Override
   public boolean onItemLongClick(AdapterView<?> parent, View view,
     int position, long id) {
   Item selectedItem = (Item)(parent.getItemAtPosition(position));

    ItemsListAdapter associatedAdapter = (ItemsListAdapter)        (parent.getAdapter());
    List<Item> associatedList = associatedAdapter.getList();
    Item associatedItem = associatedList.get(position);
    if(removeItemToList(associatedList, associatedItem)){

     view.invalidate();
     associatedAdapter.notifyDataSetChanged();

     ItemsListAdapter list2Adapter = (ItemsListAdapter)      (listView2.getAdapter());
     List<Item> list2List = list2Adapter.getList();

      addItemToList(list2List, selectedItem);
     list2Adapter.notifyDataSetChanged();
     }

     return true;
     }});

   }

  OnItemClickListener listOnItemClickListener = new OnItemClickListener(){

  @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
    long id) {
   Toast.makeText(MainActivity.this, 
     ((Item)(parent.getItemAtPosition(position))).ItemString, 
     Toast.LENGTH_SHORT).show();
    }

 };

 private void initItems(){
  items1 = new ArrayList<Item>();
  items2 = new ArrayList<Item>();

  TypedArray arrayDrawable =     getResources().obtainTypedArray(R.array.resicon);
   TypedArray arrayText = getResources().obtainTypedArray(R.array.restext);

 for(int i=0; i<arrayDrawable.length(); i++){
  Drawable d = arrayDrawable.getDrawable(i);
   String s = arrayText.getString(i);
   Item item = new Item(d, s);
   items1.add(item);
 }

  arrayDrawable.recycle();
  arrayText.recycle();
 }

 private boolean removeItemToList(List<Item> l, Item it){
  boolean result = l.remove(it);
  return result;
  }

 private boolean addItemToList(List<Item> l, Item it){
  boolean result = l.add(it);
  return result;
 }

}    

Modify activity_main.xml to have two ListView.

<LinearLayout 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"
    android:orientation="vertical"
    android:padding="4dp"
    tools:context="com.example.androidimageviewlist.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:background="@android:color/background_dark" >

        <LinearLayout
            android:id="@+id/pane1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:layout_margin="4dp"
            android:background="@android:color/background_light"
            android:orientation="vertical" >

            <ListView
                android:id="@+id/listview1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/pane2"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:layout_margin="4dp"
            android:background="@android:color/background_light"
            android:orientation="vertical" >

            <ListView
                android:id="@+id/listview2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>
  • It will be better if answer will contains some code, not just a link, because when referred page will be deleted you still will have self-contained answer – CAMOBAP Dec 06 '15 at 16:47
1

I have a list view populated with exercises. I would like to randomly select an element in an array and add that random element to another list view.

You can:

  1. get a random position in the array with Random.nextInt()
  2. retrieve the element at that position, i.e. arr[selectedPosition]
  3. put the element in the second ListView's adapter, for instance with ArrayAdapter.add().

If you don't use ArrayAdapter, you need to implement your interface for adding elements, or you can create and set a brand new adapter with ListView.setAdapter().

Also is it possible to change the original exercise list view to display only the random element?

Sure but there is some work to do. If you use ArrayAdapter, you can just clear() the adapter, then add() only the element you want to display. To not lose date, you can keep all the exercises in an array/list external to the adapters.

If you don't use ArrayAdapter, and want to implement your custom logic, remember to call notifyDataSetChanged() on the adapter after modifications, so that ListView knows to refresh itself.

Gil Vegliach
  • 3,542
  • 2
  • 25
  • 37
  • ok that makes a little more sense, can you post code example so i can see. if you need my code i can post too – Lukeriggz Dec 06 '15 at 17:15
  • yeah, start posting your code, so I can tell if there are problems with it. Also it is good practice on stack overflow – Gil Vegliach Dec 06 '15 at 17:42
  • ok thanks, i posted code hope this makes my problem more clear – Lukeriggz Dec 06 '15 at 19:21
  • I edited a bit the code, so it is more readable. As I said, you can do something on these lines: `Random r = new Random(); int i = r.nextInt(listItems.size()); String item = listItems.get(i); ArrayAdapter secondAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1); secondAdapter.add(item); secondListView.setAdapter(secondAdapter);` where `secondListView` is your other list view – Gil Vegliach Dec 06 '15 at 19:34
  • i am getting an error where ArrayAdapter secondAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1); i think another parameter needs to be declared after simple list item 1, but when i type in listitems it is saying there is an expression expected – Lukeriggz Dec 06 '15 at 20:23
  • The two-argument constructor should work. If you want to use the 4-arg constructor you can write: `new ArrayAdapter(this,android.R.layout.simple_list_item_1, android.R.id.text1, new ArrayList());` . You need a new list as the last argument. Also the first argument, `this`, must be a `Context`, so check that. (I assumed you wrote that code in an activity) – Gil Vegliach Dec 06 '15 at 22:05
1

Check my answer here I explain how to add dynamically elements into a listview.

just in case...

private EditText editTxt;
private Button btn;
private ListView list;
private ArrayAdapter<String> adapter;
private ArrayList<String> arrayList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    editTxt = (EditText) findViewById(R.id.editText);
    btn = (Button) findViewById(R.id.button);
    list = (ListView) findViewById(R.id.listView);
    arrayList = new ArrayList<String>();

    // Adapter: You need three parameters 'the context, id of the layout (it will be where the data is shown),
    // and the array that contains the data
    adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, arrayList);

    // Here, you set the data in your ListView
    list.setAdapter(adapter);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // this line adds the data of your EditText and puts in your array
            arrayList.add(editTxt.getText().toString());
            // next thing you have to do is check if your adapter has changed
            adapter.notifyDataSetChanged();
        }
    });
}
Community
  • 1
  • 1
Robert
  • 1,192
  • 1
  • 10
  • 20