ListView depopulates after I start a new activity - android

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.

Related

Custom Adapter notifyDatasetChanged() on closing dialog from adapter

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;}

ListView items don't display immediately on startup

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

How to wire up a delete button to delete one item on a listview?

I know there are lots of threads with more or less same topic but none of them covers my situation:
I am trying to get my delete button to delete one row on the list view and the delete button appear in each row I got this part to work but I can't get it to work in my Main Activity. The code keeps breaking every time I put this part in my code:
ImageButton removeButton = (ImageButton) findViewById(R.id.btnDel);
removeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onRemoveButtonClick();
}
private void onRemoveButtonClick() {
ToDoItem item = (ToDoItem) v.getTag();
notifyDataSetChanged();
}
my MainActivity works fine without this bit of code. I don't know if it is the code or if it is where I am placing it in my MainActivity if someone would please tell that would much appreciated.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = "ToDoApp";
private ToDoListManager listManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView todoList = (ListView) findViewById(R.id.todo_list);
listManager = new ToDoListManager(getApplicationContext());
ToDoItemAdapter adapter = new ToDoItemAdapter(this, listManager.getList());
todoList.setAdapter(adapter);
ImageButton addButton = (ImageButton) findViewById(R.id.add_item);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onAddButtonClick();
}
});
}
#Override
protected void onPause() {
super.onPause();
listManager.saveList();
}
private void onAddButtonClick() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.add_item);
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton(
R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Add item to list
ToDoItem item = new ToDoItem(
input.getText().toString(),
false
);
listManager.addItem(item);
Log.i(LOG_TAG, input.getText().toString());
}
});
builder.setNegativeButton(
R.string.cancel,
new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int Which) {
dialog.cancel();
}
});
builder.show();
}
private class ToDoItemAdapter extends ArrayAdapter<ToDoItem> {
private Context context;
private List<ToDoItem> items;
public ToDoItemAdapter(Context context, List<ToDoItem> items){
super(context,-1, items);
this.context = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.to_do_item_layout, parent, false);
}
TextView textView = (TextView) convertView.findViewById(R.id.item);
CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
textView.setText(items.get(position).getDescription());
checkBox.setChecked(items.get(position).isComplete());
convertView.setTag(items.get(position));
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ToDoItem item = (ToDoItem) v.getTag();
item.toggleComplete();
notifyDataSetChanged();
}
});
return convertView;
}
}
}
ToDoListManager.java
public class ToDoListManager {
private static final String APP_PREFERENCES = "todoapp";
private static final String TODO_ITEMS = "itemslist";
private List<ToDoItem> items;
private SharedPreferences savedData;
public ToDoListManager(Context context) {
savedData = context.getSharedPreferences (
APP_PREFERENCES,
Context.MODE_PRIVATE
);
String json = savedData.getString(TODO_ITEMS, null);
if (json == null) {
items = new ArrayList<>();
} else {
Type type = new TypeToken<List<ToDoItem>>() {}.getType();
items = new Gson().fromJson(json, type);
}
}
public List<ToDoItem> getList() {
return items;
}
public void addItem(ToDoItem item) {
items.add(item);
saveList();
}
public void saveList() {
SharedPreferences.Editor edit =savedData.edit();
edit.clear();
String json = new Gson().toJson(items);
edit.putString(TODO_ITEMS, json);
edit.apply();
}
}
ToDoItem.java
public class ToDoItem {
private String description;
private boolean isComplete;
public ToDoItem (String description,boolean isComplete) {
this.description = description;
this.isComplete = isComplete;
}
public String getDescription() {
return description;
}
public boolean isComplete() {
return isComplete;
}
public void toggleComplete() {
isComplete = !isComplete;
}
#Override
public String toString() {
return description;
}
}
enter image description here
1.) Add a button to your to_do_item_layout first
2.) Now add this code to add a button to each item
Button btn = (Button) convertView.findViewById(R.id.my_btn);
3.) Add a listener to it
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
items.remove(items.get(position));
}
});

how to send all the data of array list to another activity?

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

Adding objects to listview dynamically from other class in android

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);
}
}

Categories

Resources