I have a custom list adapter that reads in data from a xml file that is hosted online, each one is for a different article. My question is how do I make each list item open a different corresponding article? The articles will be hosted online.
Thank you in advance.
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import java.util.ArrayList;
import java.util.HashMap;
public class CustomizedListView extends Fragment { // All static variables
// XML node keys
static final String KEY_SONG = "song"; // parent node
static final String KEY_ID = "id";
static final String KEY_ARTIST = "artist";
static final String KEY_DURATION = "duration";
static final String KEY_THUMB_URL = "thumb_url";
ListView list;
LazyAdapter adapter;
ArrayList<HashMap<String, String>> songsList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.news, container, false);
songsList = new ArrayList<HashMap<String, String>>();
list=(ListView) rootView.findViewById(R.id.list);
new RetrieveXML().execute(URL);
// Getting adapter by passing xml data ArrayList
// Click event for single list row XMLParser parser = new XMLParser();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
return rootView;
}
class RetrieveXML extends AsyncTask<String, Void, String> {
private Exception exception;
XMLParser parser = new XMLParser();
protected String doInBackground(String... urls) {
try {
return parser.getXmlFromUrl(urls[0]);
} catch (Exception e) {
this.exception = e;
return null;
}
}
protected void onPostExecute(String xml) {
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_ARTIST, parser.getValue(e, KEY_ARTIST));
map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_ID));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
songsList.add(map);
}
adapter=new LazyAdapter(getActivity(), songsList);
list.setAdapter(adapter);
}
}
}
You have implemented:
onItemClick()
In this you get the position of item in the list as parameter. here you can write a switch case to accomplish your task. This function gets triggered when any listitem is clicked.
Something like this you can do:
private string[] mArticles={
"abc",
"def",
"ghi",
"jkl"
};
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
openArticle(mArticles[position]);
}
While creating the string array keep appropriate artile link for each item position.
Related
I have recently developed an android app, which is parsing the xml links, whenever i use the app it responds very slowly, because each time i open the app and navigate the pages on the app, it parse it then give the data,
is there any way so that i could speed up the app, i have searched for it on google, but have not got any idea, it stated to use the volley library, but no result as i am unable to use that,
plz help guys if anyone has any option , is there any way that i could parse the link and store it into the cache and then retrive from there..
package com.stepupup.pm;
import info.stepupup.tabswipe.R;
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class Cricket extends ListFragment {
static final String URL = "http://www.statenewsonline.com/category/sports/cricket/feed";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_NAME = "title";
static final String KEY_COST = "link";
static final String KEY_DESC = "content:encoded";
static final String KEY_PUB = "pubDate";
Context context;
Typeface font;
String nam,cost,desc,ti,cdesc,lnk1;
TextView t1;;
TextView t2,t3,t5,t15;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.cricket, container, false);
font=Typeface.createFromAsset(getActivity().getAssets(), "DroidHindi.ttf");
return rootView;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
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, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_NAME, (parser.getValue(e, KEY_NAME)));
map.put(KEY_COST, parser.getValue(e, KEY_COST));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
map.put(KEY_PUB, parser.getValue(e, KEY_PUB));
// map.put(KEY_CDESC, parser.getValue(e, KEY_CDESC));
// adding HashList to ArrayList
menuItems.add(map);
}
ListAdapter adapter = new SimpleAdapter(getActivity(), menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC,KEY_COST}, new int[] {
R.id.name1, R.id.description, R.id.link1}){
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewGroup view = (ViewGroup) super.getView(position, convertView, parent);
if(convertView == null) Cricket.setAppFont(view, font);
t1=(TextView)view.findViewById(R.id.name1);
t1.setTypeface(font);
t2=((TextView)view.findViewById(R.id.description));
t2.setTypeface(font);
t15=(TextView)view.findViewById(R.id.link1);
t15.setTypeface(font);
return view;
}
};
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) {
// getting values from selected ListItem
t1=(TextView)view.findViewById(R.id.name1);
nam=t1.getText().toString();
t2=((TextView)view.findViewById(R.id.description));
desc = t2.getText().toString();
t15=(TextView)view.findViewById(R.id.link1);
lnk1=t15.getText().toString();
// cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
ti = ((TextView) view.findViewById(R.id.time)).getText().toString();
// Starting new intent
Intent in = new Intent(getActivity(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, nam);
in.putExtra(KEY_COST, lnk1);
in.putExtra(KEY_DESC, desc);
in.putExtra(KEY_PUB, ti);
startActivity(in);
}
});
}
protected static void setAppFont(ViewGroup view, Typeface font2) {
// TODO Auto-generated method stub
}
}
and the folllwing is my xml file..
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ffffff" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>
Android Documentation says,
We recommend XmlPullParser, which is an efficient and maintainable way
to parse XML on Android. Historically Android has had two
implementations of this interface:
KXmlParser via XmlPullParserFactory.newPullParser().
ExpatPullParser, via Xml.newPullParser().
You can find a good example in that page. Don't forget to use Async task and do that network related stuff in background. Good luck!
One obvious problem with your code is that you do network request on the UI thread, here:
public void onActivityCreated(Bundle savedInstanceState) {
...
String xml = parser.getXmlFromUrl(URL); // getting XML
...
}
I don't know where XMLParser is coming from, but, just from the method's name, it is downloading something from the network. You should never do such things on the UI thread. Instead, this should be done on the background thread, and the results should be delivered on the UI thread.
Now which exactly mechanism to use for that is up to you. There are lots of options, with different advantages and trade-offs. AsyncTask mechanism was already mentioned, and it indeed might be an appropriate solution (but not always). Other possibilities are RxJava, RoboSpice, Guava's ListenableFutures, etc.
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.
I have been trying to sort out this class file all day and I have run into yet more problems. I believe this class file is setup completely wrong. I think the AsyncTask is incorrect as well as my onCreateView is I believe as well. What I am trying to do is download a XML file from the internet and put the information into areas for the ListView to use. I have had it working but I decided to change it for use as a fragment and that is when the problems have arose as you cannot have the same stuff for an activity as a fragment obviously. Here is my class file and as I do not understand where I have gone wrong in terms of the AsyncTask especially could I have some help. Thanks for helping me out!
Errors: The parser on the AsyncTask cannot have the symbol resolved and the xml string is incorrect for what I want to use it for. I really am lost here now.
CustomizedListView.class
public class CustomizedListView extends Fragment {
// All static variables
static final String URL = "http://api.androidhive.info/music/music.xml";
// XML node keys
static final String KEY_SONG = "song"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_ARTIST = "artist";
static final String KEY_DURATION = "duration";
static final String KEY_THUMB_URL = "thumb_url";
ListView list;
LazyAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
final View v = inflater.inflate(R.layout.list_row, container, false);
list = (ListView) v.findViewById(R.id.game_list);
return v;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
new TheTask().execute();
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_ARTIST, parser.getValue(e, KEY_ARTIST));
map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
songsList.add(map);
}
// Getting adapter by passing xml data ArrayList
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) {
}
});
}
}
class TheTask extends AsyncTask<Void,Void,Void> {
static final String URL = "http://api.androidhive.info/music/music.xml";
static final String xml = xml;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
String xml = parser.getXmlFromUrl(URL);
return null;
}
}
Logcat Error after code change:
07-20 20:48:18.941 22942-22942/com.example.app E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.app.CustomizedListView.onCreate(CustomizedListView.java:52)
at android.support.v4.app.Fragment.performCreate(Fragment.java:1437)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:877)
at android.support.v4.app.FragmentManagerImpl.performPendingDeferredStart(FragmentManager.java:807)
at android.support.v4.app.Fragment.setUserVisibleHint(Fragment.java:801)
at android.support.v4.app.FragmentPagerAdapter.setPrimaryItem(FragmentPagerAdapter.java:130)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1062)
at android.support.v4.view.ViewPager.populate(ViewPager.java:911)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1432)
at android.view.View.measure(View.java:15525)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15525)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:15525)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2434)
at android.view.View.measure(View.java:15525)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1874)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1089)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1265)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
at android.view.Choreographer.doCallbacks(Choreographer.java:562)
at android.view.Choreographer.doFrame(Choreographer.java:532)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5227)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
at dalvik.system.NativeStart.main(Native Method)
You were doing it completely wrong.. I would suggest to go and read about Multi Threaded Programming and Asynchronous Tasks a little which will help you a lot around this..
You had many issues in the code, I fixed a lot of things but I will mention the most important ones and the ones I actually remember :p
If you want to use globally defined variables then your AsyncTask class should be defined within your Activity class.. Which in your case was defined outside
When you execute a AsyncTask, it creates a new thread and the commands in the new background thread are ran independently from the ones the UI thread. My point is that, many people think the UI thread will stop for the Background thread to finish working. Which is wrong and also a common problem within programmers.
You really hate indentation. Don't you? It makes other programmers go nuts, when reading a bad indented code, which leads into your question remaining unanswered.
Here is the fixed code:
public class CustomizedListView extends Fragment {
// All static variables
static final String URL = "http://api.androidhive.info/music/music.xml";
// XML node keys
static final String KEY_SONG = "song"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_ARTIST = "artist";
static final String KEY_DURATION = "duration";
static final String KEY_THUMB_URL = "thumb_url";
ListView list;
ArrayList<HashMap<String, String>> songsList;
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
final View v = inflater.inflate(R.layout.list_row, container, false);
list = (ListView) v.findViewById(R.id.game_list);
view = v;
return v;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new TheTask().execute();
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
});
}
class TheTask extends AsyncTask<Void, Void, Void> {
static final String URL = "http://api.androidhive.info/music/music.xml";
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
songsList = new ArrayList<HashMap<String, String>>();
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_ARTIST, parser.getValue(e, KEY_ARTIST));
map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
songsList.add(map);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Getting adapter by passing xml data ArrayList
LazyAdapter adapter = new LazyAdapter(getActivity(), songsList);
((ListView) view.findViewById(R.id.game_list)).setAdapter(adapter);
super.onPostExecute(result);
}
}
}
How to this edit code for use AsyncTask.
code use for ListFragment. I try with this code on OnCreateView application allways creshed and found I mast use AsyncTask. for parse xml from url. I use custom listview.
Url=
Code is here
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AndroidXMLParsingActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
final 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, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_COST, "Datum: " + parser.getValue(e, KEY_COST));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
map.put(KEY_LINK, parser.getValue(e, KEY_LINK));
map.put(KEY_LINK1, parser.getValue(e, KEY_LINK1));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_row,
new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
R.id.naslov, R.id.novost, R.id.datum });
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) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.naslov)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.datum)).getText().toString();
String description = ((TextView) view.findViewById(R.id.novost)).getText().toString();
String link=KEY_LINK;
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_COST, cost);
in.putExtra(KEY_DESC, description);
in.putExtra(KEY_LINK, link);
in.putExtra("link1", KEY_LINK1);
startActivity(in);
}
});
}
}
I am trying to create a tab using fragments which will display a list of entries after parsing a xml page. But I am unable to extend listactivity int the tab class as it already extends fragments.I have tried implementing listfragments but it is giving me an error on ListAdapter adapter = new SimpleAdapter saying "The constructor SimpleAdapter(Protab1, ArrayList>, int, String[], int[]) is undefined".Could you please help me out.
package com.example.pro1;
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class Protab1 extends ListFragment {
// All static variables
static final String URL = "http://api.androidhive.info/pizza/?format=xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.protab1, container, false);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
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, 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_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
R.id.name, R.id.desciption, R.id.cost });
setListAdapter(adapter);
}
}
Try using this.getActivity() instead of this as first parameter of the SimpleAdapter. The first parameter takes a Context object, but since a ListFragment (or any Fragment) does not extend Context, it will not work.