Get text content in EditText ListView after click button issue - android

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

Related

How to get gridview multiple positions and store into array variable

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

List view with custom Layout

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])

How to get position of checked checkbox from ListView in android

I created custom ListView with CheckBox next to title. I want to get checked
CheckBox from ListView
I created following function for get message from ListView and send it to another ListView with Intent but I cant get the particular CheckBox position to move.
public class SpamActivity extends AppCompatActivity {
List<Message> sms;
ArrayList<Message> sms1;
ArrayList<String> al;
ListView lv;
CheckBox checkbox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.messagebox);
lv= (ListView) findViewById(R.id.lvMsg);
checkbox = (CheckBox) findViewById(R.id.checkBox);
sms = new ArrayList<>();
al=new ArrayList<>(0);
populateMessageList();
/* SpamActivity spamactivity = new SpamActivity();
al = spamactivity.al;
//InboxFragment inboxfragment = new InboxFragment();
//al = inboxfragment.list;
for (int i=0;i<sms.size();i++){
System.out.println("AddressSPS" + sms.get(i));
} */
Collections.reverse(sms);
}
public void populateMessageList() {
sms1 = new ArrayList<>();
fetchDatabaseMessage();
lv.setAdapter(new datalist(getApplicationContext(), sms1));
// to handle click event on listView item
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
// when user clicks on ListView Item , onItemClick is called
// with position and View of the item which is clicked
// we can use the position parameter to get index of clicked item
TextView textViewSMSSender = (TextView) v.findViewById(R.id.lblNumber);
TextView textViewSMSBody = (TextView) v.findViewById(R.id.lblMsg);
TextView textViewSMSDate = (TextView) v.findViewById(R.id.smsdate);
String smsSender = textViewSMSSender.getText().toString();
String smsBody = textViewSMSBody.getText().toString();
String smsDate = textViewSMSDate.getText().toString();
Intent intentspam = new Intent(getApplicationContext(), DisplaySpamsms.class);
intentspam.putExtra("number",smsSender);
intentspam.putExtra("msg",smsBody);
startActivity(intentspam);
}
});
}
// This method featch the message stored in database
public void fetchDatabaseMessage(){
DB_Message dbmessage = new DB_Message(this);
sms = dbmessage.ViewMessageData();
String addr = sms.get(0).getmAddress();
if (addr.equals(sms.get(0).getmAddress())) {
for (int i = 0; i < sms.size(); i++) {
al.add(sms.get(i).getmAddress());
//al.add(sms.get(i).getmBody());
}
}else {
System.out.println("SMS Not Displayed");
}
}
class datalist extends BaseAdapter {
Context context;
ArrayList<Message> arrayListsms;
public datalist(Context context, ArrayList<Message> arrayListsms) {
// TODO Auto-generated constructor stub
this.context = context;
this.arrayListsms = arrayListsms;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return sms.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return getItem(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflator = getLayoutInflater();
View row;
row = inflator.inflate(R.layout.row, parent, false);
// ImageView img1 = (ImageView) row.findViewById(R.id.imageView1);
final CheckBox checkBox = (CheckBox) row.findViewById(R.id.checkBox);
final TextView txt1 = (TextView) row.findViewById(R.id.lblMsg);
final TextView txt2 = (TextView) row.findViewById(R.id.lblNumber);
final TextView txt3 = (TextView) row.findViewById(R.id.smsdate);
//Long timestamp = Long.parseLong(sms.get(position).getmDate());
Calendar mcalendar = Calendar.getInstance();
//mcalendar.setTimeInMillis(timestamp);
DateFormat mformatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
txt1.setText(sms.get(position).getmBody());
txt2.setText(sms.get(position).getmAddress());
//+"\n"+mformatter.format(mcalendar.getTime())
txt3.setText(mformatter.format(mcalendar.getTime()));
final String msgBody = txt1.getText().toString();
final String msgAddr = txt2.getText().toString();
final String msgDate = txt3.getText().toString();
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Message msg = new Message();
if (isChecked) {
// selectedStrings.add(tv.getText().toString());
Toast.makeText(context, "" + msgBody, Toast.LENGTH_LONG).show();
System.out.println("Body" + msgBody);
System.out.println("Address" + msgAddr);
System.out.println("Date" + msgDate);
al.add(msgBody + msgAddr + msgDate);
// al.add(msgAddr);
// al.add(msgDate);
sms.remove(position);
ContentValues values = new ContentValues();
values.put("address", sms.get(position).getmAddress());
values.put("body", sms.get(position).getmBody());
String date = msg.getmDate();
SimpleDateFormat format = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss");
getContentResolver().insert(Uri.parse("content://sms/inbox"), values);
notifyDataSetChanged();
} else {
// selectedStrings.remove(tv.getText().toString());
}
}
});
return row;
}
}
}
When I used above function for sending message but error is that when I click on any CheckBox to send that message then automatically Different Message is sent to another activity. so, I want to get particular message position to sent it.
You can set "setOnItemClickListener" on list view and get the position.
ListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Here you can get the position
}
});
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class SharedContactListAdapter extends ArrayAdapter<ContactSynResponse> {
private Context context;
private ViewHolder viewHolder;
private SparseBooleanArray mSparseBooleanArray;
private List<ContactSynResponse> mList;
public SharedContactListAdapter(Context context, int resource,
List<ContactSynResponse> objects) {
super(context, resource, objects);
this.context = context;
mSparseBooleanArray = new SparseBooleanArray();
// mList = objects;
}
#Override
public ContactSynResponse getItem(int position) {
return super.getItem(position);
}
public ArrayList<ContactSynResponse> getCheckedItems() {
ArrayList<ContactSynResponse> mTempArry = new ArrayList<ContactSynResponse>();
for (int i = 0; i < mList.size(); i++) {
if (mSparseBooleanArray.get(i)) {
ContactSynResponse data = mList.get(i);
mTempArry.add(data);
}
}
return mTempArry;
}
class ViewHolder {
ImageView profilepic;
ChimmerTextView contactname;
ChimmerTextView contactno;
RelativeLayout completelayout;
CheckBox selectcheckbox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.sharedcontactlistdata,
parent, false);
viewHolder = new ViewHolder();
viewHolder.profilepic = (ImageView) convertView
.findViewById(R.id.profilepic_image_view);
viewHolder.contactname = (ChimmerTextView) convertView
.findViewById(R.id.contactnameTV);
viewHolder.contactno = (ChimmerTextView) convertView
.findViewById(R.id.contactnoTV);
viewHolder.completelayout = (RelativeLayout) convertView
.findViewById(R.id.completeRL);
viewHolder.selectcheckbox = (CheckBox) convertView
.findViewById(R.id.contact_checkbox);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
ContactSynResponse data = getItem(position);
viewHolder.contactname.setText(data.getName());
viewHolder.contactno.setText(data.getPhone());
viewHolder.selectcheckbox.setTag(position);
viewHolder.selectcheckbox.setOnCheckedChangeListener(new CheckListener(
data, viewHolder.selectcheckbox));
viewHolder.completelayout.setOnClickListener(new ClickListener(data,
viewHolder.selectcheckbox));
return convertView;
}
class CheckListener implements OnCheckedChangeListener {
private CheckBox checkbox;
public CheckListener(ContactSynResponse data, CheckBox checkbox) {
this.checkbox = checkbox;
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
checkbox.setButtonDrawable(R.drawable.notification_selected_checkbox);
} else {
checkbox.setButtonDrawable(R.drawable.notification_checkbox);
}
buttonView.setChecked(isChecked);
mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);
}
}
class ClickListener implements OnClickListener {
private CheckBox checkbox;
public ClickListener(ContactSynResponse data, CheckBox checkbox) {
this.checkbox = checkbox;
}
#Override
public void onClick(View v) {
if (checkbox.isSelected()) {
checkbox.setChecked(false);
checkbox.setButtonDrawable(R.drawable.notification_checkbox);
mSparseBooleanArray.put((Integer) checkbox.getTag(), false);
} else {
checkbox.setChecked(true);
checkbox.setButtonDrawable(R.drawable.notification_selected_checkbox);
mSparseBooleanArray.put((Integer) checkbox.getTag(), true);
}
}
}
}

How to start new intent after search-filtering listview?

Hi guys I have a question:
I created a listview, with search-bar etc . So when I click on an item (through switch-case) the selected new activity opens and there are no problems.
you can see the code here:
Filtered list item opens the original list items' activity
The problems start when I filter the listview, with the search-bar, and instead of opening the selected activity (let us say activity 10), it throws me back to activity 1 and so forth.
What I have figured out so far is that most probably the CustomAdapter somehow mixes my activities and does not know which activity was chosen; hence, it throws me back to the beginning.
Please guys, I am trying for over a month to solve that issue and still no hope in the horizon.
Any help appreciated.
In your code, you have given click event based on the position of listview. eg:
players = {"test1","test2","test3"}
CASE 1: when nothing is searched:
first position has player test1
case 2: when user search test2.
Now listview search for test2 and find only one instance of this, and searchlist will have only one player and it will be at the first position. Since you have given click event based on position it, first row will always take to Barca
UPDATE:
you need to change your Code as below
Group.java
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class Group extends ListActivity {
ArrayList<Players> originalValues;
LayoutInflater inflater;
int noOfPlayers = 10;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grouplist);
final EditText searchBox = (EditText) findViewById(R.id.searchBox);
ListView playersListView = (ListView) findViewById(android.R.id.list);
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
originalValues = new ArrayList<Players>();
for (int i = 0; i < noOfPlayers; i++) {
// here you initialise the class with your own data
Players players = new Players(i, "name" + i, "team", R.drawable.ic_launcher);
originalValues.add(players);
}
final CustomAdapter adapter = new CustomAdapter(this, R.layout.players, originalValues);
playersListView.setAdapter(adapter);
searchBox.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
String searchString = searchBox.getText().toString();
int textLength = searchString.length();
adapter.clearSearchResult();
for (int i = 0; i < originalValues.size(); i++) {
String playerName = originalValues.get(i).getName();
if (textLength <= playerName.length()) {
// compare the String in EditText with Names in the
// ArrayList
if (searchString.equalsIgnoreCase(playerName.substring(0, textLength)))
adapter.addSeachResult(originalValues.get(i));
}
}
adapter.notifyDataSetChanged();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
}
});
playersListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch ((int) adapter.getItemId(position)) {
case 0:
Intent newActivity = new Intent(Group.this, Barca.class);
startActivity(newActivity);
break;
case 1:
etc
}
}
});
}
}
CustomAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
class CustomAdapter extends BaseAdapter {
ArrayList<Players> searchResults;
ViewHolder viewHolder;
public CustomAdapter(Context context, int textViewResourceId, ArrayList<Players> results) {
searchResults = new ArrayList<>(results);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.players, null);
viewHolder = new ViewHolder();
viewHolder.photo = (ImageView) convertView.findViewById(R.id.photo);
viewHolder.name = (TextView) convertView.findViewById(R.id.name);
viewHolder.team = (TextView) convertView.findViewById(R.id.team);
convertView.setTag(viewHolder);
} else
viewHolder = (ViewHolder) convertView.getTag();
int photoId = (Integer) searchResults.get(position).getPicture();
viewHolder.photo.setImageDrawable(parent.getContext().getResources().getDrawable(photoId));
viewHolder.name.setText(searchResults.get(position).getName());
viewHolder.team.setText(searchResults.get(position).getTeam());
return convertView;
}
public void clearSearchResult() {
searchResults.clear();
}
public void addSeachResult(Players result) {
this.searchResults.add(result);
}
private class ViewHolder {
ImageView photo;
TextView name, team;
}
#Override
public int getCount() {
return searchResults.size();
}
#Override
public Object getItem(int position) {
return searchResults.get(position);
}
#Override
public long getItemId(int position) {
return searchResults.get(position).getId();
}
}
New Class called Player.java
public class Players {
public Players(int id,String name,String team,int picture){
this.id = id;
this.name = name;
this.team = team;
this.picture = picture;
}
private int id;
private String name;
private String team;
private int picture;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTeam() {
return team;
}
public void setTeam(String team) {
this.team = team;
}
public int getPicture() {
return picture;
}
public void setPicture(int picture) {
this.picture = picture;
}
public int getId() {
return id;
}
}

Custom listview implementation using checkboxes and buttons. Android

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

Categories

Resources