Android Xml data parsing - java

I am trying to parse XML and display it into list view but after running the app nothing happen the list display but not with XML data. I don't know if I missing something please can help me.
MainActivity class
public class MainActivity extends ListActivity {
// 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
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ListView myList=(ListView)findViewById(android.R.id.list);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = null; // getting XML
try {
xml = parser.getXmlFormUrl(URL);
} catch (IOException e) {
e.printStackTrace();
}
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.activity_main,
new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
R.id.name, R.id.desciption, R.id.cost });
setListAdapter(adapter);
// selecting single ListView item
}
}
XmlParser class
public class XMLParser {
String result;
public String getXmlFormUrl(String link) throws IOException{
URL url=new URL(link.toString());
HttpURLConnection UrlConnection= (HttpURLConnection) url.openConnection();
int status=UrlConnection.getResponseCode();
if(status==200){
InputStream inputStream=UrlConnection.getInputStream();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream,"UTF8"));
StringBuilder stringBuilder= new StringBuilder();
String line;
while ((line=bufferedReader.readLine())!=null){
stringBuilder.append((line+"\n"));
}
result=stringBuilder.toString();
inputStream.close();
}
return result;
}
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 DOM
return doc;
}
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
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 "";
}
}
ActivityMain.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="android.prgguru.com.xmlparsingg.MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#android:id/list"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="73dp" />
</RelativeLayout>
after this line I think the list should display with XML data but nothing happens
myList.setAdapter(adapter);
ids.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="desciption" type="id" />
<item name="cost" type="id" />
<item name="name" type="id" />
<item name="List" type="id"/>
</resources>

create main.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
creare list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Name Label -->
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#dc6800"
android:textSize="16sp"
android:textStyle="bold"
android:paddingTop="6dip"
android:paddingBottom="2dip" />
<!-- Description label -->
<TextView
android:id="#+id/desciption"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#acacac"
android:paddingBottom="2dip">
</TextView>
<!-- Linear layout for cost and price Cost: Rs.100 -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<!-- Cost Label -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:gravity="left"
android:textStyle="bold"
android:text="Cost: " >
</TextView>
<!-- Price Label -->
<TextView
android:id="#+id/cost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#acacac"
android:textStyle="bold"
android:gravity="left">
</TextView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
create MainActivity.java
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 MainActivity extends ListActivity {
// 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 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_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);
// 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 description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
// 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);
startActivity(in);
}
});
}
}
create XMLParser.java
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
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 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));
}
}
all the code copied from here you just need to copy paste the above code and then let me know if it is working or not

Related

NullPointerException TextView.setText(CharSequence), not clear how its still null

I've been trying for a little bit now to just get my app launching again. I modified how I pulled bitcoin price data to allow for user preferences. However since doing this I get a NullPointerException from my TextView currentPriceDisplay elements method.currentPriceDisplay.setText(getmBitcoinPrice());
I have modified values throughout my code to prevent this variable from ever actually being null, I've also checked my nav_header_main.xml file to see if I was referencing the right TextView I am. So at this point pretty stumped and I have to go to the day job. If you can have a look at my code and see if you notice anything that would be great.
MainActivity:
package com.instacoind.www.coind;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
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.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Set;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private Double mBitcoinPrice = 0.0;
public Double getmBitcoinPrice(){
return mBitcoinPrice;
}
public void setmBitcoinPrice(Double price){
this.mBitcoinPrice = price;
}
private Double mBitcoinPriceOld = 0.0;
public Double getmBitcoinPriceOld(){
return mBitcoinPriceOld;
}
public void setmBitcoinPriceOld(Double price){
this.mBitcoinPriceOld = price;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mBitcoinPrice != 0.0) {
Snackbar.make(view, "Last Change: " + priceChange(), Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}else{
Snackbar.make(view, "SYNC FAILED ERROR::01", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent start_settings = new Intent(this, SettingsActivity.class);
startActivity(start_settings);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStart(){
super.onStart();
updatePrice();
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void updatePrice(){
GetBitcoinPrice worker = new GetBitcoinPrice();
worker.execute(getPrefFiat(this), getPrefPriceIndex(this));
refreshPriceDisplays();
}
public static String getPrefFiat(Context context){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getString(context.getString(R.string.pref_currency_key),
context.getString(R.string.pref_currency_def));
}
public static String getPrefPriceIndex(Context context){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getString(context.getString(R.string.pref_source_key),
context.getString(R.string.pref_source_default));
}
public String priceChange(){
Double past = getmBitcoinPriceOld();
Double pres = getmBitcoinPrice();
Double change = 0.0;
String fin = "price_change";
if(past != null){
if(pres >= past){
change = pres - past;
fin = "+ " + Double.toString(change);
}else if(pres <= past){
change = past - pres;
fin = "- " + Double.toString(change);
}
}else{
setmBitcoinPriceOld(getmBitcoinPrice());
}
return fin;
}
public void refreshPriceDisplays(){
TextView PriceDisplay = (TextView) findViewById(R.id.current_price_display);
String error = "No Bitcoin Price";
try {
Log.v("RefreshPriceDisplays", "mBitcoinPrice: " + Double.toString(getmBitcoinPrice()));
PriceDisplay.setText(Double.toString(getmBitcoinPrice()));
}catch(NullPointerException e) {
Log.v("RefreshPriceDisplays", "mBitcoinPrice NULL");
PriceDisplay.setText("ERR");
}
}
private class GetBitcoinPrice extends AsyncTask<String, Void, Double> {
public String mPrefFiat;
public String mPrefIndex;
protected Double doInBackground(String... params) {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String bitcoinJsonStr = null;
this.mPrefFiat = params[0];
this.mPrefIndex = params[1];
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
URL url = new URL(buildUrl(this.mPrefFiat,this.mPrefIndex));
// Create the request to Index Source, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
bitcoinJsonStr = null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
bitcoinJsonStr = null;
}
bitcoinJsonStr = buffer.toString();
} catch (IOException e) {
Log.e("GetBitcoinPrice", "Error ", e);
// If the code didn't successfully get the price index data, there's no point in attemping
// to parse it.
bitcoinJsonStr = null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("GetBitcoinPrice", "Error closing stream", e);
}
}
}
if(this.mPrefIndex == "https://api.coindesk.com/v1/bpi/currentprice.json")
return parseCoindesk(bitcoinJsonStr);
else if (this.mPrefIndex == "https://api.coinbase.com/v2/prices/spot?currency=")
return parseCoinbase(bitcoinJsonStr);
else if (this.mPrefIndex == "https://www.okcoin.com/api/v1/ticker.do?symbol=")
return parseOkcoin(bitcoinJsonStr);
else if (this.mPrefIndex == "https://cex.io/api/ticker/BTC/")
return parseCex(bitcoinJsonStr);
else
return 0.0;
}
private Double parseCex(String bitcoinJsonStr){
Double price = 0.0;
try {
JSONObject obj = new JSONObject(bitcoinJsonStr);
price = obj.getDouble("bid");
Log.v("ConvertPriceStr", "Current Price is " + Double.toString(price));
if (price == null){
Log.e("CEXParsing", "Parsed to Null");
}
}catch (JSONException x){
Log.e("ConvertPriceStr", "Error Parsing bitcoinJsonStr");
}
return price;
}
private Double parseCoindesk(String bitcoinJsonStr){
Double price = 0.0;
try {
JSONObject obj = new JSONObject(bitcoinJsonStr);
JSONObject bpi = obj.getJSONObject("bpi");
JSONObject usd = bpi.getJSONObject("USD");
price = usd.getDouble("rate_float");
Log.v("ConvertPriceStr", "Current Price is " + Double.toString(price));
}catch (JSONException x){
Log.e("ConvertPriceStr", "Error Parsing bitcoinJsonStr");
}
return price;
}
private Double parseCoinbase(String bitcoinJsonStr){
Double price = 0.0;
try{
JSONObject obj = new JSONObject(bitcoinJsonStr);
JSONObject bpi = obj.getJSONObject("data");
price = bpi.getDouble("amount");
Log.v("ParseCoinbase", "Current Price is " + Double.toString(price));
}catch(JSONException e){
Log.e("ParseCoinbase", "Error Parsing bitcoinJsonStr");
}
return price;
}
private Double parseOkcoin(String bitcoinJsonStr){
Double price = 0.0;
try{
JSONObject obj = new JSONObject(bitcoinJsonStr);
JSONObject bpi = obj.getJSONObject("ticker");
price = bpi.getDouble("buy");
Log.v("ParseOkCoin", "Current Price is " + Double.toString(price));
}catch(JSONException e){
Log.e("ParseOkCoin", "Error Parsing bitcoinJsonStr");
}
return price;
}
private String buildUrl(String prefFiat, String prefIndex){
String url = null;
try {
if (prefIndex == "https://api.coinbase.com/v2/prices/spot?currency=") {
url = prefIndex + prefFiat;
} else if (prefIndex == "https://api.coindesk.com/v1/bpi/currentprice.json") {
url = prefIndex + prefFiat;
} else if (prefIndex == "https://www.okcoin.com/api/v1/ticker.do?symbol=") {
String modFiat;
modFiat = "btc_" + prefFiat;
url = prefIndex + modFiat;
} else if (prefIndex == "https://cex.io/api/ticker/BTC/") {
String modFiat;
modFiat = prefIndex + prefFiat;
url = modFiat;
} else {
url = "https://api.coindesk.com/v1/bpi/currentprice.json";
}
}catch(NullPointerException e){
Log.e("URL Builder", "Error Constructing Proper URL", e);
}
return url;
}
protected void onPostExecute(Double result){
setmBitcoinPriceOld(getmBitcoinPrice());
setmBitcoinPrice(result);
}
}
}
XML Files:
activity_main.xml:
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
app_bar_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.instacoind.www.coind.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#drawable/refresh_60_60" />
</android.support.design.widget.CoordinatorLayout>
content_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.instacoind.www.coind.MainActivity"
tools:showIn="#layout/app_bar_main">
</RelativeLayout>
nav_header_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="#dimen/nav_header_height"
android:background="#drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="#+id/coin_display"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:src="#drawable/bitcoin_80_80"
android:contentDescription="#string/coin_content_description"/>
<TextView
android:id="#+id/bpi_source_display"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:text="BPI_Source"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:textAppearance="#style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="#+id/def_currency_display"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:layout_toRightOf="#+id/bpi_source_display"
android:layout_toEndOf="#+id/bpi_source_display"
android:layout_alignParentBottom="true"
android:text="DEF_Currency" />
<TextView
android:id="#+id/current_price_display"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="40dp"
android:paddingStart="80dp"
android:paddingLeft="80dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/coin_display"
android:textAppearance="#style/TextAppearance.AppCompat.Headline"/>
</RelativeLayout>
I think the problem comes from these four method:
parseCoindesk,parseCoinbase,parseCex,parseOkcoin
In each of these(parseCex for example):
if (price == null){
Log.e("CEXParsing", "Parsed to Null");// You just print a Log!
}
}catch (JSONException x){
Log.e("ConvertPriceStr", "Error Parsing bitcoinJsonStr");
}
return price;//when price is null it can still return!
}
so, you should try to return like this:
return price == null ? 0.0 : price;
Ok, way longer than I thought it would take till I could actually sit down and work on this again. Apologies for dragging my heels, I have fixed the problem of the crash.
It occurred because I was calling my refreshPriceDisplays() method before the onCreate/AsyncTask was finished. Once I moved refreshPriceDisplays() into my onPostExecute everything went great.
And as far as the first answer to this question you raised some good points about my logic and they have been addressed as well thank you so much for your inputs!

JSONException:<String>cannot be converted to JSONObject with helps of JSON Array

$ Error:: JSONException:json string cannot be converted to
JSONObject with helps of JSON Array
This is Import libraries
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
activity_main.xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp" >
</ListView>
Internet Permission is Here
<uses-permission android:name="android.permission.INTERNET" />
error Please give me Answer How to get Multiple Values Using this Code and show into my ListView
This Is my MainActivity.java class file.
public class MainActivity extends Activity
{
private String jsonResult;
private String url = "YOUR_PHP_FILE_URL";
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
accessWebService();
}
#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;
}
// Async Task to access the web
#SuppressLint("NewApi")
private class JsonReadTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try
{
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is)
{
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try
{
while ((rLine = rd.readLine()) != null)
{
answer.append(rLine);
Log.d(answer.toString(), "String Builder Class in IF Loop");
}
}
catch (IOException e)
{
// e.printStackTrace();
Toast.makeText(getApplicationContext(),"Error..." + e.toString(), Toast.LENGTH_LONG).show();
Log.d(answer.toString(), "String Builder Class in Else Part");
}
return answer;
}
#Override
protected void onPostExecute(String result)
{
ListDrwaer();
}
}// end async task
public void accessWebService()
{
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public <jsonResult> void ListDrwaer()
{
ArrayList<Map<String,String>> userList = new ArrayList<Map<String, String>>();
Log.d(userList.toString(), "Starting JSONObject");
try
{
Log.d("Starting Try Block", "Before JSONObject");
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.getJSONArray("user_info");
Log.d(jsonMainNode.toString(), "Starting JSONObject");
for (int i = 0; i < jsonMainNode.length(); i++)
{
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String id = jsonChildNode.optString("Id:");
String name = jsonChildNode.optString("Name:");
String email = jsonChildNode.optString("Email:");
String phone = jsonChildNode.optString("Phone:");
String password = jsonChildNode.optString("Password");
String outPut = id + "-" + name+ "-" + email+ "-" + phone+ "-" + password;
userList.add(createEmployee("user_info", outPut));
Log.d(jsonChildNode.toString(), "Starting JSONObject inside For Loop");
}
}
catch (JSONException e)
{
Toast.makeText(getApplicationContext(), "Error" + e.toString(),Toast.LENGTH_SHORT).show();
Log.e("log_tag", "Failed data was:\n" + jsonResult);
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, userList,android.R.layout.simple_list_item_1,new String[] { "user_info" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createEmployee(String name, String number)
{
HashMap<String, String> employeeNameNo = new HashMap<String, String>();
employeeNameNo.put(name, number);
return employeeNameNo;
}
}
ok the error you are getting is very generic, error itself tells what you are doing wrong
$ Error:: JSONException:json string cannot be converted to JSONObject with helps of JSON Array,
I believe you have string in the JSON data, "dummy data" as it is in double quotes which you are trying to read as a JSONObject.
It is not a JSONObject but a String primitive type,
while parsing JSON you need to pay attention to what is a Object, Array and primitive-type
JSONObject
will always be enclosed in { } so this represents that data inside a parentheses is a JSONObject,
Example===>
JSONObject json = jsonArray.getJSONObject(i)
or
JSONObject json = new JSONObject("JSON DATA");
JSONArray
will always be enclosed in [ ] so this represents that data inside a square bracket is a JSONArray,
Example==> `json.getJSONArray("name of jsonArray");
Primitive-type
Boolean would like this
"isSelected":true
or
"isSelected":false
Integer would like this
"someInt":12
String would like this
"someString":"String value"
as you can see where your problem is, you need to distinguish between JSON String from JSON Object
Remove this line because you convert Json String to Json Object
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

Android - get XML from web

I'm trying to get XML datas from web and to show these datas into ListView. But something's going wrong when i run the project. Can you help me for this problem,please? Thank you.
XMLParser.java
public class XMLParser extends Activity {
public String getXmlFromUrl(String url) {
String xml = null;
try {
new Thread(new Runnable() {
public void run() {
try {
URL uri=new URL("http://api.androidhive.info/pizza/?format=xml");
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
System.out.println("done");
}
catch(Exception e) {
e.printStackTrace();
}
}
}).start();
//readfilethread.start();
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
System.out.println("here");
// HttpResponse httpResponse = httpClient.execute(httpPost);
//HttpEntity httpEntity = httpResponse.getEntity();
//xml = EntityUtils.toString(httpEntity);
} catch (Exception e) {
e.printStackTrace();
}
// return XML
return xml;
}
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 DOM
return doc;
}
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
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 "";
}
AndroidXMLParsingActivity.java
public class AndroidXMLParsingActivity extends ListActivity {
// 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 void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// -> menuItems
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);
}
// 2. 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.description, R.id.cost });
setListAdapter(adapter);
// selecting single ListView item
android.widget.ListView lv = getListView();
// listening to single list item click
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 description = ((TextView) view.findViewById(R.id.description)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleListItem.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_COST, cost);
in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
}
'
LOGCAT PART
08-25 08:34:10.211: E/AndroidRuntime(1700): FATAL EXCEPTION: main
08-25 08:34:10.211: E/AndroidRuntime(1700): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.uygulama/com.example.uygulama.AndroidXMLParsingActivity}: java.lang.NullPointerException
08-25 08:34:10.211: E/AndroidRuntime(1700): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.uygulama/com.example.uygulama.AndroidXMLParsingActivity}: java.lang.NullPointerException
08-25 08:34:10.211: E/AndroidRuntime(1700): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.uygulama/com.example.uygulama.AndroidXMLParsingActivity}: java.lang.NullPointerException
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.os.Handler.dispatchMessage(Handler.java:99)
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.os.Looper.loop(Looper.java:137)
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread.main(ActivityThread.java:5039)
....
08-25 08:34:10.341: I/System.out(1700): done
Try this codes ...
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.content.Context;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class NetActivity extends Activity {
String url = "http://api.androidhive.info/pizza/?format=xml";
// Progress dialog
ProgressDialog pDialog;
ArrayList<String> title;
ArrayList<String> description;
ArrayList<String> id;
ArrayList<String> cost;
ItemAdapter adapter1;
ListView list;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_net);
list = (ListView) findViewById(R.id.list);
title = new ArrayList<String>();
description = new ArrayList<String>();
id = new ArrayList<String>();
cost = new ArrayList<String>();
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("item");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("name");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
title.add(""+ ((Node) nameList.item(0)).getNodeValue());
System.out.println("name : "+((Node) nameList.item(0)).getNodeValue());
Element fstElmnt1 = (Element) node;
NodeList nameList1 = fstElmnt1.getElementsByTagName("id");
Element nameElement1 = (Element) nameList1.item(0);
nameList1 = nameElement1.getChildNodes();
description.add(""+ ((Node) nameList1.item(0)).getNodeValue());
System.out.println("id : "+ ((Node) nameList1.item(0)).getNodeValue());
Element fstElmnt2 = (Element) node;
NodeList nameList2 = fstElmnt2.getElementsByTagName("cost");
Element nameElement2 = (Element) nameList2.item(0);
nameList2 = nameElement2.getChildNodes();
id.add(""+ ((Node) nameList2.item(0)).getNodeValue());
System.out.println("cost : "+ ((Node) nameList2.item(0)).getNodeValue());
Element fstElmnt3 = (Element) node;
NodeList nameList3 = fstElmnt3.getElementsByTagName("description");
Element nameElement3 = (Element) nameList3.item(0);
nameList3 = nameElement3.getChildNodes();
cost.add(""+ ((Node) nameList3.item(0)).getNodeValue());
System.out.println("description : "+ ((Node) nameList3.item(0)).getNodeValue());
}
} 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();
adapter1 = new ItemAdapter(this);
list.setAdapter(adapter1);
}
}
class ItemAdapter extends BaseAdapter {
final LayoutInflater mInflater;
private class ViewHolder {
public TextView title_text;
public TextView des_text;
public TextView id_text;
public TextView cost_text;
}
public ItemAdapter(XmlParsing xmlParsing) {
// TODO Auto-generated constructor stub
super();
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//#Override
public int getCount() {
return title.size();
}
//#Override
public Object getItem(int position) {
return position;
}
//#Override
public long getItemId(int position) {
return position;
}
//#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = mInflater.inflate(R.layout.mainpage_listitem_activity, parent, false);
holder = new ViewHolder();
holder.title_text = (TextView) view.findViewById(R.id.title_text);
holder.des_text = (TextView) view.findViewById(R.id.des_text);
holder.id_text = (TextView) view.findViewById(R.id.id_text);
holder.cost_text = (TextView) view.findViewById(R.id.cost_text);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.title_text.setText(""+title.get(position));
holder.des_text.setText(""+description.get(position));
holder.id_text.setText(""+id.get(position));
holder.cost_text.setText(""+cost.get(position));
return view;
}
}
}

parsing xml asynctask and writing in listview

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

pass xml file from local storage

i want to pass a xml file from my internal storage
with my Activity:
my error:
07-06 01:58:39.494: E/Error:(15253): Unexpected token (position:TEXT /sdcard/xml.xlm...#1:24 in java.io.StringReader#4152db98)
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParserLocal parser = new XMLParserLocal();
//String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement("storage/emulated/0/xml.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, parser.getValue(e, KEY_COST));
map.put(KEY_COST2, parser.getValue(e, KEY_COST2));
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);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_ID, KEY_COST, 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);
// 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 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_COST, cost);
in.putExtra(KEY_DESC, description);
in.putExtra(KEY_ID, deviceid);
in.putExtra(KEY_texton, on);
in.putExtra(KEY_textoff, off);
startActivity(in);
}
});
and here my XMLParserLocal:
package de.heron.cloudbox;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
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 XMLParserLocal {
// constructor
public XMLParserLocal() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public String getXmlFromUrl(String url) {
String xml = "/xml.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));
}
}
can someone help me with my probelm?
edit:
here my xml there i want to pass with my Activity, i have take empty on parts of xml there was other words:
<?xml version="1.0" encoding="utf-8"?>
<devices>
<device>
<deviceid>empty</deviceid>
<devicename>empty</devicename>
<actions>empty</actions>
<actions2>empty</actions2>
<devicetype>empty</devicetype>
<texton>empty</texton>
<textoff>empty</textoff>
</device>
<device>
<deviceid>empty</deviceid>
<devicename>empty</devicename>
<actions>empty</actions>
<actions2>empty</actions2>
<devicetype>empty</devicetype>
<texton>empty</texton>
<textoff>empty</textoff>
</device>
</devices>
The XML you posted above isn't valid. You have
</device>
<device>
<device>
which has two open device tags in a row. Then you open another right before you end the xml section
<device>
</devices>

Categories