I tried to implement for adding more items to my adapter but its refreshing every time instead of adding new items to bottom of the list.I searched through the internet but i didn't get the solution Here is my code:
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
private DataListAdapter dataListAdapter;
Activity _activity;
ArrayList<DataObject> dataArrayList;
private ListView lv;
private String jsonResult;
boolean loadingMore = false;
private DataObject dataObject;
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_activity = this;
lv = (ListView) findViewById(R.id.listView1);
View footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.loading_view, null, false);
this.lv.addFooterView(footerView);
if (isOnline(_activity)) {
new LoadJsonData().execute();
scrollNotifyChange();
}
}
private void scrollNotifyChange() {
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//what is the bottom item that is visible
int lastInScreen = firstVisibleItem + visibleItemCount;
//is the bottom item visible & not loading more already? Load more!
if ((lastInScreen == totalItemCount) && !(loadingMore)) {
// //start a new thread for loading the items in the list
Thread thread = new Thread(null, loadMoreListItems);
thread.start();
}
}
});
}
private Runnable loadMoreListItems = new Runnable() {
#Override
public void run() {
//Set flag so we cant load new items 2 at the same time
loadingMore = true;
//Reset the array that holds the new items
//Simulate a delay, delete this on a production environment!
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
jsonResult = doInBackground();
runOnUiThread(returnRes);
}
};
private Runnable returnRes = new Runnable() {
#Override
public void run() {
onPostExecute(jsonResult);
loadingMore = false;
}
};
public String doInBackground() {
String jsonResult = "";
// jsonResult=get("https://datatables.net/examples/server_side/scripts/server_processing.php");
// return jsonResult;
InputStream inputStream = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet("https://datatables.net/examples/server_side/scripts/server_processing.php");
HttpResponse httpResponse = httpclient.execute(request);
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null) {
jsonResult = convertInputStreamToString(inputStream);
} else {
jsonResult = "Did not work!";
}
} catch (Exception e) {
Log.e(TAG, "GET failed", e);
}
return jsonResult;
}
public void onPostExecute(String result) {
try {
// progress.dismiss();
dataArrayList = new ArrayList<DataObject>();
JSONObject dataJsontObject = new JSONObject(result);
JSONArray dataJsonArray = dataJsontObject.getJSONArray("data");
for (int i = 0; i < dataJsonArray.length(); i++) {
JSONArray dataSubArray = dataJsonArray.getJSONArray(i);
dataObject = new DataObject();
dataObject.setName((String) dataSubArray.get(0));
dataObject.setType((String) dataSubArray.get(1));
dataObject.setProfession((String) dataSubArray.get(2));
dataObject.setCountry((String) dataSubArray.get(3));
dataObject.setCurrency((String) dataSubArray.get(5));
dataArrayList.add(dataObject);
}
dataListAdapter = new DataListAdapter(dataArrayList);
dataListAdapter.add(dataObject);
// lv.setAdapter(dataListAdapter);
// dataListAdapter.add(dataObject);
dataListAdapter.notifyDataSetChanged();
lv.setAdapter(dataListAdapter);
lv.smoothScrollToPosition(dataListAdapter.getCount());
} catch (JSONException e) {
e.printStackTrace();
}
}
public static boolean isOnline(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
private class LoadJsonData extends AsyncTask<Void, Void, String> {
ProgressDialog progress;
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = ProgressDialog.show(_activity, "Progress",
"Please wait", true);
}
#Override
protected String doInBackground(Void... params) {
String jsonResult = "";
// jsonResult=get("https://datatables.net/examples/server_side/scripts/server_processing.php");
// return jsonResult;
InputStream inputStream = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet("https://datatables.net/examples/server_side/scripts/server_processing.php");
HttpResponse httpResponse = httpclient.execute(request);
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null) {
jsonResult = convertInputStreamToString(inputStream);
} else {
jsonResult = "Did not work!";
}
} catch (Exception e) {
Log.e(TAG, "GET failed", e);
}
return jsonResult;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
progress.dismiss();
if(loadingMore)
{
// listViwe.removeFooterView(loadingFooter);
loadingMore = false;
}
dataArrayList = new ArrayList<DataObject>();
JSONObject dataJsontObject = new JSONObject(result);
JSONArray dataJsonArray = dataJsontObject.getJSONArray("data");
for (int i = 0; i < dataJsonArray.length(); i++) {
JSONArray dataSubArray = dataJsonArray.getJSONArray(i);
DataObject dataObject = new DataObject();
dataObject.setName((String) dataSubArray.get(0));
dataObject.setType((String) dataSubArray.get(1));
dataObject.setProfession((String) dataSubArray.get(2));
dataObject.setCountry((String) dataSubArray.get(3));
dataObject.setCurrency((String) dataSubArray.get(5));
dataArrayList.add(dataObject);
}
dataListAdapter = new DataListAdapter(dataArrayList);
lv.setAdapter(dataListAdapter);
dataListAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
if(loadingMore)
{
// listViwe.removeFooterView(loadingFooter);
loadingMore = false;
}
}
}
}
public class DataListAdapter extends BaseAdapter {
ArrayList<DataObject> dataListObject = new ArrayList<DataObject>();
public DataListAdapter(ArrayList<DataObject> dataListObject) {
this.dataListObject = dataListObject;
}
#Override
public int getCount() {
return dataListObject.size();
}
#Override
public Object getItem(int position) {
return dataListObject.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void add(DataObject dataObject){
// Log.v("AddView", country.getCode());
this.dataListObject.add(dataObject);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(_activity);
convertView = inflater.inflate(R.layout.single_row, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.type = (TextView) convertView.findViewById(R.id.type);
holder.profession = (TextView) convertView.findViewById(R.id.profession);
holder.country = (TextView) convertView.findViewById(R.id.country);
holder.currency = (TextView) convertView.findViewById(R.id.currecy);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final DataObject current = dataListObject.get(position);
holder.name.setText("Name--" + current.getName());
holder.type.setText("Type--" + current.getType());
holder.profession.setText("Professoion--" + current.getProfession());
holder.country.setText("Country--" + current.getCountry());
holder.currency.setText("Currency--" + current.getCurrency());
return convertView;
}
}
static class ViewHolder {
TextView name;
TextView type;
TextView profession;
TextView country;
TextView currency;
}
public static String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
inputStream.close();
return result;
}
}
you need to create an adapter inside onCreate method
like this:
ArrayList<DataObject> list;
onCreate() {
list=new ArrayList();
ListAdapter dataListAdapter =new ListAdapter(list) // creating an adapter with empty list of data
listView.setAdpater(adpater);
}
then, in onPostExceute() method :
add data to the ArrayList and notifythe adapter
like this:
onPostExecute(){
....
.....
list.add(dataObject); //here you can add 'n' number of object to the list
dataListAdapter.notifyDataSetChanged(); // notify the adapter to update the listview
.....
}
EDIT : I updated this answer as per #user3422948 request
DataListAdapter dataListAdapter;
ArrayList<DataObject> dataArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_activity = this;
//edit: declare your arraylist and adapter here
dataArrayList = new ArrayList<DataObject>();
dataListAdapter = new DataListAdapter(dataArrayList);
lv = (ListView) findViewById(R.id.listView1);
View footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.loading_view, null, false);
this.lv.addFooterView(footerView);
if (isOnline(_activity)) {
new LoadJsonData().execute();
scrollNotifyChange();
}
}
......
.......
public void onPostExecute(String result) {
try {
// progress.dismiss();
//dataArrayList = new ArrayList<DataObject>(); //edit
JSONObject dataJsontObject = new JSONObject(result);
JSONArray dataJsonArray = dataJsontObject.getJSONArray("data");
for (int i = 0; i < dataJsonArray.length(); i++) {
JSONArray dataSubArray = dataJsonArray.getJSONArray(i);
dataObject = new DataObject();
dataObject.setName((String) dataSubArray.get(0));
dataObject.setType((String) dataSubArray.get(1));
dataObject.setProfession((String) dataSubArray.get(2));
dataObject.setCountry((String) dataSubArray.get(3));
dataObject.setCurrency((String) dataSubArray.get(5));
dataArrayList.add(dataObject);
}
//edit: your creating new adapter for every execution
//dataListAdapter = new DataListAdapter(dataArrayList);
//dataListAdapter.add(dataObject);
// lv.setAdapter(dataListAdapter);
// dataListAdapter.add(dataObject);
dataListAdapter.notifyDataSetChanged();
//lv.setAdapter(dataListAdapter);
lv.smoothScrollToPosition(dataListAdapter.getCount());
} catch (JSONException e) {
e.printStackTrace();
}
}
the problem is for every execution you are creating new Adapter
you should see this link how to use notifyDataSetChanged in listView
AsyncTask spawns a new intelligent thread on its own, runs things in background and also posts results of UI thread in onPostExecute method.
You should not call the methods of AsyncTask on your own. Android does it by itself. Instead of calling a new thread in scrollchangelistener,like:
Thread thread = new Thread(null, loadMoreListItems);
call
new LoadJsonData().execute();
you don't need two Runnable threads to do the same thing your asyncTask does.
The problem is this code of yours:
dataListAdapter = new DataListAdapter(dataArrayList);
lv.setAdapter(dataListAdapter);
Every time your scrolling reaches the end, it eventually calls the onPostExecute method to post results on the UI. But here you are making a new Adapter eveytime with a new dataset which is why it always refreshes the whole list.
Remove this part and set it inside onCreate of your Activity.Add new values to your adapter's datalist in onPostExecute.
Then just do a notifyDataSetChanged inside onPostExecute of your AsyncTask.
I am trying to Parse XML which is getting stored in a list view. Here is my code:
XMLParser.java
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
/**
* Getting XML DOM element
* #param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/** Getting node value
* #param elem element
*/
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
AndroidXMLParsingActivity.java
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
static final String URL = "http://www.findyourfate.com/rss/dailyhoroscope-feed.asp?sign=Capricorn";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_DESC = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
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_TITLE, parser.getValue(e, KEY_TITLE));
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_TITLE, KEY_DESC}, new int[] {
R.id.name, R.id.desciption});
setListAdapter(adapter);
}
}
Now I want to store this parsed value in a string, instead of this list. But when I try parser.getValue(e, KEY_DESC)); I dont know what is element here. How should I do if I want KEY_DESC to set as text of textview t1.?
EDIT:
I tried doing like this but it shows NullPointer exception. Here is what I tried:
XMLParserActivity.class:
public class XMLParserActivity extends Fragment {
Button b1;
TextView t1;
EditText e1;
String sunsign;
static final String URL = "http://www.findyourfate.com/rss/dailyhoroscope-feed.asp?sign=Capricorn";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_DESC = "description";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.horoscope,
container, false);
e1 = (EditText) rootView.findViewById(R.id.editText1);
b1 = (Button) rootView.findViewById(R.id.button1);
t1 = (TextView) rootView.findViewById(R.id.textView1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
sunsign = e1.getText().toString();
ShowResult(sunsign);
// Toast.makeText(getActivity(), ""+fullname,
// Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
private void ShowResult(String fullname) {
// TODO Auto-generated method stub
new Thread(new Runnable(){
public void run()
{
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);
Element e = (Element) nl.item(0);
String desc = parser.getValue(e, KEY_DESC);
t1.setText(desc);
}
}).start();
DoStyling();
}
public void DoStyling() {
// TODO Auto-generated method stub
t1.setVisibility(View.VISIBLE);
//Toast.makeText(getActivity(), ""+lovenumarray, Toast.LENGTH_SHORT).show();
}
}
LogCat:
10-14 18:44:35.712: E/AndroidRuntime(17084): FATAL EXCEPTION: main
10-14 18:44:35.712: E/AndroidRuntime(17084): java.lang.NullPointerException
10-14 18:44:35.712: E/AndroidRuntime(17084): at tech.know.merge.calove.HoroscopeFragment.DoStyling(HoroscopeFragment.java:82)
10-14 18:44:35.712: E/AndroidRuntime(17084): at tech.know.merge.calove.HoroscopeFragment.ShowResult(HoroscopeFragment.java:76)
10-14 18:44:35.712: E/AndroidRuntime(17084): at tech.know.merge.calove.HoroscopeFragment.access$0(HoroscopeFragment.java:59)
10-14 18:44:35.712: E/AndroidRuntime(17084): at tech.know.merge.calove.HoroscopeFragment$1.onClick(HoroscopeFragment.java:49)
10-14 18:44:35.712: E/AndroidRuntime(17084): at android.view.View.performClick(View.java:4211)
10-14 18:44:35.712: E/AndroidRuntime(17084): at android.view.View$PerformClick.run(View.java:17446)
10-14 18:44:35.712: E/AndroidRuntime(17084): at android.os.Handler.handleCallback(Handler.java:725)
10-14 18:44:35.712: E/AndroidRuntime(17084): at android.os.Handler.dispatchMessage(Handler.java:92)
10-14 18:44:35.712: E/AndroidRuntime(17084): at android.os.Looper.loop(Looper.java:153)
10-14 18:44:35.712: E/AndroidRuntime(17084): at android.app.ActivityThread.main(ActivityThread.java:5297)
10-14 18:44:35.712: E/AndroidRuntime(17084): at java.lang.reflect.Method.invokeNative(Native Method)
10-14 18:44:35.712: E/AndroidRuntime(17084): at java.lang.reflect.Method.invoke(Method.java:511)
10-14 18:44:35.712: E/AndroidRuntime(17084): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
10-14 18:44:35.712: E/AndroidRuntime(17084): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
10-14 18:44:35.712: E/AndroidRuntime(17084): at dalvik.system.NativeStart.main(Native Method)
Hello Here You can do solve your problem using DOM Parser
class getData extends AsyncTask<Void, Void, String> {
private ProgressDialog mProgress;
private String responseString;
private String result;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mProgress = new ProgressDialog(DOMXMLParsingActivity.this);
mProgress.setMessage("Loading");
mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgress.setCancelable(false);
mProgress.show();
}
#Override
protected String doInBackground(Void... unsued) {
try {
HttpPost httpPost = new HttpPost(
"http://www.findyourfate.com/rss/dailyhoroscope-feed.asp?sign=Capricorn");
httpPost.addHeader("Accept", "application/xml");
httpPost.addHeader("Content-Type", "application/xml");
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = (HttpResponse) httpclient
.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
responseString = EntityUtils.toString(httpResponse
.getEntity());
System.out.println("pankaj " + responseString);
result = "true";
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("error" + e);
result = "false";
}
return result;
}
#Override
protected void onPostExecute(String sResponse) {
mProgress.dismiss();
if (result.equals("true")) {
XMLDOMParser parser = new XMLDOMParser();
ArrayList<Data> datas = new ArrayList<Data>();
InputStream stream = new ByteArrayInputStream(
responseString.getBytes());
Document doc = parser.getDocument(stream);
NodeList nodeList = doc.getElementsByTagName("item");
for (int i = 0; i < nodeList.getLength(); i++) {
Element e = (Element) nodeList.item(i);
Data data = new Data();
data.setName(parser.getValue(e, "title"));
data.setUsername(parser.getValue(e, "description"));
datas.add(data);
System.out.println("pankaj " + parser.getValue(e, "title")
+ " " + parser.getValue(e, "description") + " "
+ parser.getValue(e, "link"));
}
listView.setAdapter(new CustomListAdapter(
DOMXMLParsingActivity.this, datas));
} else {
}
}
}
package com.example.demowork;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.util.Log;
public class XMLDOMParser {
public Document getDocument(InputStream inputStream) {
Document document = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = factory.newDocumentBuilder();
InputSource inputSource = new InputSource(inputStream);
document = db.parse(inputSource);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return document;
}
public String getValue(Element item, String name) {
NodeList nodes = item.getElementsByTagName(name);
return this.getTextNodeValue(nodes.item(0));
}
private final String getTextNodeValue(Node node) {
Node child;
if (node != null) {
if (node.hasChildNodes()) {
child = node.getFirstChild();
while (child != null) {
if (child.getNodeType() == Node.TEXT_NODE) {
return child.getNodeValue();
}
child = child.getNextSibling();
}
}
}
return "";
}
}
I have an xml parser class which crashes if I'm not connected to the internet. Is there anyway that I can get the class to go to a layout that says, "no connection" or something similar when a connection is not present. thanks
Xml Parser
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
/**
* Getting XML DOM element
* #param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/** Getting node value
* #param elem element
*/
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
Activity that uses parser
public class CustomizedListView extends Fragment { // All static variables
static final String URL = "http://graffiti.hostoi.com/00Graffiti00/lists/00main00.xml";
// 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";
static final String KEY_LINK = "key";
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);
XMLParser parser = new XMLParser();
// Getting adapter by passing xml data ArrayList
// Click event for single list row
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(getActivity(), Article.class);
new Bundle();
intent.putExtra( "b", songsList.get(position).get(KEY_LINK));
startActivity(intent);
}
});
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_LINK, parser.getValue(e, KEY_LINK));
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);
}
}
Try this..
Add the below class in your package
Utils.java
import android.content.Context;
import android.net.ConnectivityManager;
import android.util.Log;
public class Utils {
public static boolean connectivity(Context c) {
if(c != null)
{
ConnectivityManager connec = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isConnected()||mobile.isConnected())
return true;
else if (wifi.isConnected() && mobile.isConnected())
return true;
else
return false;
} catch (NullPointerException e) {
Log.d("ConStatus", "No Active Connection");
return false;
}
}
else
{
Log.v("utils--", "null");
return false;
}
}
}
And before calling that RetrieveXML AsyncTask use like below code.
if(Utils.connectivity(getActivity()))
{
new RetrieveXML().execute(URL);
XMLParser parser = new XMLParser();
}
else
{
Toast.makeText(getActivity(), "Please connect to working internet connection.", Toast.LENGTH_SHORT).show();
}
I can't get data from rss...null exception
I retrieve from this link, it only has
<?xml version="1.0" encoding="utf-8"?>
<GoldQuotes>
<Price Date="2013-11-28 09:22" Value="1244.30" />
<Price Date="2013-11-28 09:20" Value="1243.10"/>
<Price Date="2013-11-28 09:18" Value="1243.30"/>
[...]
</GoldQuotes>
this is my java fragment code
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpConnection.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(in);
Element docEle = dom.getDocumentElement();
NodeList nl = docEle.getElementsByTagName("GoldQuotes"); //***
if ((nl != null) && (nl.getLength() > 0)) {
for (int i = 0; i < nl.getLength(); i++) {
dissectNode(nl, i);
}
}//if
[...]
public void dissectNode(NodeList nl, int i) {
try {
Element entry = (Element) nl.item(i);
Element price = (Element) entry.getElementsByTagName("Price").item(0);
String priceValue = price.getAttribute("Value"); //get gold value
SingleNewsItem singleItem = new SingleNewsItem(priceValue);
newsList.add(singleItem);
} catch (DOMException e) {
e.printStackTrace();
}
}// dissectNode
After I do NodeList nl = docEle.getElementsByTagName("GoldQuotes"). I test with nl.getLength() which returns 0..
Am I missing anything?
The document you are trying to parse is not rss, just a custom xml format. After you parse it, it's enough to modify our code like this:
// this returns the root element, ie "GoldQuotes"
Element docEle = dom.getDocumentElement();
// get the list of Price elements children of the root
NodeList nl = docEle.getElementsByTagName("Price");
if ((nl != null) && (nl.getLength() > 0)) {
for (int i = 0; i < nl.getLength(); i++) {
// get the i-th Price element from the nodelist
Element entry = (Element) nl.item(i);
// get its Value attribute
String priceValue = entry.getAttribute("Value");
[....]
}
}
Try this..
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
String url = "https://www.igolder.com/GoldData.ashx?type=Historical&hours=24¤cy=USD&tz=UTC&unit=oz&output=xml";
ProgressDialog pDialog;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
new XmlParsing(url).executeOnExecutor(
AsyncTask.THREAD_POOL_EXECUTOR, new String[] { null });
else
new XmlParsing(url).execute(new String[] { null });
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class XmlParsing extends AsyncTask<String, Void, String> {
// variables passed in:
String urls;
// constructor
public XmlParsing(String urls) {
this.urls = urls;
}
#Override
protected void onPreExecute() {
pDialog = ProgressDialog.show(NetActivity.this,
"Fetching Details..", "Please wait...", true);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
URL url;
try {
url = new URL(urls);
DocumentBuilderFactory dbf = DocumentBuilderFactory
.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("GoldQuotes");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("Price");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
String priceValue = nameElement.getAttribute("Value"); //get gold value
SingleNewsItem singleItem = new SingleNewsItem(priceValue);
newsList.add(singleItem);
System.out.println("Value : "
+ (nameElement.getAttribute("Value")));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// Now we have your JSONObject, play around with it.
if (pDialog.isShowing())
pDialog.dismiss();
}
}
}
i want to parse my xml in asynctask because it won´t work without asynctask on android 4.0 +.The problem is that i cant write my strings in listview on my asynctask.
Here is my xml parsing activity:
package de.heron.cloudbox;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class AndroidXMLParsingActivity extends ListActivity{
String dwnload_file_path = "http://h.t-softec.de/heron.website.app/android/everhomeapp.xml";
String dest_file_path = "http://h.t-softec.de/heron.website.app/android/everhomeapp.xml";
Button b1;
ProgressDialog dialog = null;
///storage/emulated/0/everhomeapp.xml
// All static variables
static final String URL = "http://h.t-softec.de/heron.website.app/android/everhomeapp.xml";
//file:///storage/emulated/0/everhomeapp.xml
// XML node keys
static final String KEY_ITEM = "device"; // parent node
static final String KEY_ID = "deviceid";
static final String KEY_NAME = "devicename";
static final String KEY_actionid = "actions";
static final String KEY_actionid2 = "actions2";
static final String KEY_DESC = "devicetype";
static final String KEY_texton = "texton";
static final String KEY_textoff = "textoff";
ArrayList<String> mImageLink;
String[] actions = new String[] {
"Alle Räume",
"Wohnzimmer",
"Küche",
"Gäste-Wc"
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
overridePendingTransition( R.anim.leftright, R.anim.rightleft );
setTitle("Geräte");
getActionBar().setDisplayHomeAsUpEnabled(true);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
try{
XMLParserLocal parser = new XMLParserLocal();
File file = new File("/sdcard/everhomeapp.xml");
InputStream is = new FileInputStream(file.getPath());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(is));
doc.getDocumentElement().normalize();
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
for (int i = 0; i < nl.getLength(); i++) {
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_actionid, parser.getValue(e, KEY_actionid));
map.put(KEY_actionid2, parser.getValue(e, KEY_actionid2));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
map.put(KEY_texton, parser.getValue(e, KEY_texton));
map.put(KEY_textoff, parser.getValue(e, KEY_textoff));
menuItems.add(map);
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
// Adding menuItems to ListView
ListAdapter adapter2 = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_ID, KEY_actionid, KEY_texton, KEY_textoff}, new int[] {
R.id.name, R.id.desciption, R.id.cost, R.id.deviceid,R.id.on,R.id.off });
setListAdapter(adapter2);
// 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.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String cost2 = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String deviceid = ((TextView) view.findViewById(R.id.deviceid)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
String on = ((Button) view.findViewById(R.id.on)).getText().toString();
String off = ((Button) view.findViewById(R.id.off)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_actionid, cost);
in.putExtra(KEY_actionid2, cost2);
in.putExtra(KEY_DESC, description);
in.putExtra(KEY_ID, deviceid);
in.putExtra(KEY_texton, on);
in.putExtra(KEY_textoff, off);
startActivity(in);
}
});
try {
URL url = new URL("http://h.t-softec.de/heron.website.app/android/everhomeapp.xml");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot,"everhomeapp.xml");
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
parseFile();
fileOutput.close();
} catch (MalformedURLException e) {
e.printStackTrace();
parseFile();
} catch (IOException e) {
e.printStackTrace();
parseFile();
}
}
public void parseFile(){
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
try{
XMLParserLocal parser = new XMLParserLocal();
File file = new File("/sdcard/everhomeapp.xml");
InputStream is = new FileInputStream(file.getPath());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(is));
doc.getDocumentElement().normalize();
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_actionid, parser.getValue(e, KEY_actionid));
map.put(KEY_actionid2, parser.getValue(e, KEY_actionid2));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
map.put(KEY_texton, parser.getValue(e, KEY_texton));
map.put(KEY_textoff, parser.getValue(e, KEY_textoff));
menuItems.add(map);
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_ID, KEY_actionid, KEY_texton, KEY_textoff}, new int[] {
R.id.name, R.id.desciption, R.id.cost, R.id.deviceid,R.id.on,R.id.off });
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String deviceid = ((TextView) view.findViewById(R.id.deviceid)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
String on = ((Button) view.findViewById(R.id.on)).getText().toString();
String off = ((Button) view.findViewById(R.id.off)).getText().toString();
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_actionid, cost);
in.putExtra(KEY_DESC, description);
in.putExtra(KEY_ID, deviceid);
in.putExtra(KEY_texton, on);
in.putExtra(KEY_textoff, off);
startActivity(in);
}
});
}
public void parsexmllocal(){
mImageLink = new ArrayList<String>();
try{
File file = new File("mnt/sdcard/kursywalut.xml");
InputStream is = new FileInputStream(file.getPath());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(is));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("image");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
mImageLink.add(fstElmnt.getAttribute("link"));
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
public void downloadFile(String url, String dest_file_path) {
try {
File dest_file = new File(dest_file_path);
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(dest_file));
fos.write(buffer);
fos.flush();
fos.close();
hideProgressIndicator();
} catch(FileNotFoundException e) {
hideProgressIndicator();
return;
} catch (IOException e) {
hideProgressIndicator();
return;
}
}
void hideProgressIndicator(){
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return super.onCreateOptionsMenu(menu);
}
public void clicksound(View view){
MediaPlayer mp = MediaPlayer.create(this, R.raw.clicksound);
mp.start();
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case R.id.refresh:
try {
URL url = new URL("http://h.t-softec.de/heron.website.app/android/everhomeapp.xml");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot,"everhomeapp.xml");
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
Toast.makeText(this, "Geräteliste erfolgreich aktualisiert!", Toast.LENGTH_LONG).show();
fileOutput.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Handler handler4 = new Handler();
handler4.postDelayed(new Runnable()
{
#Override
public void run()
{
parseFile();
}
}, 100);
break;
case R.id.change:
Intent i = new Intent(this, SettingsActivity.class);
startActivity(i);
break;
case android.R.id.home:
Intent i2 = new Intent(this, AndroidXMLParsingActivity2.class);
startActivity(i2);
break;
}
return true;
}
}
and here is my singlemenuitemactivity:
package de.heron.cloudbox;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class SingleMenuItemActivity extends Activity {
EditText txtCode;
// XML node keys
static final String KEY_NAME = "name";
static final String KEY_actionid = "cost";
static final String KEY_actionid2 = "cost2";
static final String KEY_DESC = "description";
static final String KEY_ID = "deviceid";
static final String KEY_texton = "texton";
static final String KEY_textoff = "textoff";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get XML values from previous intent
String name = in.getStringExtra(KEY_NAME);
String cost = in.getStringExtra(KEY_actionid);
String cost2 = in.getStringExtra(KEY_actionid2);
String description = in.getStringExtra(KEY_DESC);
String deviceid = in.getStringExtra(KEY_ID);
String on = in.getStringExtra(KEY_texton);
String off = in.getStringExtra(KEY_textoff);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCost = (TextView) findViewById(R.id.cost_label);
TextView lblDesc = (TextView) findViewById(R.id.description_label);
TextView lblid = (TextView) findViewById(R.id.id_label);
// TextView lblon = (Button) findViewById(R.id.on);
// TextView lbloff = (Button) findViewById(R.id.off);
Button lblon = (Button)findViewById(R.id.on);
lblon.getText().toString();
lblon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences settings = getSharedPreferences("UserInfo", 0);
txtCode.setText(settings.getString("Code", "").toString());
String[] url={"http://everhome.de/api/applive/", (settings.getString("Code", "")), "/" + KEY_ID,"/" + KEY_actionid};
new onoff(SingleMenuItemActivity.this).execute(url);
}});
Button lbloff = (Button)findViewById(R.id.off);
lbloff.getText().toString();
lbloff.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String[] url={"http://everhome.de/api/applive/", "8ef43502ad3dc04f87b4a48b993878c0","/" + KEY_ID,"/" + KEY_actionid2};
new onoff(SingleMenuItemActivity.this).execute(url);
}
});
lblName.setText(name);
lblCost.setText(cost);
lblCost.setText(cost2);
lblDesc.setText(description);
lblid.setText(deviceid);
lblon.setText(on);
lbloff.setText(off);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setIcon(R.drawable.ic_launcher);
setTitle("Geräte");
Button devices = (Button) findViewById(R.id.devices);
devices.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(SingleMenuItemActivity.this, AndroidXMLParsingActivity.class);
startActivity(i);
}
});
Button scenes = (Button) findViewById(R.id.scenes);
scenes.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(SingleMenuItemActivity.this, AndroidXMLParsingActivity2.class);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case R.id.refresh:
break;
}
return true;
}
}
i hope anybody can help me to resolve my problem.
Update:
thats was the test with asynctask:
class xmlparse extends AsyncTask<Void, Void, Void> {
static final String KEY_ITEM = "device"; // parent node
static final String KEY_ID = "deviceid";
static final String KEY_NAME = "devicename";
static final String KEY_actionid = "actions";
static final String KEY_actionid2 = "actions2";
static final String KEY_DESC = "devicetype";
static final String KEY_texton = "texton";
static final String KEY_textoff = "textoff";
#Override
protected Void doInBackground(Void... params) {
/*
make connection & download XML here,
use your XML parser class object to parse the xml from here
create ArrayList & etc. from here...
*/
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
//
//File xml = parser.getXmlFromUrl(URL); // getting XML
//Document doc = parser.getDomElement(xml); // getting DOM element
try{
XMLParserLocal parser = new XMLParserLocal();
File file = new File("/sdcard/everhomeapp.xml");
InputStream is = new FileInputStream(file.getPath());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(is));
doc.getDocumentElement().normalize();
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_actionid, parser.getValue(e, KEY_actionid));
map.put(KEY_actionid2, parser.getValue(e, KEY_actionid2));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
map.put(KEY_texton, parser.getValue(e, KEY_texton));
map.put(KEY_textoff, parser.getValue(e, KEY_textoff));
// adding HashList to ArrayList
menuItems.add(map);
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// postexecute logic
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// pre execute logic
super.onPreExecute();
}
}
but the problem is that i want to put the strings(menu items ) in listview with the listadapter:
ListAdapter adapter2 = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_ID, KEY_actionid, KEY_texton, KEY_textoff}, new int[] {
R.id.name, R.id.desciption, R.id.cost, R.id.deviceid,R.id.on,R.id.off });
setListAdapter(adapter2);
// 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.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String cost2 = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String deviceid = ((TextView) view.findViewById(R.id.deviceid)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
String on = ((Button) view.findViewById(R.id.on)).getText().toString();
String off = ((Button) view.findViewById(R.id.off)).getText().toString();
and i dont know how i can make this when the parser runs in asynctask.
that make the parser to put the menuitems to the listadapter:
menuItems.add(map);
Reference your adapter through a WeakReference when initializing your Asynctask.
Parametrize the AsyncTask to return whatever you need to return, e.g. a List<String>. The connection and data pulling happens in doInBackground.
In onPostExecute, check your WeakReference.get is not null and populate the adapter.
You can use the droidQuery library to asynchronously download an XML Document given a URL. For example:
$.ajax(new AjaxOptions().url("http://www.example.com")
.type("GET")
.context(this)
.dataType("xml")
.success(new Function() {
#Override
public void invoke($ droidQuery, Object... params) {
Document xml = (Document) params[0];
//TODO parse xml here. This is the UI Thread, so you can also modify your TextViews here.
}
})
.error(new Function() {
#Override
public void invoke($ droidQuery, Object... params) {
AjaxError e = (AjaxError) params[0];
droidQuery.alert("Error: " + e.status + ": " + e.error);
}
}));