Now I am displaying images in grid-view, it working fine. In that grid-view i am going to select few images, i want store selected multiple images position in array variable (example: if i select position 1, 4 ,10. i want that particular position id and i want to store it array like 1,4,10,15,). I will put my activity and adapter code below. Thank you in advance.
Activity
public class EM_event_total_userSeats extends AppCompatActivity implements RestCallback,AdapterView.OnItemClickListener {
String user_id,first_name,last_name,name,emailid,contact_no,gender1,date_of_birth,country_id,postal_code,rolename,profession_response,Street_Address,City,photo;
GridView GridUserSeats;
;
TextView textView1,textView2,Tvposition;
ImageView Ivseats;
public static EM_event_total_userseatsAdapter adapter;
ArrayList<EM_event_total_UserSeatsModel> EMeventuserseatslist;
View savedView;
View previous = null;
String event_id = "EVEPRI62";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.em_event_total_user_seats);
initviews();
callSeatsApi();
GridUserSeats.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
String a = String.valueOf(position);
Toast.makeText(EM_event_total_userSeats.this, a + "#Selected", Toast.LENGTH_SHORT).show();
v.setBackgroundColor(Color.GREEN);
adapter.notifyDataSetChanged();
}
});
}
private void initviews() {
GridUserSeats=(GridView)findViewById(R.id.GridUserSeats);
GridUserSeats.setOnItemClickListener(this);
textView1=(TextView) findViewById(R.id.textView1);
// textView2=(TextView) findViewById(R.id.textView2);
Intent intent = getIntent();
first_name = intent.getStringExtra("first_name");
last_name = intent.getStringExtra("last_name");
}
private void callSeatsApi() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("events", event_id);
RestService.getInstance(EM_event_total_userSeats.this).getUserSeats(map, new MyCallback<ArrayList<EM_event_total_UserSeatsModel>>(EM_event_total_userSeats.this,
EM_event_total_userSeats.this, true, "Finding seats....", GlobalVariables.SERVICE_MODE.EM_SEATS));
}
#Override
public void onFailure(Call call, Throwable t, GlobalVariables.SERVICE_MODE mode) {
}
#Override
public void onSuccess(Response response, GlobalVariables.SERVICE_MODE mode)
{
switch (mode)
{
case EM_SEATS:
EMeventuserseatslist = (ArrayList<EM_event_total_UserSeatsModel>)response.body();
adapter = new EM_event_total_userseatsAdapter(EMeventuserseatslist, getApplicationContext());
GridUserSeats.setAdapter(adapter);
break;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
Adapter
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import cfirst.live.com.R;
import cfirst.live.com.model.BasketModel;
import cfirst.live.com.model.EM_event_total_UserSeatsModel;
public class EM_event_total_userseatsAdapter extends ArrayAdapter<EM_event_total_UserSeatsModel> implements View.OnClickListener {
ArrayList<EM_event_total_UserSeatsModel> dataSet;
public ArrayList<EM_event_total_UserSeatsModel> EMeventuserseatslist = new ArrayList<EM_event_total_UserSeatsModel>();
Context mContext;
ViewHolder holder;
String user_seats;
private int[] tagCollection;
private String[] mobileValues;
private String[] mobileValuesD;
private static class ViewHolder {
TextView TvEmUserSeats;
ImageView IvUsreSeats,available,selctedimag;
}
private String[] strings;
List<Integer> selectedPositions = new ArrayList<>();
public EM_event_total_userseatsAdapter(ArrayList<EM_event_total_UserSeatsModel> data, Context context) {
super(context, R.layout.list_em_get_seats, data);
this.dataSet = data;
this.mContext=context;
}
public int getTagFromPosition(int position) {
return tagCollection[position];
}
#Override
public void onClick(View v) {
int position=(Integer) v.getTag();
Object object= getItem(tagCollection[position]);
EM_event_total_UserSeatsModel dataModel=(EM_event_total_UserSeatsModel) object;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
EM_event_total_UserSeatsModel dataModel = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.list_em_get_seats, parent, false);
viewHolder.TvEmUserSeats = (TextView) convertView.findViewById(R.id.TvEmUserSeats);
viewHolder.IvUsreSeats = (ImageView) convertView.findViewById(R.id.IvUsreSeats);
result=convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result=convertView;
}
String blue_available = "seat3.png";
String red_booked = "seat1.png";
String get_seat = dataModel.getBookedStatus();
viewHolder.TvEmUserSeats.setText(dataModel.getSeatName());
if(Integer.parseInt(get_seat) == 1){
Picasso.with(mContext).load("imageurl + red_booked).into(viewHolder.IvUsreSeats);
}else
{
Picasso.with(mContext).load("imageurl + blue_available).into(viewHolder.IvUsreSeats);
}
return convertView;
}
}
It's simple. You can use SparseBooleanArray for this purpose. Just add the following methods as is in your adapter:
public void toggleSelection(int item) {
if (selectedItems.get(item, false)) {
selectedItems.delete(item);
} else {
selectedItems.put(item, true);
}
notifyDataSetChanged();
}
public void setSelectedItems(List<Object> objects) {
if (objects != null) {
for (Object object : objects) {
toggleSelection(object.getId());
}
notifyDataSetChanged();
}
}
public void clearSelections() {
selectedItems.clear();
notifyDataSetChanged();
}
public int getSelectedItemCount() {
return selectedItems.size();
}
public List<Integer> getSelectedItems() {
List<Integer> items =
new ArrayList<Integer>(selectedItems.size());
for (int i = 0; i < selectedItems.size(); i++) {
items.add(selectedItems.keyAt(i));
}
return items;
}
Use the set selection method to store the selected status of your item.
Don't forget to initialize SparseBooleanArray in your constructor.
SparseBooleanArray SparseBooleanArray = new SparseBooleanArray();
After that, use toggleSelection(position); to change the selected status of an item, then after performing selections, call getSelectedItem() to get the selected items in an array.
// create an Arraylist and add the selected position in a list
List <int> selectedArray = new ArrayList<>();
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int click = (int) parent.getItemAtPosition(position);
selectedArray.add(click);
}
Related
I have created a list with a custom row but I do not know what's wrong.
This is the main activity
package com.example.fahdmana.lest;
public class MainActivity extends AppCompatActivity{
ListView listView;
final int[] movie_poster_resouce = {
R.drawable.apple,
R.drawable.banana,
R.drawable.cherry,
R.drawable.mango,
R.drawable.orange,
R.drawable.strawberry,
R.drawable.tomato
};
String[]movies_title;
String[]movies_rating;
MovieAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.List1);
movies_title = getResources().getStringArray(R.array.Movies_names);
movies_rating = getResources().getStringArray(R.array.Ratings);
int i =0;
for (String titles : movies_title){
MovieDataProvider dataProvider =
new MovieDataProvider(movie_poster_resouce[i],titles,movies_rating[i]);
i++;
adapter = new MovieAdapter(getApplicationContext(),R.layout.row);
listView.setAdapter(adapter);
adapter.add(dataProvider);
}
}
}
And this is my adapter
package com.example.fahdmana.lest;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MovieAdapter extends ArrayAdapter {
final List list = new ArrayList();
public MovieAdapter( Context context, int resource) {
super(context, resource);
}
static class DataHandeler{
ImageView poster;
TextView title;
TextView rating;
}
#Nullable #Override
public void add( Object object) {
super.add(object);
list.add(object);
}
#Nullable #Override
public int getCount() {
return list.size();
}
#Nullable #Override
public Object getItem(int position) {
return this.list.get(position);
}
#Nullable #Override
public View getView (int position,
#NonNull View convertView,
#NonNull ViewGroup parent) {
View row;
row = convertView;
DataHandeler handler;
if (convertView ==null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.row, parent, false);
handler = new DataHandeler();
handler.poster = (ImageView) row.findViewById(R.id.image_view);
handler.title = (TextView) row.findViewById(R.id.movie_title);
handler.rating = (TextView) row.findViewById(R.id.movie_rating);
row.setTag(handler);
} else {
handler = (DataHandeler) row.getTag();
}
MovieDataProvider dataProvider;
dataProvider = (MovieDataProvider)this.getItem(position);
handler.poster.setImageResource(dataProvider.
getMovie_poster_resource());
//here i get some warning
handler.title.setText(dataProvider.getMovie_title());
handler.rating.setText(dataProvider.getMovie_rating());
return row;
}
}
And this is my data provider
package com.example.fahdmana.lest;
public class MovieDataProvider {
private int movie_poster_resource;
private String movie_title;
private String movie_rating;
public MovieDataProvider(int movie_poster_resource, String movie_title, String movie_rating){
this.setMovie_poster_resource(movie_poster_resource);
this.setMovie_title(movie_title);
this.setMovie_rating(movie_rating);
}
public int getMovie_poster_resource() {
return movie_poster_resource;
}
public void setMovie_poster_resource(int movie_poster_resource) {
this.movie_poster_resource = movie_poster_resource;
}
public String getMovie_title() {
return movie_title;
}
public void setMovie_title(String movie_title) {
this.movie_title = movie_title;
}
public String getMovie_rating() {
return movie_rating;
}
public void setMovie_rating(String movie_rating) {
this.movie_rating = movie_rating;
}
}
I am pretty sure this is your problem.
for (String titles : movies_title){
MovieDataProvider dataProvider =
new MovieDataProvider(movie_poster_resouce[i],titles,movies_rating[i]);
i++;
adapter = new MovieAdapter(getApplicationContext(),R.layout.row);
listView.setAdapter(adapter);
adapter.add(dataProvider);
}
You have this in your main activity. You really dont want to loop through your list and inside of that loop call your adapter.
You want to create a list of your objects and then call the adapter .... something like this...
ListViewAdapterResults adapter = new ListViewAdapterResults(listView.getContext(), scheduleModelList);
listView.setAdapter(adapter);
Where scheduleModelList is my list of objects. Hopefully that makes sense.
Happy coding.
Looking through your code, you may want to do something like this....
Put this at the top
List<MovieDataProvider> list;
Then this right after your setContentView
list = new ArrayList<>();
Replace that loop you have with this:
for (int i = 0; i < movie_title.length; i++) {
list.add(new MovieDataProvider(movie_poster_resouce[i],titles,movies_rating[i]));
}
MovieAdapter adapter = new MovieAdapter(listView.getContext(), list);
listView.setAdapter(adapter);
Let me know if you have any questions.
MovieAdapter (this is your adapter class)
listView.getContext() (this is the ID of your listview [you may have it named something else])
It's been a very long time since I have worked with Arrays.... you have have to +1 or -1 inside of the for loop. (i < movie_title.length [maybe +1 or -1])
Here is my MainActivity.java where I define an OnClickListener on the items. Here I am always getting a wrong value of the item after filtering.
If there are 10 items in the ListView then after filtering if I get 3 items and the correct position is like 3,6,9 then I am getting 0,1,2 instead.
package com.focusmedica.maadiabetes;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends Activity {
private MainAdapter adapter;
private static ListView lvFiltered;
private static ArrayList<DataModel> data=new ArrayList<>();;
MyDatabase handler;
private EditText etSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvFiltered =(ListView)findViewById(R.id.lvFiltered);
etSearch = (EditText)findViewById(R.id.etSearch);
etSearch.setText("");
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
handler=new MyDatabase(this);
data=handler.getChapterDetails();
adapter = new MainAdapter(this,data);
lvFiltered.setAdapter(adapter);
lvFiltered.setTextFilterEnabled(true);
lvFiltered.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, SubActivity.class);
intent.putExtra("position", position);
startActivity(intent);
}
});
etSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
if(cs.length()>0) {
etSearch.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.delete, 0);
}else{
etSearch.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
// When user changed the Text
adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
etSearch.setOnTouchListener(new View.OnTouchListener() {
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP) {
if(etSearch.getCompoundDrawables()[2]!=null){
if(event.getX() >= (etSearch.getRight()- etSearch.getLeft() - etSearch.getCompoundDrawables()[2].getBounds().width())) {
etSearch.setText("");
}
}
}
return false;
}
});
}
}
here is Adapter class
package com.focusmedica.maadiabetes;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by windev on 8/2/2016.
*/
public class MainAdapter extends BaseAdapter implements Filterable {
ArrayList<DataModel> dataSet;
Context context;
DataModel content;
public ArrayList<DataModel> orig;
public MainAdapter(Context context, ArrayList dataSet) {
super();
this.context = context;
this.dataSet = dataSet;
}
#Override
public int getCount() {
return dataSet.size();
}
#Override
public Object getItem(int position) {
return dataSet.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
class ViewHolder {
private TextView tvChapterName;
private ImageView ivChapterIcon;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
final ViewHolder viewHolder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.card_layout, null);
viewHolder = new ViewHolder();
viewHolder.tvChapterName = (TextView) view.findViewById(R.id.tvChapterName);
viewHolder.ivChapterIcon=(ImageView)view.findViewById(R.id.ivChapterIcon);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
content = dataSet.get(position);
viewHolder.tvChapterName.setText(content.getChapterName());
viewHolder.ivChapterIcon.setImageResource(R.drawable.caticon);
return view;
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<DataModel> results = new ArrayList<>();
final ArrayList<DataModel> ids = new ArrayList<>();
if (orig == null)
orig = dataSet;
if (constraint != null) {
if (orig != null && orig.size() > 0) {
for (final DataModel g : orig) {
if (g.getChapterName().toLowerCase().contains(constraint.toString())||
g.getChapterName().toUpperCase().contains(constraint.toString()))
results.add(g);
}
}
oReturn.values = results;
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
dataSet = (ArrayList<DataModel>) results.values;
notifyDataSetChanged();
}
};
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
To get the "old" position (which is equivalent to the item ID) for an item in the filtered list:
#Override
public long getItemId(int position) {
int itemID;
// orig will be null only if we haven't filtered yet:
if (orig == null)
{
itemID = position;
}
else
{
itemID = orig.indexOf(dataSet.get(position));
}
return itemID;
}
Now use this method with the OnItemClickListener:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, SubActivity.class);
intent.putExtra("position", adapter.getItemId(position) );
startActivity(intent);
}
Note: if you ever need to use notifyDatasetChanged() it might be a good idea to override this method as well:
#Override
public void notifyDatasetChanged()
{
// either this or: orig = dataSet;
orig = null;
super.notifyDatasetChanged();
}
After filtering the 'ArrayList' will add data from the 0th position. So you will get position as 0,1,2. You have to use id instead of position.
Store data which you want to get, in an array and retrieve data select by user using position from the same array in onClick method of listview.
In my app, I have the goal of, when a user selects a list item, that ParseObject becomes associated with that user. I am using a ListAdapter to create a CustomList.
Here is my List Activity:
package android.bignerdranch.com.mobilemidwife;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.parse.ParseObject;
import com.parse.ParseQueryAdapter;
public class MidwifeResultList extends ListActivity {
private ParseQueryAdapter<ParseObject> mainAdapter;
private CustomMidwifeAdapter midwifeListAdapter;
//calls Adapter; Adapter manages data model
//adapts it to individual entries in widget
//inflates, assigns it to rows
ArrayAdapter<String> madapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
//initialize main ParseQueryAdapter
mainAdapter = new CustomMidwifeAdapter(this);
//which keys in Midwife object
mainAdapter.setTextKey("practicename");
mainAdapter.setTextKey("education");
mainAdapter.setTextKey("yearsinpractice");
mainAdapter.setTextKey("practicephilosophy");
setListAdapter(mainAdapter);
mainAdapter.loadObjects();
}
protected void onListItemClick (ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent intent = new Intent(this, SelectedMidwife.class);
intent.putExtra("practicename", "practicename");
startActivity(intent);
}
}
I have this Adapter:
public class CustomMidwifeAdapter extends ParseQueryAdapter<ParseObject> {
public CustomMidwifeAdapter(Context context) {
super(context, new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery create() {
// Here we can configure a ParseQuery to display
// midwives
ParseQuery query = new ParseQuery("midwifefirm");
query.whereEqualTo("userType", "midwife");
return query;
}
});
}
#Override
public View getItemView(ParseObject object, View view, ViewGroup parent) {
if (view == null) {
view = View.inflate(getContext(), R.layout.activity_midwife_result_list, null);
}
//use midwifefirm as item view/list
super.getItemView(object, view, parent);
// find in layout the practice name
TextView titleTextView = (TextView) view.findViewById(R.id.practicename);
//in the midwifefirm data model, call getPracticename
titleTextView.setText(object.getString("practicename"));
// Add education view
TextView EducationView = (TextView) view.findViewById(R.id.education);
EducationView.setText(object.getString("education"));
// Add yearsexperience view
TextView ExperienceView = (TextView) view.findViewById(R.id.yearsinpractice);
ExperienceView.setText(object.getString("yearsinpractice"));
//Add practice philosophy view
TextView PracticePhilosophyView = (TextView) view.findViewById(R.id.practicephilosophy);
PracticePhilosophyView.setText(object.getString("practicephilosophy"));
return view;
}
}
Ordinarily, I would setup a for loop, loop through the listitems..not sure where to start.
Thanks for any help.
Michael
Here is how I have handled custom adapters with listviews using parse. Hopefully this helps.
//setting up the listview
mYourListView = (ListView) findViewById(R.id.yourListView);
mYourCustomAdapter = new YourCustomAdapter(yourActivity.this, new ArrayList<whateverYourParseClassIs>());
mYourListView.setAdapter(mYourCustomAdapter);
YourCustomAdapter.java
public class YourCustomAdapter extends ArrayAdapter<whateverYourClassIs> {
private final Context mContext;
private List<whateverYourClassIs> mNumbers;
private TextView mNumber1;
private TextView mNumber2;
public YourCustomAdapter(Context context, List<whateverYourClassIs> objects) {
super(context, R.layout.your_layout_for_adapter, objects);
this.mContext = context;
this.mNumbers = objects;
}
public View getView(final int position, View convertView, final ViewGroup parent) {
if (convertView == null) {
LayoutInflater mLayoutInflater = LayoutInflater.from(mContext);
convertView = mLayoutInflater.inflate(R.layout.your_layout_for_adapter, null);
}
final whateverYourClassIs individualRecord = mNumbers.get(position);
mNumber1 = (TextView) convertView.findViewById(R.id.number1);
mNumber2 = (TextView) convertView.findViewById(R.id.number2);
mNumber1.setText(String.valueOf(individualRecord.get("whatever you want")));
mNumber2.setText(String.valueOf(individualRecord.get("whatever you want")));
return convertView;
}
}
YourQuery
public void updateYourData() {
ParseQuery<whateverYourClassIs> query = ParseQuery.getQuery(YourParseClass.class);
query.whereEqualTo("user", ParseUser.getCurrentUser());
query.findInBackground(new FindCallback<whateverYourParseclass>() {
#Override
public void done(List<whateverYourParseclass> objects, ParseException error) {
if (objects != null) {
mYourCustomAdapter.add(objects.get(0));
mYourCustomAdapter.notifyDataSetChanged();
}
}
});
}
Or a query that has a loop
public void updateYourData() {
ParseQuery<whateverYourClassIs> query = ParseQuery.getQuery(YourParseClass.class);
query.whereEqualTo("user", ParseUser.getCurrentUser());
query.findInBackground(new FindCallback<whateverYourParseclass>() {
#Override
public void done(List<whateverYourParseclass> objects, ParseException error) {
if (objects != null) {
mYourCustomAdapter.clear();
for (int i = 0; i < objects.size(); i++) {
mYourCustomAdapter.add(objects.get(i));
mYourCustomAdapter.notifyDataSetChanged();
}
}
In your adapter you simply get the objects (and it's position) passed into it by your query and query specific column names you want to get information from. Let me know if this helps or if you need any clarification.
I have implemented a custom adapter class for controlling my listview. I'm implementing a button, a textbox and a checkbox against each row in the listview. I have a couple of buttons that are not part of the listview. They are below the listview. Now when I check any number of boxes and press the button that is not part of the listview, I want to be able to delete the checked boxes (if there are any). In other words, I want to b able to delete the checked items with the click of a button that is not part of the listview.
Here's my main class...
public class ASvideofiles extends Activity implements OnClickListener {
int count = 0;
private String[] vidNames;
private String[] vidPaths;
private ListView myList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.asvideofiles);
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
Button b2 = (Button) findViewById(R.id.button2);
b2.setOnClickListener(this);
File f = new File(Environment.getExternalStorageDirectory(),
"ABC/XYZ/");
File[] files = f.listFiles();
vidNames = new String[files.length];
vidPaths = new String[files.length];
if(files != null) {
for(int i=0; i < files.length; i++) {
vidNames[i] = files[i].getName();
vidPaths[i] = files[i].getPath();
count ++;
}
}
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < files.length; i++) {
list.add(vidNames[i]);
}
myList = (ListView)findViewById(R.id.listView1);
myList.setAdapter(new AScustomadapter(ASvideofiles.this, list));
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.button1) {
} else if(v.getId() == R.id.button2) {
}
}
}
Here's my Adapter class...
public class AScustomadapter extends BaseAdapter {
private ArrayList<String> mListItems;
private LayoutInflater mLayoutInflater;
int i = 0;
private ArrayList<Integer> checkedIndices = new ArrayList<Integer>();
public AScustomadapter(Context context, ArrayList<String> arrayList) {
mListItems = arrayList;
//get the layout inflater
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mListItems.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
public int getTotalCheckedCount() {
return checkedIndices.size();
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = mLayoutInflater.inflate(R.layout.list_item, null);
holder.itemName = (TextView) view.findViewById(R.id.list_item_text_view);
holder.cb1 = (CheckBox) view.findViewById(R.id.checkBox1);
view.setTag(holder);
} else {
holder = (ViewHolder)view.getTag();
}
final String stringItem = mListItems.get(position);
if (stringItem != null) {
if (holder.itemName != null) {
holder.itemName.setText(stringItem);
}
}
holder.cb1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
if(checkedIndices.contains(position)){
}else {
checkedIndices.add(position);
}
}else {
checkedIndices.remove((Integer)position);
}
}
});
if(checkedIndices.contains((Integer)position)) {
holder.cb1.setChecked(true);
} else {
holder.cb1.setChecked(false);
}
//this method must return the view corresponding to the data at the specified position.
return view;
}
private static class ViewHolder {
protected TextView itemName;
protected CheckBox cb1;
}
}
The rows are basically populated with videos, so all in all, I want to be able to delete the selected videos against which the check boxes are checked and the delete button is pressed. Help required. Thanks in advance.
Maintain a Boolean Array which keeps track of the position of the rows of checked CheckBoxes.
Then in your Button onClickListener remove those items from the ArrayList and pass this updated ArrayList to your adapter.
Finally call notifyDataSetChanged()
Here , i have a solution for you. I have added your adapter class in the main activity itself. Basically i have created two array list of type string. When you check a checkbox, the corresponding textview value is stored in it the list CHECKEDLIST. In the other list ALLVALUES, all the values are stored.
On button click i match both the lists and if a match occurs, then i remove that value from ALLVALUES and call notifydatasetchanged
package com.example.test;
import java.io.File;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class MainActivity extends Activity implements OnClickListener {
private ArrayList<String> checkedIndices = new ArrayList<String>();
ArrayList<String> list = new ArrayList<String>();
AScustomadapter adapter;
int count = 0;
private String[] vidNames = {"a","b","c","d","e","f","g","h","i"};
private ListView myList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
for (int i = 0; i < vidNames.length; i++) {
list.add(vidNames[i]);
}
myList = (ListView)findViewById(R.id.list);
adapter = new AScustomadapter(getApplicationContext(), list);
myList.setAdapter(adapter);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.button1) {
for (int i = 0; i < checkedIndices.size(); i++) {
for(int j = 0; j <list.size();j++){
if(list.get(j).contains(checkedIndices.get(i))){
list.remove(j);
}
}
}
adapter.notifyDataSetChanged();
}
}
public class AScustomadapter extends BaseAdapter {
private ArrayList<String> mListItems;
private LayoutInflater mLayoutInflater;
int i = 0;
public AScustomadapter(Context context, ArrayList<String> arrayList) {
mListItems = arrayList;
//get the layout inflater
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mListItems.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
public int getTotalCheckedCount() {
return checkedIndices.size();
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = mLayoutInflater.inflate(R.layout.list_item, null);
holder.itemName = (TextView) view.findViewById(R.id.list_item_text_view);
holder.cb1 = (CheckBox) view.findViewById(R.id.checkBox1);
view.setTag(holder);
} else {
holder = (ViewHolder)view.getTag();
}
final String stringItem = mListItems.get(position);
if (stringItem != null) {
if (holder.itemName != null) {
holder.itemName.setText(stringItem);
}
}
holder.cb1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//is chkIos checked?
if (((CheckBox) v).isChecked()) {
if(!checkedIndices.contains(getItem(index).toString()))
checkedIndices.add(getItem(index).toString()); }
else {
checkedIndices.remove(getItem(index).toString());
}
//case 2
}
});
if(checkedIndices.contains((Integer)position)) {
holder.cb1.setChecked(true);
} else {
holder.cb1.setChecked(false);
}
//this method must return the view corresponding to the data at the specified position.
return view;
}
private class ViewHolder {
protected TextView itemName;
protected CheckBox cb1;
}
}
}
I have a Listview of EditText and I need to get the String values of each edited row when I click a confirm button, but I don't know how.
I have tried to adapt some sample with no success ( I get always the default values and not the edited values).
My attempt is this
public class MyActivity extends Activity {
static int nItems;
ImageButton confirmButton;
ListView myList;
ListViewAdapterEditText adapterG1, adapterG2, adapterG3;
#Override
public void onCreate(Bundle savedInstanceState) {
.....
myList = (ListView) findViewById(R.id.listaG1);
myList.setItemsCanFocus(true);
adapterG1 = new ListViewAdapterEditText();
myList.setAdapter(adapterG1);
}
OnClickListener mConfirmButtonListener = new OnClickListener() {
public void onClick(View v) {
ArrayList a1 = adapterG1.getItems();
for (int i = 0; i < nItems; i++) {
System.out.println(a1.get(i)
+ "\n\n");
}
};
public class ListViewAdapterEditText extends BaseAdapter {
private LayoutInflater mInflater;
public ArrayList myItems = new ArrayList();
ListItem listItem;
public ListViewAdapterEditText() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < nItems; i++) {
listItem = new ListItem();
listItem.caption = "Caption" + i;
myItems.add(listItem);
}
notifyDataSetChanged();
}
public int getCount() {
return myItems.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public ArrayList<String> getItems() {
ArrayList<String> items = new ArrayList<String>();
for (int i = 0; i < nItems; i++) {
ListItem li = (ListItem) myItems.get(i);
items.add(li.getCaption());
}
return items;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.list_item_row,
null);
holder.caption = (EditText) convertView
.findViewById(R.id.ItemCaption);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Fill EditText with the value you have in data source
holder.caption.setText(((ListItem) myItems.get(position)).caption);
// holder.caption.setText(myItems.get(position).caption);
holder.caption.setId(position);
// we need to update adapter once we finish with editing
holder.caption
.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
final int position = v.getId();
final EditText Caption = (EditText) v;
((ListItem) myItems.get(position)).caption = Caption
.getText().toString();
}
}
});
return convertView;
}
class ViewHolder {
EditText caption;
}
class ListItem {
String caption;
public String getCaption() {
return caption;
}
}
}
}
Could someone help me to solve this problem?
Are you sure your OnFocusChangeListener is called? If you edit the text in EditText then tap the confirm button, this listener will not be called in touch mode since the focus is still on the EditText.
Update: Consider the situation you edited the text in a EditText while didn't confirm and scrolled the ListView so that the item view is recycled, I'm not sure what is your preferred way, but if you want store the edited data, you can use setRecyclerListener(android.widget.AbsListView.RecyclerListener) to get notified when a item view is recycled so you can saved the edit result. To save the result of EditText showing on screen, you use methods like getChildAt to get item views visible on screen then get the EditText's text.
Update2: Another better and clean way is use TextWatcher and addTextChangeListener, this will notifies you when the text in EditText is changed.
Update3: I just write the following sample and test it, and it works on my phone. :)
Update4: I removed the previous code cause its performance is bad and creates a lot objects, you can check the following full sample instead:
Activity code :
package com.example.asynctasktest;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
/**
* #author Daniel Chow
*
* May 26, 2013 12:57:49 AM
*/
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listview);
final TestAdapter adapter = new TestAdapter(this);
listView.setAdapter(adapter);
Button confirmButton = (Button) findViewById(R.id.confirm_button);
confirmButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
List<String> items = adapter.getItems();
for (int i = 0, n = items.size(); i < n; i++) {
Log.e("", items.get(i));
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Adapter code:
/**
*
*/
package com.example.asynctasktest;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
/**
* #author Daniel Chow
*
* May 26, 2013 1:13:02 AM */
public class TestAdapter extends BaseAdapter {
private List<String> items = new ArrayList<String>();
private Context context;
public TestAdapter(Context context) {
this.context = context;
for (int i = 0; i < 12; i++) {
items.add("caption " + i);
}
}
public List<String> getItems() {
return new ArrayList<String>(items);
}
#Override
public int getCount() {
return 12;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = new EditText(context);
holder = new ViewHolder();
holder.editText = (EditText) convertView;
holder.watcher = new EditTextWatcher();
holder.editText.addTextChangedListener(holder.watcher);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.watcher.setTarget(position);
holder.editText.setText(items.get(position));
return convertView;
}
private class EditTextWatcher implements TextWatcher {
private int target;
public void setTarget(int target) {
this.target = target;
}
#Override
public void afterTextChanged(Editable s) {
items.set(target, s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
}
private static class ViewHolder {
EditText editText;
EditTextWatcher watcher;
}
}
I usually follow a simpler technique
public class Item_Adapter extends BaseAdapter {
private String[] Val;
public Item_Adapter () {
Val= new String[nItems];
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
///bla bla
holder.caption
.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
final int position = v.getId();
final EditText Caption = (EditText) v;
((ListItem) myItems.get(position)).caption = Caption
.getText().toString();
Val[position]= Caption
.getText().toString();
}
}
});
///bla bla
return convertView;
}
/////most important returning your array so you can use it in the Activity
public String[] getVal() {
return Val;
}