My project includes an "accept/deny incoming data" window that on "accept" should add the incoming data dynamically to a listview and the database that the listview gets the data from. My listadapter is an inner class.
My code in the main class relating to the populating of the listview:
public class MainActivity extends Activity {
private List<Assignment> allDeliveries= new ArrayList<Assignment>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
populateDeliveryList();
populateListView();
registerClickCallBack();
final MySQLiteHelper db = new MySQLiteHelper(this);
accept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout newdeliverylayout= (RelativeLayout) findViewById(R.id.newdeliverylayout);
allDeliveries.add(incomingAssignment);
db.addAssignment(incomingAssignment);
MyListAdapter adapter = new MyListAdapter();
adapter.notifyDataSetChanged();
}
});
deny.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout newdeliverylayout= (RelativeLayout) findViewById(R.id.newdeliverylayout);
newdeliverylayout.setVisibility(RelativeLayout.GONE);
}
});
private void populateDeliveryList() {
MySQLiteHelper db = new MySQLiteHelper(this);
List<Assignment> list = db.getAllAssignments();
for (int i = 0; i < list.size();i++)
{
allDeliveries.add(list.get(i));
}
}
private void populateListView() {
ArrayAdapter<Assignment> adapter = new MyListAdapter();
ListView list = (ListView) findViewById(R.id.deliveriesListView);
list.setAdapter(adapter);
}
}
This is my inner class, the listadapter:
private class MyListAdapter extends ArrayAdapter<Assignment> {
public MyListAdapter() {
super(MainActivity.this, R.layout.item_view, allDeliveries);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null) {
itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false);
}
Assignment nyDelivery = allDeliveries.get(position);
TextView adressText = (TextView) itemView.findViewById(R.id.item_adressView);
adressText.setText(nyDelivery.getAdress());
TextView zipText = (TextView) itemView.findViewById(R.id.item_zipcodePlaceView);
zipText.setText(nyDelivery.getZipcode());
TextView companyText = (TextView) itemView.findViewById(R.id.item_companyView);
companyText.setText(nyDelivery.getSenderreceiver());
TextView typeText = (TextView) itemView.findViewById(R.id.item_driveTypeView);
typeText.setText(nyDelivery.getType() + nyDelivery.getID());
return itemView;
}
}
}
The code in "accept" seems to do nothing except adding the incoming assignment to the database.
It is a simple change of declaring MyListAdapter in your MainActivity and instantiate it once in the populateListView,
public class MainActivity extends Activity {
private List<Assignment> allDeliveries= new ArrayList<Assignment>();
MyListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
populateDeliveryList();
populateListView();
registerClickCallBack();
final MySQLiteHelper db = new MySQLiteHelper(this);
accept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout newdeliverylayout= (RelativeLayout) findViewById(R.id.newdeliverylayout);
allDeliveries.add(incomingAssignment);
db.addAssignment(incomingAssignment);
adapter.notifyDataSetChanged();
}
});
deny.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout newdeliverylayout= (RelativeLayout) findViewById(R.id.newdeliverylayout);
newdeliverylayout.setVisibility(RelativeLayout.GONE);
}
});
private void populateDeliveryList() {
MySQLiteHelper db = new MySQLiteHelper(this);
List<Assignment> list = db.getAllAssignments();
for (int i = 0; i < list.size();i++)
{
allDeliveries.add(list.get(i));
}
}
private void populateListView() {
adapter = new MyListAdapter();
ListView list = (ListView) findViewById(R.id.deliveriesListView);
list.setAdapter(adapter);
}
}
Related
I am making android app for college. App is about fitness(tracking kcal,workouts...). i have stuck on part where i want to notifyDatasetChange for my adapter. On my Activity i have 2 list views(first is showing exercises and second is showing selected exercises for todays workout). I made easily first ListView to update when user "create" new type of exercise for itself because Arraylist and called from current activity ,but for second ListView i made Dialog in its adapter class and i want on closing that dialog to update ListView. Here is my code and classes:
public class MyWorkoutActivity extends AppCompatActivity {
ListView lv;
ListView lvsess;
Button create;
#Override
public void onBackPressed(){
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_workout);
create=(Button) findViewById(R.id.btn_addexercise);
WorkoutDay workoutDay = SugarRecord.findById(WorkoutDay.class, (long) 1);
List<WorkoutDay> workoutDayArrayList = new ArrayList<>();
if(workoutDay.getWorkouts()!="") {
String[] workouts = workoutDay.getWorkouts().split(":");
String[] sets = workoutDay.getSets().split(":");
String[] reps = workoutDay.getReps().split(":");
String[] kgs = workoutDay.getKgs().split(":");
String[] duration = workoutDay.getDuration().split(":");
for (int i = 0; i < workouts.length; i++) {
workoutDayArrayList.add(new WorkoutDay(workouts[i],sets[i],reps[i],kgs[i],duration[i]));
}
}
final ArrayList<WorkoutDay> ddd = new ArrayList<>();
ddd.addAll(workoutDayArrayList);
List<Exercise> exerciseList = Exercise.listAll(Exercise.class);
final ArrayList<Exercise> exerciseArrayList= new ArrayList<>();
exerciseArrayList.addAll(exerciseList);
lv=(ListView) findViewById(R.id.lv_exercises);
lvsess=(ListView)findViewById(R.id.lv_currentsess);
final SessionAdapter sessionAdapter = new SessionAdapter(this,ddd);
final ExerciseAdapter exerciseAdapter= new ExerciseAdapter (this,exerciseArrayList);
lv.setAdapter(exerciseAdapter);
lvsess.setAdapter(sessionAdapter);
create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
List<String> cathegories = new ArrayList<String>();
cathegories.add("Chest");
cathegories.add("Biceps");
cathegories.add("Triceps");
cathegories.add("Legs");
cathegories.add("Core");
cathegories.add("Abdomens");
cathegories.add("Cardio");
cathegories.add("Free style");
final Dialog addyourown= new Dialog(MyWorkoutActivity.this);
addyourown.setTitle("Add your exercise");
addyourown.setContentView(R.layout.addyourownex);
Button btn = (Button)addyourown.findViewById(R.id.btn_dialog_add);
final EditText et = (EditText)addyourown.findViewById(R.id.et_dialog_insertname);
final Spinner spinner = (Spinner)addyourown.findViewById(R.id.sp_cath);
ArrayAdapter<String> adapter ;
adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,cathegories);
spinner.setAdapter(adapter);
addyourown.show();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(et.getText().toString().isEmpty()){
Toast.makeText(getApplicationContext(),"EMPTY INPUT",Toast.LENGTH_SHORT).show();
}else {
Exercise exercise = new Exercise(et.getText().toString(), spinner.getSelectedItem().toString());
exercise.save();
exerciseArrayList.add(exercise);
exerciseAdapter.notifyDataSetChanged();
addyourown.cancel();
}
}
});
}
});
}
and my adapter class with dialog
public class ExerciseAdapter extends ArrayAdapter<Exercise> {
public Dialog newDialog;
public ExerciseAdapter(#NonNull Context context, ArrayList<Exercise> exercises) {
super(context,0,exercises);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
final Exercise exercise = getItem(position);
if(convertView==null){
convertView= LayoutInflater.from(getContext()).inflate(R.layout.exercises_layout,parent,false);
}
TextView name = (TextView)convertView.findViewById(R.id.tv_exercise);
ImageButton ib= (ImageButton)convertView.findViewById(R.id.ib_plus);
name.setText(exercise.getName());
ib.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
newDialog = new Dialog(v.getRootView().getContext());
if(exercise.getCathegory().equals("Cardio")) {
newDialog.setContentView(R.layout.cardio_layout);
final EditText duration = (EditText)newDialog.findViewById(R.id.et_duration);
Button bt = (Button) newDialog.findViewById(R.id.btn_carconfirm);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(duration.getText().toString().equals("")){
Toast.makeText(getContext(),"EMPTY INPUT",Toast.LENGTH_SHORT).show();
}else {
WorkoutDay workoutDay = SugarRecord.findById(WorkoutDay.class,(long)1);
workoutDay.extendCardio(exercise.getName(),duration.getText().toString());
workoutDay.save();
newDialog.cancel();
}
}
});
} else {
newDialog.setContentView(R.layout.instervalue_exercises);
final EditText sets = (EditText)newDialog.findViewById(R.id.et_series);
final EditText reps = (EditText)newDialog.findViewById(R.id.et_reps) ;
final EditText kgs = (EditText)newDialog.findViewById(R.id.et_kg);
Button bt = (Button) newDialog.findViewById(R.id.btn_confirm);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sets.getText().toString().equals("") || reps.getText().toString().equals("") || kgs.getText().toString().equals("")){
Toast.makeText(getContext(),"EMPTY INPUT",Toast.LENGTH_SHORT).show();
}else {
WorkoutDay workoutDay = SugarRecord.findById(WorkoutDay.class,(long)1);
workoutDay.extendExercise(exercise.getName(),sets.getText().toString(),reps.getText().toString(),kgs.getText().toString());
workoutDay.save();
newDialog.cancel();
}
}
});
}
newDialog.show();
}
});
return convertView;}
i want to remove listview item in my list.. But When I click On Button nothing happened. please tell ME Where I m Doing Wrong...this code can add item but only remove item cant...
//listview java
public class MemberActivity extends AppCompatActivity implements BaseColumns {
ListView mylist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_member);
final ListView listview;
final ListViewAdapter adapter;
//final ArrayList<String> items = new ArrayList<String>();
mylist = (ListView) findViewById(R.id.listview1);
final LinearLayout linewarLayout1 = (LinearLayout) findViewById(R.id.addmember);
final LinearLayout linewarLayout2 = (LinearLayout) findViewById(R.id.buttongroup);
adapter = new ListViewAdapter();
listview = (ListView) findViewById(R.id.listview1);
final View header = getLayoutInflater().inflate(R.layout.listview_header, null, false);
listview.setAdapter(adapter);
Button addButton = (Button) findViewById(R.id.add);
addButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
mylist.setVisibility(View.INVISIBLE);
linewarLayout2.setVisibility(View.INVISIBLE);
linewarLayout1.setVisibility(View.VISIBLE);
}
});
final EditText name = ((EditText) findViewById(R.id.etName));
final EditText ID = ((EditText) findViewById(R.id.etID));
final EditText Major = ((EditText) findViewById(R.id.etMajor));
Button btnDone = (Button) findViewById(R.id.btnDone);
btnDone.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
//TextView cnttxt = (TextView)findViewById(R.id.count);
//cnttxt.setText(adapter.getCount());
adapter.addItem(name.getText().toString(), ID.getText().toString(), Major.getText().toString());
name.setText("");
ID.setText("");
Major.setText("");
Toast.makeText(getApplicationContext(), "add.", Toast.LENGTH_LONG).show();
mylist.setVisibility(View.VISIBLE);
linewarLayout2.setVisibility(View.VISIBLE);
linewarLayout1.setVisibility(View.INVISIBLE);
}
});
Button btnCancel = (Button) findViewById(R.id.btnCancel);
btnCancel.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
name.setText("");
ID.setText("");
Major.setText("");
mylist.setVisibility(View.VISIBLE);
linewarLayout2.setVisibility(View.VISIBLE);
linewarLayout1.setVisibility(View.INVISIBLE);
}
});
// delete button
Button deleteButton = (Button) findViewById(R.id.delete);
deleteButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
int count, checked;
count = adapter.getCount();
if (count > 0) {
listview.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
checked = listview.getCheckedItemPosition();
if (checked > -1 && checked < count) {
adapter.removeitem(checked);
listview.clearChoices();
adapter.notifyDataSetChanged();
}
}
}
});
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View v, int position, long id) {
// get item
ListViewItem item = (ListViewItem) parent.getItemAtPosition(position);
String nameStr = item.getname();
String IDStr = item.getID();
String majorStr = item.getmajor();
}
});
}
}//adapter
public class ListViewAdapter extends BaseAdapter {
private ArrayList<ListViewItem> listViewItemList = new ArrayList<ListViewItem>();
public ListViewAdapter() {
}
#Override
public int getCount() {
return listViewItemList.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
final Context context = parent.getContext();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.listview_item, parent, false);
}
TextView nameTextView = (TextView) convertView.findViewById(R.id.list_name);
TextView IDTextView = (TextView) convertView.findViewById(R.id.list_ID);
TextView majorTextView = (TextView) convertView.findViewById(R.id.list_major);
ListViewItem listViewItem = listViewItemList.get(position);
nameTextView.setText(listViewItem.getname());
IDTextView.setText(listViewItem.getID());
majorTextView.setText(listViewItem.getmajor());
return convertView;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public Object getItem(int position) {
return listViewItemList.get(position);
}
public void removeitem(int position) {
listViewItemList.remove(position);
notifyDataSetChanged();
}
public void addItem(String name, String ID, String major) {
ListViewItem item = new ListViewItem();
item.setname(name);
item.setID(ID);
item.setmajor(major);
listViewItemList.add(item);
notifyDataSetChanged();
}
}
//ListViewItem java
public class ListViewItem {
private String nameStr;
private String IDStr;
private String majorStr;
public void setname(String name) {
nameStr = name;
}
public void setID(String ID) {
IDStr = ID;
}
public void setmajor(String major) {
majorStr = major;
}
public String getname() {
return this.nameStr;
}
public String getID() {
return this.IDStr;
}
public String getmajor() {
return this.majorStr;
}
}
Update your code as below. Set choice mode to CHOICE_MODE_SINGLE when you crate listview and before set adapter. Remove CHOICE_MODE_SINGLE from button click.
listview = (ListView) findViewById(R.id.listview1);
listview.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
listview.setAdapter(adapter);
Also, You need to setItemChecked in onItemClick of listview.
Check below example code.
public class MainActivity extends Activity {
private ListView mListView;
private String[] mData = new String[] { "xxx", "yyy", "zzz", "aaa" };
private BaseAdapter mAdapter;
private int mLastCorrectPosition = -1;
private int mButtonPosition = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.list_view);
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_activated_1, mData);
mListView.setAdapter(mAdapter);
mListView.setSelector(new ColorDrawable(0));
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == mButtonPosition) {
if (mLastCorrectPosition != -1) {
mListView.setItemChecked(mLastCorrectPosition, true);
}
else {
mListView.setItemChecked(mButtonPosition, false);
}
// here show dialog
}
else {
mLastCorrectPosition = position;
// here refresh fragment
}
}
});
}
}
I am building an android app where it READ from data Parse.com
I am using a CustomAdapter to display data like this
public class Dining extends Activity {
public Button but12;
public void init12() {
but12 = (Button) findViewById(R.id.button12);
but12.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent toy3 = new Intent(Dining.this, Dining_select.class);
startActivity(toy3);
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dining);
init12();
}
}
class CustomAdapter extends ParseQueryAdapter<ParseObject> {
public CustomAdapter(Context context) {
super(context, new ParseQueryAdapter.QueryFactory<ParseObject>(){
public ParseQuery create() {
ParseQuery query = new ParseQuery("RestaurantDetail");
/* query.whereEqualTo("Name", true);*/
return query;
}
});
}
#Override
public View getItemView(ParseObject object, View v, ViewGroup parent) {
if (v == null) {
v = View.inflate(getContext(), R.layout.dining, null);
}
super.getItemView(object, v, parent);
ParseImageView todoImage = (ParseImageView) v.findViewById(R.id.icon);
ParseFile imageFile = object.getParseFile("Logo");
if (imageFile != null) {
todoImage.setParseFile(imageFile);
todoImage.loadInBackground();
}
TextView titleTextView = (TextView) v.findViewById(R.id.textView3);
titleTextView.setText(object.getString("Name"));
return v;
}
}
Then i am also using another class to call the table and display
public class Dining1 extends Dining {
private CustomAdapter urgentTodosAdapter;
private ParseQueryAdapter<ParseObject> mainAdapter;
private ListView dininglist;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.dining1);
mainAdapter = new ParseQueryAdapter<ParseObject>(this, "RestaurantDetail");
urgentTodosAdapter = new CustomAdapter(this);
dininglist = (ListView) findViewById(R.id.dininglistview1);
dininglist.setAdapter(urgentTodosAdapter);
urgentTodosAdapter.loadObjects();
}
}
problem is it does not display any information and i don't understand why.
please help
Daily Screen :-
public class DailyScreen extends AppCompatActivity implements AdapterView.OnItemClickListener {
ImageView add, edit;
MyCustomAdapter adapter1;
Button ok;
Button next2;
final Context context = this;
ListView listView;
private ArrayAdapter<String> adapter;
List<Milk> items=new ArrayList();
public List<Milk> getItems() {
return items;
}
public void setItems(List<Milk> items) {
this.items = items;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.daily_listview);
add = (ImageView) findViewById(R.id.add);
edit = (ImageView) findViewById(R.id.edit);
listView = (ListView) findViewById(R.id.list);
next2 = (Button) findViewById(R.id.next2);
Milk milkDefault=new Milk("Toned Milk",0);
items.add(milkDefault);
//this.setArrayList((ArrayList<String>) Arrays.asList(items));
adapter1 = new MyCustomAdapter(items, this);
listView.setAdapter(adapter1);
listView.setOnItemClickListener(this);
registerForContextMenu(listView);// to set context menu in list view
}
#Override
protected void onResume() {
super.onResume();
next2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(DailyScreen.this, SupplierActivity.class);
intent.putExtra("LIST_ITEMS",List,items);//
startActivity(intent);
}
});
add.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(DailyScreen.this);
dialog.setTitle("Enter new Milk");
dialog.setContentView(R.layout.dialog_box);
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
final EditText editText = (EditText) dialog.findViewById(R.id.pro);
String data = editText.getText().toString();
//button initialization
Button ok = (Button) dialog.findViewById(R.id.ok);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String data = editText.getText().toString();
if (!data.isEmpty()) {
items.add(new Milk(data,0));
adapter1.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "product name is :" + data, Toast.LENGTH_LONG).show();
dialog.cancel();
}
else{
Toast.makeText(DailyScreen.this, "Please enter the data", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
MyCustomAdapter class
public class MyCustomAdapter extends BaseAdapter implements ListAdapter {
private List<Milk> list = new ArrayList<Milk>();
private Context context;
public MyCustomAdapter(List<Milk> list, Context context) {
this.list = list;
this.context = context;
}
#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(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.custom_layout, null);
}
TextView name = (TextView) view.findViewById(R.id.text);
name.setText(list.get(position).getNsme());
final TextView milkCount = (TextView) view.findViewById(R.id.milkcount);
milkCount.setText(""+list.get(position).getAmount());
ImageView increment = (ImageView) view.findViewById(R.id.add);
ImageView decrement = (ImageView) view.findViewById(R.id.sub_item);
increment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int a = Integer.parseInt(milkCount.getText().toString().trim());
a = a + 1;
milkCount.setText("" + a);
list.get(position).setAmount(a);
}
});
decrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int a = Integer.parseInt(milkCount.getText().toString().trim());
if (a == 0) {
a = 0;
} else {
a = a - 1;
}
milkCount.setText("" + a);
list.get(position).setAmount(a);
}
});
return view;
}
Milk class
public class Milk {
private String nsme ;
private int amount ;
public Milk(String nsme, int amount) {
this.nsme = nsme;
this.amount = amount;
}
public String getNsme() {
return nsme;
}
public void setNsme(String nsme) {
this.nsme = nsme;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
i have tried all thing to send all the data of list view to another activty please suggest me how can i do it ??
Make the list static and u can then access it in any activity. Make sure u initialise the list
milk class extends serializable firstly
then u do
make object of milk class in mainactivity class
Milk milk=new Milk(this);
Intent i=new Intent(getApplicationContext(),Update.class);
i.putExtra("emnumber",(Serializable)milk);
startActivity(i);
then u can pick the value in update class
if(getIntent().getSerializableExtra("emnumber")!=null) {
con = (ArrayList<Contact>) getIntent().getSerializableExtra("emnumber");
email_mobile = contactList.get(0).nsme;
pass__word = contactList.get(0).amount;
you can implement as:
public class Milk implements Parcelable{
......
}
Send arraylist as:
intent.putExtra("files", "your arraylist");
obtain arraylist as:
Intent inIntent = getIntent();
list=inIntent.getParcelableArrayListExtra("files");
Try this. May be it help.
Send arraylist to activity through extras.
intent.putStringArrayListExtra("ARRAY_LIST", arrayList);
Retrieve arraylist in activity.
arrayList= i.getStringArrayListExtra("ARRAY_LIST");
If u have to send arraylist other than string then.
intent.putParcelableArrayListExtra("ARRAY_LIST", (ArrayList<Milk>) milkArrayList);
Milk class must be parcellable
I'm new to making ListViews with CustomAdapters (this is my first attempt) and I'm not sure how well/efficient I made it. So what I'm trying to do is get the name that is highlighted red in the ListView. I do this with the getSelectedName method. However, in the BuildInput class, when I intent to the MainActivity and intent back to the BuildInput class, the ListView is completely gone. Since the ListView is gone, so is the highlighted red name and the getSelectedName method doesn't work.
How do I keep the ListView from depopulating when I intent to the MainActivity?
public class Names {
public String name;
public Names(){
super();
}
public Names(String name){
super();
this.name = name;
-
public class CustomAdapter extends ArrayAdapter<Names>{
private ArrayList<Names> items;
private TextView tvHolder;
private String selectedName = "";
public CustomAdapter (Context context, ArrayList<Names> items){
super(context, 0, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Names names = getItem(position);
if(convertView == null)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_namechoices, parent, false);
}
Names nm = items.get(position);
if (nm != null){
final TextView tv = (TextView)convertView.findViewById(R.id.nameItem);
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (tvHolder != null) {
tvHolder.setBackgroundColor(Color.WHITE);
v.setBackgroundColor(Color.RED);
tvHolder = tv;
selectedName = tv.getText().toString();
} else {
v.setBackgroundColor(Color.RED);
tvHolder = tv;
selectedName = tv.getText().toString();
}
}
});
}
TextView tv = (TextView)convertView.findViewById(R.id.nameItem);
tv.setText(names.name);
return convertView;
}
public String getSelectedName(){
return selectedName;
}
}
-
public class BoardInput extends Activity {
private EditText mUserInput;
private Button mConfirm;
private Button mReady;
private ArrayList<Names> arrayOfNames = new ArrayList<Names>();
private CustomAdapter adapter;
private ListView listview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_boardinput);
adapter = new CustomAdapter(BoardInput.this, arrayOfNames);
listview = (ListView) findViewById(R.id.listview);
listview.setAdapter(adapter);
mUserInput = (EditText) findViewById(R.id.nameInput);
mConfirm = (Button) findViewById(R.id.confirm);
mConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mUserInput.getText().toString().equals("")) {
Toast.makeText(getApplicationContext(), "Please enter a name.", Toast.LENGTH_SHORT);
} else {
arrayOfNames.add(new Names(mUserInput.getText().toString()));
mUserInput.setText("");
adapter = new CustomAdapter(BoardInput.this, arrayOfNames);
listview = (ListView) findViewById(R.id.listview);
listview.setAdapter(adapter);
}
}
});
mReady = (Button) findViewById(R.id.ready);
mReady.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if (adapter.getSelectedName().isEmpty()){
Log.d("NULL","NULL");
}
else{
Log.d("BoardInput", adapter.getSelectedName());
Intent i = new Intent(BoardInput.this, MainActivity.class);
startActivity(i);
}
}
});
}
This is what the BoardInput class creates:
You type a name in the edittext and clicking confirm will add the name to the listview and clear the edittext. When you click on a name in the listview, it will highlight red and that's the name I need to use in my MainActivity class.
I have made some Changes in your code:
public class BoardInput extends Activity {
private EditText mUserInput;
private Button mConfirm;
private Button mReady;
private List<String> names = new ArrayList<>();
private ArrayList<Names> arrayOfNames = new ArrayList<Names>();
private CustomAdapter adapter;
private ListView listview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_boardinput);
adapter = new CustomAdapter(BoardInput.this, arrayOfNames);
listview = (ListView) findViewById(R.id.listview);
listview.setAdapter(adapter);
mUserInput = (EditText) findViewById(R.id.nameInput);
mConfirm = (Button) findViewById(R.id.confirm);
mConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mUserInput.getText().toString().equals("")) {
Toast.makeText(getApplicationContext(), "Please enter a name.", Toast.LENGTH_SHORT);
} else {
arrayOfNames.add(new Names(mUserInput.getText().toString()));
mUserInput.setText("");
**Edited**:
adapter.notifyDataSetChanged();
listview.invalidateView();
}
}
});
mReady = (Button) findViewById(R.id.ready);
mReady.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if (adapter.getSelectedName().isEmpty()){
Log.d("NULL","NULL");
}
else{
Log.d("BoardInput", adapter.getSelectedName());
Intent i = new Intent(BoardInput.this, MainActivity.class);
startActivity(i);
}
}
});
}
When you intent to the MainActivity and not finish the BoardInputActivity the ListView will still exist when the MainActivity is closed. But when you intent to the BoardInputActivity everything will be reconstructed including the adapter.