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;}
Related
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.
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);
}
}
The problem: I want to remove a item from my listview using a button in another activity.
I have tried several kinds of code, but it just doesn't seem to work.
Right know I use serializable to bundle the object to the other activity.
But I don't know how to remove it, from the other activity.
Can anybody help me with that?
Can I use the button from the second activity, in the first activity to delete the item from the listview?
Class A where I got my ListView
public class ListActivity extends Activity {
ListView list;
Button exit;
SimpleAdapter adapter;
final List<Map<String, String>> data = new ArrayList<Map<String, String>>();
#Override``
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
list = (ListView) findViewById(R.id.list);
exit = (Button) findViewById(R.id.btnExit);
// Registration numbers
final String[] title = new String[] { "XMT 123", "KLE 456", "CKL 789",
"MRP 012", "DSV 345" };
// Name of the truck drivers
final String[] subtitle = new String[] { "Peter Lund", "Hans Larsson",
"Erik Petersson", "Bjørn Lundal", "Lars Svensson" };
for (int i = 0; i < title.length; i++) {
Map<String, String> datalist = new HashMap<String, String>();
datalist.put("title", title[i]);
datalist.put("subtitle", subtitle[i]);
data.add(datalist);
}
// getDataInList();
adapter = new SimpleAdapter(this, data,
android.R.layout.simple_list_item_2, new String[] { "title",
"subtitle" }, new int[] { android.R.id.text1,
android.R.id.text2 });
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Intent intent = new Intent(ListActivity.this,
InformationActivity.class);
intent.putExtra("updateReg", title[position].toString());
intent.putExtra("updateName", subtitle[position].toString());
}
});
exit.setOnClickListener(new OnClickListener() {
// Closes the application
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
Class B where I got my accept button.
When I click accept, the item from the listview in Class A should be removed.
public class InformationActivity extends Activity {
TextView name;
TextView reg;
TextView product;
TextView productNo;
Button accept;
Button edit;
Button exit;
AlertDialog dialog;
ListView list;
String result;
EditText search;
int requestCode = 1;
SimpleAdapter adapter;
Context context = InformationActivity.this;
ArrayList<Materials> materialList = new ArrayList<Materials>();
// Materials
final static String[] material = new String[] { "Betong", "Grus", "Järn",
"Metall", "Grus fin", "Grus grov", "Sten" };
// Material numbers
final static String[] materialNo = new String[] { "123", "234", "345",
"456", "567", "789", "012" };
private void getDataInList() {
for (int i = 0; i < 7; i++) {
Materials mats = new Materials(result, result);
mats.setMaterialName(material[i]);
// mats.setMaterialNo(material[i]);
materialList.add(mats);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information_activity);
name = (TextView) findViewById(R.id.name);
reg = (TextView) findViewById(R.id.reg);
product = (TextView) findViewById(R.id.product);
productNo = (TextView) findViewById(R.id.productNo);
accept = (Button) findViewById(R.id.btnAccept);
edit = (Button) findViewById(R.id.btnEdit);
list = (ListView) findViewById(R.id.list);
Bundle extras = getIntent().getExtras();
String selected_item = extras.getString("updateReg");
reg = (TextView) findViewById(R.id.reg);
reg.setText(selected_item);
Bundle extras1 = getIntent().getExtras();
String selected_item1 = extras1.getString("updateName");
name = (TextView) findViewById(R.id.name);
name.setText(selected_item1);
getDataInList();
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder popup = new AlertDialog.Builder(
InformationActivity.this);
popup.setTitle("Välj ny artikel");
// Search field
final EditText search = new EditText(context);
popup.setView(search);
search.setHint("Sök här...");
popup.setSingleChoiceItems(material, -1,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
materialList.get(which);
Toast.makeText(getApplicationContext(),
material[which], Toast.LENGTH_SHORT)
.show();
result = material[which];
}
});
// PositiveButton, updates the material info field.
popup.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
product.setText(result);
}
});
// NegativeButton, closes the pop-up.
popup.setNegativeButton("Avbryt",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
dialog = popup.create();
dialog.show();
}
});``
//Remove item
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
You should not directly remove the item from the view, but from the data displayed in it.
For example if your ListView is displaying items from an ArrayList, just remove the item in the ArrayList from you Activity B, and call myAdapter.notifyDataSetChanged() when back in the Activity A, which contains the adapter.
You can remove items by accessing to the ArrayList or by overriding the remove() method if you have only access to the adapter (assuming your adapter extends ArrayAdapter).
Also, you may have to override usefull Adapter methods like getCount(), getView()...
Thanks to all.
I found another solution thanks to remove row from another activity
Class A
public class ListActivity extends Activity {
ListView list;
Button exit;
static List<ListItems> items = new ArrayList<ListItems>();
public static int deletePos;
static ListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
list = (ListView) findViewById(R.id.list);
exit = (Button) findViewById(R.id.btnExit);
// Registration numbers
final String[] title = new String[] { "XMT 123", "KLE 456", "CKL 789",
"MRP 012", "DSV 345" };
// Name of the truck drivers
final String[] subtitle = new String[] { "Peter Lund", "Hans Larsson",
"Erik Petersson", "Bjørn Lundal", "Lars Svensson" };
items = new ArrayList<ListItems>();
for (int i = 0; i < title.length; i++) {
ListItems s = new ListItems(title[i], subtitle[i]);
items.add(s);
}
adapter = new ListAdapter(this, android.R.layout.simple_list_item_2,
items);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Intent intent = new Intent(ListActivity.this,
InformationActivity.class);
intent.putExtra("updateReg", title[position].toString());
intent.putExtra("updateName", subtitle[position].toString());
deletePos = position;
adapter.notifyDataSetChanged();
startActivity(intent);
}
});
exit.setOnClickListener(new OnClickListener() {
// Closes the application
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
Class B
public class InformationActivity extends Activity {
TextView name;
TextView reg;
TextView product;
TextView productNo;
Button accept;
Button edit;
Button exit;
AlertDialog dialog;
ListView list;
String result;
EditText search;
Context context = InformationActivity.this;
ArrayList<Materials> materialList = new ArrayList<Materials>();
// Materials
final static String[] material = new String[] { "Betong", "Grus", "Järn",
"Metall", "Grus fin", "Grus grov", "Sten" };
// Material numbers
final static String[] materialNo = new String[] { "123", "234", "345",
"456", "567", "789", "012" };
private void getDataInList() {
for (int i = 0; i < 7; i++) {
Materials mats = new Materials(result, result);
mats.setMaterialName(material[i]);
// mats.setMaterialNo(material[i]);
materialList.add(mats);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information_activity);
name = (TextView) findViewById(R.id.name);
reg = (TextView) findViewById(R.id.reg);
product = (TextView) findViewById(R.id.product);
productNo = (TextView) findViewById(R.id.productNo);
accept = (Button) findViewById(R.id.btnAccept);
edit = (Button) findViewById(R.id.btnEdit);
list = (ListView) findViewById(R.id.list);
Bundle extras = getIntent().getExtras();
String selected_item = extras.getString("updateReg");
reg = (TextView) findViewById(R.id.reg);
reg.setText(selected_item);
Bundle extras1 = getIntent().getExtras();
String selected_item1 = extras1.getString("updateName");
name = (TextView) findViewById(R.id.name);
name.setText(selected_item1);
getDataInList();
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder popup = new AlertDialog.Builder(
InformationActivity.this);
popup.setTitle("Välj ny artikel");
// Search field
final EditText search = new EditText(context);
popup.setView(search);
search.setHint("Sök här...");
popup.setSingleChoiceItems(material, -1,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
materialList.get(which);
Toast.makeText(getApplicationContext(),
material[which], Toast.LENGTH_SHORT)
.show();
result = material[which];
}
});
// PositiveButton, updates the material info field.
popup.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
product.setText(result);
}
});
// NegativeButton, closes the pop-up.
popup.setNegativeButton("Avbryt",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
dialog = popup.create();
dialog.show();
}
});
// Remove item
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int deletePos = ListActivity.deletePos;
ListActivity.items.remove(deletePos);
ListActivity.adapter.notifyDataSetChanged();
finish();
}
});
}
}
How would I use shared preferences to store the state of my checkbox for the next time the app is opened? I'm using a custom adapter so am guessing it has to be placed inside that but I'm not quite sure.
My Adapter:
public class MobileArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
private ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();
public MobileArrayAdapter(Context context, String[] values) {
super(context, R.layout.list_adapter, values);
this.context = context;
this.values = values;
for (int i = 0; i < this.getCount(); i++) {
itemChecked.add(i, false);
}
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.list_adapter,
parent, false);
}
// in your code you search for the CheckBox with the id checkBox1 2 times so I assumed that you are referring to the same view.
CheckBox cBox = (CheckBox) rowView.findViewById(R.id.checkBox1);
cBox.setTextColor(0xFFFFFFFF);
cBox.setText(values[position]);
cBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
itemChecked.set(position, true);
// do some operations here
} else {
itemChecked.set(position, false);
// do some operations here
}
}
});
cBox.setChecked(itemChecked.get(position));
return rowView;
}
}
My main Activity:
public class TheKevinAndEricaBoxActivity extends Activity {
/** Called when the activity is first created. */
private String[] myString;
private String list;
private String[] myString2;
private String list2;
private static final Random rgenerator = new Random();
private static final Random rgenerator2 = new Random();
MediaPlayer mp;
final Context mContext = this;
final Context context = this;
private Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Resources res = getResources();
addListenerOnButton();
myString = res.getStringArray(R.array.myArray);
list = myString[rgenerator.nextInt(myString.length)];
myString2 = res.getStringArray(R.array.myArray2);
list2 = myString2[rgenerator.nextInt(myString2.length)];
}
public void addListenerOnButton() {
final Context context2 = this;
ImageButton ibg = (ImageButton) findViewById(R.id.buttongallery);
ibg.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context2, App2Activity.class);
startActivityForResult(intent, 0);
}
});
ImageButton ib = (ImageButton) findViewById(R.id.imagebutton1);
ib.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View erica) {
AlertDialog.Builder b = new AlertDialog.Builder(
TheKevinAndEricaBoxActivity.this);
b.setMessage(myString[rgenerator.nextInt(myString.length)]);
b.setTitle(R.string.title1);
b.setIcon(R.drawable.menuiconerica);
b.setPositiveButton("Back",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
});
Dialog d = b.create();
d.show();
}
});
ImageButton ib2 = (ImageButton) findViewById(R.id.imagebutton2);
ib2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View kevin) {
AlertDialog.Builder b = new AlertDialog.Builder(
TheKevinAndEricaBoxActivity.this);
b.setMessage(myString2[rgenerator2.nextInt(myString2.length)]);
b.setTitle(R.string.title2);
b.setIcon(R.drawable.menuiconkevin);
b.setPositiveButton("Back",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
});
Dialog d = b.create();
d.show();
}
});
ImageButton Ib3 = (ImageButton) findViewById(R.id.imagebutton3);
Ib3.setOnClickListener(new View.OnClickListener() {
public void onClick(View lemonclick) {
mp = MediaPlayer.create(getApplicationContext(),R.raw.lemonspeech);
mp.start();
}
});
button = (Button) findViewById(R.id.button01);
// add button listener
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.list);
dialog.setTitle("The List");
// set the custom dialog components - text, image and button
//TextView text = (TextView) dialog.findViewById(R.id.TextView01);
//text.setText("Did you not read the button? :P i'm not finshed on this yet XD");
ListView listView = (ListView) findViewById(R.id.myList);
String[] values = new String[] { "value1", "value2", };
MobileArrayAdapter mAdapter = new MobileArrayAdapter(getBaseContext(), values);
ListView mListView = (ListView) dialog.findViewById(R.id.myList);
mListView.setAdapter(mAdapter);
Button dialogButton = (Button) dialog.findViewById(R.id.Button01);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
});
}
}
In the OnCLickListener for your Button add this:
//...
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.list);
dialog.setTitle("The List");
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefsEditor = prefs.edit();
String currentlyStored = prefs.getString("checked_list", null);
int[] savedStatus = null;
if (currentlyStored != null) {
String[] tmp = currentlyStored.split(",");
savedStatus = new int[tmp.length];
for (int i = 0; i < tmp.length; i++) {
savedStatus[i] = Integer.parseInt(tmp[i]);
}
}
adapter = new MobileArrayAdapter(this, soundnames, savedStatus);
ListView mListView = (ListView) dialog.findViewById(R.id.myList);
mListView.setAdapter(mAdapter);
//...
where:
private SharedPreferences prefs;
private SharedPreferences.Editor prefsEditor;
private MobileArrayAdapter adapter;
are fields in your class with the ListView(the adapter field will hold your adapter object that you set on the list).
Modify the constructor of your custom adapter like this:
public MobileArrayAdapter(Context context, String[] values,
int[] oldStatus) {
super(context, R.layout.adapters_simpleplay_row, values);
this.context = context;
this.values = values;
// make every CheckBox unchecked and then loop through oldStatus(if
// not null)
for (int i = 0; i < this.getCount(); i++) {
itemChecked.add(i, false);
}
if (oldStatus != null) {
for (int j = 0; j < oldStatus.length; j++) {
itemChecked.set(oldStatus[j], true);
}
}
}
Also add the following method in your custom adapter MobileArrayAdapter:
public ArrayList<Boolean> getCheckedStatus() {
return itemChecked;
}
Last in the listener for your dialogButton add this:
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String toStore = "";
ArrayList<Boolean> status = adapter.getCheckedStatus();
for (int i = 0; i < status.size(); i++) {
if (status.get(i)) {
toStore += i + ",";
}
}
prefsEditor.putString("checked_list", toStore.equals("") ? null
: toStore.substring(0, toStore.length() - 1));
prefsEditor.commit();
dialog.dismiss();
}
});
To save selections make a method saveSelections and call it in onPause() and onDestroy(), or create a Button to do the same for you...
Edit:
Since you are using a ListView which is MultipleChoice I suppose you can do this in onCreate...
listView = (ListView) findViewById(R.id.list);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice,
android.R.id.text1, names));
Create these three methods outside onCreate()
private void LoadSelections() {
SharedPreferences sp = getPreferences(MODE_PRIVATE);
if (sp.contains(LOAD_LIST)) {
String savedItems = sp.getString(LOAD_LIST, "");
this.selectedItems.addAll(Arrays.asList(savedItems.split(",")));
int count = this.listView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
String currentItem = (String) listView.getAdapter().getItem(i);
if (this.selectedItems.contains(currentItem)) {
this.listView.setItemChecked(i, true);
}
}
}
}
public void SaveSelections() {
SharedPreferences sp = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor prefEditor = sp.edit();
String savedItems = getSavedItems();
prefEditor.putString(LOAD_LIST, savedItems);
prefEditor.commit();
}
private String getSavedItems() {
String savedItems = "";
int count = listView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
if (listView.isItemChecked(i)) {
if (savedItems.length() > 0) {
savedItems += "," + listView.getItemAtPosition(i);
} else {
savedItems += listView.getItemAtPosition(i);
}
}
}
return savedItems;
}
Then in onPause(), do this:
#Override
protected void onPause() {
SaveSelections();
super.onPause();
}
Then finally in onCreate call this..
LoadSelections();
You can make a string of 0 & 1 and store it using shared preference. The number of checkboxes (or the number of view) you are using will be the length of string. You save it accordingly.
Eg:
String s[]="0000000000";
for (i=0;i<s.length();i++)
if (checkboxAtLocation(i)==true) //checkboxAtLocation() will return a boolean variable on basis of its checked or not
s[i]=1;
Now store this string.
On starting activity again, use this string to set the checkbox.
This is bit complex to implement but most efficient way as per my knowledge.
I hope it solves your doubt.