I have a strange glitch with my program. I'm trying to follow a tutorial in regards to generating and displaying listView items using firebase.
The problem with my program is that on start up I cannot see any of my list items however when I start to create a new item the list populates itself with all my previous entries and my newly created one.
From my research on similar problems there has been talk of using notifydatasetchanged to update my listview however some people have said that when calling an ArrayAdapter there is no need to do this as data is constantly being updated.
**CustomAdapter Class**
/**
* Created by MarkB on 14/03/2017.
*/
public class CustomAdapter extends BaseAdapter {
Context c;
ArrayList<User> users;
public CustomAdapter (Context c, ArrayList<User> users) {
this.c = c;
this.users = users;
}
#Override
public int getCount() {
return users.size();
}
#Override
public Object getItem(int position) {
return users.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
if (convertView==null)
{
convertView = LayoutInflater.from(c).inflate(R.layout.model,viewGroup,false);
}
//Find TextView items on the model.xml
TextView nameTxt = (TextView) convertView.findViewById(R.id.nameTxt);
TextView surnameTxt = (TextView) convertView.findViewById(R.id.surnameTxt);
TextView ageTxt = (TextView) convertView.findViewById(R.id.ageTxt);
TextView weightTxt = (TextView) convertView.findViewById(R.id.weightTxt);
TextView genderTxt = (TextView) convertView.findViewById(R.id.genderTxt);
final User u = (User) this.getItem(position);
nameTxt.setText(u.getName());
surnameTxt.setText(u.getSurname());
ageTxt.setText(u.getAge());
weightTxt.setText(u.getWeight());
genderTxt.setText(u.getGender());
//ONITEMCLICK
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(c,"Hi " + u.getName(), Toast.LENGTH_SHORT).show();
Intent startMenuActivity = new Intent(c, Menu_Activity.class);
c.startActivity(startMenuActivity);
}
});
return convertView;
}
}
**Home_Screen_Activity Class*
public class Home_Screen_Activity extends AppCompatActivity {
DatabaseReference db;
FirebaseHelper helper;
CustomAdapter adapter;
ListView lv;
EditText nameTxt, surnameTxt, ageTxt, weightTxt;
Spinner genderSpinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
lv = (ListView) findViewById(R.id.listView);
//INITIALISE FIREBASE DB
db = FirebaseDatabase.getInstance().getReference();
helper = new FirebaseHelper(db);
//ADAPTER
adapter = new CustomAdapter(this, helper.retrieve());
lv.setAdapter(adapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
displayInputDialog();
}
});
}
//DISPLAY INPUT DIALOG
private void displayInputDialog() {
final Dialog d = new Dialog(this);
d.setTitle("Save To Firebase");
d.setContentView(R.layout.input_dialog);
nameTxt = (EditText) d.findViewById(R.id.nameEditText);
surnameTxt = (EditText) d.findViewById(R.id.surnameEditText);
ageTxt = (EditText) d.findViewById(R.id.ageEditText);
weightTxt = (EditText) d.findViewById(R.id.weightEditText);
genderSpinner = (Spinner) d.findViewById(R.id.genderSpinner);
Button saveBtn = (Button) d.findViewById(R.id.saveBtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//GET DATA
String name = nameTxt.getText().toString();
String surname = surnameTxt.getText().toString();
String age = ageTxt.getText().toString();
String weight = weightTxt.getText().toString();
String gender = genderSpinner.getSelectedItem().toString();
//SET DATA
User u = new User();
u.setName(name);
u.setSurname(surname);
u.setAge(age);
u.setWeight(weight);
u.setGender(gender);
//SIMPLE VALIDATION
if (name != null && name.length() > 0) {
//THEN SAVE
if (helper.save(u)) {
//IF SAVED CLEAR EDITTXT
nameTxt.setText("");
surnameTxt.setText("");
ageTxt.setText("");
weightTxt.setText("");
genderSpinner.setSelection(0);
adapter = new CustomAdapter(Home_Screen_Activity.this, helper.retrieve());
lv.setAdapter(adapter);
d.dismiss();
}
}
else
{
Toast.makeText(Home_Screen_Activity.this, "Name Must Not Be Empty", Toast.LENGTH_SHORT).show();
}
}
});
d.show();
}
}
Any help is appreciated. I honestly don't understand where this glitch is coming from. There is no mention of this glitch in my logcat either
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 have created three TextView in my custom ListView, and I want to add value in Arraylist so I made code and i can add item like where line 21. but I want add using Edittext and button. so I made function 'additem' in ListViewAdapter.
if click 'btndone' button in memberActivity, 'additem' will run. But nothing happens and nothing change.....please teach how to fix..
*memberActivity.java
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);
// Create Adapter
adapter = new ListViewAdapter();
// Refer to list view and adapter
listview = (ListView) findViewById(R.id.listview1);
listview.setAdapter(adapter);
// add 1st item.
adapter.addItem("오정엽",
"201102087", "컴퓨터공학");
// add 2nd item.
adapter.addItem("임경원",
"201203074", "소프트웨어공학");
// add 3rd item.
adapter.addItem("심준식",
"201405938", "소프트웨어공학");
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("");
mylist.setVisibility(View.VISIBLE);
linewarLayout2.setVisibility(View.VISIBLE);
linewarLayout1.setVisibility(View.INVISIBLE);
}
});
*ListViewItem.java
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 ;
}
*ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
private ArrayList<ListViewItem> listViewItemList = new ArrayList<ListViewItem>() ;
public ListViewAdapter() {
}
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;
}
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);
}
}
call 'notifyDatasetChanged()' after adding data. It will Work.
setContentView(R.layout.activity_violation);
db = new DatabaseHelper(this);
sqLiteDatabase = db.getReadableDatabase();
spinner = (Spinner) findViewById(R.id.spinner1);
loadspinnerdata();
txtTexts = (TextView) findViewById(R.id.texts);
btnBack = (Button) findViewById(R.id.btnBack);
btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listviewData();
}
});
strSelectedItem = spinner.getSelectedItem().toString();
listview = (ListView) findViewById(R.id.listView);
LayoutInflater inflater = getLayoutInflater();
ViewGroup header = (ViewGroup) inflater.inflate(R.layout.list_header, listview, false);
listview.addHeaderView(header, null, false);
listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list_query = "select _id,section,offence,fine from tblSection";
Cursor clistview = sqLiteDatabase.rawQuery(list_query, null);
listadapter = new ListAdapter(this, clistview, 0);
listview.setAdapter(listadapter);private void listviewData() {
int cntChoice = listview.getCount();
String checked = "";
String unchecked = "";
SparseBooleanArray sparseBooleanArray = listview.getCheckedItemPositions();
for(int i = 0; i < cntChoice; i++)
{
if(sparseBooleanArray.get(i))
{
checked += listview.getItemAtPosition(i).toString() + "\n";
}
else if(!sparseBooleanArray.get(i))
{
unchecked+= listview.getItemAtPosition(i).toString() + "\n";
}
}
I am using cursorAdapter in order to populate listview from database?so I am not getting position as i get from getView method in arrayAdapter
public class ListAdapter extends CursorAdapter{
TextView tvSection,tvOffence,tvId,tvFine;
CheckBox chkBox;
ArrayAdapter<String> objects;
private boolean chkItem;
CompoundButton.OnCheckedChangeListener myCheckChangList;
public ListAdapter(Context context, Cursor c, int _id) {
super(context, c,_id);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
return LayoutInflater.from(context).inflate(R.layout.listview_item,viewGroup,false);
}
public class ViewHolder{
TextView tvSection,tvOffence,tvId,tvFine;
CheckBox chkBox;
boolean chkItem;
boolean selected = false;
public ViewHolder(boolean chkItem){
super();
this.chkItem=chkItem;
}
public ViewHolder() {
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder=null;
holder = new ViewHolder();
holder.tvSection = (TextView) view.findViewById(R.id.txtSection);
holder.tvOffence = (TextView) view.findViewById(R.id.txtOffence);
holder.tvId = (TextView) view.findViewById(R.id.txtId);
holder.tvFine = (TextView) view.findViewById(R.id.txtFine);
holder.chkBox = (CheckBox) view.findViewById(R.id.checkBox);
holder.chkBox.setOnCheckedChangeListener(myCheckChangList);
view.setTag(holder);
strFine=cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
String strSection = cursor.getString(cursor.getColumnIndexOrThrow("section"));
String strOffence = cursor.getString(cursor.getColumnIndexOrThrow("offence"));
int strFine = cursor.getInt(cursor.getColumnIndexOrThrow("fine"));
holder.tvSection.setText(strSection);
holder.tvOffence.setText(strOffence);
holder.tvFine.setText(String.valueOf(strFine));
final ViewHolder finalHolder = holder;
}
I tried this but this isn't working.I tried checkbox.setOnclicklistener which gives me the checked row value single item but not multiple checked item.I tried sparseboolean array also.
If you are trying to get selected values from listing using checkbox,try this way it will work
public class CardViewActivity extends AppCompatActivity {
private Toolbar toolbar;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<Student> studentList;
private Button btnSelection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
btnSelection = (Button) findViewById(R.id.btnShow);
studentList = new ArrayList<Student>();
for (int i = 1; i <= 15; i++) {
Student st = new Student("Student " + i, "androidstudent" + i
+ "#gmail.com", false);
studentList.add(st);
}
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Android Students");
}
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
// create an Object for Adapter
mAdapter = new CardViewDataAdapter(studentList);
// set the adapter object to the Recyclerview
mRecyclerView.setAdapter(mAdapter);
btnSelection.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String data = "";
List<Student> stList = ((CardViewDataAdapter) mAdapter)
.getStudentist();
for (int i = 0; i < stList.size(); i++) {
Student singleStudent = stList.get(i);
if (singleStudent.isSelected() == true) {
data = data + "\n" + singleStudent.getName().toString();
/*
* Toast.makeText( CardViewActivity.this, " " +
* singleStudent.getName() + " " +
* singleStudent.getEmailId() + " " +
* singleStudent.isSelected(),
* Toast.LENGTH_SHORT).show();
*/
}
}
Toast.makeText(CardViewActivity.this,
"Selected Students: \n" + data, Toast.LENGTH_LONG)
.show();
}
});
}
}
http://android-pratap.blogspot.in/2015/01/recyclerview-with-checkbox-example.html
On clicking outside the adapter, use the following code. "ListAdapter" should be the Adapter class name.
ListAdapter.unCheck((ViewGroup)view.getParent());
If your on clicking is inside the adapter, then ignore the above code and use the below one.
unCheck((ViewGroup)view.getParent());
make the following function in Adapter.
public static void unCheck(ViewGroup vg) {
for (int i = 0; i < vg.getChildCount(); i++) {
View v = vg.getChildAt(i);
if (v instanceof CheckBox) {
((CheckBox) v).setChecked(true);
} else if (v instanceof ViewGroup) {
unCheck((ViewGroup) v);
}
}
}
The above function will checked all the checkBox of the list view. Have Fun. Take Care.
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.
I have this issue:
I created a Listview with a custom ArrayAdapter composed by 3 EditText, on the activity where the Listview is inserted there is a button for add new line into the Listview cloned by the last one.
The behavior of the list is that when I click the ADD button all the
changes made to the lines of the listview are lost.
I figure out the I need to insert some code for save the changes into the ArrayAdapter's objects, but I can't fine a good solution for do it.
Can you pleas give me some advices?
Thank you.
ArrayAdapter
public class ExerciseAdapter extends ArrayAdapter<Exercise_p_obj> {
private int resource;
private LayoutInflater inflater;
private ArrayList<Exercise_p_obj> listExercises = new ArrayList<Exercise_p_obj>();
public ExerciseAdapter(Context context, int resourceId, ArrayList<Exercise_p_obj> objects) {
super(context, resourceId, objects);
resource = resourceId;
inflater = LayoutInflater.from(context);
listExercises = objects;
}
#Override
public View getView(final int position, View v, ViewGroup parent) {
// Recuperiamo l'oggetti che dobbiamo inserire a questa posizione
final Exercise_p_obj exercise_p = getItem(position);
final ViewHolder holder;
if (v == null) {
v = inflater.inflate(resource, parent, false);
holder = new ViewHolder();
holder.et_reps = (EditText) v.findViewById(R.id.et_reps);
holder.et_kg = (EditText) v.findViewById(R.id.et_kg);
holder.et_rest = (EditText) v.findViewById(R.id.et_rest);
holder.bt_del = (Button) v.findViewById(R.id.bt_del);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.et_reps.setText(String.valueOf(exercise_p.getReps()));
holder.et_kg.setText(String.valueOf(exercise_p.getWeight()));
holder.et_rest.setText(String.valueOf(exercise_p.getRest()));
holder.bt_del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listExercises.remove(position);
notifyDataSetChanged();
}
});
return v;
}
private static class ViewHolder {
EditText et_reps;
EditText et_kg;
EditText et_rest;
Button bt_del;}}
Main Activity
public class ExerciseCreate extends AppCompatActivity {
Toolbar toolbar;
ListView listView;
Button btAdd;
Button btDel;
ExerciseAdapter exerciseAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.createexercise);
listView = (ListView) findViewById(R.id.exerciselistView);
btAdd = (Button) findViewById(R.id.bt_add);
toolbar = (Toolbar) findViewById(R.id.app_bar);
exerciseAdapter = new ExerciseAdapter(this, R.layout.rowexercise,new ArrayList<Exercise_p_obj>());
exerciseAdapter.add(new Exercise_p_obj(1,1,1,1,1,1));
listView.setAdapter(exerciseAdapter);
setSupportActionBar(toolbar);
btAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final int count = exerciseAdapter.getCount();
Exercise_p_obj clone = exerciseAdapter.getItem(count - 1);
exerciseAdapter.add(new Exercise_p_obj(0, clone.getId_exer_h(), clone.getReps(), clone.getSecs(), clone.getWeight(), clone.getRest()));
}
});
}}
Use separate list with data. When you want to add new item you firstly add it to list and then you need to call adapter.notifyDataSetChanged()
public class ExerciseCreate extends AppCompatActivity {
Toolbar toolbar;
ListView listView;
Button btAdd;
Button btDel;
ExerciseAdapter exerciseAdapter;
List<Exercise_p_obj> items = new ArrayList<Exercise_p_obj>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.createexercise);
listView = (ListView) findViewById(R.id.exerciselistView);
btAdd = (Button) findViewById(R.id.bt_add);
toolbar = (Toolbar) findViewById(R.id.app_bar);
items.add(new Exercise_p_obj(1,1,1,1,1,1));
exerciseAdapter = new ExerciseAdapter(this, R.layout.rowexercise,items);
listView.setAdapter(exerciseAdapter);
setSupportActionBar(toolbar);
btAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final int count = items.size();
Exercise_p_obj clone = items.get(count - 1);
items.add(new Exercise_p_obj(0, clone.getId_exer_h(), clone.getReps(), clone.getSecs(), clone.getWeight(), clone.getRest()));
exerciseAdapter.notifyDataSetChanged();
}
});
}
}