My ListView won't refresh after I key in new data. It will only refresh if I change tabs. I put in notifyDataSetChange() but it still doesn't work. Help!
public class Tab4 extends Fragment {
TextView title;
TextView DateTitle;
TextView AmountTitle;
TextView DescTitle;
ListView ExpensesList;
List<Expenses> Expenses;
Expenses expenses;
ExpensesListAdapter adapter;
Toast mToast;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.tab4, container, false);
title = (TextView) rootView.findViewById(R.id.Title);
DateTitle = (TextView) rootView.findViewById(R.id.DateTitle);
AmountTitle = (TextView) rootView.findViewById(R.id.AmountTitle);
DescTitle = (TextView) rootView.findViewById(R.id.DescTitle);
ExpensesList = (ListView) rootView.findViewById(R.id.ExpensesList);
Expenses = new ArrayList<Expenses>();
expenses = new Expenses();
mToast = Toast.makeText(getActivity().getApplicationContext(), "",
Toast.LENGTH_SHORT);
ExpensesList.setAdapter(adapter);
adapter = new ExpensesListAdapter(
getActivity().getApplicationContext(), Expenses);
if (expenses.getAllExpenses().size() == 0) {
title.setText("Total number of record is 0");
DateTitle.setVisibility(View.GONE);
AmountTitle.setVisibility(View.GONE);
DescTitle.setVisibility(View.GONE);
} else {
for (int i = 0; i < expenses.getAllExpenses().size(); i++) {
Expenses.add(expenses.getAllExpenses().get(i));
System.out.println("Expenses are "
+ expenses.getAllExpenses().get(i));
adapter.notifyDataSetChanged();
ExpensesList.invalidateViews();
}
title.setText("Total number of record is "
+ expenses.getAllExpenses().size());
}
ExpensesList.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
final int position, long id) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity());
builder.setMessage("ARE YOU SURE YOU WANT TO DELETE THIS RECORD?");
builder.setCancelable(false);
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
expenses = new Expenses();
expenses = expenses.getAllExpenses().get(
position);
expenses.delete();
Expenses.remove(position);
adapter.notifyDataSetChanged();
title.setText("Total number of record is "
+ expenses.getAllExpenses().size());
mToast.setText("Record has been deleted");
mToast.show();
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
builder.show();
return false;
}
});
return rootView;
}
}
class ExpensesListAdapter extends BaseAdapter {
List<Expenses> Expenses;
Context context;
LayoutInflater inflater;
public ExpensesListAdapter(Context context, List<Expenses> Expenses) {
this.context = context;
this.Expenses = Expenses;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return Expenses.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView Date;
TextView Amount;
TextView Desc;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder = new Holder();
convertView = inflater.inflate(R.layout.listview_expenseslist, null);
holder.Date = (TextView) convertView.findViewById(R.id.ExpensesDate);
holder.Amount = (TextView) convertView
.findViewById(R.id.ExpensesAmount);
holder.Desc = (TextView) convertView.findViewById(R.id.ExpensesDesc);
holder.Date.setText(Expenses.get(position).Date);
holder.Amount.setText(String.valueOf(Expenses.get(position).Amount));
holder.Desc.setText(Expenses.get(position).Desc);
return convertView;
}
}
My listview won't refresh after i key in new data. It will only
refresh if i change tabs.
Becuase currently adding new data in Expenses ArrayList.
To update new item in ListView Adapter, need to add item in data-sorcude which is used inside adapter for getting data and getCount` method.
To achive same create a method in ExpensesListAdapter :
public void addAllItem(List<Expenses> strItem){
this.Expenses.addAll(strItem);
this.notifyDataSetChanged();
}
Now call addNewItem method to add new item when AlertDialog positive button click :
adapter.addNewItem(expenses.getAllExpenses());
Related
i have two custom GridView, I want to set Onclick Listener for first GridView, i did it inside its adapter , working fine ... but when generate items in second GridView the onclick listener read values from second GridView when i press on item in first GridView!
The onclick listener working fine if the second GridView empty
I have no idea how to fix this
The problem with holder.tvgroup1 and holder.tvgroup_delete_icon
Thanks
First GridView Adapter
public class GroupGeneratedAdapter extends BaseAdapter {
ArrayList<String> result;
Context context;
int[] imageId;
private static LayoutInflater inflater = null;
GroupGeneratedAdapter(GroupMakerG groupMakerG, ArrayList<String> UserNameinput) {
// TODO Auto-generated constructor stub
result = UserNameinput;
context = groupMakerG;
// imageId=prgmImages;
inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView tvgroup, tvgroup1;
ImageView tvgroup_delete_icon;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder = new Holder();
// View rowView;
if (convertView == null) {
convertView = inflater.inflate(R.layout.group_generated_original, parent, false);
}
holder.tvgroup = (TextView) convertView.findViewById(R.id.tvgroup);
holder.tvgroup1 = (TextView) convertView.findViewById(R.id.tvgroup1);
holder.tvgroup_delete_icon = (ImageView) convertView.findViewById(R.id.tvgroup_delete_icon);
// holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
holder.tvgroup.setText(String.valueOf(position + 1) + "-");
holder.tvgroup1.setText(result.get(position));
// holder.img.setImageResource(imageId[position]);
holder.tvgroup_delete_icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GroupMakerG.GroupOfNames.remove(position);
GroupMakerG.MainGroup.invalidateViews();
if (GroupMakerG.arraySugestion.size() > 0) {
GroupMakerG.arraySugestion.clear();
GroupMakerG.makeSuggestions();
} else {
GroupMakerG.makeSuggestions();
}
GroupMakerG.GeneratedGroup.setAdapter(null);
GroupMakerG.No_Of_Groups.setText("");
GroupMakerG.numoftries = 0;
GroupMakerG.Group_num_tries.setText("0");
GroupMakerG.GroupNameLength.setText(String.valueOf(GroupMakerG.GroupOfNames.size()));
}
});
holder.tvgroup1.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(context );
builder.setTitle("Modify Item No." + " " + (position + 1));
// I'm using fragment here so I'm using getView() to provide ViewGroup
// but you can provide here any other instance of ViewGroup from your Fragment / Activity
View viewInflated = LayoutInflater.from(context).inflate(R.layout.modify_name_mainlist, (ViewGroup) parent.findViewById(android.R.id.content), false);
// Set up the input
final EditText input = (EditText) viewInflated.findViewById(R.id.client_name_input);
input.setText(GroupMakerG.GroupOfNames.get(position));
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
builder.setView(viewInflated);
// Set up the buttons
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
String m_Text = input.getText().toString();
if (m_Text.trim().equals("")) {
// Toast.makeText(context, "You should enter name", Toast.LENGTH_SHORT).show();
Toast toast = Toast.makeText(context,context.getString(R.string.group_you_should_enter_name), Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
} else {
GroupMakerG.GroupOfNames.set(position, m_Text);
GroupMakerG.MainGroup.invalidateViews();
GroupMakerG.GeneratedGroup.setAdapter(null);
GroupMakerG.numoftries = 0;
GroupMakerG.Group_num_tries.setText("0");
Toast toast = Toast.makeText(context, context.getString(R.string.group_item_changed), Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
return false;
}
});
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(context, "You Clicked "+ result.get(position), Toast.LENGTH_LONG).show();
}
});
return convertView;
}
}
Second GridView Adapter
public class GroupGeneratedAdapterG extends BaseAdapter {
private ArrayList<String> resultg;
int[] imageId;
private static LayoutInflater inflaterg = null;
private static int generated_group_counter;
Context contextg;
GroupGeneratedAdapterG(GroupMakerG groupMaker, ArrayList<String> UserNameoutput) {
// TODO Auto-generated constructor stub
resultg = UserNameoutput;
contextg = groupMaker;
// imageId=prgmImages;
inflaterg = (LayoutInflater) contextg.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
generated_group_counter = 0;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return resultg.size();
}
#Override
public Object getItem(int positiong) {
// TODO Auto-generated method stub
return positiong;
}
#Override
public long getItemId(int positiong) {
// TODO Auto-generated method stub
return positiong;
}
public class Holder {
TextView tvgroupg, tvgroup1g;
// ImageView img;
}
#Override
public View getView(final int positiong, View convertViewg, ViewGroup parentg) {
// TODO Auto-generated method stub
generated_group_counter = generated_group_counter + 1;
Holder holderg = new Holder();
// View rowView;
if (convertViewg == null) {
convertViewg = inflaterg.inflate(R.layout.group_generated_generated, parentg, false);
}
holderg.tvgroupg = (TextView) convertViewg.findViewById(R.id.tvgroupg);
holderg.tvgroup1g = (TextView) convertViewg.findViewById(R.id.tvgroup1g);
// holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
String[] ary = resultg.get(positiong).split("!##%");
if (ary[1].length() > 4) {
if (ary[1].substring(0, 5).equals("Group")) {
holderg.tvgroupg.setText("");
holderg.tvgroup1g.setText(ary[1]);
} else {
holderg.tvgroupg.setText(ary[0]);
holderg.tvgroup1g.setText(ary[1]);
}
} else {
holderg.tvgroupg.setText(ary[0]);
holderg.tvgroup1g.setText(ary[1]);
}
convertViewg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(contextg, "You Clicked "+ String.valueOf(resultg.get(positiong)), Toast.LENGTH_LONG).show();
}
});
return convertViewg;
}
}
I am developing a application which fetches some data from a web service and displays in a list view. I have implemented a custom adapter which is extended by BaseAdapter. In the getView() method I inflate the raw also.. Those are working perfectly.
My problem is I have implemented code to show a dialog box when user click on an list item, but now I want to show another dialog box which has a custom list inside it (when Yes button clicked). I also want to show some data in that listview. [I have a ArrayList filled with the data that I wanted] . I'm writing the code inside my adapter class. Can anyone give me some idea how to do it ?
This is my code:
public class NewsRowAdapter extends BaseAdapter {
private Context mContext;
private Activity activity;
private static LayoutInflater inflater=null;
private ArrayList<HashMap<String, String>> data;
int resource;
//String response;
//Context context;
//Initialize adapter
public NewsRowAdapter(Context ctx,Activity act, int resource,ArrayList<HashMap<String, String>> d) {
super();
this.resource=resource;
this.data = d;
this.activity = act;
this.mContext = ctx;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void dialogshow(final String Date,final String Start,final String End){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
alertDialogBuilder.setTitle("Confirm your Action!");
// set dialog message
alertDialogBuilder
.setMessage("Click yes to exit!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
//MainActivity.this.finish();
// Toast.makeText(mContext, "Yes clicked", Toast.LENGTH_LONG).show();
//check similer records
// ShortList sh = new ShortList();
// ArrayList<HashMap<String, String>> duplicateList;
// duplicateList=sh.getDuplicated(Date, Start, End);
//if duplicates > 1 then show the popup list
// if(duplicateList.size()>1){
AlertDialog.Builder alertDialogBuilder2 = new AlertDialog.Builder(activity);
LayoutInflater infl = activity.getLayoutInflater();
//View vi = infl.inflate(id, root)
alertDialogBuilder2.setView(infl.inflate(R.layout.dialog_row, null))
.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "Accepted", Toast.LENGTH_LONG).show();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
alertDialogBuilder2.show();
// }
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
alertDialogBuilder.show();
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View vi = convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.row,null);
final TextView firstname = (TextView) vi.findViewById(R.id.fname);
final TextView lastname = (TextView) vi.findViewById(R.id.lname);
final TextView startTime = (TextView) vi.findViewById(R.id.stime);
final TextView endTime = (TextView) vi.findViewById(R.id.etime);
final TextView date = (TextView) vi.findViewById(R.id.blank);
final ImageView img = (ImageView) vi.findViewById(R.id.list_image);
HashMap<String, String> song = new HashMap<String, String>();
song =data.get(position);
firstname.setText(song.get(MainActivity.TAG_PROP_FNAME));
lastname.setText(song.get(MainActivity.TAG_PROP_LNAME));
startTime.setText(song.get(MainActivity.TAG_STIME));
endTime.setText(song.get(MainActivity.TAG_ETIME));
date.setText(song.get(MainActivity.TAG_DATE));
//imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), img);
Button accept = (Button) vi.findViewById(R.id.button1);
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final int x = (int) getItemId(position);
/*Intent zoom=new Intent(mContext, Profile.class);
zoom.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
zoom.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(zoom);*/
// get the intent from the hashmap check if there is similar date and time.
//then store them in a list or array.
String getDate = (String) date.getText();
String getStartTime = startTime.getText().toString();
String getEndTime = endTime.getText().toString();
dialogshow(getDate,getStartTime,getEndTime);
}
});
vi.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String getFname = firstname.getText().toString();
Toast.makeText(parent.getContext(), "view clicked: "+getFname , Toast.LENGTH_SHORT).show();
//get the id of the view
//check the id of the request
//call the web service acording to the id
Intent zoom=new Intent(parent.getContext(), Profile.class);
parent.getContext().startActivity(zoom);
}
});
return vi;
}
You are on the right track, Here is what i used to dynamically display a Dialog with a list of items in it.
For reference a similar Question was asked here : Android custom list dialog
//String[] list_data; Preloaded with a String array
final CharSequence[] items = new CharSequence[list_data.length];
for (int i = 0; i < list_data.length; i++) {
items[i] = list_data[i];
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select the data you want");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Get the id of the item
diag_callback();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void diag_callback() {
//Do someting when the user has made his selection
}
Hope this sorts out your problem.
For your concern I hope that you know creating customized list view.
Fallow undermentioned code that contains customized dialog with customized list view. I hope you can perform Adapter and model part by your's
final Dialog new_dialog = new Dialog(getParent());
new_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
new_dialog.setContentView(R.layout.customize_dialog_list_view);
new_dialog.setCancelable(false);
cuc = new CommanUtilityClass();
SharedPreferences sp = getSharedPreferences("provider",0);
String services = sp.getString("services","");
Log.i("Servicesss",bAllServices);
TextView service = (TextView) new_dialog.findViewById(R.id.cdlv_service_provider);
TextView hour = (TextView) new_dialog.findViewById(R.id.cdlv_working_hours);
TextView appointment_time = (TextView) new_dialog.findViewById(R.id.cdlv_appoint_time);
TextView appointment_date = (TextView) new_dialog.findViewById(R.id.cdlv_appoint_date);
String[] ampm = myTiming[which].split(":");
Log.d("xxxooo", ampm[0]);
appointment_time.setText(Html.fromHtml("<b>Appointment time :</b>" + myTimingToShow[which].split("/")[0]));
appointment_date.setText(Html.fromHtml("<b>Appointment date :</b>" + selected));
service.setText(Html.fromHtml("<b>Service provider :</b>"+ cuc.toTheUpperCase(bsp_name)));
hour.setText(Html.fromHtml("<b>Working hours :</b>"+ cuc.toTheUpperCase(bsp_availability)));
lv = (ListView) new_dialog.findViewById(R.id.cdlv_list);
CustomDialogArrayAdapter cdaa = new CustomDialogArrayAdapter(getApplicationContext(),m_ArrayList);
lv.setAdapter(cdaa);
new_dialog.show();
ImageButton btn_cdlv_cancel = (ImageButton) new_dialog.findViewById(R.id.cdlv_cancel);
btn_cdlv_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new_dialog.dismiss();
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(
AdapterView<?> arg0,
View arg1,
int arg2,
long arg3) {
Log.d("checkforbookedslots", booked_slots);
final_time_selected = myTiming[which];
String final_duration = m_ArrayList.get(arg2).provider_service_duration;
Log.d("adiadicheck", check_for_booking_list);
if (checkOverlapSlot(final_time_selected,final_duration)) {
Log.d("gp","seven12aa");
SharedPreferences sp = getSharedPreferences("booking_detail",0);
SharedPreferences.Editor editor = sp.edit();
editor.putString("provider_service",m_ArrayList.get(arg2).provider_service);
editor.putString("provider_service_duration",m_ArrayList.get(arg2).provider_service_duration);
editor.putString("provider_service_price",m_ArrayList.get(arg2).provider_service_price);
editor.putString("service_id",m_ArrayList.get(arg2).provider_service_id);
editor.commit();
SessionManagement sm = new SessionManagement(getParent());
// sm.checkLogin();
if (sm.isLoggedIn()) {
Log.d("viv2","1");
Intent edit = new Intent(SelectedService.this,UserLoggedActivity.class);
TabGroupActivity parentActivity = (TabGroupActivity) getParent();
parentActivity.startChildActivity("UserLoggedActivity",edit);
} else {
Log.d("viv2","2");
Intent edit = new Intent(SelectedService.this,UserNoLoggedActivity.class);
TabGroupActivity parentActivity = (TabGroupActivity) getParent();
parentActivity.startChildActivity("UserNoLoggedActivity",edit);
}
new_dialog.dismiss();
}
}
});
CUSTOM DIALOG BOX WITH CUSTOM LISTVIEW :::
public class MainActivity extends Activity {
private Button btnOpenDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<String> strArrlst = new ArrayList<String>();
for (int i = 0; i < 15; i++) {
strArrlst.add("Number: " + i);
}
btnOpenDialog = (Button) findViewById(R.id.btn_open_dialog);
btnOpenDialog.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("Dialog box is btn click", "");
final Dialog dialog = new Dialog(MainActivity.this);
Toast.makeText(getApplicationContext(), "btn is click", Toast.LENGTH_SHORT).show();
// tell the Dialog to use the dialog.xml as it's layout
// description
dialog.setContentView(R.layout.custom_dailog_box);
dialog.setTitle("Android Custom Dialog Box");
TextView txt = (TextView) dialog.findViewById(R.id.txt);
txt.setText("This is an Android custom Dialog Box Example! Enjoy!");
ListView dialogLIst = (ListView) dialog.findViewById(R.id.lstvw_open_custom_dialog);
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1, android.R.id.text1,
// values);
// dialogLIst.setAdapter(adapter);
AdapterListC adapListC = new AdapterListC(getApplicationContext(), strArrlst);
dialogLIst.setAdapter(adapListC);
dialogLIst.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
dialog.dismiss();
Toast.makeText(getApplicationContext(), "This is click position is" + position, Toast.LENGTH_SHORT).show();
}
});
dialog.show();
}
});
}
#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 CLASS:::
public class AdapterListC extends BaseAdapter {
public AdapterListC(Context context_, ArrayList<String> arrlstString) {
super();
this.context_ = context_;
this.arrlstString = arrlstString;
mInflater = (LayoutInflater) context_.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
Context context_;
ArrayList<String> arrlstString;
private LayoutInflater mInflater;
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrlstString.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrlstString.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Viewolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listitem, null);
holder = new Viewolder();
holder.txtName = (TextView) convertView.findViewById(R.id.txt_listitem);
convertView.setTag(holder);
} else {
holder = (Viewolder) convertView.getTag();
}
holder.txtName.setText(arrlstString.get(position).toString());
return convertView;
}
class Viewolder {
TextView txtName;
}
}
I have a custom baseadapter that creates comment boxes. Everything works great on it until I want to add data. When I try to add the data it deletes the previous data and adds the new data. How do I make it so it keeps all the data? Is my Add method incorrect? Here is my baseadapter,
class CreateCommentLists extends BaseAdapter{
Context ctx_invitation;
String[] listComments;
String[] listNumbers;
String[] listUsernames;
public CreateCommentLists(String[] comments, String[] usernames, String[] numbers, DashboardActivity context)
{
super();
ctx_invitation = context;
listComments = comments;
listNumbers = usernames;
listUsernames = numbers;
}
#Override
public int getCount() {
if(null == listComments)
{
return 0;
}
// TODO Auto-generated method stub
return listComments.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listComments[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
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
usernameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("usernameOfProfile",listUsernames[position]);
startActivity(i);
finish();
}
});
numberButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("NumberProfile",listNumbers[position]);
startActivity(i);
finish();
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
public void add(String[] comments, String[] usernames,
String[] numbers) {
listComments = comments;
listNumbers = usernames;
listUsernames = numbers;
}
public int getCount1() {
if(null == listComments)
{
return 0;
}
// TODO Auto-generated method stub
return listComments.length;
}
public Object getItem1(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
public long getItemId1(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView1(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
usernameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("usernameOfProfile",listUsernames[position]);
startActivity(i);
finish();
}
});
numberButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("NumberProfile",listNumbers[position]);
startActivity(i);
finish();
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
}
Setting the adapter:
final CreateCommentLists mycmlist = new CreateCommentLists(comments, usernames, numbers, DashboardActivity.this);
lstComments = (ListView)findViewById(android.R.id.list);
lstComments.setAdapter(mycmlist);
This is what how I call the add method,
mycmlist.add(comments,usernames,numbers);
mycmlist.notifyDataSetChanged();
In your add method you're setting the arrays to new values listComments = comments; That's replacing your old data with the new data.
You could use System.arrayCopy() to resize your listArrays to the new size and append the new items. A much less tedious approach, however, would be to store your arrays as List<String>, allowing you to add more items without worrying about resizing lists.
The result would look something like this...
public class CommentsAdapter extends BaseAdapter
{
private LayoutInflater inflater;
private List<String> comments;
private List<String> numbers;
private List<String> usernames;
public CommentsAdapter(Context context)
{
inflater = LayoutInflater.from(context);
comments = new ArrayList<String>();
numbers = new ArrayList<String>();
usernames = new ArrayList<String>();
}
public void add(String[] comments, String[] numbers, String[] usernames)
{
this.comments.addAll(Arrays.asList(comments));
this.numbers.addAll(Arrays.asList(numbers));
this.usernames.addAll(Arrays.asList(usernames));
notifyDataSetChanged();
}
#Override
public int getCount()
{
if (comments == null)
return 0;
return comments.size();
}
#Override
public String getItem(int position)
{
return comments.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
convertView = inflater.inflate(R.layout.list_item, parent, false);
convertView.setTag(new ViewHolder(convertView));
}
ViewHolder holder = (ViewHolder) convertView.getTag();
holder.commentView.setText(comments.get(position));
//Other view bind logic here...
return convertView;
}
private static class ViewHolder
{
public TextView commentView;
public TextView numbersView;
public TextView usernamesView;
public Button usernameButton;
public Button numberButton;
public ViewHolder(View v)
{
commentView = (TextView) v.findViewById(R.id.listComment);
numbersView = (TextView) v.findViewById(R.id.listNumber);
usernamesView = (TextView) v.findViewById(R.id.listPostedBy);
usernameButton = (Button) v.findViewById(R.id.listUsernameButton);
numberButton = (Button) v.findViewById(R.id.listNumberButton);
}
}
}
I also highly recommend reading this page on the Android Developer's site: http://developer.android.com/training/improving-layouts/smooth-scrolling.html
Your current adapter implementation is very inefficient, and that page should help you iron out some kinks.
You probably need to add the String[] array to the existing one, instead of replacing it.
Add this function which joins two arrays (Sadly there is no already-implemented method for Java):
String[] concat(String[] A, String[] B) {
String[] C= new String[A.length + B.length];
System.arraycopy(A, 0, C, 0, A.length);
System.arraycopy(B, 0, C, A.length, B.length);
return C;
}
Credits: Sun Forum
And then change the add method to this:
public void add(String[] comments, String[] usernames,
String[] numbers) {
listComments = concat(listComments, comments);
listUsernames = concat(listUsernames, usernames);
listNumbers = concat(listNumbers, numbers);
}
And you had a typo in your code. In the add method, the listUsernames and listNumbers should be swapped I think.. I fixed it for you.
I have a ListView Item that has 2 buttons in it. There are multiple ListView items so there are many buttons. How can I assign a different value to each button? What I want to happen is every button leads to the same activity, but when it goes to the new activity it sends a value that the button was assigned. Then the activity can handled the value. I want the values assigned to the buttons to be the same as what the text is set to, here is my baseAdapter
class CreateCommentLists extends BaseAdapter{
Context ctx_invitation;
String[] listComments;
String[] listNumbers;
String[] listUsernames;
public CreateCommentLists(String[] comments, String[] usernames, String[] numbers, DashboardActivity context)
{
super();
ctx_invitation = context;
listComments = comments;
listNumbers = usernames;
listUsernames = numbers;
}
#Override
public int getCount() {
if(null == listComments)
{
return 0;
}
// TODO Auto-generated method stub
return listComments.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
usernameButton.setText("Go to " + listUsernames[position]);
numberButton.setText("Go to " + listNumbers[position]);
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
}
usernameButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
intent.putExtra("param", listUsernames[position]);
startActivity(intent);
}
});
}
I have a list view with multi columns... Want to change the background color of a row item that is selected or clicked. Have referred to various articles on stackoverflow but they dont seem to help...What i ve done in OnItemClick is .setBackgroundColor. Cannot use the selector as would want to remember the color change in the sense the row that I have changed color for, when the application relaunches should remember the change...I put the flag value in database and can set the color in getView but how to do it for first time? Here is the code.....
public class AdminMultiColumn extends Activity
{
private ArrayList<HashMap<String,String>> list;
ArrayList<String> al;
AlertDialog.Builder alertDialogBuilder;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.admin_checkoutlist);
lview = (ListView)findViewById(R.id.admin_list);
populateList();
Admin_checkoutlist adapter = new Admin_checkoutlist(this,list);
lview.setAdapter(adapter);
}
private void populateList() {
list = new ArrayList<HashMap<String,String>>();
al = new ArrayList<String>();
testday = c.get(Calendar.DAY_OF_MONTH);
testmonth = c.get(Calendar.MONTH)+1;
testyear = c.get(Calendar.YEAR);
dateget = testday+"-"+testmonth+"-"+testyear;
mdb.open();
va.open();
Cursor c1 = va.getNameTimeinTimeout(dateget);
DatabaseUtils.dumpCursor(c1);
if(c1.moveToFirst())
{
do{
idfromdb = c1.getString(0);
al.add(idfromdb);
namefromdb = c1.getString(1);
al.add(namefromdb);
timefromdb = c1.getString(2);
al.add(timefromdb);
timeoutfromdb = c1.getString(3);
al.add(timeoutfromdb);
}while(c1.moveToNext());
}
c1.close();
va.close();
mdb.close();
Log.d("pavan","data retrived "+namefromdb+" "+timeoutfromdb+" "+timefromdb+" "+idfromdb);
for(int i = 0;i<al.size();i=i+4)
{
temp = new HashMap<String,String>();
temp.put(FIRST_COLUMN, al.get(i));
temp.put(SECOND_COLUMN, al.get(i+1));
temp.put(THIRD_COLUMN, al.get(i+2));
temp.put(FOURTH_COLUMN, al.get(i+3));
Log.d("pavan","test here for admin");
list.add(temp);
}
}
//adapter class goes here////////////
public class Admin_checkoutlist extends BaseAdapter implements OnItemClickListener
{
public ArrayList<HashMap<String,String>> list;
Activity activity;
public Admin_checkoutlist(Activity activity, ArrayList<HashMap<String,String>> list)
{
super();
this.activity = activity;
this.list = list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int pos) {
// TODO Auto-generated method stub
return list.get(pos);
}
#Override
public long getItemId(int pos) {
// TODO Auto-generated method stub
return 0;
}
public class ViewHolder
{
TextView txtFirst;
TextView txtSecond;
TextView txtThird;
TextView txtFOURTH;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.temp, null);
holder = new ViewHolder();
holder.txtFirst = (TextView)convertView.findViewById(R.id.uid);
holder.txtSecond = (TextView)convertView.findViewById(R.id.nametext);
holder.txtThird = (TextView)convertView.findViewById(R.id.checkintext);
holder.txtFOURTH = (TextView)convertView.findViewById(R.id.checkouttext);
convertView.setTag(holder);
lview.setOnItemClickListener(this);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
HashMap<String, String> map = list.get(position);
holder.txtFirst.setText(map.get(FIRST_COLUMN));
holder.txtSecond.setText(map.get(SECOND_COLUMN));
holder.txtThird.setText(map.get(THIRD_COLUMN));
holder.txtFOURTH.setText(map.get(FOURTH_COLUMN));
return convertView;
}//getview ends here.
#Override
public void onItemClick(final AdapterView<?> parent, final View view, int pos,
long id) {
// TODO Auto-generated method stub
Object listItem = parent.getFirstVisiblePosition()+pos+1;
//lview.getChildAt(pos).setBackgroundColor(R.color.blue);
view.setBackgroundColor(pos);
idtosend = listItem.toString();
Log.d("pavan","id is"+idtosend);
/////alert displaing block starts here////////////////////////////////
alertDialogBuilder = new AlertDialog.Builder(AdminMultiColumn.this);
alertDialogBuilder.setTitle("Alert");
alertDialogBuilder
.setMessage("Check out now")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
Toast.makeText(getApplicationContext(), "Checkout successfull", Toast.LENGTH_LONG).show();
testhour = c.get(Calendar.HOUR_OF_DAY);
testmin = c.get(Calendar.MINUTE);
testsec = c.get(Calendar.SECOND);
timings = testhour+":"+testmin+":"+testsec;
mdb.open();
va.open();
va.upDate(idtosend,timings);
Toast.makeText(getApplicationContext(), "update the checkout options "+timings, Toast.LENGTH_SHORT).show();
va.close();
mdb.close();
/*Intent go = new Intent(AdminMultiColumn.this,MultiColumn.class);
startActivity(go);*/
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
///////alert displaing block ends here//////////////////////////////////
}
}
}
What I have done now is within the getView method, taking the convertView and setting the background resource to a color, that too is not working...below is the code...
if(holder.txtFOURTH!=null)
{
convertView.setBackgroundColor(R.drawable.image_border);
}
else
{
Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_SHORT).show();
}
There two points -
pos is not a good option as color
Instead of view.setBackgroundColor(pos); sue
LinearLayout row = (LinearLayout)view.findViewById(R.id.list_row);
if(null!=row){
//<listAdapter>.notifyDataSetChanged();
row.setBackgroundResource(R.drawable.);
}
assuming the your list row has LinearLayout in root having id "list_row", chage this as per your layout.
but there will be problem this as when you click on the second row it also be selected stated and better to call list.notifydatasetchaged there are few more option look over them, may fill your requirement
android-selected-state-listview-example
android-how-do-i-highlight-a-row-in-listview
highlighting-the-selected-item-in-the-listview-in-android