I'm parsing XML from URL. What changes has been made to parse same XML file from raw folder. Have any idea to how to reduce code ?
This my xml file :umesh.xml
<?xml version="1.0" encoding="utf-8"?>
<appdata>
<brand name="Lovely Products">
<product>Hat</product>
<product>Gloves</product>
</brand>
<brand name="Great Things">
<product>Table</product>
<product>Chair</product>
<product>Bed</product>
</brand>
</appdata>
Below is my java file :
DataHandler.java
package com.umesh.xmlparsing;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.graphics.Color;
import android.util.Log;
import android.widget.TextView;
public class DataHandler extends DefaultHandler{
//list for imported product data
private ArrayList<TextView> theViews;
//string to track each entry
private String currBrand = "";
//flag to keep track of XML processing
private boolean isProduct = false;
//context for user interface
private Context theContext;
//constructor
public DataHandler(Context cont) {
super();
theViews = new ArrayList<TextView>();
theContext = cont;
}
//start of the XML document
public void startDocument () { Log.i("DataHandler", "Start of XML document"); }
//end of the XML document
public void endDocument () { Log.i("DataHandler", "End of XML document"); }
//opening element tag
public void startElement (String uri, String name, String qName, Attributes atts)
{
//handle the start of an element
//find out if the element is a brand
if(qName.equals("brand"))
{
//set product tag to false
isProduct = false;
//create View item for brand display
TextView brandView = new TextView(theContext);
brandView.setTextColor(Color.rgb(73, 136, 83));
//add the attribute value to the displayed text
String viewText = "Items from " + atts.getValue("name") + ":";
brandView.setText(viewText);
//add the new view to the list
theViews.add(brandView);
}
//the element is a product
else if(qName.equals("product"))
isProduct = true;
}
//closing element tag
public void endElement (String uri, String name, String qName)
{
//handle the end of an element
if(qName.equals("brand"))
{
//create a View item for the products
TextView productView = new TextView(theContext);
productView.setTextColor(Color.rgb(192, 199, 95));
//display the compiled items
productView.setText(currBrand);
//add to the list
theViews.add(productView);
//reset the variable for future items
currBrand = "";
}
}
//element content
public void characters (char ch[], int start, int length)
{
//process the element content
//string to store the character content
String currText = "";
//loop through the character array
for (int i=start; i<start+length; i++)
{
switch (ch[i]) {
case '\\':
break;
case '"':
break;
case '\n':
break;
case '\r':
break;
case '\t':
break;
default:
currText += ch[i];
break;
}
}
//prepare for the next item
if(isProduct && currText.length()>0)
currBrand += currText+"\n";
}
public ArrayList<TextView> getData()
{
//take care of SAX, input and parsing errors
try
{
//set the parsing driver
System.setProperty("org.xml.sax.driver","org.xmlpull.v1.sax2.Driver");
//create a parser
SAXParserFactory parseFactory = SAXParserFactory.newInstance();
SAXParser xmlParser = parseFactory.newSAXParser();
//get an XML reader
XMLReader xmlIn = xmlParser.getXMLReader();
//instruct the app to use this object as the handler
xmlIn.setContentHandler(this);
//provide the name and location of the XML file **ALTER THIS FOR YOUR FILE**
URL xmlURL = new URL("http://mydomain.com/umesh.xml");
//open the connection and get an input stream
URLConnection xmlConn = xmlURL.openConnection();
InputStreamReader xmlStream = new InputStreamReader(xmlConn.getInputStream());
//build a buffered reader
BufferedReader xmlBuff = new BufferedReader(xmlStream);
// uuu XmlResourceParser todolistXml = getResources().getXml(R.raw.c4mh_clinics);
//parse the data
xmlIn.parse(new InputSource(xmlBuff));
}
catch(SAXException se) { Log.e("AndroidTestsActivity",
"SAX Error " + se.getMessage()); }
catch(IOException ie) { Log.e("AndroidTestsActivity",
"Input Error " + ie.getMessage()); }
catch(Exception oe) { Log.e("AndroidTestsActivity",
"Unspecified Error " + oe.getMessage()); }
//return the parsed product list
return theViews;
}
}
XMLParsing.java
package com.umesh.xmlparsing;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;
public class XMLParsing extends Activity {
TextView tv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get a reference to the layout
LayoutInflater inflater = getLayoutInflater();
LinearLayout mainLayout = (LinearLayout) inflater.inflate(R.layout.main,null);
try
{
//create an instance of the DefaultHandler class
//**ALTER THIS FOR YOUR CLASS NAME**
DataHandler handler = new DataHandler(getApplicationContext());
//get the string list by calling the public method
ArrayList<TextView> newViews = handler.getData();
//convert to an array
Object[] products = newViews.toArray();
//loop through the items, creating a View item for each
for(int i=0; i<products.length; i++)
{
//add the next View in the list
mainLayout.addView((TextView)products[i]);
}
}
catch(Exception pce) { Log.e("AndroidTestsActivity", "PCE "+pce.getMessage()); }
setContentView(mainLayout);
}
}
Please See below link of my answer, it will solve your problem.
Local XML Parsing
Related
URL url = new URL("https://www.setindia.com");
URLConnection urlConnectionObject = url.openConnection();
xmlHandlerObject = new XMLHandler();
xmlReaderObject.setContentHandler(xmlHandlerObject);
xmlReaderObject.parse(new InputSource(urlConnectionObject.getInputStream()));
// error on the last line please get me an explanation (new to android) and is this right
MAIN ACTIVITY:
package com.example.testparser;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyStore;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends Activity {
public static String TAG = "MYParser";
GettersSetters getData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "OnCreate");
View layout = findViewById(R.id.layout);
TextView tittle[];
TextView country[];
XMLHandler xmlHandlerObject = null;
try{
Log.d(TAG, "try");
SAXParserFactory saxParserFactoryObject = SAXParserFactory.newInstance(); //obtain and configure a SAX based parser
SAXParser saxParserObject = saxParserFactoryObject.newSAXParser(); //obtaining object for SAX parser
XMLReader xmlReaderObject = saxParserObject.getXMLReader();
URL url = new URL("https://www.setindia.com/setindia_api/episode/1?date=22-10-2013&hd=1");
URLConnection urlConnectionObject = url.openConnection();
xmlHandlerObject = new XMLHandler();
xmlReaderObject.setContentHandler(xmlHandlerObject);
Log.d(TAG, "about to get an error");
xmlReaderObject.parse(new InputSource(urlConnectionObject.getInputStream()));
Log.d(TAG, "try end");
}
catch (Exception e) {
Log.e(TAG, e.getMessage());
}
Log.d(TAG, "OnCreate fetching the data from the xml");
getData = xmlHandlerObject.getXMLData();
tittle = new TextView[getData.getTittle().size()];
country = new TextView[getData.getCountry().size()];
for (int i = 0; i < getData.getTittle().size(); i++) {
tittle[i] = new TextView(this);
tittle[i].setText("ITEM is : " + getData.getTittle().get(i));
country[i] = new TextView(this);
country[i].setText("Country is :" + getData.getTittle().get(i));
((ViewGroup) layout).addView(tittle[i]);
((ViewGroup) layout).addView(country[i]);
setContentView(R.layout.main);
}
}
#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;
}
}
GettersSetters :
package com.example.testparser;
import java.lang.reflect.Array;
import java.util.ArrayList;
import android.util.Log;
public class GettersSetters {
private ArrayList<String> tittle = new ArrayList<String>();
private ArrayList<String> country = new ArrayList<String>();
public ArrayList<String> getCountry(){
return country;
}
public ArrayList<String> getTittle(){
return tittle;
}
public void setCountry(String country){
this.country.add(country);
Log.i("This is the country : ",country);
}
public void setTittle(String tittle){
this.tittle.add(tittle);
Log.i("This is the tittle : ",tittle);
}
}
XMLHandler:
package com.example.testparser;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class XMLHandler extends DefaultHandler {
public static String TAG = "MYParser";
public static GettersSetters data = null;
String elementValue = null ;
Boolean elementOn = false;
public GettersSetters getXMLData(){
Log.e(TAG, "getXMLdata -> "+data.toString());
return data;
}
public void setXMLData(GettersSetters data){
XMLHandler.data = data;
Log.e(TAG, "setXmldata");
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
elementOn = true;
Log.d(TAG, "Checking the first element"+localName.equalsIgnoreCase("item"));
if(localName.equalsIgnoreCase("item"))
{
Log.d(TAG, "Creating a new getter setter instance");
data = new GettersSetters();
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
if(elementOn)
{
elementValue = new String(ch,start,length);
elementOn =false;
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
elementOn = false;
super.endElement(uri, localName, qName);
if(localName.equalsIgnoreCase("country"))
data.setCountry(elementValue);
if(localName.equalsIgnoreCase("tittle"))
data.setTittle(elementValue);
}
}
MAIN.Xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="SAGAR HERE"
android:textSize="20dp"
android:gravity="center_horizontal"
android:id="#+id/layout"
/>
</LinearLayout>
Don't do network operations on UI Thread (main).
You can use AsyncTask which enables proper and easy use of the UI thread. it allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers (It uses an inner thread pool). See more at: AsyncTask API
I am doing a project of TCP socket connection.
receiving json data from server and display it into a list view.
server sends data continually for every 1 sec.
I am getting an error of index out of bound exception Invalid index 4 size is 4.
My code is as follow.
I think problem is with User u = list.get(position); and runonUIthread.
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity{
String str;
ArrayList<User> list = new ArrayList<User>();;
ArrayAdapter<User> adb;
ListView lv;
SQLiteAdapter sqladapter = new SQLiteAdapter(MainActivity.this);;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
lv = (ListView) findViewById(R.id.listView1);
new Thread(new Client()).start();
Timer tm = new Timer();
}
public class Client implements Runnable{
#Override
public void run() {
try {
Socket s = new Socket("My IP",My Port);
while(s.isConnected()){
BufferedReader in = new BufferedReader(new InputStreamReader(
s.getInputStream()));
int nRead;
char[] data = new char[1024+512];
String decoded= "";
Date date = new Date();
long time = date.getTime();
while ((nRead = in.read(data, 0, data.length)) != -1) {
decoded += new String(data,0,nRead);
if(decoded.contains("{") && decoded.contains("}")){
str = decoded.substring(decoded.indexOf('{'),decoded.indexOf('}')+1);
decoded = decoded.substring(decoded.indexOf('}')+1);
if(!decoded.contains("{"))
decoded = "";
try {
JSONArray results = new JSONArray("["+str+"]");
for (int i = 0; i < results.length(); i++) {
JSONObject jsonObject;
jsonObject = results.getJSONObject(i);
String symbol = jsonObject.getString("Symbol");
double high = Double.parseDouble(jsonObject.getString("High"));
double low = Double.parseDouble(jsonObject.getString("Low"));
sqladapter = sqladapter.opentowrite();
boolean insertOrUpdate = sqladapter.checkDB(symbol);
if(insertOrUpdate== false){
User user = new User(jsonObject.getString("Symbol"),
jsonObject.getString("AskPrice"),
jsonObject.getString("BidPrice"),
jsonObject.getString("Open"),
jsonObject.getString("High"),
jsonObject.getString("Low"),
jsonObject.getString("Close"),
jsonObject.getString("PerChange"),
jsonObject.getString("NetChange"),
jsonObject.getString("Volume"));
sqladapter.insert(user);
list.add(user);
}
else{
int j;
for(j = 0; j<list.size();j++){
User obj = list.get(j);
if(obj.getSymbol().equalsIgnoreCase(symbol)){
list.remove(obj);
System.out.println("REMOVIED "+obj.getSymbol());
break;
}
}
User user2 = new User(jsonObject.getString("Symbol"),
jsonObject.getString("AskPrice"),
jsonObject.getString("BidPrice"),
jsonObject.getString("Open"),
high+"",low+"",
jsonObject.getString("Close"),
jsonObject.getString("PerChange"),
jsonObject.getString("NetChange"),
jsonObject.getString("Volume"));
list.add(j,user2);
System.out.println("ADDED :"+j);
}
updateList();
runOnUiThread(new Runnable() {
#Override
public void run() {
lv.setAdapter(adb);
adb.notifyDataSetChanged();
lv.invalidateViews();
lv.getCount();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
System.out.println(date.getTime()- time);
}
}
s.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void updateList() {
adb = new ArrayAdapter<User>(MainActivity.this, R.layout.rssitemview,list){
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view=convertView;
if(null == view) {
LayoutInflater vi = (LayoutInflater)MainActivity.this.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.rssitemview, null);
}
User u = list.get(position);
if(null != u)
{
TextView title = (TextView)view.findViewById(R.id.symbol);
TextView persend = (TextView)view.findViewById(R.id.persent);
TextView ltp = (TextView)view.findViewById(R.id.ltp);
TextView open = (TextView)view.findViewById(R.id.open);
TextView high = (TextView)view.findViewById(R.id.high);
TextView low = (TextView)view.findViewById(R.id.low);
TextView close = (TextView)view.findViewById(R.id.close);
title.setText(u.getSymbol().substring(0, 5));
ltp.setText(u.getPerChange().substring(0, 4));
persend.setText(u.getVolume().substring(0, 4));
open.setText(u.getOpen().substring(0, 4));
high.setText(u.getHigh().substring(0, 4));
low.setText(u.getLow().substring(0, 4));
close.setText(u.getClose().substring(0, 4));
}
return view;
}
};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Please help..
I am developing an application in which i need to read a resource file. I am saving my file (named "sample")in raw directory of res folder. When i tried to access it in code, by writing its resource id as R.raw.sample , it gives the following error.
Error(30,60)Cannot find symbol variable raw.
I am using intellij idea 11.0.3 and platform for android is 2.3.3.
The code is as follows...
package com.example;
import android.content.Context;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class SampleLoader {
public SampleLoader(){
}
public static int[] readFromFile(Context ctx, int resId){
String sample = readRawTextFile(ctx,resId);
int [] arr = stringToIntArray(sample);
return arr;
}
public static String readRawTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputReader = new InputStreamReader(inputStream);
BufferedReader buffReader = new BufferedReader(inputReader);
String line;
StringBuilder text = new StringBuilder();
try {
//while (( line = buffReader.readLine()) != null) {
if (( line = buffReader.readLine()) != null) {
text.append(line);
//text.append('\n');
}
} catch (IOException e) {
return null;
}
return text.toString();
}
public static int[] stringToIntArray(String line){
int[] sample = new int[line.length()-2];
String s ;
for (int i=0; i<line.length(); i++)
{
if(i>1)
{ sample[i] = Character.getNumericValue(line.charAt(i));
}
}
return sample;
}
public void populateListOfSamples(){
}
}
package com.example;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(createContent());
}
LinearLayout createContent(){
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
ViewGroup.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.FILL_PARENT);
linearLayout.setLayoutParams(params);
final int[] arr6 = SampleLoader.readFromFile(this,R.raw.sample) ;
final Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.no3);
final ImageView imageView1 = new ImageView(this);
imageView1.setVisibility(View.INVISIBLE);
final TextView textView = new TextView(this);
String str2 = "Byte Array will appear here!";
textView.setText(str2);
final Button btn2 = new Button(this);
final Button btn = new Button(this);
btn.setText("Convert Pic to Byte Array");
btn.setOnClickListener(new View.OnClickListener() { //Event handler for click event.
public void onClick(View v) {
textView.setText(str3);
btn2.setVisibility(View.VISIBLE);
}
});
btn2.setText("Convert Byte Array to Pic");
btn2.setVisibility(View.INVISIBLE);
btn2.setOnClickListener(new View.OnClickListener() { //Event handler for click event.
public void onClick(View v) {
btn.setVisibility(View.INVISIBLE);
final Bitmap imag = filing.arrtoimg(arr6);
textView.setVisibility(View.INVISIBLE);
imageView1.setVisibility(View.VISIBLE);
imageView1.setImageBitmap(imag);
}
});
linearLayout.addView(imageView1);
linearLayout.addView(btn);
linearLayout.addView(btn2);
linearLayout.addView(textView);
return linearLayout;
}
}
I need to show toast message when the server is not responding
when I press the login button, some parameters are passed to AgAppMenu screen which use url connection to server and get xml response in AgAppHelperMethods screen. The
probelm is when the server is busy or the network is not avaibale, I can't show toast message on catch block although it shows the log message.
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent ;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginScreen extends Activity implements OnClickListener {
EditText mobile;
EditText pin;
Button btnLogin;
Button btnClear;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.agapplogin);
TextView lblMobileNo = (TextView) findViewById(R.id.lblMobileNo);
lblMobileNo.setTextColor(getResources()
.getColor(R.color.text_color_red));
mobile = (EditText) findViewById(R.id.txtMobileNo);
TextView lblPinNo = (TextView) findViewById(R.id.lblPinNo);
lblPinNo.setTextColor(getResources().getColor(R.color.text_color_red));
pin = (EditText) findViewById(R.id.txtPinNo);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnClear = (Button) findViewById(R.id.btnClear);
btnLogin.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
postLoginData();
}
});
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
cleartext();
}
});
/*
*
* btnClear.setOnClickListener(new OnClickListener() { public void
* onClick(View arg0) {
*
* } });
*/
}
public void postLoginData()
{
if (pin.getTextSize() == 0 || mobile.getTextSize() == 0) {
AlertDialog.Builder altDialog = new AlertDialog.Builder(this);
altDialog.setMessage("Please Enter Complete Information!");
} else {
Intent i = new Intent(this.getApplicationContext(), AgAppMenu.class);
Bundle bundle = new Bundle();
bundle.putString("mno", mobile.getText().toString());
bundle.putString("pinno", pin.getText().toString());
i.putExtras(bundle);
startActivity(i);
}
}
#Override
public void onClick(View v) {
}
public void cleartext() {
{
pin.setText("");
mobile.setText("");
}
}
}
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class AgAppMenu extends Activity {
String mno, pinno;
private String[][] xmlRespone;
Button btnMiniStatement;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agappmenu);
mno = getIntent().getExtras().getString("mno");
pinno = getIntent().getExtras().getString("pinno");
setTitle("Welcome to the Ag App Menu");
AgAppHelperMethods agapp =new AgAppHelperMethods();
// xmlRespone = AgAppHelperMethods.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno + "&channel=INTERNET");
xmlRespone = agapp.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno + "&channel=INTERNET");
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnKeyListener;
public class AgAppHelperMethods extends Activity {
private static final String LOG_TAG = null;
private static AgAppHelperMethods instance = null;
public static String varMobileNo;
public static String varPinNo;
String[][] xmlRespone = null;
boolean flag = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agapphelpermethods);
}
protected AgAppHelperMethods() {
}
public static AgAppHelperMethods getInstance() {
if (instance == null) {
instance = new AgAppHelperMethods();
}
return instance;
}
public static String getUrl() {
String url = "https://demo.accessgroup.mobi/";
return url;
}
public String[][] AgAppXMLParser(String parUrl) {
String _node, _element;
String[][] xmlRespone = null;
try {
String url = AgAppHelperMethods.getUrl() + parUrl;
URL finalUrl = new URL(url);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(finalUrl.openStream()));
doc.getDocumentElement().normalize();
NodeList list = doc.getElementsByTagName("*");
_node = new String();
_element = new String();
xmlRespone = new String[list.getLength()][2];
// this "for" loop is used to parse through the
// XML document and extract all elements and their
// value, so they can be displayed on the device
for (int i = 0; i < list.getLength(); i++) {
Node value = list.item(i).getChildNodes().item(0);
_node = list.item(i).getNodeName();
_element = value.getNodeValue();
xmlRespone[i][0] = _node;
xmlRespone[i][1] = _element;
}// end for
throw new ArrayIndexOutOfBoundsException();
}// end try
// will catch any exception thrown by the XML parser
catch (Exception e) {
Toast.makeText(AgAppHelperMethods.this,
"error server not responding " + e.getMessage(),
Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
}
// Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
return xmlRespone;
}
`
AgAppHelperMethods isn't really an Activity. You've derived this class from Activity, but then you've created Singleton management methods (getInstance()) and you are instantiating it yourself. This is bad. Don't do this.
Normally Android controls the instantiation of activities. You don't ever create one yourself (with new).
It looks to me like AgAppHelperMethods just needs to be a regular Java class. It doesn't need to inherit from anything. Remove also the lifecycle methods like onCreate().
Now you will have a problem with the toast, because you need a context for that and AgAppHelperMethods isn't a Context. To solve that you can add Context as a parameter to AgAppXMLParser() like this:
public String[][] AgAppXMLParser(Context context, String parUrl) {
...
// Now you can use "context" to create your toast.
}
When you call AgAppXMLParser() from AgAppMenu just pass "this" as the context parameter.
I'm trying to make an SAX Parser for Android and started off by reading only one tag from the external XML file. I get an 'Unfortunately, -- has stopped' error. I looked at the Log file and it gives my a null reference error. My guess is the XMLAdapter class isn't working fine and I haven't been able to figure the problem out.
Here's my Main activity:
package com.vint.michiganbus;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.view.Window;
import android.util.Log;
public class listView extends Activity {
XMLGettersSetters data;
private static final String TAG = "listView";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
View layout = findViewById(R.id.layout);
TextView title[];
Log.i(TAG, "data is hello");
try {
/**
* Create a new instance of the SAX parser
**/
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxP = saxPF.newSAXParser();
XMLReader xmlR = saxP.getXMLReader();
URL url = new URL("http://mbus.pts.umich.edu/shared/public_feed.xml"); // URL of the XML
/**
* Create the Handler to handle each of the XML tags.
**/
XMLHandler myXMLHandler = new XMLHandler();
xmlR.setContentHandler(myXMLHandler);
xmlR.parse(new InputSource(url.openStream()));
} catch (Exception e) {
System.out.println(e);
}
data = XMLHandler.data;
/**
* Makes the TextView length the size of the TextView arrays by getting the size of the
**/
title = new TextView[data.get().size()];
/**
* Run a for loop to set All the TextViews with text until
* the size of the array is reached.
*
**/
for (int i = 0; i < data.get().size(); i++) {
title[i] = new TextView(this);
title[i].setText("Title = "+data.get().get(i));
((ViewGroup) layout).addView(title[i]);
}
setContentView(layout);
//setContentView(R.layout.listview);
}
}
Here's my XML Handler:
package com.vint.michiganbus;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class XMLHandler extends DefaultHandler {
private static final String TAG = "In Handler";
String elementValue = null;
Boolean elementOn = false;
public static XMLGettersSetters data = null;
public static XMLGettersSetters getXMLData() {
return data;
}
public static void setXMLData(XMLGettersSetters data) {
XMLHandler.data = data;
}
/**
* This will be called when the tags of the XML starts.
**/
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
elementOn = true;
Log.i(TAG, "starting Element "+localName);
if (localName.equals("livefeed"))
{
data = new XMLGettersSetters();
} else if (localName.equals("routecount")) {
/**
* We can get the values of attributes for eg. if the CD tag had an attribute( <CD attr= "band">Akon</CD> )
* we can get the value "band". Below is an example of how to achieve this.
*
* String attributeValue = attributes.getValue("attr");
* data.setAttribute(attributeValue);
*
* */
}
}
/**
* This will be called when the tags of the XML end.
**/
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
elementOn = false;
/**
* Sets the values after retrieving the values from the XML tags
* */
if (localName.equalsIgnoreCase("routecount"))
data.set(elementValue);
/*else if (localName.equalsIgnoreCae("artist"))
data.setArtist(elementValue);
else if (localName.equalsIgnoreCase("country"))
data.setCountry(elementValue);
else if (localName.equalsIgnoreCase("company"))
data.setCompany(elementValue);
else if (localName.equalsIgnoreCase("price"))
data.setPrice(elementValue);
else if (localName.equalsIgnoreCase("year"))
data.setYear(elementValue);*/
}
/**
* This is called to get the tags value
**/
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (elementOn) {
elementValue = new String(ch, start, length);
elementOn = false;
}
}
}
And this is my GetterSetter class
package com.vint.michiganbus;
import java.util.ArrayList;
public class XMLGettersSetters {
private ArrayList<String> routecount = new ArrayList<String>();
public ArrayList<String> get() {
return routecount;
}
public void set(String company) {
this.routecount.add(company);
}
}
Any help will be greatly appreciated!
ps: If anyone has suggestions how to handle the XML in the URL efficiently I'd love that!
The error might be that you're trying to retrieve a web file from the activity thread. I would create an AsyncTask, put all my parser code in the doInBackground() method from AsyncTask.
Something that would look like this :
private class DownloadFilesTask extends AsyncTask<Document, Integer, Document>
{
Document doc;
String xml;
public DownloadFilesTask(){}
protected Document doInBackground(Document... params)
{
xml = xmlFunctions.getXML("Your URL");
doc = XmlFunctions.XMLfromString(xml);
return doc;
}
protected void onPostExecute(Document result)
{
//Some code changing UI from the nodes you've just parsed
}
}
then you can call this class in your onCreate using :
new DownloadTaskfiles().execute();
Hope this is of some help!