Text not appearing in listview - android

I have a listview in which i wanted to have custom typeface e.g. Arial. for this i subclassed the SimpleAdapter and implemented the the typeface for textviews in the list. But after this implementation, the list appears to be blank but the onClick is still working and clicking on the blank list item navigates me to the next activity as required.
Code
public class TopNewsActivity extends ListActivity {
public static final String LOG_TAG = "Infra";
private ProgressDialog progressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
new BackgroundAsyncTask().execute();
}
public class BackgroundAsyncTask extends AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(TopNewsGroup.group);
progressDialog.setCancelable(true);
progressDialog.setMessage("Loading...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setProgress(0);
progressDialog.show();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(String... paths) {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
String xml = XMLfunctions.getTopNewsXML();
Document doc = XMLfunctions.XMLfromString(xml);
int numResults = XMLfunctions.numResults(doc);
Log.d(LOG_TAG, "Number of Results: " + numResults);
if ((numResults <= 0)) {
Toast.makeText(TopNewsActivity.this, "No Result Found",Toast.LENGTH_LONG).show();
return null;
}
NodeList nodes = doc.getElementsByTagName("result");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nodes.item(i);
map.put("id", XMLfunctions.getValue(e, "id"));
map.put("title", XMLfunctions.getValue(e, "title"));
map.put("date", XMLfunctions.getValue(e, "date"));
map.put("recordDate", XMLfunctions.getValue(e, "recordDate"));
mylist.add(map);
}
return mylist;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
ListAdapter adapter = new MySimpleAdapter(TopNewsActivity.this, result, R.layout.list_item, new String[] { "title", "date" }, new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
progressDialog.dismiss();
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
#SuppressWarnings("unchecked")
#Override
public void onItemClick(AdapterView<?> a, View view, final int position, long id) {
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Intent i = new Intent(TopNewsActivity.this, NewsDetails.class);
i.putExtra("content_id", o.get("id"));
i.putExtra("title", o.get("title"));
i.putExtra("date", o.get("recordDate"));
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
View v = TopNewsGroup.group.getLocalActivityManager().startActivity("ShowNews", i).getDecorView();
// Again, replace the view
TopNewsGroup.group.replaceView(v);
}
});
}
}
public class MySimpleAdapter extends SimpleAdapter {
public MySimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}
public View getView(int position, View view, ViewGroup parent){
Typeface localTypeface1 = Typeface.createFromAsset(getAssets(), "fonts/arial.ttf");
View v = view;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
TextView tt = (TextView) v.findViewById(R.id.item_title);
tt.setBackgroundColor(R.color.white);
tt.setTypeface(localTypeface1);
tt.setTextColor(android.R.color.black);
TextView bt = (TextView) v.findViewById(R.id.item_subtitle);
bt.setBackgroundColor(R.color.white);
bt.setTypeface(localTypeface1);
bt.setTextColor(R.color.grey);
return v;
/*Typeface localTypeface1 = Typeface.createFromAsset(getAssets(), "fonts/arial.ttf");
View v = super.getView(position, view, parent);
((TextView) v).setTypeface(localTypeface1);
return v;*/
}
}
}

In the Declaration of Simple Adapter use this code
public MySimpleAdapter(Context context, ArrayList<? extends Map<String, String>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}
Or in other places , Change your ArrayList to List . I feel there's a conflict there .
Rahul, Use this link to understand a bit more on using SimpleAdapter

the answer is quite simple as it was my mistake, wasn't providing the ItemText to be viewed to the getView method:
public class MySimpleAdapter extends SimpleAdapter {
private ArrayList<HashMap<String, String>> results;
public MySimpleAdapter(Context context, ArrayList<HashMap<String, String>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
this.results = data;
}
public View getView(int position, View view, ViewGroup parent){
Typeface localTypeface1 = Typeface.createFromAsset(getAssets(), "fonts/arial.ttf");
View v = view;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
TextView tt = (TextView) v.findViewById(R.id.item_title);
tt.setText(results.get(position).get("title"));
tt.setTypeface(localTypeface1);
TextView bt = (TextView) v.findViewById(R.id.item_subtitle);
bt.setText(results.get(position).get("date"));
bt.setTypeface(localTypeface1);
return v;
}
}
:)

Related

How to use CustomAdapter with ListView from XML Async Task

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

Android Show autocomplete values within a HashMap

public class Select_outlet_sales extends Activity {
private AutoCompleteTextView select_outlet;
ArrayList<HashMap<String, String> > ar=new ArrayList<HashMap<String, String> >();
HashMap<String, String> x=new HashMap<String, String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_outlet_sales);
select_outlet = (AutoCompleteTextView) findViewById(R.id.select_outlet);
select_outlet.setTextIsSelectable(true);
getValues();
ArrayAdapter<HashMap<String, String>> adapter = new ArrayAdapter<HashMap<String, String>>(
this, android.R.layout.simple_dropdown_item_1line, ar);
select_outlet.setAdapter(adapter);
}
public void getValues() {
x.put("id"," aaaaa");
ar.add(x);
}
}
Here I used the above code to show data stored in a Hashmap but i want to display only the value of id. But when i try that it shows the entire hash map.Can you help me to do that?
Don't use ar but do something like this
List<String> strings = new ArrayList<String>();
for(int i = 0; i < x.size(); i++)
{
strings.add(x.get("id"));
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line,strings);
select_outlet.setAdapter(adapter);
That's because inside ArrayAdapter created list of HashMaps. You should translate your HashMap into ArrayList<Pair<String, String>> for example and override method getView of ArrayAdapter.
class MyAdapter extends ArrayAdapter<Pair<String, String>>{
public MyAdapter (Context context, List<Pair<String, String>> data) {
super(context, android.R.layout.simple_list_item_1,data);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null) {
view = new TextView(getContext());
}
((TextView)view).setText(getItem(position).second);
return view;
}
}
Add this to your code:
select_outlet.setOnItemClickListener( new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String, String> hashMap = (HashMap<String, String>)parent.getItemAtPosition
(position);
Iterator<String> iterator = hashMap.keySet().iterator();
while(iterator.hasNext()) {
String key = (String) iterator.next();
String value = (String)hashMap.get(key);
select_outlet.setText(value);
}
}
});
This will show only "aaaaa"in AutoComplete textbox.

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

not able to populate list from json android

I am trying to populate list object from an api.
This is one method jsonresult.
protected void onPostExecute(String result)
{
JSONArray con;
//String tag_name="tests";
//String tag_id="ID";
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
try
{
JSONObject jsonObject = new JSONObject(result);
if("success".equals(jsonObject.getString("result")))
{ Toast.makeText(getBaseContext(),jsonObject.getString("tests"),Toast.LENGTH_SHORT).show();
//String nKey=jsonObject.getString("nKey");
// switchActivity(nKey);
//Toast.makeText(getBaseContext(),nKey,Toast.LENGTH_SHORT).show();
try{
con = jsonObject.getJSONArray("tests");
for(int i = 0; i < con.length(); i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject c = con.getJSONObject(i);
map.put("EXAM", "" + c.getString("exam"));
map.put("ID", "" + c.getString("id"));
mylist.add(map);
}}catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.textview,new String[] { "exam", "id" },new int[] { R.id.exam, R.id.id });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
}
else
{
Toast.makeText(getBaseContext(),jsonObject.getString("message"),Toast.LENGTH_LONG).show();
}
}
catch (Exception e)
{
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
}
giving error at
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.textview,new String[] { "exam", "id" },new int[] { R.id.exam, R.id.id });
ERROR:
The constructor SimpleAdapter(examlist.ReadJSONResult, ArrayList<HashMap<String,String>>, int, String[], int[]) is undefined
Create a Custom Adpater for inflating the ListView.
public class MyListAdapter extends BaseAdapter {
ArrayList<HashMap<String, String>> data;
Activity a;
private static LayoutInflater inflater=null;
public MyListAdapter(Activity act, ArrayList<HashMap<String, String>> UserAndMessage)
{
data = UserAndMessage;
inflater = (LayoutInflater)act.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
a = act;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertview, ViewGroup parent) {
View vi = convertview;
if(null == vi)
{
vi = inflater.inflate(R.layout.listitem, null);
TextView ID= (TextView) vi.findViewById(R.id.ID);
TextView Exam= (TextView) vi.findViewById(R.id.exam);
HashMap<String,String> item = data.get(position);
ID.setText(item.get("name"));
EXAM.setText(item.get("message"));
}
return vi;
}
}
from onPostExecute() set ListView's Adapter as below:
myList = (ListView) findViewById(R.id.listView1);
myList.setAdapter(new MyListAdapter(this, UserAndMessage));
It's because there's not such constructor for ListAdapter as you use it. As a Context (first parameter) you're passing examlist.ReadJSONResult and you should pass a Context of a Activity in which the View which uses this ListAdapter is placed.
If the class in which you're setting ListAdapter is not an Activity, then you should pass the Activity's Context to this class and store it for example as a member field for further use.
For example your class is named ReadJSONResult. Create a constructor which takes Context as a parameter:
public ReadJSONResult(Context context) {
m_context = context; // There needs to be a field member in ReadJSONResult class called m_context
}
Thanks to that, in the Activity where you create ReadJSONResult object, you pass the Activity's Context to constructor and then you can create your ListAdapter like this:
ListAdapter adapter = new SimpleAdapter(m_context, mylist , R.layout.textview,new String[] { "exam", "id" },new int[] { R.id.exam, R.id.id });

in spinner items display the list array to replace drawable images how can implemented

i am using spinner in some application in spinner item list array this text replaced in drawable images how can its implemented
personalinformation = (Spinner) findViewById(R.id.SpinnerCategory);
ArrayAdapter<?> adapterDefaultpersonal = ArrayAdapter.createFromResource(Animals.this, R.array.Animalinformation, android.R.layout.simple_spinner_item);
adapterDefaultpersonal.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
personalinformation.setAdapter(adapterDefaultpersonal);
How can the R.array.Animalinformation array list items replaced in drawable images be implemented?
Yes it is look at the code below..
array of data
//stores the image database icons
private static Integer[] imageIconDatabase = { R.drawable.ball, R.drawable.catmouse, R.drawable.cube, R.drawable.fresh, R.drawable.guitar, R.drawable.orange, R.drawable.teapot };
//stores the image database names
private String[] imageNameDatabase = { "ball", "catmouse", "cube", "fresh", "guitar", "orange", "teapot" };
creating List of hashmaps
private void initializeImageList() {
// TODO Auto-generated method stub
ArrayList<HashMap<String, Object>> spinnerList = new ArrayList<HashMap<String,Object>>();
for (int i = 0; i < imageNameDatabase.length; i++) {
HashMap map = new HashMap();
map.put("Name", imageNameDatabase[i]);
map.put("Icon", imageIconDatabase[i]);
spinnerList.add(map);
}
ImageView imageView = new ImageView(this);
imageView.setBackgroundResource((spinnerList.get(0).get("Icon"));
spinnerList.get(0).get("Name");
}
// assigning spinner to adapter
public void createAddDialog() { // TODO
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.list_editoradd_dialog);
Spinner spin = (Spinner) findViewById(R.id.spinnerAddImageList);
CustomSpinnerAdapter adapter = new CustomSpinnerAdapter(this, spinnerData, R.layout.spinner_view, new String[] { "Name", "Icon" }, new int[] { R.id.imageNameSpinner, R.id.imageIconSpinner });
spin.setAdapter(adapter);
}
the adapter used above is as given below..
class CustomSpinnerAdapter extends SimpleAdapter {
LayoutInflater mInflater;
private List<? extends Map<String, ?>> dataRecieved;
public CustomSpinnerAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
dataRecieved = data;
mInflater = LayoutInflater.from(context);
}
#SuppressWarnings("unchecked")
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null) {
convertView = mInflater.inflate(R.layout.spinner_view,null);
}
HashMap<String, Object> data = (HashMap<String, Object>) getItem(position);
((TextView) convertView.findViewById(R.id.imageNameSpinner)).setText((String) dataRecieved.get(position).get("Name"));
((ImageView) convertView.findViewById(R.id.imageIconSpinner)).setBackgroundResource(dataRecieved.get(position).get("Icon")));
return convertView;
}
}

Categories

Resources