Custom ListView is not updated when items are inserted - java

I have a custom listview with custom adapter extending BaseAdapter if i add items to this list view in OnCreate method they show up in list, but if i add them from other methods like a packet listener method then items do not show up , on the screen below this listview there is a textbox if i select textbox to entertext using virtual keyboard immediately the listview gets populated with previousely inserted items which didnt show up. This activity is a chat window basically
I have tried calling notifyDataSetChanged, invalidate on Layout or on listview but nothing helped.
What i think is i need to have a way to refresh activity , as same thing must be happening when the virtual keyboard pops up .
Help will be highly appreciated
Thanks
Code:
package com.arounds;
public class ChatActivity extends Activity implements OnClickListener,PacketListener{
private ListView chatView;
private ChatListViewCustomAdapter adapter;
private String user;
private XMPPConnection connection;
private Conversation conv;
private ChatActivity selfRef = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_win);
AroundApplication app = (AroundApplication) this.getApplicationContext();
connection = app.getConnection();
chatView = (ListView) findViewById(R.id.conversationList);
adapter = new ChatListViewCustomAdapter(this);
chatView.setAdapter(adapter);
// set send btn listener
ImageButton send = (ImageButton)findViewById(R.id.imgBtnSend);
send.setOnClickListener(this);
ImageButton smiley = (ImageButton)findViewById(R.id.imgBtnSmiley);
smiley.setOnClickListener(this);
// get the parameter passed by previouse activity
Bundle b = this.getIntent().getExtras();
String temp = b.getString("user");
user = temp;
TextView v = (TextView)this.findViewById(R.id.txtViewTitle_chat);
v.setText(temp);
v = (TextView)this.findViewById(R.id.txtViewDescription_chat);
temp = b.getString("status");
v.setText(temp);
//chatView.setOnItemClickListener(this);
HashMap convs = app.getConversations();
if(convs.containsKey(user) == true)
conv = (Conversation) convs.get(user);
else {
conv = new Conversation();
convs.put(user,conv);
}
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(this,filter);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == R.id.imgBtnSend)
{
EditText msg = (EditText)this.findViewById(R.id.editChat);
String s = msg.getText().toString();
Message message = new Message(user, Message.Type.chat);
message.setBody(s);
connection.sendPacket(message);
ArrayList<ChatMessage> m = conv.messages;
String currentDate = DateFormat.getDateInstance().format(new Date());
m.add(new ChatMessage(s,currentDate));
adapter.addItem("I said",s,currentDate,Constants.SEND_LIST_TYPE);
//adapter.notifyDataSetChanged();
}
else
{
//View view = this.findViewById(R.id.linerLayoutChat);
chatView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
public void processPacket(Packet packet) {
// TODO Auto-generated method stub
System.out.println("in");
Message message = (Message) packet;
if (message.getBody() != null) {
System.out.println("in1");
String fromName = StringUtils.parseBareAddress(message.getFrom());
ArrayList<ChatMessage> m = conv.messages;
String currentDate = DateFormat.getDateInstance().format(new Date());
m.add(new ChatMessage(message.getBody(),currentDate));
adapter.addItem(fromName+" said",message.getBody(),currentDate,Constants.REC_LIST_TYPE);
//chatView.postInvalidate();
}
}
}
Adapter class:
public class ChatListViewCustomAdapter extends BaseAdapter
{
public ArrayList<ChatListItem> items;
public Activity context;
public LayoutInflater inflater;
public Boolean temp=false;
public ChatListViewCustomAdapter(Activity context) {
super();
this.context = context;
this.items = new ArrayList<ChatListItem>();
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
TextView txtViewTitle;
TextView txtViewDescription;
TextView txtViewDate;
}
public void addItem(String title,String desc,String d,int type)
{
ChatListItem item = new ChatListItem(title,desc,d,type);
items.add(item);
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ChatListItem item = items.get(position);
ViewHolder holder;
System.out.println("Title:"+item.title+" type:"+item.type);
if(convertView==null)
{
holder = new ViewHolder();
int type = this.getItemViewType(position);
if(type == 0)
{
convertView = inflater.inflate(R.layout.list_item_even, null);
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.txtViewTitleEven);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.txtViewDescriptionEven);
holder.txtViewDate = (TextView) convertView.findViewById(R.id.txtViewDateEven);
}
else
{
convertView = inflater.inflate(R.layout.list_item_odd, null);
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.txtViewTitleOdd);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.txtViewDescriptionOdd);
holder.txtViewDate = (TextView) convertView.findViewById(R.id.txtViewDateOdd);
}
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
holder.txtViewTitle.setText(item.title);
holder.txtViewDescription.setText(item.desc);
holder.txtViewDate.setText(item.date);
return convertView;
}
#Override
public int getItemViewType(int position) {
ChatListItem item = items.get(position);
return item.type;
}
#Override
public int getViewTypeCount() {
return 2;
}
}

Handle all the updates within your Adapter and ensure you invoke notifyDataSetChanged() after you update it (within your Adapter)?

In cases where notifyDataSetChanged() does not work, re-set the adapter on the ListView by calling ListView.setAdapter() with the same Adapter again. This should refresh the view.

the only thing I can see not right are these methods:
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
These methods should return proper values.
items.get(position) and position respectively.

Related

Order items in a Multi Values Listview in Android

I'm looking to some way for sort my items inside my listview. Which is a multi values Listview with 3 items for each row. I use a Custom ListViewAdapter to achieve this, but they are sorted in order of introduction inside the ArraysList. Something like:
1-2-3-4-5-6....
I want to inverse this order, having in top of my Listview the last item introduced:
6-5-4-3-2-1....
Here is my Custom ListViewAdapter:
public class ListViewAdapter extends BaseAdapter {
static class ViewHolder {
TextView number;
TextView elapsedTime;
TextView totalTime;
}
public static final String FIRST_COLUMN="First";
public static final String SECOND_COLUMN="Second";
public static final String THIRD_COLUMN="Third";
public ArrayList<HashMap<String, String>> list;
Activity activity;
public ListViewAdapter(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 position) {
// TODO Auto-generated method stub
return list.get(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
LayoutInflater inflater=activity.getLayoutInflater();
final ViewHolder viewHolder;
if(convertView == null){
convertView = inflater.inflate(R.layout.timer_row, null);
viewHolder = new ViewHolder();
viewHolder.number = (TextView) convertView.findViewById(R.id.number);
viewHolder.elapsedTime = (TextView) convertView.findViewById(R.id.elapsed_time);
viewHolder.totalTime =(TextView) convertView.findViewById(R.id.total_time);
convertView.setTag(viewHolder);
}
else{
viewHolder = (ViewHolder) convertView.getTag();
}
HashMap<String, String> map=list.get(position);
viewHolder.number.setText(map.get(FIRST_COLUMN));
viewHolder.elapsedTime.setText(map.get(SECOND_COLUMN));
viewHolder.totalTime.setText(map.get(THIRD_COLUMN));
return convertView;
}
}
And here is how I call it in my activity:
//ListView Adapter
mListviewLayout = (RelativeLayout)v.findViewById(R.id.listview_times_layout);
mTimesListview = (ListView)v.findViewById(R.id.times_listview);
mTimesArrayList = new ArrayList<HashMap<String,String>>();
mListViewAdapter= new ListViewAdapter(mActivity, mTimesArrayList);
mTimesListview.setAdapter(mListViewAdapter);
Finally, here is how I introduce items inside the Hashmap:
btnNextCicle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isTimerPaused()) {
onTimerStop();
} else {
mListviewLayout.setVisibility(View.VISIBLE);
mCiclesCounter++;
HashMap<String, String> newEntry = new HashMap<String, String>();
newEntry.put(ListViewAdapter.FIRST_COLUMN, "#" + mCiclesCounter);
newEntry.put(ListViewAdapter.SECOND_COLUMN, Util.getTimeForTimer(mElapsedCicleTime));
newEntry.put(ListViewAdapter.THIRD_COLUMN, Util.getTimeForTimer(mTimeInMilliseconds));
mCicleStartTime = SystemClock.elapsedRealtime();
mTimesArrayList.add(newEntry);
}
}
});
You can subclass HashMap<String, Sting> and make it implements Comparable. Then you can use Arrays.sort(yourComparable) to sort the array the way you want.

Fix Number Of Column And Row in Grid View

I am Listing all the Apps installed on device in Fragment which having gridview inside. what i want to do is, i want 4 col * 5 rows(20 App in one fragment only) , if i install new app (app count 21) it must set on the next fragment and set at the top left of new fragment , fragment should generate dynamically , and add to viewpager.
here is my code. MainActivity :
public class MainActivity extends FragmentActivity {
ViewPager pager;
AppViewAdapter adapter;
GridFrag gridFrag;
FragmentManager fragmentManager;
FragmentTransaction transaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindView();
init();
addListener();
}
private void bindView() {
pager = (ViewPager) findViewById(R.id.slideingpager);
}
private void init() {
adapter = new AppViewAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
}
}
GridFragment.java :
public class GridFrag extends android.support.v4.app.Fragment implements
OnItemClickListener {
GridView gridView;
ViewAdapter viewAdapter;
PackageManager packageManager;
int columnsOfGridView;
public class AppDetails {
Drawable icon;
String label;
}
AppDetails packages[];
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.gridfrag, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
packageManager = getActivity().getPackageManager();
gridView = (GridView) getActivity().findViewById(R.id.grid);
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> packList = packageManager.queryIntentActivities(
mainIntent, 0);
packages = new AppDetails[packList.size()];
for (int i = 0; i < packList.size(); i++) {
packages[i] = new AppDetails();
packages[i].icon = packList.get(i).loadIcon(packageManager);
packages[i].label = packList.get(i).loadLabel(packageManager)
.toString();
}
viewAdapter = new ViewAdapter(getActivity(), packages);
gridView.setAdapter(viewAdapter);
int totalApps = gridView.getCount();
Toast.makeText(getActivity(), "Total "+ totalApps + " App(s)Found",Toast.LENGTH_SHORT).show();
gridView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(),
"You Clicked on : " + packages[position].label,
Toast.LENGTH_SHORT).show();
}
}
ViewAdapter.java (GridAdapter)
public class ViewAdapter extends BaseAdapter {
private Context context;
AppDetails setPacksForAdapter[];
public ViewAdapter(Context c, AppDetails apps[]) {
context = c;
setPacksForAdapter = apps;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return setPacksForAdapter.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder {
ImageView imgDefaultAppIcon;
TextView tvDefaultAppLabel;
}
#Override
public View getView(int pos, View v, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder = new ViewHolder();
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.grid_view, null);
holder.imgDefaultAppIcon = (ImageView) v
.findViewById(R.id.ivAppIcon);
holder.tvDefaultAppLabel = (TextView) v
.findViewById(R.id.tvAppLabel);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imgDefaultAppIcon.setImageDrawable(setPacksForAdapter[pos].icon);
holder.tvDefaultAppLabel.setText(setPacksForAdapter[pos].label);
return v;
}
}
AppViewAdepter.java (For ViewPager)
public class AppViewAdapter extends FragmentPagerAdapter {
List<Fragment> fragmentsList;
public AppViewAdapter(FragmentManager fm) {
super(fm);
this.fragmentsList = new ArrayList<Fragment>();
for (int i = 0; i <= 2; i++) {
if (i % 2 == 0)
fragmentsList.add(new GridFrag());
else
fragmentsList.add(new FragTwo());
}
}
#Override
public Fragment getItem(int arg0) {
return fragmentsList.get(arg0);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return fragmentsList.size();
}
}
Set Layoutparams dynamically height of rootview of single grid in Adapter in getView() Method
(Device height / 5) - statusBarHieght
Some code : in getView() of Adapter
int grid_height = ((Helper.get_device_height(context)) / 5) - statusBarHeight;
GridView.LayoutParams layoutParams = (android.widget.AbsListView.LayoutParams) view.getLayoutParams();
layoutParams.height = grid_height;
view.setLayoutParams(layoutParams);
and,
gridview XML set columns=4
It will solve your problem.
Hope it will help you !
in your layout.xml by default <android:columnCount="auto_fit"> is set, you have to change it to as 4 by dong this <android:columnCount="4"> and to set rows similarly also in java you can do this like following setColumnCount(4) and setRowCount(5)

how to referesh listview after fixed interval of time?

I make demo in which I show data from webservice .Which is working fine .Mean I am able to display data on listview when I hit service first time.But I need hit server again and again and get new data .I am able to get new data .but I need to show new data on listview but my list become blank or empty when I got new data . why ?
here is my code .
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.departure_dashboard);
Log.d("=========onCreate", "constructor");
try {
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("Response");
Log.d("=========onCreate", message);
listView=(ListView)findViewById(R.id.listView1);
data = new Gson().fromJson(message, deparaturedaseboarddto.class);
adapter = new CustomListAdapter(this, data.getData());
listView.setAdapter(adapter);
timer =new Timer();
timer.scheduleAtFixedRate(new alertTask(), 0, 4000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
when Timer start I used alerk task.and call webservice again and again
public class alertTask extends TimerTask {
#Override
public void run() {
// TODO Auto-generated method stub
WebserviceMethod callDepartudeDashboard=new WebserviceMethod();
callDepartudeDashboard.setObserver(Departuredashboardscreen.this);
callDepartudeDashboard.getwebService(ConstantVariable.dashboardWebServiceURL+"a/"+"departuredashboard"+"?crsCode=hnh");
}
}
It is the method which give response again and again ...
#Override
public void getWebserviceResponse(String result) {
// TODO Auto-generated method stub
Log.d("timer", result);
data.getData().clear();
deparaturedaseboarddto localData = new Gson().fromJson(result, deparaturedaseboarddto.class);
data=localData
adapter.notifySetDataChanged();
}
here is my custom adapter for listview
public class CustomListAdapter extends BaseAdapter{
ArrayList<deparaturedaseboarddto> deparaturedaseboarddto;
private Context context;
public CustomListAdapter( Context context, ArrayList<deparaturedaseboarddto> deparaturedaseboarddto){
this.deparaturedaseboarddto=deparaturedaseboarddto;
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return deparaturedaseboarddto.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return deparaturedaseboarddto.get(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 = convertView;
if (v == null) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = mInflater.inflate(R.layout.row_listitem, null);
}
final TextView platFormName = (TextView) v
.findViewById(R.id.item_platform);
final TextView schDepart = (TextView) v
.findViewById(R.id.item_schDepart);
final TextView expDepart = (TextView) v
.findViewById(R.id.item_expectdepart);
final TextView arrival = (TextView) v
.findViewById(R.id.item_arrival);
final TextView exparrival = (TextView) v
.findViewById(R.id.item_expertarrival);
final TextView stationName = (TextView) v
.findViewById(R.id.item_stationName);
final String platformValue = deparaturedaseboarddto.get(position).getPlatformNo();
final String schDepartValue= deparaturedaseboarddto.get(position).getSchDepart();
final String schExpectValue= deparaturedaseboarddto.get(position).getExpDepart();
final String arrivalValue= deparaturedaseboarddto.get(position).getDestSchArrival();
final String exparrivalValue= deparaturedaseboarddto.get(position).getDestSchArrival();
String stationNameValue= deparaturedaseboarddto.get(position).getDestinationStation().getStationName();
platFormName.setText(platformValue);
schDepart.setText(schDepartValue);
expDepart.setText(schExpectValue);
arrival.setText(arrivalValue);
exparrival.setText(exparrivalValue);
stationName.setText(stationNameValue);
return v;
}
public void notifySetDataChanged() {
// TODO Auto-generated method stub
notifyDataSetChanged();
}
}
It is because your Adapter is still holding the old reference to the dataset which is emptied when you call data.getData().clear();
To clarify, when you first create your adapter,
adapter = new CustomListAdapter(this, data.getData());
You are passing an ArrayList, data.getData() to your adapter, and that is the ArrayList your Adapter will read data from.
Now, when you have received new data, you pointed data to localData, but your adapter is not aware of this.
#Override
public void getWebserviceResponse(String result) {
// TODO Auto-generated method stub
Log.d("timer", result);
data.getData().clear();
deparaturedaseboarddto localData = new Gson().fromJson(result,deparaturedaseboarddto.class);
data=localData;
adapter.notifySetDataChanged();
}
So instead of doing data = localData;, you should do data.addAll(localData.getData()); then call notifyDataSetChanged();
Basically you want to use one single ArrayList and just keep removing data from it and adding new data to it.

Can not identify the cause of Application crash

I have this following class which when runs and comes to a certain line in the class the application crashes. If i comment out that line the application runs well. When i look at the logcat i don't find any CausedBy Text. So can not figure out the cause of this crash. Someone please help me out to solve this.
public class Secondscreen extends Activity {
int total=0;
final ArrayList<Listitem> arrayList=new ArrayList<Listitem>();
BaseAdapter adapter =null;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondscreen);
ListView lv= (ListView) findViewById(R.id.listView1);
final TextView showtotal = (TextView) findViewById(R.id.totalprice);
final Button thirdBtn = (Button) findViewById(R.id.third);
final Controller aController = (Controller) getApplicationContext();
final int cartSize = aController.getCart().getCartSize();
//Addition of item to arraylist
if(cartSize >0)
{
for(int i=0;i<cartSize;i++)
{
String pName = aController.getCart().getProducts(i).getProductName();
int pPrice = aController.getCart().getProducts(i).getProductPrice();
int pQuantity = aController.getCart().getProducts(i).getProductQuantity();
String pDisc = aController.getCart().getProducts(i).getProductDesc();
total = total + pPrice;
Listitem item=new Listitem(pName, pPrice, pDisc, pQuantity);
Log.e("quantity", ""+pQuantity);
Log.e("Intem's quantity", ""+item.getQuantity());
arrayList.add(item);
Log.e("Arraylist item quantity", ""+arrayList.get(i).getQuantity());
}
showtotal.setText(""+total);
}
adapter= new BaseAdapter(){
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public View getView(final int position, View view, ViewGroup viewgroup) {
if (view == null) {
view=inflater.inflate(R.layout.pattern, null);
}
TextView tv=(TextView) view.findViewById(R.id.nameview);
TextView tv2=(TextView) view.findViewById(R.id.pdesc);
TextView tv3=(TextView) view.findViewById(R.id.priceView);
TextView tv4=(TextView) view.findViewById(R.id.quantityView);
Button btn=(Button) view.findViewById(R.id.patternButton);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int tempstore=arrayList.get(position).getPrice();
total=total-tempstore;
arrayList.remove(position);
showtotal.setText(""+total);
ModelProducts tempProductObject = aController.getProducts(position);
aController.getCart().removeProducts(tempProductObject);
adapter.notifyDataSetChanged();
int cartSize2 = aController.getCart().getCartSize();
}
});
tv.setText(arrayList.get(position).getName());
tv2.setText(""+arrayList.get(position).getPrice());
tv3.setText(arrayList.get(position).getDesc());
tv4.setText(arrayList.get(position).getQuantity()); //<-this is the line which when gets executed causes the application to crash.
return view;
}
};
lv.setAdapter(adapter);
}
}
yes getQuantity() returns an int value
So change this
tv4.setText(arrayList.get(position).getQuantity());
to
tv4.setText(String.valueOf(arrayList.get(position).getQuantity()));
What happens is setText(int) looks for a Resource with the int value if not found you end up getting ResourceNotFoundException
What you want is setText(CharacterSequence) so you need use String.valueof(intvalue)

How to access elements in a ListView when long clicked

I am working on an application that has a ListView of movies. The list is declared as an array in strings.xml. It has elements, Title, Gross and Date Released. When a row is long clicked, it brings up a context menu that allows the user to edit said row or delete it. When the user picks Edit, he/she is brought to a 2nd screen with 3 Edit Text corresponding to Title, Gross and Date. The EditText fields are initialized with the data from the clicked row. Here is my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] titleList = getResources().getStringArray(R.array.title_array);
String[] grossList = getResources().getStringArray(R.array.gross_array);
String[] dateList = getResources().getStringArray(R.array.date_array);
results = new ArrayList<Lab8_082588FetchDetails>();
for (int i = 0; i < titleList.length; i++) {
Lab8_082588FetchDetails sr = new Lab8_082588FetchDetails();
sr.setTitle(titleList[i]);
sr.setGross(grossList[i]);
sr.setDate(dateList[i]);
results.add(sr);
}
adapter = new SampleCustomAdapter(results);
setListAdapter(adapter);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
registerForContextMenu(lv);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
// places the contents of the XML to the menu
inflater.inflate(R.menu.context_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
switch (item.getItemId()) {
case R.id.delete:
results.remove(info.position);
adapter.notifyDataSetChanged();
return true;
case R.id.edit:
System.out.println(info.id);
System.out.println(info.position);
Intent newData = new Intent(Lab8_082588.this, Lab8_082588Edit.class);
results.get(info.position);
TextView movieTitle = (TextView) findViewById(R.id.title);
TextView movieGross = (TextView) findViewById(R.id.gross);
TextView movieDate = (TextView) findViewById(R.id.date);
String startTitle = movieTitle.getText().toString();
String startGross = movieGross.getText().toString();
String startDate = movieDate.getText().toString();
newData.putExtra(Lab8_082588Edit.TITLE_STRING, startTitle);
newData.putExtra(Lab8_082588Edit.GROSS_STRING, startGross);
newData.putExtra(Lab8_082588Edit.DATE_STRING, startDate);
startActivityForResult(newData, Lab8_082588.EDIT_MOVIE);
return true;
default:
return super.onContextItemSelected(item);
}
}
For the Edit screen:
public class Lab8_082588Edit extends Activity {
public static final String TITLE_STRING = "TITLE_STRING";
public static final String GROSS_STRING = "GROSS_STRING";
public static final String DATE_STRING = "DATE_STRING";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addedit);
initialize();
}
private void initialize() {
// TODO Auto-generated method stub
Intent prepopulate = getIntent();
EditText movieTitle = (EditText) findViewById(R.id.etTitle);
EditText movieGross = (EditText) findViewById(R.id.etGross);
EditText movieDate = (EditText) findViewById(R.id.etDate);
String startTitle = prepopulate.getStringExtra(Lab8_082588Edit.TITLE_STRING);
String startGross = prepopulate.getStringExtra(Lab8_082588Edit.GROSS_STRING);
String startDate = prepopulate.getStringExtra(Lab8_082588Edit.DATE_STRING);
movieTitle.setText(startTitle);
movieGross.setText(startGross.replaceAll(",", "").replace("$", ""));
movieDate.setText(startDate);
}
My FetchDetails class
public class Lab8_082588FetchDetails implements Comparable<Lab8_082588FetchDetails> {
private String title;
private String gross;
private String date;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getGross() {
return gross;
}
public void setGross(String gross) {
this.gross = gross;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
#Override
public int compareTo(Lab8_082588FetchDetails another) {
// TODO Auto-generated method stub
return title.compareTo(another.title);
}
}
My Adapter:
private class SampleCustomAdapter extends BaseAdapter {
public SampleCustomAdapter(ArrayList<Lab8_082588FetchDetails> movies) {
internalList = movies;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return internalList.size();
}
#Override
public Object getItem(int index) {
// TODO Auto-generated method stub
return internalList.get(index);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View view;
if (convertView == null) {
view = inflater.inflate(R.layout.row, null);
} else {
view = convertView;
}
// extract the views to be populated
TextView title = (TextView) view.findViewById(R.id.title);
TextView gross = (TextView) view.findViewById(R.id.gross);
TextView date = (TextView) view.findViewById(R.id.date);
// extract the object that will fill these
Lab8_082588FetchDetails movie = internalList.get(position);
title.setText(movie.getTitle());
date.setText(movie.getDate());
gross.setText(movie.getGross());
// return the view
return view;
}
}
My problem is that, indeed, the Edit Texts get populated, but only with the data from the first item in the entire list (e.g. Titanic is first on the list, and is the only one being populated). Even if I click the nth row movie in the listview, Titanic is still the one being retrieved. How do I solve this?
Edit: I realize that somehow, the code is only considering the first element of the list. How do I access the elements of the other rows?
I realize that somehow, the code is only considering the first
element of the list. How do I access the elements of the other rows?
You should never do a search with findViewById for items which are in a ListView row. In the onContextItemSelected callback you have the position of the element clicked so you could use it to get the data associated with this row:
case R.id.edit:
Intent newData = new Intent(Lab8_082588.this, Lab8_082588Edit.class);
// I hope you implemented the adapter correctly
Lab8_082588FetchDetails item = (Lab8_082588FetchDetails) getListView().getItemAtPosition(info.position);
String startTitle = item.getTitle();
String startGross = item.getGross();
String startDate = item.getDate();
newData.putExtra(Lab8_082588Edit.TITLE_STRING, startTitle);
newData.putExtra(Lab8_082588Edit.GROSS_STRING, startGross);
newData.putExtra(Lab8_082588Edit.DATE_STRING, startDate);
startActivityForResult(newData, Lab8_082588.EDIT_MOVIE);
return true;

Categories

Resources