I want to add populate my listview using arrayadapter, im currently using simpleadapter. the reason i want to change my adapter is so that i can use the method notifyDataSetChanged(),
so can anyone show me how to do that using my codes below? i would really appreciate it
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
static final String URL = "https://news.instaforex.com/news";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_PUBDATE = "pubDate";
static final String KEY_DESCRIPTION = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ArrayList<HashMap<String, Spanned>> menuItems = new ArrayList<HashMap<String, Spanned>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, Spanned> map = new HashMap<String, Spanned>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_TITLE, Html.fromHtml(parser.getValue(e, KEY_TITLE)));
map.put(KEY_PUBDATE, Html.fromHtml(parser.getValue(e, KEY_PUBDATE)));
map.put(KEY_DESCRIPTION, Html.fromHtml(parser.getValue(e, KEY_DESCRIPTION)));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_TITLE, KEY_PUBDATE }, new int[] {
R.id.name, R.id.cost });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String title = menuItems.get(position).get(KEY_TITLE).toString();
String pubDate = menuItems.get(position).get(KEY_PUBDATE).toString();
String description= menuItems.get(position).get(KEY_DESCRIPTION).toString();
System.out.println("PubDate==>"+pubDate+"\n Description===>"+description);
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_TITLE, title);
in.putExtra(KEY_PUBDATE, pubDate);
in.putExtra(KEY_DESCRIPTION, description);
startActivity(in);
}
});
}
}
notifyDataSetChanged() is a BaseAdapter method, the parent class of SimpleAdapter and ArrayAdapter. SimpleAdapter and ArrayAdapter are different mainly with respect to the data provided to the AdapterView. While a SimpleAdapter is backed by XML data, an ArrayAdapter is backed by an array of arbitrary data.
In other words there's no need to change the type of adapter.
Now the documentation states that a SimpleAdapter is "an easy adapter to map static data to views" which is discussed in more detail e.g. here. But fact is that a SimpleAdapter works with dynamic data too.
If you still want to switch to an ArrayAdapter then you have to overwrite the ArrayAdapter's getView() method because an ArrayAdapter supports only a single TextView per row (unlike the SimpleAdapter that supports mapping of multiple values to multiple Views for a single row).
There are numerous tutorials on ArrayAdapter out there, e.g. this one:
http://www.vogella.com/articles/AndroidListView/article.html#adapterown_example.
Related
I am working on health related app. In ListView I want to assign value to each item. For example milk contains 21 calories so I want to assign 21 to ListView item milk.
Here is my activity code containing ListView.
public class FoodEntry extends AppCompatActivity {
// Array of strings...
String[] food = {"Naan","Pav bhaji","chole tikiya", "rice", "soybean", "milk", "curd"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_entry);
ArrayAdapter adapter = new ArrayAdapter<>(this, R.layout.activity_item, food);
ListView listViewFoodItems = (ListView)findViewById(R.id.listViewFood);
listViewFoodItems.setAdapter(adapter);
}
}
Instead of using a String[] to store your data like you're doing here:
// Array of strings...
String[] food = {"Naan","Pav bhaji","chole tikiya", "rice", "soybean", "milk", "curd"};
Use a new object, such as CalorieCount.
// Array of CalorieCount
CalorieCount[] food = { new CalorieCount("Naan", 20) ... };
You can use SimpleAdapter with Hashmap
foodItems= new ArrayList<HashMap<String, String>>();
//create first item object
HashMap<String, String> item1= new HashMap<String, String>();
item1.put("name", "Naan");
item1.put("calories", "21");
foodItems.add(item1)//add multiple items like this
String[] from = { "name"};
// view id's to which data to be binded
int[] to = { R.id.name};
//Creating Adapter
ListAdapter adapter = new SimpleAdapter(MainActivity.this, foodItems,
R.layout.activity_item, from, to);
//Setting Adapter to ListView
listViewFoodItems.setAdapter(adapter);
To know more visit How SimpleAdapter Binds Hashmap Data to items of ListView
I want to use AsynTask to do custom list with xml from url. I am novice so I don´t know how to structure this properly. When the fragment start doesn´t display nothing. I am using Swipe views with fragments but I don´t know how correct the issue
public class UltimasFragment extends Fragment {
static final String URL = "http://myurl.com/songs";
// XML node keys
static final String KEY_SONG = "songs"; // parent node
static final String KEY_ID = "id_song";
static final String KEY_TITLE = "name";
static final String KEY_THUMB_URL = "picture";
static final String KEY_ARTIST = "duration";
View view;
ListView list;
LazyAdapter adapter;
private ProgressDialog dialog;
public ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.ultimas, container, false);
new MiTarea().execute();
list=(ListView) view.findViewById(R.id.lista);
// Getting adapter by passing xml data ArrayList
//adapter=new LazyAdapter(this, songsList);
adapter=new LazyAdapter(getActivity(), songsList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String idrecibida =songsList.get(+position).get("id_song");
String nombrerecibido =songsList.get(+position).get("name");
String caratularecibida =songsList.get(+position).get("picture");
String nuestraoprecibida =songsList.get(+position).get("duration");
}
});
return view;
}
private class MiTarea extends AsyncTask<String, String, String>{
protected void onPreExecute() {
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Actualizando...");
dialog.setIndeterminate(false);
dialog.setCancelable(true);
dialog.show();
}
protected String doInBackground(String... args) {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_SONG);
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
songsList.add(map);
}
return xml;
}
protected void onPostExecute(String bytes) {
dialog.dismiss();
// adding HashList to ArrayList
}
}
}
Here is how to impement async task
http://developer.android.com/reference/android/os/AsyncTask.html
The preExecute method allow you to perform operations before starting the job you want to do asyncronously.
the doInBackground method is here to do your async job.
the on postExecute method will receive what doInBackground returns if it returns something.
if you need to pass parameters to your class like a context, my advice is to make a constructor and passing parameters to it ;)
hope it helped.
regards.
The three parameters are: the parameter type of doInBackground, the parameter type of onProgressUpdate and the parameter type of onPostExecute.
See here the usage:
http://developer.android.com/reference/android/os/AsyncTask.html
Remember to call setReteainInstance(true) in the fragment in this case, because if the fragment is remove you lost the reference to the AsyncTask.
So, so far i built a list of json object like this
public class list extends ListActivity{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
Intent i = getIntent();
String snopel = i.getStringExtra("nopel");
String snama = i.getStringExtra("nama");
String salamat = i.getStringExtra("alamat");
String sgolongan = i.getStringExtra("golongan");
TextView tx_nopel = (TextView)findViewById(R.id.l_nopel);
TextView tx_nama= (TextView)findViewById(R.id.l_nama);
TextView tx_alamat = (TextView)findViewById(R.id.l_alamat);
TextView tx_golongan = (TextView)findViewById(R.id.l_golongan);
tx_nopel.setText(snopel);
tx_nama.setText(snama);
tx_alamat.setText(salamat);
tx_golongan.setText(sgolongan);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("nopel", snopel));
ArrayList<HashMap<String, String>> lr = new ArrayList<HashMap<String, String>>();
JSON json_lr = new JSON();
JSONObject jobj_lr = json_lr.getJSON("http://10.0.2.2/KP/pdam/listtagihan.php", pairs);
try {
int length = jobj_lr.getInt("panjang");
for(int n = 1; n <= length; n++){
String m = Integer.toString(n);
JSONObject row = jobj_lr.getJSONObject(m);
String snomor = row.getString("nomor");
String sbulan = row.getString("bulan");
String stahun = row.getString("tahun");
String stagihan = "Rp. " + row.getString("tagihan");
HashMap<String, String> rek = new HashMap<String, String>();
rek.put("nomor", snomor);
rek.put("bulan", sbulan);
rek.put("tahun", stahun);
rek.put("tagihan", stagihan);
lr.add(rek);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter_lr = new SimpleAdapter(this, lr, R.layout.list_data,
new String[]{"nomor","bulan","tahun","tagihan"},
new int[]{R.id.textView1, R.id.textView2, R.id.textView3, R.id.textView4});
setListAdapter(adapter_lr);
ListView lv_lr = getListView();
lv_lr.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Intent i = new Intent(list.this, rincian.class);
i.putExtra("nomor", ((TextView)view.findViewById(R.id.textView1)).getText().toString());
startActivity(i);
}
});
}
}
that will show one listview in one listactivity, but I wonder if I can make 2 custom listviews in 1 list activity, but I can't figure out how to
I think that it's impossible because in listactivity we must set the adapter that can just choose 1 list adapter like this setListAdapter(adapter_lr);
but I want to know for sure is it true?
Thanks in advance.
why you need two listview in one Activity ?
if you want two listview then you can extends Activity and add two listview in layout file.
Now,
ListView listView1=(ListView)findViewById(R.id.listview1);
ListView listView2=(ListView)findViewById(R.id.listview2);
You can create two custom list view in one list activity by declaring them in xml file
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="Value in dps"
></ListView>
<ListView
android:id="#+id/list1"
android:layout_width="fill_parent"
android:layout_height="Value in dps"
></ListView>
one list id must be #android:id/list other can be anything of yor choice and you can set adapters as you want in code.
You need to extend Activity class in YourClass, and you can have as many List view from layout.
I am trying to get my head round using SimpleAdapter however I am struggling with one item.
How do I return the array of data for the selected view?
Here is the code I use to generate it.
// Data for List Adapter
List<Map<String, Object>> resourceNames = new ArrayList<Map<String, Object>>();
// Make Hashmap of Results Hashmaps
generateData(resourceNames);
//Source information from Hashmap keys (FROM)
String keynames[]={"names","descriptions"};
// Target Views for Data (TO)
int[] targets = new int[] { R.id.textfield_name,R.id.textfield_description};
// Create my Simple Adapter
SimpleAdapter adapter = new SimpleAdapter(this, resourceNames,
R.layout.listrow, keynames,targets
);
setListAdapter(adapter);
}
I then use an onclick listener to get the data using the following code:
setContentView(R.layout.listview);
final ListView listView = getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
Toast.makeText(arg1.getContext(),
getString(R.string.selected) + " " + position,
Toast.LENGTH_SHORT).show();
// How do I return the entire data that I used
}
});
I can see above how I get the position of the data in the array- but how do I return the actual results data being shown in the view??
Declare List<Map<String, Object>> resourceNames = new ArrayList<Map<String, Object>>();
globally and in ListView's onItemClick() just put line,
Map<String, Object> map = resourceNames.get(position);
I have the following in one of my tabs:
ListView list=(ListView)findViewById(R.id.countries);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, COUNTRIES);
list.setAdapter(adapter);
static final String[] COUNTRIES = new String[] {
"List Item 1", "List Item 2", "List Item 3" };
This list is within a tab. I want to change it so when one of the items is clicked (say we call it London Big Ben, I want to somehow attach co-ordinates to that) it diverts to Google Maps either via WebView (easiest) or MapView appears over the tab (but the tab bar is still visible).
Can anyone provide links to tutorials or assistance?
This is the code where i am put my data inside arraylist which i am fetching from Web Service.
public static ArrayList<HashMap<String, String>> mylist;
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("Name",name);
map.put("Vicinity", vicinity);
map.put("Latitude", lat);
map.put("Longitude", lng);
mylist.add(map);
}
After this below is the code of ListView Activity class. Where i have implemented on click listner and on click of listview calling another activity and passing the position of the list which is clicked.
ListViewActivity Class code
public class ListViewActivity extends ListActivity implements OnItemClickListener{
private ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listingatms);
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.listdata,
new String[] {"Name", "Vicinity"},
new int[] { R.id.item_title, R.id.item_subtitle});
setListAdapter(adapter);
lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
// TODO Auto-generated method stub
Intent showMapMenusIntent = new Intent(ListViewActivity.this, MapMenus.class);
showMapMenusIntent.putExtra("Position", position);
startActivity(showMapMenusIntent);
}
If you want to show the map in the same activity then use the postion variable and on the basis of that you can get all the values from mylist(ArrayList).
For e.g position = mylist.get(position).get("Name"));
This way you will be able to get all the details from ArrayList and use it as per your requirement.
Hope this will help you...