getView() is not working as i supposed - android

I am going to develop a APP where i am using customize alert dialog. Data have come from database to this alert-dialog.
menu_to_showdialogCursor = dh.rawQuery("SELECT _id ,item_name,Item_cost FROM order_customer WHERE item_name LIKE ? AND Item_cost LIKE ?", new String[]{"%","%"});
OrderListAdapter orderAdapter = new OrderListAdapter(MainScreen.this,menu_to_showdialogCursor );
orderList.setAdapter(orderAdapter);
ABove line is calling my Adapter class.Now i ma going to show my getView() in adapter class
public View getView(int position, View convertView, ViewGroup parent) {
OrderViewHolder orderViewHolder = null;
if (convertView == null) {
orderViewHolder = new OrderViewHolder();
convertView = inflater.inflate(R.layout.order_list_row, null);
orderViewHolder.setTvTitle((TextView) convertView
.findViewById(R.id.orderTitle));
orderViewHolder.setTvPrice((TextView) convertView
.findViewById(R.id.orderPrice));
orderViewHolder.setIvDelete((ImageButton) convertView
.findViewById(R.id.deleteOrder));
convertView.setTag(orderViewHolder);
} else {
orderViewHolder = (OrderViewHolder) convertView.getTag();
}
if (position != 0)
{
System.out.println(" value of position :"+position);
List lit = new ArrayList();
List litp = new ArrayList();
// System.out.println(" value of postion of cursor : ");
OrderViewHolder odr_obj = null;
if (oStarterCursor.moveToFirst()) {
do{
odr_obj = new OrderViewHolder();
title = oStarterCursor.getString(oStarterCursor.getColumnIndex("item_name"));
System.out.println("value of title :"+title);
lit.add(title);
price = oStarterCursor.getString(oStarterCursor.getColumnIndex("Item_cost"));
System.out.println("value of price :"+price);
litp.add(price);
}while(oStarterCursor.moveToNext());
}
// _id = oStarterCursor.getInt(oStarterCursor.getColumnIndex("_id"));
if (title != null) {
title = title.trim();
Iterator it = lit.iterator();
while (it.hasNext()) {
int i =0;
//System.out.println(" data iterator "+it.next().toString());
String test =it.next().toString();
System.out.println(" iterator vavue :"+test);
orderViewHolder.getTvTitle().setText(test);
}
orderViewHolder.getTvTitle().setTextColor(R.color.black);
orderViewHolder.getTvTitle().setTextSize(12);
orderViewHolder.getTvTitle().setTypeface(Typeface.DEFAULT);
orderViewHolder.getTvTitle().setGravity(
Gravity.CENTER_VERTICAL);
}
if (price != null) {
price = price.trim();
orderViewHolder.getTvPrice().setText(price + ".00");
orderViewHolder.getTvTitle().setTextColor(R.color.black);
orderViewHolder.getTvTitle().setTextSize(12);
orderViewHolder.getTvTitle().setTypeface(Typeface.DEFAULT);
orderViewHolder.getTvTitle().setGravity(
Gravity.CENTER_VERTICAL);
}
//_id = oStarterCursor.getInt(oStarterCursor.getColumnIndex("_id"));
//convertView.setTag(R.id.orderTitle, _id);
if (orderViewHolder.getIvDelete() != null) {
//orderViewHolder.getIvDelete().setTag(R.id.orderTitle, _id);
}
}
return convertView;}
Problem is that in my data base there is two row as in below image..
But in my alert dialog only showing one row twice. I did not get where is logical mistake.For conveniences i am going to show my screen-shot
So Where is problem i can't get please some body help me take out of this problem.

I think it's your line :
if (position != 0)
The first line of an adapter is 0 so it will not set the data for the first line of data.

I believe its because you are using getView wrong, getView does not just get called once it gets called many times. you are looping through your cursor each time getView is called so you are only displaying the last item in the cursor after you loop through your 2 lists.
if you are getting data from a cursor you should be using SimpleCursorAdapter and then override bindView and just use the cursor variable in the method each time its called
Edit
basically along the lines of this
oStarterCursor.moveToPosition(position);
orderViewHolder.getTvTitle().setText(oStarterCursor.getString(oStarterCursor.getColumnIndex("item_name")));
is all you need to get the data really

Related

How to change color of textView in android listView on comparing JSON data?

I am fetching JSON Data to listView successfully, but i want to change the color of the textView in that listView by comparing JSON data.
For ex-
if in JSON {"status":"approved"} - green color
else if {"status" : "disapproved"} - red color
I'm able to change it using getView in SimpleAdapter but not able to compare strings there.
when i print the status, its is only showing "approved".
i can't filter "disapproved" in else if condition.
SimpleAdapter adapter = new SimpleAdapter(getActivity(), mylist, R.layout.list_leave_approval,
new String[]{
TAG_STATUS
},
new int[]{
R.id.status}) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//return super.getView(position, convertView, parent);
View v = convertView;
if (v == null) {
// View v = convertView;
LayoutInflater vi = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_leave_approval, null);
TextView test = (TextView) v.findViewById(R.id.status);
// String str = jsonObject.getString("status");
Log.d("Day", "get view STATUS: " + strStatus);
// jsonObject = jsonArray.getJSONObject(i);
if (strStatus.equals(" Approved ")) {
test.setBackgroundColor(getResources().getColor(R.color.green));
// txtStatus.setText("DEC");
} else if (strStatus.equals(" Disapproved ")) {
test.setBackgroundColor(getResources().getColor(android.R.color.holo_red_light));
}
}
return super.
getView(position, v, parent);
}
};
list.setAdapter(adapter);
You can do like this.
Here string will be your parsed json string.
JSONObject jObj = new JSONObject(String);
if (jObj.getString("status").equalsIgnoreCase("approved")) {
textView1.setTextColor(Color.GREEN)
} else {
textView1.setTextColor(Color.RED)
}
I advise you to read about MVC design pattern
You should keep your JSON in a data object (model in MVC) for example Status object and put all the needed data from json to this object
When filling the listView adjust the view according to the statuses:
if(items[index].getStatus.equals("approved"))
textView.setTextColor(ContextCompat.getColor(context, R.color.green));
else if(items[index].getStatus.equals("disapproved"))
textView.setTextColor(ContextCompat.getColor(context, R.color.red));
You will need to override a more complex type of Adapter in order to do what you want, SimpleAdapter only allows setting the text in a very simple way as a String.
Something like ArrayAdapter might be a better fit, in that case you could use the code Michael A has shown in the getView method of ArrayAdapter to change the display of the text.
You might also look into SpannableString which allows adding color to text, but this would require being able to provide code to determine the status of the item.

Not getting the Same ListView item before and After insert using Cursor

I have a ListView which by using CursorAdapter I m inflating its rows . And I am using SwapCursor in order to refresh the ListView.
I am also able to get the listView standStill once I add the Content in the DB and Swap the Cursor after that.
Now the Problem is on swapCursor / notifyDatasetChanged / changeCursor it is refreshing the listView.But not maitaining the same item which was present Earlier into the listView.
It is changing the content of item by its previous one once I refresh the listView.
This is How I got ListView standStill after swapCursor() :
if (result_cursor != null) {
CursorDemo cursorDemo = new CursorDemo(ORMLiteActivity.this , result_cursor);
cursorDemo.swapCursor(result_cursor);
View v = listViewDb.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
int firstPosition = listViewDb.getFirstVisiblePosition();
listViewDb.setAdapter(cursorDemo);
listViewDb.setSelectionFromTop(firstPosition , top);
}
So Now I would get the same ListView item before or After swapCursor
Any Answer is Truely Appreciated...
I figure using this:
if (result_cursor != null) {
CursorDemo cursorDemo = new CursorDemo(ORMLiteActivity.this , result_cursor);
cursorDemo.swapCursor(result_cursor);
View v = listViewDb.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
int firstPosition = listViewDb.getFirstVisiblePosition();
int after_insert_position = (firstPosition == 0) ? 0 : firstPosition+1;
listViewDb.setAdapter(cursorDemo);
listViewDb.setSelectionFromTop( after_insert_position , top);
}

BaseAdapter not getting refreshed after data set is changed: Android

I am using a list adapter and feeding a list to it, which is made from a TreeMap.
Treemap is required as I need that the data for the list comes from three places and I need to collect it all and then have it sorted basing on a time stamp.
Now, when the new data comes in, the adapter doesn't update, even when I call notifyDataSetChanged().
I have attached my code below:
LinkedList<DeviceDataInfo> tsDataList = response
.getDeviceDataInfoList();
for (DeviceDataInfo data : tsDataList) {
// if (data.getAttrValue().equals("14")){
String eventMsg = null;
if (data.getAttrValue() != null) {
eventMsg = getEventMessage(
Float.valueOf(data.getAttrValue()),
data.getAttrName());
if (eventMsg != null) {
long time = data.getTime();
String eventDate = mCurrentDoorSensor
.getFormattedDate(time);
String eventTime = mCurrentDoorSensor
.getFormattedTime(time);
SensorListModel item = new SensorListModel(eventTime,
eventDate, eventMsg);
if (!mDoorSensorHistory.containsKey(time)) {
// add item to the tree
mDoorSensorHistory.put(time, item);
}
}
}
}
SensorListModel[] list = new SensorListModel[mDoorSensorHistory
.size()];
list = mDoorSensorHistory.values().toArray(list);
mList = new ArrayList<SensorListModel>(Arrays.asList(list));
mSensorProgressBar.setVisibility(View.GONE);
mSensorProgressBarText.setVisibility(View.GONE);
if (isAdded()) {
if (mSensorAdaptor == null) {
mSensorAdaptor = new SensorListAdaptor(getActivity(),
mList, "DOOR");
mSensorList.setAdapter(mSensorAdaptor);
} else {
// mSensorAdaptor = new SensorListAdaptor(getActivity(),
// mList, "DOOR");
((BaseAdapter) mSensorList.getAdapter())
.notifyDataSetChanged();
}
}
Could someone, please, let me know what is going wrong?
Thanks
For future reference: This solved it
#Sunny : try mSensorAdaptor.addAll(list);mSensorAdaptor.notifyDataSetChanged(); if addAll method is not available then you will need to define addAll method in SensorListAdaptor which all two ArrayLists – ρяσѕρєя K 15 mins ago

Custom ListView Items repeated

I am trying to add dynamic textview to listview items.textviews can be of 1-2 or more than that depending on data I have succeed in adding the textview but problem is textviews are repeated on scroll.
I am creating new object of textview each time in loop.I am aware of the problem that android tries to reuse existing view but i have to add new view every time.
Here is my code in custom adapter:
public class ViewHolder {
TextView text1;
LinearLayout linearLayout;
TextView t;
TextView t1;
}
getView method
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.two_item_icon_text, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView.findViewById(R.id.text1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.linearLayout = (LinearLayout) convertView.findViewById(R.id.lin_lay_dynamic);
holder.text1.setText("" + DATA1[position]);
String tmp, dateparsed;
dateparsed = DATA1[position].substring(0, DATA1[position].indexOf(":"));
for (int x = 0; x < calendareventholder1.size(); x++) {
objHolder = (CalendarEventHolder) calendareventholder1.get(x);
if (objHolder.opendate.equals(displaydate[current])) {
tmp = objHolder.dtstarttime.toString().substring(0, objHolder.dtstarttime.toString().indexOf(":"));
if (Integer.parseInt(tmp) >= Integer.parseInt(dateparsed) && Integer.parseInt(tmp) < Integer.parseInt(dateparsed) + 1) {
holder.t = new TextView(convertView.getContext());
holder.t.setText(":-d ");
holder.t.setOnClickListener(this);
if (Common.isChildSessionAlerted(String.valueOf(objHolder.id), getApplicationContext(), object1)) {
holder.t.setText(holder.t.getText() + objHolder.dtstarttime + " " + objHolder.dtendtime + " :-a");
} else {
holder.t.setText(holder.t.getText() + objHolder.dtstarttime + " " + objHolder.dtendtime);
}
holder.t.setTag(objHolder.id);
holder.t.setTextSize(Common.getPreferenceInt(getApplicationContext(), Common.PREF_FONT_SIZE, 10));
holder.t.setTextColor(Color.BLACK);
holder.t.setText(getSmiledText(ScheduleActivity.this,
holder.t.getText().toString()));
holder.linearLayout.addView(holder.t);
holder.t1 = new TextView(convertView.getContext());
holder.t1.setOnClickListener(this);
holder.t1.setText(objHolder.title);
holder.t1.setTag(objHolder.id);
holder.t1.setTextSize(Common.getPreferenceInt(getApplicationContext(), Common.PREF_FONT_SIZE, 10));
holder.t1.setTextColor(Color.BLACK);
holder.linearLayout.addView(holder.t1);
}
}
}
return convertView;
}
Its a little hard to really understand what is in holder since it isn't super descriptive, but if I am reading your question right, the reason you are getting repeated items is because you are just adding Views and never deleting what was there before. ListView recycles views, meaning what was there previously stays there. As it scrolls it actually keeps reusing views rather than creating new ones. I won't go into detail because there are a bunch of question on here with similar problems. But at the top you should do
getView() {
/*previous stuff, and holder.linearLayout must have been set!*/
if(holder.linearLayout.getChildCount() > 0)
holder.linearLayout.removeAllViews();
This way any views already there will be removed. One last thing, you should also check out this. Immensely helpful in understanding why you have to do what I posted.

Image in listview via database+assets

I have a database which has a name of an animal, and in an other column a sound of the animal.
The listview works fine, and now I would like to extend it with an image out of the assets.
For this I've read about how to get the assets data and use it.
An example I've tried worked fine for me.
Now I want this "assets" code (at least I think I want this) in the extended BaseAdapter class.
Unfortunately I'm doing something wrong as I can't use the getAssets() in the BaseAdapter.
The problem starts in the try-catch block: " getAssets " doesn't get recognized
Which way would I think of solving this?
Creating another class in which this assets code can run in an extended "Activity"?
Or are there better ways of showing an image via database info in a listview?
Thank you for your support in my quest to get familiar with Android / Java.
public View getView(int position, View convertView, ViewGroup parent) {
// get view reference
View view = convertView;
// if null
if(view == null) {
// inflate new layout
view = mInflater.inflate(R.layout.layout_list_item, null);
// create a holder
ViewHolder holder = new ViewHolder();
// find controls
holder.txtName = (TextView)view.findViewById(R.id.txtName);
holder.txtPicture = (ImageView)view.findViewById(R.id.txtPicture);
// set data structure to view
view.setTag(holder);
}
// get selected user info
UserInfo userInfo = mListUserInfo.get(position);
// if not null
if(userInfo != null) {
// query data structure
ViewHolder holder = (ViewHolder)view.getTag();
// set data to display
holder.txtName.setText(userInfo.getName() + ", " + userInfo.getPicture() );
try {
// get input stream
InputStream ips = getAssets().open( userInfo.getPicture() + ".jpg");
Log.d("Imageloading", "Reading: " + ips);
// load image as Drawable
Drawable d = Drawable.createFromStream(ips, null);
// set image to ImageView
holder.txtPicture.setImageDrawable( d );
}
catch(IOException ex) {
Log.e("Imageloading", "Could not load '" + ex.getMessage()+ "'!");
}
}
// return view
return view;
}
I've just edited the code.
To solve the getAssets() thing I've done the following:
holder.txtPicture.setImageDrawable( getSomePicture(null, userInfo.getPicture() + ".jpg") );
public Drawable getSomePicture(Context myContext, String WhichPicture) throws IOException {
// get input stream
InputStream ips = myContext.getAssets().open( WhichPicture );
Log.d("Imageloading", "Reading: " + ips);
// load image as Drawable
Drawable d = Drawable.createFromStream(ips, null);
return d;
}
This still is not the solution, researching some more....
Found an interesting source for Lazy Loading
to call getAssets() function in non-activity class you need reference to Context. In your updated code you called function 'getSomePicture()' and passed null to myContext parameter. that means your code will fail because you have myContext.getAssets() later in your method code.
try to do this in your getView method:
Context context = getContext();
holder.txtPicture.setImageDrawable( getSomePicture(context, userInfo.getPicture() + ".jpg") );
You won't have access to the getAssets() method because that is a method that only the Context (and it's subclass, Activity) have. What I find is easiest here is to make your BaseAdapter subclasses private inner classes of the Activity in which it is to be used. That way, you'll have access to the getAssets() method.
Here is what this might look like:
public class YourExampleActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
}
private class YourListAdapter extends BaseAdapter {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// get view reference
View view = convertView;
// if null
if(view == null) {
// inflate new layout
view = mInflater.inflate(R.layout.layout_list_item, null);
// create a holder
ViewHolder holder = new ViewHolder();
// find controls
holder.txtName = (TextView)view.findViewById(R.id.txtName);
holder.txtPicture = (ImageView)view.findViewById(R.id.txtPicture);
// set data structure to view
view.setTag(holder);
}
// get selected user info
UserInfo userInfo = mListUserInfo.get(position);
// if not null
if(userInfo != null) {
// query data structure
ViewHolder holder = (ViewHolder)view.getTag();
// set data to display
holder.txtName.setText(userInfo.getName() + ", " + userInfo.getPicture() );
try {
// get input stream
InputStream ips = getAssets().open( userInfo.getPicture() + ".jpg");
Log.d("Imageloading", "Reading: " + ips);
// load image as Drawable
Drawable d = Drawable.createFromStream(ips, null);
// set image to ImageView
holder.txtPicture.setImageDrawable( d );
}
catch(IOException ex) {
Log.e("Imageloading", "Could not load '" + ex.getMessage()+ "'!");
}
}
// return view
return view;
}
// Override other key methods of BaseAdapter here
}
}
Alternatively, you could take in a Context object in the constructor when the BaseAdapter subclass is instantiated, and keep a reference to that with which to call getAssets() on. Please post a comment if you need an example of this.

Categories

Resources