I want to read XML data from URL and have tried in different ways. But unable to find the answer. Iam developing a agumented reality application, where iam reading location information from XML ( which is in URL )
Iam new bee to android as well
I have the following XML data.
<specialoffers>
<categories>
<category>
<![CDATA[ 0% Installment Payment Plan Offers ]]>
</category>
<merchants>
<merchantname>
<![CDATA[ EmaxIPP ]]>
</merchantname>
<merchantbigimage>
<![CDATA[
http://www.XXX.com/Images/Emax%20New%20-%20190x73-1_tcm20-48180.jpg
]]>
</merchantbigimage>
<merchantsmallimage>
<![CDATA[
http://www.XXX.com/Images/Emax%20New%20-%20104x75-1_tcm20-48179.jpg
]]>
</merchantsmallimage>
<merchantmobileimage>
<![CDATA[ http://www.XXX.com ]]>
</merchantmobileimage>
<mobilehighlight>
<![CDATA[
Enjoy 0% Installment Payment Plan for 3 months on
all purchases made </b>
]]>
</mobilehighlight>
<highlight>
<![CDATA[
Enjoy 0% Installment Payment Plan for 3 months on all purchases
made with your </b>
]]>
</highlight>
<locations>
<location>
<emirate>
<![CDATA[ XXX]]>
</emirate>
<address>
<![CDATA[ Center 1 ]]>
</address>
<latitude>
<![CDATA[ 51.169601 ]]>
</latitude>
<longitude>
<![CDATA[ 61.240395 ]]>
</longitude>
</location>
</merchants>
</categories>
</specialoffers>
Here is the code....
AndroidXMLParsingActivity.java
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
static final String URL = "http://www.adcb.com/specialoffers-test.xml";
// XML node keys
static final String KEY_ITEM = "categories"; // parent node
static final String KEY_ID = "category";
#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));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_ID, "KEY_DESC", "100" }, 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_ID, name);
in.putExtra("100", cost);
in.putExtra("KEY_DESC", description);
startActivity(in);
}
});
}
}
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));
}
}
SingleMenuItemActivity.java
public class SingleMenuItemActivity extends Activity {
// XML node keys
static final String KEY_ID = "category";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
#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_ID);
String cost = in.getStringExtra(KEY_COST);
String description = in.getStringExtra(KEY_DESC);
// 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);
lblName.setText(name);
lblCost.setText(cost);
lblDesc.setText(description);
}
}
You can use xmlpullparser like this :
XmlPullParserFactory pullParserFactory;
try {
pullParserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = pullParserFactory.newPullParser();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
I found a link demonstrating the same example as per your need.Please go through this link
Or just go the android way . A developer guide link
Hope it helps you.
Use SimpleXml xml parsing API for android it'll make your coding easy.
Related
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();
}
After much research, I can't manage to layout some XML data in my android app.
There is my MainActivity.java :
public class MainActivity extends Activity {
TextView textview1;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetXmlTask task = new GetXmlTask(textview1 , "http://www.3pi.tf/test.xml"); // get the XML
Log.i("TAG", "test1");
task.execute(); // execute the task
Log.i("TAG","test2");
textview1 = (TextView) findViewById(R.id.textview1);
Log.i("TAG", "test4");
}
}
And there is my GetXmlTask.java :
public class GetXmlTask extends AsyncTask<Void, Void, String>{
public WeakReference<TextView> textViewReference;
public String url;
public GetXmlTask(TextView textview, String url) {
this.textViewReference = new WeakReference<TextView>(textview);
this.url = url;
}
public String THEXML = null;
public String doInBackground(Void... sUrl) {
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://3pi.tf/test.xml");
Log.i("TAG2",""+request);
HttpResponse response = httpclient.execute(request);
Log.i("TAG2",""+response);
HttpEntity resEntity = response.getEntity();
Log.i("TAG2",""+resEntity);
THEXML = EntityUtils.toString(resEntity);
Log.i("DONNEES XML",""+THEXML);
}
catch(Exception e){ e.printStackTrace(); }
return THEXML;
}
public Document getDomElement(String task) {
Log.i("TAG2","test01");
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try{
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(task));
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;
}
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 "";
}
//Retrieve each element child element value by using node name of element.
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
As you can see, I put some logcat in to see how it passes through.
I can see all my XML in the logcat with the variable "THEXML" but I can't layout to my mobile app... I did all the method in an AsyncTask because that was highly recommended..
Please help me
Thank you
Use a interface as a callback to the activity
GetXmlTask task = new GetXmlTask(ActivityName.this, "http://www.3pi.tf/test.xml");
Then in GetXmlTask
ReturnData mCallback;
public GetXmlTask(Context context, String url) { // Constructor in asynctask
this.url = url;
mCallback = (ReturnData)context;
}
Then
public interface ReturnData
{
public void Returnxml(String xml);
}
In doInbackground you return THEXML
return THEXML;
In onPostExecute
#Override
public void onPostExecute(String result)
{
super.onPostExecute(result);
if(mCallback!=null)
{
mCallback.Returnxml(result);
}
}
In MainActivity implement the interface
public class MainActivity extends Activity implements ReturnData {
Then
public void Retunxml(String data)
{
textView1.setText(data);
}
You should overwrite the onPostExecute method of AsynckTask and handle there the operation over your downloaded file if it is different from null. In you case something like this:
protected void onPostExecute(Void result) {
if(THEXML !=null)
{
//do something
}
}
I'm trying to parse xml data from this URL:http://cloud.tfl.gov.uk/TrackerNet/LineStatus but am getting a NullPointerException on the line that read:
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
Before I show the code, I'd just like to say whats going on. First I download the XML file to the SDCard in
saveToSdCard();
Then I retrieve it with
getDataFromSDcard();
Here is my code:
Main Activity:
public class DashboardFragment extends SherlockFragment {
private CardUI mCardView;
String TUBE_STATUS_URL;
String KEY_ITEM = "LineStatus";
String KEY_LINE = "Line";
String KEY_NAME = "name";
String KEY_STATUS_DETAILS = "StatusDetails";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.activity_dashboard,
container, false);
// Get the URL's
TUBE_STATUS_URL = "http://cloud.tfl.gov.uk/TrackerNet/LineStatus";
// Find the cards in inflated layout
CardUI cardGroup = (CardUI) rootView.findViewById(R.id.cardsview);
fillCards(cardGroup);
DownloadFeedsTask task = new DownloadFeedsTask();
task.execute(new String[] { "" });
return rootView;
}
private void fillCards(CardUI cardGroup) {
// Fill cards with data
// init CardView
mCardView = cardGroup;
mCardView.setSwipeable(true);
// create a stack
CardStack delayStack = new CardStack();
delayStack.setTitle("Tube Lines with delays");
// add cards to stack
delayStack.add(new MyCard("Jubilee Line", MyCard.LINE_UNAVAILABLE));
delayStack.add(new MyCard("Victoria Line", MyCard.LINE_AVAILABLE));
delayStack
.add(new MyCard("Piccadilly Line", MyCard.LINE_IN_MAINTENANCE));
delayStack.add(new MyCard("Northern", MyCard.LINE_AVAILABLE));
// create a stack
CardStack activeStack = new CardStack();
activeStack.setTitle("Active Tube Lines");
// add cards to stack
activeStack.add(new MyCard("Jubilee Line", MyCard.LINE_HIDE_STATUS));
activeStack.add(new MyCard("Victoria Line", MyCard.LINE_HIDE_STATUS));
// add stack to cardView
mCardView.addStack(delayStack);
mCardView.addStack(activeStack);
// draw cards
mCardView.refresh();
}
#Override
public boolean onOptionsItemSelected(
com.actionbarsherlock.view.MenuItem item) {
return super.onOptionsItemSelected(item);
}
private class DownloadFeedsTask extends AsyncTask<String, Void, String> {
ArrayList<HashMap<String, String>> menuItems;
#Override
protected String doInBackground(String... urls) {
try {
saveToSdCard();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String response = "";
XMLParser parser = new XMLParser();
String xml = getDataFromSDcard(); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_NAME, e.getAttribute(KEY_NAME));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
// adapter = new SimpleAdapter(
// mCtx,
// menuItems,
// R.layout.list_item,
// new String[] { KEY_ADVERT, KEY_CONTACT, KEY_DATE },
// new int[] { R.id.textView1, R.id.textView2, R.id.textView3 });
return response;
}
private String getDataFromSDcard() {
// Get data from SDCard
// Find the directory for the SD Card using the API
// *Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
// Get the text file
File file = new File(sdcard, "Folder/test.xml");
// Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
// You'll need to add proper error handling here
}
return text.toString();
}
private void saveToSdCard() throws IOException {
try {
URL url = new URL(TUBE_STATUS_URL);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream is = url.openStream();
File testDirectory = new File(
Environment.getExternalStorageDirectory() + "/Folder");
if (!testDirectory.exists()) {
testDirectory.mkdir();
}
FileOutputStream fos = new FileOutputStream(testDirectory
+ "/test.xml");
byte data[] = new byte[1024];
int count = 0;
long total = 0;
int progress = 0;
while ((count = is.read(data)) != -1) {
total += count;
int progress_temp = (int) total * 100 / lenghtOfFile;
if (progress_temp % 10 == 0 && progress != progress_temp) {
progress = progress_temp;
}
fos.write(data, 0, count);
}
is.close();
fos.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPostExecute(String result) {
// Toast.makeText(getActivity(), String.valueOf(menuItems.size()),
// Toast.LENGTH_LONG).show();
// Log.d("Commuter+", String.valueOf(menuItems.size()));
}
}
}
And my XMLParser class:
public class XMLParser {
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;
}
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;
}
Log.d("Commuter+", String.valueOf(doc.toString().length()));
// 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 "";
}
}
I tried fixing this by testing my code with other URLs that had XML data and it worked, but there seems to be a problem when I use this URL.
public class XMLParser {
// constructor
public XMLParser() {
}
public String getXmlFromUrl(String url) {
String responseBody = null;
getset d1 = new getset();
String d = d1.getData(); // text
String y = d1.getYear(); // year
String c = d1.getCircular();
String p = d1.getPage();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("YearID", y));
nameValuePairs.add(new BasicNameValuePair("CircularNo", c));
nameValuePairs.add(new BasicNameValuePair("SearchText", d));
nameValuePairs.add(new BasicNameValuePair("pagenumber", p));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
responseBody = EntityUtils.toString(entity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return responseBody;
}
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());
// i m getting Exception here
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));
}
}
I am getting Exception in this class for parsing data. I want print this message in another class which extends from Activity. Can you please tell me how? I tried much but not able to do..
public class AndroidXMLParsingActivity extends Activity {
public int currentPage = 1;
public ListView lisView1;
static final String KEY_ITEM = "docdetails";
static final String KEY_NAME = "heading";
public Button btnNext;
public Button btnPre;
public static String url = "http://dev.taxmann.com/TaxmannService/TaxmannService.asmx/GetNotificationList";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// listView1
lisView1 = (ListView) findViewById(R.id.listView1);
// Next
btnNext = (Button) findViewById(R.id.btnNext);
// Perform action on click
btnNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
currentPage = currentPage + 1;
ShowData();
}
});
// Previous
btnPre = (Button) findViewById(R.id.btnPre);
// Perform action on click
btnPre.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
currentPage = currentPage - 1;
ShowData();
}
});
ShowData();
}
public void ShowData() {
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);
int displayPerPage = 5; // Per Page
int TotalRows = nl.getLength();
int indexRowStart = ((displayPerPage * currentPage) - displayPerPage);
int TotalPage = 0;
if (TotalRows <= displayPerPage) {
TotalPage = 1;
} else if ((TotalRows % displayPerPage) == 0) {
TotalPage = (TotalRows / displayPerPage);
} else {
TotalPage = (TotalRows / displayPerPage) + 1; // 7
TotalPage = (int) TotalPage; // 7
}
int indexRowEnd = displayPerPage * currentPage; // 5
if (indexRowEnd > TotalRows) {
indexRowEnd = TotalRows;
}
// Disabled Button Next
if (currentPage >= TotalPage) {
btnNext.setEnabled(false);
} else {
btnNext.setEnabled(true);
}
// Disabled Button Previos
if (currentPage <= 1) {
btnPre.setEnabled(false);
} else {
btnPre.setEnabled(true);
}
// Load Data from Index
int RowID = 1;
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
// RowID
if (currentPage > 1) {
RowID = (displayPerPage * (currentPage - 1)) + 1;
}
for (int i = indexRowStart; i < indexRowEnd; i++) {
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map = new HashMap<String, String>();
map.put("RowID", String.valueOf(RowID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
// adding HashList to ArrayList
menuItems.add(map);
RowID = RowID + 1;
}
SimpleAdapter sAdap;
sAdap = new SimpleAdapter(AndroidXMLParsingActivity.this, menuItems,
R.layout.list_item, new String[] { "RowID", KEY_NAME },
new int[] { R.id.ColRowID, R.id.ColName });
lisView1.setAdapter(sAdap);
}
}
This my class where I want to Print that message
You can simply surround your code with a Try/Catch block like this:
String xml;
Document doc;
NodeList nl;
try {
xml = parser.getXmlFromUrl(url); // getting XML
doc = parser.getDomElement(xml); // getting DOM element
nl = doc.getElementsByTagName(KEY_ITEM);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
This way you don't have to make any changes in your XMLParser class and you can easily handle any exceptions occurring while parsing your code in the main class itself. Also, for displaying error messages, Toast is the best thing according to me.
Hope this helps.. Thanks.
I would say, add throws SAXException in XMLParser.getDomElement() method and don't catch SAXException in this method as:
public Document getDomElement(String xml) throws SAXException {
Catch the SAXException in AndroidXMLParsingActivity.ShowData() where you are calling getDomElement() method and print the message in the desired way e.g.
public void ShowData() {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(url); // getting XML
Document doc = null;
try{
doc = parser.getDomElement(xml); // getting DOM element
}catch(SAXException sae){
//print the desired message here
}
.......
.......
}
For showing Message from Non Activity Class you will need to pass Current Activity Context as:
public class XMLParser {
Context context
// constructor
public XMLParser(Context conts) {
context =conts;
}
///YOUR CODE
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());
Toast.makeToast(context, e.toString(), Toast.Long).show();
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
Toast.makeToast(context, e.toString(), Toast.Long).show();
// i m getting Exception here
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
Toast.makeToast(context, e.toString(), Toast.Long).show();
return null;
}
Simply pass the constructor to your XMLParser class and used that there as your constructor. Or, you can try with use of getApplicationContext() You can simply show the Toast when you getting an exception like below -
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());
Toast.makeToast(con, e.toString(), Toast.Long).show(); // Will show the message of exception
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
Toast.makeToast(con, e.toString(), Toast.Long).show(); // Will show the message of exception
// i m getting Exception here
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
Toast.makeToast(con, e.toString(), Toast.Long).show(); // Will show the message of exception
return null;
}
Update
Okay, just pass the constructor as per below - Where you are calling that XMLparser class just call like below -
....
XMLParser xml = new XMLParser(AndroidXMLParsingActivity.this);
....
And, in XMLParser class there mention your constructor like below -
public class XMLParser {
Context con;
public XMLParser(Context context) {
con = context;
}
......
}
And, use this con as your constructor in your XMLParser class.
I have a google map inside my android application, I have some saved data in mysql db with latitude and longitude and i want to read that data from mysql db.
I have wrote code but the app is still error .
myphp is :
<?php
$link = mysql_connect('localhost', 'root', '') or die('Cannot connect to the DB');
mysql_select_db('joe', $link) or die('Cannot select the DB');
/* grab the posts from the db */
$query = "SELECT lattitude, longitude FROM tracking";
$result = mysql_query($query, $link) or die('Errorquery: '.$query);
$rows = array();
while ($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
$data = "{joel:".json_encode($rows)."}";
echo $data;
?>
I have 3 java activities
public class lagiiiiteslagi extends ListActivity {
private static String url = "http://10.0.2.2/labiltrack/daftartracking.php";
// JSON Node names
private static final String TAG_lattitude = "lattitude";
private static final String TAG_longitude = "longitude";
// contacts JSONArray
JSONArray lattitude = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
lattitude = json.getJSONArray(TAG_lattitude);
// looping through All Contacts
for(int i = 0; i < lattitude.length(); i++) {
JSONObject c = lattitude.getJSONObject(i);
// Storing each json item in variable
String lattitude = c.getString(TAG_lattitude);
String longitude = c.getString(TAG_longitude);
// Phone number is agin JSON Object
//JSONObject phone = c.getJSONObject(TAG_PHONE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String,String>();
// adding each child node to HashMap key => value
map.put(TAG_lattitude, lattitude);
map.put(TAG_longitude, longitude);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e){
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.main,
new String[] { TAG_lattitude, TAG_longitude }, new int[] {
R.id.TextViewResult, R.id.TextViewResult1 });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
// TODO Auto-generated method stub
// getting values from selected ListItem
//String lattitude = ((TextView)) view.findViewById(R.id.TextViewResult)).getText().toString();
//String longitude = ((TextView)) view.findViewById(R.id.TextViewResult1)).getText(lattitude).toString();
String lattitude = ((TextView) view.findViewById(R.id.TextViewResult)).getText().toString();
String longitude = ((TextView) view.findViewById(R.id.TextViewResult1)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_lattitude, lattitude);
in.putExtra(TAG_longitude, longitude);
startActivity(in);
}
});
}
}
this JSONparser class :
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser(){
}
public JSONObject getJSONFromUrl(String url) {
// TODO Auto-generated method stub
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
}catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
this is use to display in listview :
public class SingleMenuItemActivity extends Activity {
// JSON node keys
private static final String TAG_lattitude = "lattitude";
private static final String TAG_longitude = "longitude";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String lattitude = in.getStringExtra(TAG_lattitude);
String longitude = in.getStringExtra(TAG_longitude);
// Displaying all values on the screen
TextView lbllattitude = (TextView) findViewById(R.id.listlat);
TextView lbllongitude = (TextView) findViewById(R.id.listlong);
lbllattitude.setText(lattitude);
lbllongitude.setText(longitude);
}
}
I just want to display that lattitude and longitude in listview but still error, I'm new to android, I hope some one help me,
Thank in advance !
check this link for json help...
I suggest to to use log like Log.e("JSON", json); in different place to find the point where the error actually happens.