How to use CustomAdapter with ListView from XML Async Task - android

I achieved populate a ListView using StringBuilder from a Internet XML Source.
With this code the listView is populated with only one String but I want populate the listview by elements: getIdLine and getTimeLeft (With CustomAdapter) for customize the layout of the listView items in separated Strings.
How to achieve this?
EDITED CODE
FragmentActivity.class
private ListView listViewEMT;
private ArrayList<HashMap<String, String>> yourList;
... AsyncTask
protected void onPostExecute(String string) {
super.onPostExecute(string);
CustomAdapter adapter = new CustomAdapter(getActivity(), yourList);
listViewEMT.setAdapter(adapter);
this.progressDialog.dismiss();
}
/** RSS HANDLER CLASS */
class RSSHandler extends DefaultHandler {
StringBuffer chars;
private Arrival currentArrival;
RSSHandler() {
this.currentArrival = new Arrival();
this.chars = new StringBuffer();
}
public void characters(char[] arrc, int n, int n2) {
this.chars.append(new String(arrc, n, n2));
}
public void endElement(String string, String string2, String string3) throws SAXException {
super.endElement(string, string2, string3);
if ((string2.equalsIgnoreCase("idStop")) && (this.currentArrival.getIdStop() == null)) {
this.currentArrival.setIdStop(this.chars.toString());
}
if ((string2.equalsIgnoreCase("idLine")) && (this.currentArrival.getIdLinea() == null)) {
this.currentArrival.setIdLinea(this.chars.toString());
}
if ((string2.equalsIgnoreCase("TimeLeftBus")) && (this.currentArrival.getTimeLeft() == 0)) {
int n = Integer.valueOf((String)(this.chars.toString()));
this.currentArrival.setTimeLeft(n);
}
if (!(string2.equalsIgnoreCase("Arrive"))) return;
yourList.add((HashMap<String, String>)(currentArrival.getMap()));
this.currentArrival = new Arrival();
}
public void startElement(String string, String string2, String string3, org.xml.sax.Attributes attributes) throws SAXException {
super.startElement(string, string2, string3, attributes);
this.chars = new StringBuffer();
string2.equalsIgnoreCase("Arrive");
}
}
Arrival.class
...getters and setters
public HashMap<String, String> getMap() {
HashMap<String, String> map;
map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put("KEY1", idLinea);
map.put("KEY2", String.valueOf(timeLeft));
return map;
}
CustomAdapter.class Thanks to Nabin
public class CustomAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
private List<String> listString;
public CustomAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.emt_item, null);
TextView tv1 = (TextView) vi.findViewById(R.id.itemLine);
TextView tv2 = (TextView) vi.findViewById(R.id.itemTime);
HashMap<String, String> map;
map = data.get(position);
tv1.setText(map.get("KEY1"));
tv2.setText(map.get("KEY2"));
return vi;
}
}

Create a custom adapter as following:
public class ArrayAdapter extends BaseAdapter{
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
private List<String> listString;
public ArrayAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//your getView method here
}
GetView Method
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.custom, null);
TextView tv1 = (TextView) vi.findViewById(R.id.tvone);
TextView tv2 = (TextView) vi.findViewById(R.id.tvtwo);
HashMap<String, String> map = new HashMap<String, String>();
map = data.get(position);
tv1.setText(map.get("KEY1"));
tv2.setText(map.get("KEY2"));
return vi;
}
Make array list as:
ArrayList<HashMap<String, String>> yourList;
And fill yourList as
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put("KEY1", value1);
map.put("KEY2", value2);
yourList.add(map);
And while making object of the custom adapter
CustomAdapter adapter = new CustomAdapter(YourActivity.this, yourList);
list.setAdapter(adapter);
For list you can do
list = (ListView) getView().findViewById(android.R.id.list);

Related

How to change Background Color of row in List View Using List View Column Field

I want to change the back ground of my list view row if the column value is same the the list view back ground would be change here is my code.
public class FillList extends AsyncTask<String, String, String> {
String z = "";
List<Map<String, String>> prolist = new ArrayList<Map<String, String>>();
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String r) {
Toast.makeText(getActivity(), r, Toast.LENGTH_SHORT).show();
String[] from = {"C", "D", "E"};
int[] views = {R.id.accname, R.id.openingbalance, R.id.closingblanace};
final SimpleAdapter ADA = new SimpleAdapter(getActivity(),
prolist, R.layout.reportlayout, from,
views);
lstpro.setAdapter(ADA);
}
#Override
protected String doInBackground(String... params) {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
final String stringlevel = getArguments().getString("level");
String query = "select * from GLSCOADetail where AccLevelNo<='"+ stringlevel +"'";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
ArrayList<String> data1 = new ArrayList<String>();
while (rs.next()) {
Map<String, String> datanum = new HashMap<String, String>();
datanum.put("C", rs.getString("AccName"));
datanum.put("D", rs.getString("OpeningBalance"));
datanum.put("E", rs.getString("ClosingBalance"));
prolist.add(datanum);
}
z = "Success";
}
} catch (Exception ex) {
z = ex.getMessage();
}
return z;
}
}
I want to change my list view background on database filed if my database field match with list view then color of row would change please help me out.
Main (Activity)
public class Main extends Activity
{
private CustomAdapter adapter;
public ListView mListView = null;
public ArrayList<ListModel> CustomListViewValuesArr = new ArrayList<ListModel>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_layout);
mListView = (ListView) findViewById(R.id.list);
setListData();
adapter = new CustomAdapter(this, CustomListViewValuesArr);
mListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
/****** Function to set data in ArrayList *************/
public void setListData()
{
CustomListViewValuesArr.add(new ListModel("No1"));
CustomListViewValuesArr.add(new ListModel("No2"));//same
CustomListViewValuesArr.add(new ListModel("No3"));
CustomListViewValuesArr.add(new ListModel("No4"));
CustomListViewValuesArr.add(new ListModel("No2"));//same
}
}
listview_layout.xml (Activity xml)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
CustomAdapter (Adapter)
public class CustomAdapter extends BaseAdapter
{
/*********** Declare Used Variables *********/
private Activity mActivity;
private ArrayList<ListModel> mList;
private static LayoutInflater mInflater = null;
private ListModel tempValues = null;
private int i=0;
/************* CustomAdapter Constructor *****************/
public CustomAdapter(Activity a, ArrayList d) {
/********** Take passed values **********/
mActivity = a;
mList = d;
/*********** Layout inflator to call external xml layout () ***********/
mInflater = ( LayoutInflater ) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if(mList.size()<=0)
return 1;
return mList.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder
{
public TextView text;
}
/****** Depends upon mList size called for each row , Create each ListView row *****/
public View getView(int position, View convertView, ViewGroup parent)
{
View vi = convertView;
ViewHolder holder;
if(convertView==null){
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = mInflater.inflate(R.layout.tabitem, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.text = (TextView) vi.findViewById(R.id.textView);
/************ Set holder with LayoutInflater ************/
vi.setTag( holder );
}
else
holder=(ViewHolder)vi.getTag();
if(mList.size() <= 0)
{
holder.text.setText("No Data");
}
else
{
tempValues = null;
tempValues = ( ListModel ) mList.get( position );
holder.text.setText( tempValues.getName() );
}
if(isDuplicate(tempValues.getName()))// this Method to check duplicate.
{
// Set a background color for ListView regular row/item
vi.setBackgroundColor(Color.parseColor("#FFB6B546"));
}
else
{
// Set the background color for alternate row/item
vi.setBackgroundColor(Color.parseColor("#FFCCCB4C"));
}
return vi;
}
private boolean isDuplicate(String item)
{
int count = 0;
for (int i = 0; i < mList.size(); i++)
{
ListModel listModel = mList.get(i);
if(item.equals(listModel.getName()))
count++;
}
if(count > 1)
return true;
else
return false;
}
}
ListModel (Model Class)
public class ListModel {
private String name ="";
/*********** Set Methods ******************/
public ListModel(String name)
{
this.name = name;
}
public void setName(String CompanyName)
{
this.name = CompanyName;
}
/*********** Get Methods ****************/
public String getName()
{
return this.name;
}
}
tabitem (ListView Adapter xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:id="#+id/textView" />
</LinearLayout>

Show the Elements from ArrayList of map ,in list form in Android

I have a A data stored in ArrayList< HashMap< String, String> > retrieved from JSON
in the form (i.e.)
[{price: =1685 name: =Monographie Der Gattung Pezomachus (Grv.) by Arnold F. Rster}]
And I need to show the all map elements into list form in Android.
I've tried many ways but I'm unable to do it .
Also help me to know about the layouts to use in it
EDITED:
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(myarr_list);
setListAdapter(adapter);
And in the MySimpleArrayAdapter Class, in Constructor
public MySimpleArrayAdapter( ArrayList<HashMap<String,String>> pl) {
LayoutInflator inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
The control does not proceed after this,
MySimpleArrayAdapter Class
public class MySimpleArrayAdapter extends BaseAdapter{
ArrayList<HashMap<String, String>> ProductList = new ArrayList<HashMap<String, String>>();
LayoutInflater inflater;
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#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;
}
//Constructor
public MySimpleArrayAdapter( ArrayList<HashMap<String,String>> pl) {
this.ProductList = pl;
inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public View getView(int position, View convertView, ViewGroup parent) {
View myview = convertView;
if (convertView == null) {
myview = inflater.inflate(R.layout.show_search_result, null);
}
TextView price = (TextView) myview.findViewById(R.id.price);
TextView name = (TextView) myview.findViewById(R.id.name);
HashMap<String, String> pl = new HashMap<String, String>();
pl = ProductList.get(position);
//Setting
price.setText(pl.get("price"));
name.setText(pl.get("name"));
return myview;
}
}
I am editing here a onPostExecute class from SearchResultsTask extended by AsyncTask
protected void onPostExecute(JSONObject json) {
if (json != null && json.length() > 0) {
try {
JSONArray json_results = (JSONArray)(json.get("results"));
String parsedResult = "";
System.out.println("-> Size ="+ json_results.length());
for(int i = 0; i < json_results.length(); i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject json_i = json_results.getJSONObject(i);
map.put("name: ",json_i.getString("name") + "\n");
map.put("price: ",json_i.getString("price") + "\n");
arr_list.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
System.out.println("-> Size =====arr_llist ="+ arr_list.size());
// CustomListAdapter adapter = new CustomListAdapter (arr_list);
//final StableArrayAdapter adapter = new StableArrayAdapter(this, R.id.result, arr_list);
// listview.setAdapter(adapter);
MyListActivity obj1 = new MyListActivity();
Bundle icicle = null;
obj1.onCreate(icicle);
}
public class MyListActivity extends Activity {
public void onCreate(Bundle icicle) {
// System.out.println("In my list Activity");
// super.onCreate(icicle);
//populate list
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this,arr_list);
// System.out.println("in 2");
adapter.getView(0, listview, listview);
listview.setAdapter(adapter);
}
}
#Override
public int getCount() {
return ProductList.size() ;
}
//Constructor
public MySimpleArrayAdapter( ArrayList<HashMap<String,String>> pl, Context c) {
this.ProductList = pl;
inflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
getSystemService() is method of context, you are calling it on instance of adapter.

Press button in listView adapter to get data in this row

I have a listView that shows data that in sqlite, I'm using baseAdapter.
The list row contains text and button.
I press the button in each row to give me each data of the selected row from the database (not pressing the row itself)
This is code of listView:
tipsList = new ArrayList<HashMap<String, String>>();
list = (ListView) rootView.findViewById(R.id.tipList);
do {
map = new HashMap<String, String>();
map.put(DAO.TIP_ID, c.getString(c.getColumnIndex(c.getColumnName(0))));
map.put(DAO.TIP_CONTENT, c.getString(c.getColumnIndex(c.getColumnName(1))));
map.put(DAO.TIP_FAVORITE, c.getString(c.getColumnIndex(c.getColumnName(2))));
// adding HashList to ArrayList
tipsList.add(map);
} while (c.moveToNext());
tipsAdapter = new TipsAdapter(getActivity(), tipsList, tipType, db);
list.setAdapter(tipsAdapter);
And this is code of TipsAdapter.java
public class TipsAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
Context context;
Typeface tf;
String tipID;
String tipText;
String isFavorite;
DAO db;
HashMap<String, String> quote;
int selectedTipType;
public TipsAdapter(Activity a, ArrayList<HashMap<String, String>> d, int selectedTipType, DAO db) {
activity = a;
data = d;
context = a;
this.selectedTipType = selectedTipType;
this.db = db;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// ==============================================================================
public int getCount() {
return data.size();
}
// ==============================================================================
public Object getItem(int position) {
return position;
}
// ==============================================================================
public long getItemId(int position) {
return position;
}
// ==============================================================================
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.tip_list_row, null);
TextView tipContent = (TextView) vi.findViewById(R.id.tip_text); // tip
final ImageView favStar = (ImageView) vi.findViewById(R.id.favorite_star);
tf = Typeface.createFromAsset(activity.getAssets(), "fonts/bauhausm_0.ttf");
tipContent.setTypeface(tf);
quote = new HashMap<String, String>();
quote = data.get(position);
tipText = quote.get(DAO.TIP_CONTENT).trim();
favStar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// I want here get all data like tipId - tipText - tipFavotite of the current row in toast
}
});
return vi;
}
}
How to get the data of the current row when press the button?
Hope anyone got my mean.
Thanks in advance.
Maybe you can set the tag of your button.
favStar.setTag(position);
favStar.setOnClickListener (new OnClickListener()
{
#Override
public void onClick(View view) {
int position = (int) view.getTag();
HashMap<String, String>() quote = data.get(position);
String tipText = qout.get(DAO.TIP_CONTENT);
String tipContent = ......;
}
}
I Solved it by myself by making position as final and put quote = data.get(position); inside the listener of the button.

Items in listview not setting up using BaseAdapter and SimpleAdapter

I'm facing problem with setting up the items in ListView, I'm using an Async task for updating the items. Here is what I have done so far.
Async Task onPostExecute()
#Override
protected void onPostExecute(String result) {
notifyList = new ArrayList<HashMap<String, String>>();
try {
JSONObject rootObj = new JSONObject(result);
JSONObject jSearchData = rootObj.getJSONObject("notifications");
int maxlimit = 5;
for (int i = 0; i < maxlimit; i++) {
JSONObject jNotification0 = jSearchData.getJSONObject(""
+ i + "");
String text = jNotification0.getString("text");
String amount = jNotification0.getString("amount");
String state = jNotification0.getString("state");
System.out.println(text);
System.out.println(amount);
System.out.println(state);
HashMap<String, String> map = new HashMap<String, String>();
map.put("text", text);
map.put("amount", amount);
notifyList.add(map);
}
if (notification_adapter != null) {
notification_list.setAdapter(new CustomNotificationAdapter(
notifyList));
}
} catch (Exception e) {
e.printStackTrace();
}
}
Here is my CustomNotification class which extends BaseAdapter
public class CustomNotificationAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> notificationData = new ArrayList<HashMap<String, String>>();
public CustomNotificationAdapter(
ArrayList<HashMap<String, String>> notificationData) {
this.notificationData = notificationData;
}
#Override
public int getCount() {
return notificationData.size();
}
#Override
public Object getItem(int position) {
return notificationData.get(position).get("text").toString();
}
#Override
public long getItemId(int position) {
return notificationData.get(position).get("text").hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
LayoutInflater inflater = getLayoutInflater();
vi = inflater.inflate(R.layout.custom_notification_list, null);
TextView notificationText = (TextView) findViewById(R.id.notificationText);
TextView notificationAmount = (TextView) findViewById(R.id.notificationPoint);
notificationText
.setText(notificationData.get(position).get("text"));
notificationAmount.setText(notificationData.get(position).get(
"amount"));
return vi;
}
}
NotificationAdapter class which extends SimpleAdapter
public class NotificationAdapter extends SimpleAdapter {
List<Map<String, String>> cur_list = new ArrayList<Map<String, String>>();
public NotificationAdapter(Context context,
List<? extends Map<String, ?>> data, int resource, String[] from,
int[] to) {
super(context, data, resource, from, to);
}
}
I'm able to get all the data from JSONResponse but I'm not able to show it on the list. What am I missing?
Any kind of help will be appreciated.
Try replacing this:
if (notification_adapter != null) {
notification_list.setAdapter(new CustomNotificationAdapter(
notifyList));
}
with this:
notification_adapter = new CustomNotificationAdapter(notifyList);
notification_list.setAdapter(notification_adapter);
This will set the adapter to the new JSON data even if notification_adapter was previously null.
Call notification_adapter.notifyDataSetChanged() after updating your adapter's data or remove the if (notification_adapter != null) {if you want it easy and bad.
to update your data:
public void updateData(ArrayList<HashMap<String, String> notificationData){
this.notificationData = notificationData;
this.notifyDataSetChanged();
}
Inside your adapter, and call it like: notification_adapter.updateData(notifyList);

Android List view SectionIndexer - list view not displaying curent scroll letter

I am trying to use secionIndexer with fast scroll in list view.
I have implemented but
on scroll of list it should popup the current letter at which we have scrolled,
but its not showing that.
on debug mode I came to know that getSectipons() and getPositionForSection() are never called in my case ,
but in any other simple example that i tried from web it does make a call to those functions.
Pelase suggest me what to do
//##################
here is code of my adapter
//#######################
public class MyListAdapter extends ArrayAdapter<Object> implements SectionIndexer {
Activity context;
Object[] listData;
HashMap<String, Integer> alphaIndexer;
String[] sections;
public MyListAdapter(Activity context, Object[] objects) {
super(context, R.layout.new_invest_row, objects);
this.context = context;
listData = objects;
alphaIndexer = new HashMap<String, Integer>();
//changes here
ArrayList myArrayList = new ArrayList();
for (int ix=0; ix<objects.length; ix++) {
myArrayList.add(objects[ix]);
}
Collections.sort(myArrayList, new Comparator<HashMap<String, String>>(){
public int compare(HashMap<String, String> one, HashMap<String, String> two) {
return one.get("Name").compareToIgnoreCase(two.get("Name"));
}
});
listData = myArrayList.toArray();
//Arrays.sort(listData);
for (int i = listData.length - 1; i >= 0; i--) {
final HashMap<String, String> obj = (HashMap<String, String>)listData[i];
String element = obj.get("Name");
alphaIndexer.put(element.substring(0, 1).toUpperCase(), i);
}
Set<String> keys = alphaIndexer.keySet(); // set of letters
// Copy into a List for sorting
Iterator<String> it = keys.iterator();
ArrayList<String> keyList = new ArrayList<String>();
while (it.hasNext()) {
String key = it.next();
keyList.add(key);
}
Collections.sort(keyList);
// Convert to array
sections = new String[keyList.size()];
keyList.toArray(sections);
for(int c=0;c < sections.length;c++)Log.e("secction<"+c+">","+"+sections[c]);
Log.e("alphaIndexer","+"+alphaIndexer);
}
static class ViewHolder {
TextView txtName;
TextView txtOwner;
TextView txtStartDate;
TextView txtEndDate;
TextView txtStatus;
ImageView imgIcon;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.new_invest_row, null, true);
holder = new ViewHolder();
**holder.txtName = (TextView) rowView.findViewById(R.id.invest_row_name);**
//my custom code here
rowView.setTag(holder);
} else {
holder = (ViewHolder) rowView.getTag();
}
#SuppressWarnings("unchecked")
final HashMap<String, String> obj = (HashMap<String, String>)listData[position];
String str = obj.get("Name");
if(null == str){
str = "";
}
holder.txtName.setText(str);
//#################
//my custom code here
return rowView;
}
public int getPositionForSection(int section) {
String letter = sections[section];
Log.e("alphaIndexer.get(letter)","+"+alphaIndexer.get(letter));
return alphaIndexer.get(letter);
}
public int getSectionForPosition(int arg0) {
// TODO Auto-generated method stub
return 1;
}
public Object[] getSections() {
return sections;
}
}
//#######################
I assume that in adapter when I am passing the textViewId its not taking the currect textVewId as the sectionIndexer functions are never called.
In the Layout new_invest_row I am getting custom row which have an icon and few textViews.
I am sorting the list on the basis of name of the Object that I am displaying in each row.
i want indexer to work on the name of the object.
Please help me with exact solution

Categories

Resources