Difficulty in using xml pull parser - android

I am trying to parse the xml file:
<?xml version="1.0"?>
<root>
<command>
<word>cancel</word>
<explanation>cancel print requested with lp</explanation>
</command>
<command>
<word>cat file</word>
<explanation>Display the file</explanation>
</command>
</root>
I am using XML pull parser for this.My program is
package com.example.androidsample2;
import java.io.IOException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Activity;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView myXmlContent = (TextView)findViewById(R.id.my_xml);
String stringXmlContent;
try {
stringXmlContent = getEventsFromAnXML(this);
myXmlContent.setText(stringXmlContent);
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String getEventsFromAnXML(Activity activity)
throws XmlPullParserException, IOException
{
StringBuffer stringBuffer = new StringBuffer();
Resources res = activity.getResources();
XmlResourceParser xpp = res.getXml(R.xml.xmlfile);
xpp.next();
int eventType = xpp.getEventType();
String tag;
while ((eventType = xpp.next()) != XmlPullParser.END_DOCUMENT)
{
if(XmlPullParser.START_TAG==eventType)
{
tag=xpp.getName();
//stringBuffer.append("\n"+tag);
if(tag=="word")
{
eventType=xpp.next();
stringBuffer.append("\n"+xpp.getText().toString());
}
}
}
return stringBuffer.toString();
}
}
How can i obtain the "explanation" by using "word".i.e how can i obtain "cancel print requested with lp" by using "cancel"?

The following line might work in C# but not in Java:
if(tag=="word")
Instead, write:
if (tag.equals("word"))
Update:
String word = null;
while ((eventType = xpp.next()) != XmlPullParser.END_DOCUMENT)
...
if (tag.equals("word"))
{
eventType = xpp.next();
word = xpp.getText();
}
else if (tag.equals("explanation"))
{
eventType = xpp.next();
if ("cancel".equals(word))
{
stringBuffer.append("\n" + xpp.getText());
}
}

Related

Parse XML using parsedata() loses login in session in Android

I am having an issue with the parseData() java function in android studio. I need to use it several times in one activity. The first time it loads, it grabs information from a url and displays the information in a list. This part works grea but now I need to be able to click on each listing and run the parseData per unit, each item has a unique url that I need to trigger, the url tells the database to decrease qty by one for that item. When I try to run parseNewData(),the second parseData function, in the file and pass it the unique url, it loses the cookies or does not pass the authorization (login session) so app fails with the error below. The log of the url returns 302 redirect, I think the login session information is lost or not passing correctly to url, it tries to send back to login activity and then causes a fail on "HttpResponse responseNew = LoginActivity.client.execute(httppost);"
Any help would be great.
Activity Code
package com.mike_scanncer_example.mike_scanner;
import java.io.IOException;
import java.net.URL;
import java.lang.Object;
import android.app.Activity;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import java.net.HttpURLConnection;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.kosalgeek.genasync12.AsyncResponse;
import com.kosalgeek.genasync12.PostResponseAsyncTask;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
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 java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Vector;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class Search_Result extends Activity {
private Handler mHandler=new Handler();
ProgressDialog dialog;
String ticket_no="";
String cname="";
String order_no="";
String card_no="";
String url="";
Vector<Vector<String>> data =null;
String [] number=null;
String [] checkedin =null;
String [] type=null;
String auth="";
String msg="";
String status="";
String reply="";
String mssg="";
String c_time="";
boolean f=true;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.ticket_check);
ImageButton back = (ImageButton) findViewById(R.id.back_search);
back.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Search_Result.this.finish();
}
});
Bundle extra = getIntent().getExtras();
Log.v("bundle", String.valueOf(extra));
url=extra.getString("url");
Log.v("LOG", url);
data = new Vector<Vector<String>>();
final ListView l1 =(ListView)findViewById(R.id.ticket_list);
dialog = ProgressDialog.show(Search_Result.this,"",
"Loading...", true);
l1.setDivider(null);
final Thread t =new Thread(new Runnable() {
public void run() {
parseData();
}
});
t.start();
Thread t1 =new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mHandler.post(new Runnable() {
public void run() {
dialog.cancel();
if(auth.equals("success"))
{
Log.v("login-info",auth);
number=new String[data.size()];
checkedin=new String[data.size()];
type=new String[data.size()];
for(int j=0; j<data.size(); j++)
{
number[j]=data.get(j).get(0);
checkedin[j]=data.get(j).get(1);
type[j]=data.get(j).get(2);
}
}
else
{
if(msg.equals("Please Login First"))
{
Intent intent = new Intent(Search_Result.this, LoginActivity.class);
startActivity(intent);
Toast.makeText(Search_Result.this, msg, Toast.LENGTH_SHORT).show();
}
else
{
//Toast.makeText(Search_Result.this, msg, Toast.LENGTH_SHORT).show();
AlertDialog.Builder dialog2 = new AlertDialog.Builder(Search_Result.this);
dialog2.setMessage("Sorry!\nRecord not found.");
dialog2 .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id)
{
finish();
}
});
dialog2.show();
}
}
l1.setAdapter(new EfficientAdapter(getApplicationContext()));
l1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0,
View arg1, int position, long id) {
}
});
}
});
}
});
t1.start();
}
private void parseData()
{
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = null;
try {
sp = spf.newSAXParser();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Get the XMLReader of the SAXParser we created.
XMLReader xr = null;
try {
xr = sp.getXMLReader();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Create a new ContentHandler and apply it to the XML-Reader
MyExampleHandlerGarbageDepot myExampleHandler = new MyExampleHandlerGarbageDepot();
xr.setContentHandler(myExampleHandler);
// Parse the xml-data from our URL.
try {
String urlToHit = url;
URL url=new URL(urlToHit);
HttpPost httppost = new HttpPost(url.toString());
HttpResponse response = LoginActivity.client.execute(httppost);
// Get hold of the response entity
HttpEntity entity = response.getEntity();
InputStream instream = null;
if (entity != null)
{
instream = entity.getContent();
}
xr.parse(new InputSource(instream));
//HttpPost http=new HttpPost(url.toString());
//HttpResponse res=client.execute(http);
// Log.v("response code",""+res);
// xr.parse(new InputSource(url.openStream()));
} catch (MalformedURLException e) {
Log.d("Net Disconnected", "NetDisconeeted");
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
Log.d("Net Disconnected", "NetDisconeeted");
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
Log.d("Net Disconnected", "NetDisconeeted");
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class MyExampleHandlerGarbageDepot extends DefaultHandler
{
private Vector<String> singleItem1=null;
// private boolean Rss = false;
//private int i=0;
// ===========================================================
// Methods
// ===========================================================
#Override
public void startDocument() throws SAXException {
//this.myParsedExampleDataSet = new ParsedExampleDataSet();
}
#Override
public void endDocument() throws SAXException {
// Nothing to do
}
#Override
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
if(localName.equals("Reply"))
{
auth=atts.getValue("replyCode");
msg=atts.getValue("msg");
Log.v("#####",auth);
}
else if(localName.equals("Tickets")){
}
else if(localName.equals("Ticket"))
{
singleItem1=new Vector<String>();
singleItem1.add(atts.getValue("number"));
singleItem1.add(atts.getValue("checkedin"));
singleItem1.add(atts.getValue("type"));
}
}
/** Gets be called on closing tags like:
* </tag> */
#Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if(localName.equals("Tickets"))
{
}
else if(localName.equals("Ticket"))
{
data.add(singleItem1);
}
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
#Override
public void characters(char ch[], int start, int length) {
}
}
private void parseNewData(String new_url)
{
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = null;
try {
sp = spf.newSAXParser();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Get the XMLReader of the SAXParser we created.
XMLReader xr = null;
try {
xr = sp.getXMLReader();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Create a new ContentHandler and apply it to the XML-Reader
MyHandlerGarbageDepot myExampleHandler = new MyHandlerGarbageDepot();
xr.setContentHandler(myExampleHandler);
// Parse the xml-data from our URL.
try {
String urlToHit = new_url;
Log.v("test123", new_url);
URL url=new URL(urlToHit);
HttpPost httppost = new HttpPost(url.toString());
HttpResponse responseNew = LoginActivity.client.execute(httppost);
// Get hold of the response entity
HttpEntity entity = responseNew.getEntity();
InputStream instream = null;
if (entity != null)
{
instream = entity.getContent();
}
xr.parse(new InputSource(instream));
//HttpPost http=new HttpPost(url.toString());
//HttpResponse res=client.execute(http);
// Log.v("response code",""+res);
// xr.parse(new InputSource(url.openStream()));
} catch (MalformedURLException e) {
Log.d("Net Disconnected", "NetDisconeeted");
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
Log.d("Net Disconnected", "NetDisconeeted");
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
Log.d("Net Disconnected", "NetDisconeeted");
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class MyHandlerGarbageDepot extends DefaultHandler
{
private boolean checkin =false;
// private boolean Rss = false;
//private int i=0;
// ===========================================================
// Methods
// ===========================================================
#Override
public void startDocument() throws SAXException {
//this.myParsedExampleDataSet = new ParsedExampleDataSet();
}
#Override
public void endDocument() throws SAXException {
// Nothing to do
}
#Override
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
if(localName.equals("Reply"))
{
reply=atts.getValue("replyCode");
mssg=atts.getValue("msg");
c_time=atts.getValue("time");
Log.v("#####",auth);
}
if(localName.equals("Checkedin"))
{
checkin = true;
}
}
/** Gets be called on closing tags like:
* </tag> */
#Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if(localName.equals("Checkedin"))
{
checkin=false;
}
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
#Override
public void characters(char ch[], int start, int length) {
if(checkin)
{
status = new String(ch,start,length);
}
}
}
private class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.ticket_list, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.ticket_num);
holder.text1 = (TextView) convertView.findViewById(R.id.ticket_type);
holder.check_img = (ImageButton) convertView.findViewById(R.id.ticket_status);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(data.get(position).get(0));
holder.text1.setText(data.get(position).get(2));
if(data.get(position).get(1).equals("0")){
holder.check_img.setBackgroundDrawable(getResources().getDrawable(R.drawable.check_inbut));
}
else{
holder.check_img.setBackgroundDrawable(getResources().getDrawable(R.drawable.checked_in_but));
}
holder.check_img.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(data.get(position).get(1).equals("0")){
//Toast.makeText(Search_Result.this,"check",Toast.LENGTH_SHORT).show();
url=Config.baseUrl+"checkin/"+Config.eventId+"/"+data.get(position).get(0);
parseNewData(url);
if(reply.equals("success"))
{
if(status.equals("0"))
{
holder.check_img.setBackgroundDrawable(getResources().getDrawable(R.drawable.check_inbut));
}
else
{
holder.check_img.setBackgroundDrawable(getResources().getDrawable(R.drawable.check_back));
Toast.makeText(Search_Result.this, "Check out", Toast.LENGTH_SHORT).show();
}
}
else
{
if(mssg.equals("Please Login First"))
{
Intent intent = new Intent(Search_Result.this, LoginActivity.class);
startActivity(intent);
Toast.makeText(Search_Result.this, mssg, Toast.LENGTH_SHORT).show();
}
}
}
else{
url=Config.baseUrl+"checkinInfo/"+Config.eventId+"/"+data.get(position).get(0);
//parseNewData(url);
Log.v("LOG", url);
AlertDialog.Builder builder = new AlertDialog.Builder(Search_Result.this);
AlertDialog.Builder builder1 = builder.setMessage("Ticket is already checked in")
.setCancelable(false)
.setPositiveButton("view details", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String contents = data.get(position).get(0);
Intent intent = new Intent(Search_Result.this, Ticket_detail.class);
intent.putExtra("ticket_no", contents);
intent.putExtra("event_id", Config.eventId);
startActivity(intent);
}
})
.setNegativeButton("close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.show();
}
}
});
return convertView;
}
}
static class ViewHolder {
TextView text;
TextView text1;
ImageButton check_img;
}
}
OUTPUT ERROR LOG
> E/AndroidRuntime: FATAL EXCEPTION: main
> Process: com.mike_scanncer_example.mike_scanner, PID: 2516
> android.os.NetworkOnMainThreadException
> at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
> at com.android.org.conscrypt.Platform.blockGuardOnNetwork(Platform.java:300)
> at com.android.org.conscrypt.OpenSSLSocketImpl.shutdownAndFreeSslNative(OpenSSLSocketImpl.java:1194)
> at com.android.org.conscrypt.OpenSSLSocketImpl.close(OpenSSLSocketImpl.java:1189)
> at org.apache.http.impl.SocketHttpClientConnection.shutdown(SocketHttpClientConnection.java:188)
> at org.apache.http.impl.conn.DefaultClientConnection.shutdown(DefaultClientConnection.java:155)
> at org.apache.http.impl.conn.SingleClientConnManager$PoolEntry.shutdown(SingleClientConnManager.java:445)
> at org.apache.http.impl.conn.SingleClientConnManager.getConnection(SingleClientConnManager.java:249)
> at org.apache.http.impl.conn.SingleClientConnManager$1.getConnection(SingleClientConnManager.java:195)
> at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:332)
> at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)
> at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492)
> at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470)
> at com.mike_scanncer_example.mike_scanner.Search_Result.parseNewData(Search_Result.java:403)
> at com.mike_scanncer_example.mike_scanner.Search_Result.access$200(Search_Result.java:63)
> at com.mike_scanncer_example.mike_scanner.Search_Result$EfficientAdapter$1.onClick(Search_Result.java:579)
> at android.view.View.performClick(View.java:5637)
> at android.view.View$PerformClick.run(View.java:22429)
> at android.os.Handler.handleCallback(Handler.java:751)
> at android.os.Handler.dispatchMessage(Handler.java:95)
> at android.os.Looper.loop(Looper.java:154)
> at android.app.ActivityThread.main(ActivityThread.java:6119)
> at java.lang.reflect.Method.invoke(Native Method)
> at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
> at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
> Disconnected from the target VM, address: 'localhost:8648', transport:
> 'socket'
Your exception is stated in the error output
NetworkOnMainThreadException
It looks to me like it occurs in your parseData exception here:
HttpPost httppost = new HttpPost(url.toString());
HttpResponse response = LoginActivity.client.execute(httppost);
You cannot make Network calls on the Main Thread. In your onCreate call, instead of the Runnables, I would look at using AsyncTask. It will clean up the code in the onCreate method and gives you an override to use when the call is done (protected void onPostExecute)

Java.lang.IllegalArgumentException: host=null, port=4444

If I run my app in the emulator my app crashes immediately. I get the error 'Caused by: java.lang.IllegalArgumentException: host=null, port=4444.' Logcat says the error comes from InetSocketAdress. This is my server code:
package com.imptmd.charliemacdonald.desleutelaar_v3;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
/**
* Created by Charlie on 26-3-2015.
*/
public class Server extends AsyncTask<Void, Void, String> {
private String message;
private String ip;
public static int port = 4444;
private String serverResponse = null;
public Server(String ip, int port, String message ) {
super();
//IP, Port en bericht om naar server te sturen
this.message = message;
this.ip = ip;
this.port = port;
}
#Override
protected String doInBackground(Void... params) {
try {
Socket serverSocket = new Socket();
serverSocket.connect(new InetSocketAddress(this.ip, this.port), 4444);
this.sendMessage(message, serverSocket);
InputStream input;
try {
input = serverSocket.getInputStream();
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(input));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line);
}
responseStreamReader.close();
this.serverResponse = stringBuilder.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Response: " + serverResponse);
} catch (UnknownHostException e) {
Log.d("debug", "can't find host");
} catch (SocketTimeoutException e) {
Log.d("debug", "time-out");
} catch (IOException e) {
e.printStackTrace();
}
return serverResponse;
}
private void sendMessage(String message, Socket serverSocket) {
OutputStreamWriter outputStreamWriter = null;
try {
outputStreamWriter = new OutputStreamWriter(serverSocket.getOutputStream());
} catch (IOException e2) {
e2.printStackTrace();
}
if (outputStreamWriter != null) {
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
PrintWriter writer = new PrintWriter(bufferedWriter, true);
writer.println(message);
}
}
}
The code of the class where the user can fill in the IP:
package com.imptmd.charliemacdonald.desleutelaar_v3;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.concurrent.ExecutionException;
public class GebruikerIP extends Activity {
private Boolean serverCheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
setTitle("Slotenbedrijf De Sleutelaar");
//Check voor internet verbinding
if(NetwerkCheck.isInternetAvailable(GebruikerIP.this))
{
}
else
{
Toast.makeText(GebruikerIP.this, "Er is helaas geen internetverbinding geconstateerd, daarom wordt nu de laatst opgehaalde informatie getoond.!", Toast.LENGTH_LONG).show();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gebruikerip);
Button ipButton = (Button) findViewById(R.id.serverbutton);
ipButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
verbindServer();
}
});
//Enter key afvangen
EditText ipInvoer = (EditText) findViewById(R.id.ipinvoeren);
ipInvoer.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
switch(keyCode) {
case KeyEvent.KEYCODE_ENTER:
verbindServer();
break;
default:
return false;
}
return true;
}
});
}
//server connectie maken voor ophalen van diensten
public void verbindServer() {
TextView ipVeld = (TextView) findViewById(R.id.ipinvoeren);
String ip = ipVeld.getText().toString();
Log.i("ip", ip);
String response = null;
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("slotenlijst", "");
} catch (JSONException e) {
e.printStackTrace();
}
try {
try {
response = new Server(ip,
4444, jsonObject.toString()).execute().get();
//exceptions afvangen
} catch (InterruptedException e)
{
}
} catch (ExecutionException e1)
{
}
if (response == null) {
serverCheck = false;
Toast.makeText(this, "Verbinden met server mislukt, staat server aan?", Toast.LENGTH_LONG).show();
} else {
//doorgaan naar MainActivity
serverCheck = true;
HoofdschermFragment.serverIp = ip;
Intent startApp = new Intent(this, MainActivity.class);
startActivity(startApp);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_gebruiker_ip, 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();
return super.onOptionsItemSelected(item);
}
}
I can't find out how I can fix this error. Help would me appreciated. Thanks!
change it to
InetAddress inetServer = InetAddress.getByName(IP);
than
Socket socket = new Socket(inetServer, devicePort);
and if you are using for Server Socket than use below line
ServerSocket socket = new ServerSocket(devicePort,int backlognumber, inetServer);

Parsing an xml url to display in form of cards

I am trying to parse a xml file and display the feeds in form of separate cards. This is what my code looks like till now:
package com.bliss.android.helloworld.main;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import com.google.android.glass.app.Card;
import com.google.android.glass.widget.CardScrollAdapter;
import com.google.android.glass.widget.CardScrollView;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
public class SecondScreen extends Activity {
ArrayList<Card> headlines = new ArrayList<Card>();
ArrayList links = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
new PostTask().execute("http://feeds.pcworld.com/pcworld/latestnews");
CardScrollView csvCardsView = new CardScrollView(this);
csaAdapter cvAdapter = new csaAdapter();
csvCardsView.setAdapter(cvAdapter);
csvCardsView.activate();
setContentView(csvCardsView);
}
private class PostTask extends AsyncTask<String, Integer, String> {
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String url=params[0];
try{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
boolean insideItem = false;
// Returns the type of current event: START_TAG, END_TAG, etc..
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem){
Card newCard = new Card(SecondScreen.this);
newCard.setText(xpp.nextText());
headlines.add(newCard); //extract the headline
}
} else if (xpp.getName().equalsIgnoreCase("link")) {
if (insideItem)
links.add(xpp.nextText()); //extract the link of article
}
}else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
insideItem=false;
}
eventType = xpp.next(); //move to next element
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return url;
}
}
private class csaAdapter extends CardScrollAdapter
{
#Override
public int findIdPosition(Object id)
{
return -1;
}
#Override
public int findItemPosition(Object item)
{
return headlines.indexOf(item);
}
#Override
public int getCount()
{
return headlines.size();
}
#Override
public Object getItem(int position)
{
return headlines.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
return headlines.get(position).toView();
}
}
public InputStream getInputStream(URL url) {
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
}
I do not get any error but there is nothing displayed on the card. I cant figure out whats the reason. Is it because of Card(SeconScreen.this). But if I dont put that it gives me an error saying constructor not defined.

android : parsing XML and insert to sqlite database

Assume that I have file XML like this :
<?xml version="1.0"?>
<P>
<Content>
<id>1016576</id>
<date>20.08.2012</date>
<placeOfBirth>KUALA LUMPUR</placeOfBirth>
</Content>
<Content>
<id>1016620</id>
<date>20.08.2012</date>
<placeOfBirth>SINGAPORE</placeOfBirth>
</Content>
<Content>
<id>1020907</id>
<date>20.08.2012</date>
<placeOfBirth>SINGAPORE</placeOfBirth>
</Content>
</P>
I want to parse all the text and insert into database table which have _id, date and placeOfBirth column. I've tried this :
Activity activity1 = this;
String str="";
Resources res = activity1.getResources();
XmlResourceParser xmlPharser = res.getXml(R.xml.fileXML);
String id,date,pob;
//database
final databaseHelper myDbHelper = new databaseHelper(this);
myDbHelper.open();
//insert into table while parsing xml
try {
xmlPharser.next();
int eventType = xmlPharser.getEventType();
String event = ""+eventType;
Log.d("Event", event);
while (eventType != XmlPullParser.END_DOCUMENT)
{
if(eventType == XmlPullParser.START_TAG )
{
if( xmlPharser.getName() == "id")
{
id=xmlPharser.getText();
}
else if ( xmlPharser.getName() == "date" )
{
date = xmlPharser.getText();
}
else if ( xmlPharser.getName() == "placeOfBirth" )
{
pob = xmlPharser.getText();
}
myDbHelper.insertData(id,date,pob);
myDbHelper.close();
}
eventType = xmlPharser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
It doesn't get any error LogCat display, but it dosen't test the condition at each START_TAG.
How can I resolve this problem...
All answer would be appreciated..thanks
Parsing XML can get really nasty if you're not careful, specially with this parsers; you could try some other with simpler APIs or clearer ways of going through the hierarchy (ie. JDOM). You should also take a look at the examples at the Android developer's site, it's really straight forward (Parsing XML Data).
All that been said, I fixed it for you. This should work (at least it does for me). Be careful though, it doesn't have any error checking on malformed XML or database stuff.
import java.io.IOException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Activity;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
XmlResourceParser parser = getResources().getXml(R.xml.filexml);
final databaseHelper myDbHelper = null;
try {
myDbHelper = new databaseHelper(this);
myDbHelper.open();
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equals("Content")) {
String id = null, date = null, pob = null;
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
name = parser.getName();
if (name.equals("id")) {
id = readText(parser);
} else if (name.equals("date")) {
date = readText(parser);
} else if (name.equals("placeOfBirth")) {
pob = readText(parser);
}
}
myDbHelper.insertData(id,date,pob);
}
}
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (myDbHelper != null) {
myDbHelper.close();
}
}
}
private String readText(XmlPullParser parser) throws IOException,
XmlPullParserException {
String result = "";
if (parser.next() == XmlPullParser.TEXT) {
result = parser.getText();
parser.nextTag();
}
return result;
}
One more comment, change the xml file name to lowercase ;)

Parsing GPX files with SAX parser or XmlPullParser

I have a number of gpx files that my app creates and will need to parse at a later stage in the app.
I'm having trouble parsing them in general. I've seen alot of examples of parsers on this site and others but they all use objects like Tracksand TrakcPoints but what these classes contain can't be found. I would really like just to be able to parse the file and sort it into an ArrayList of Location. I will need to get the long and lat from the file as well as the time and elevation.
Can some one help me with this problem?
I don't mind if use SAX parser or an Xml pull parseror another method of doing it.
Figured it out, might not be the most elegant way of doing it but it works
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
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.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.location.Location;
public class GpxReader
{
private static final SimpleDateFormat gpxDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
public static List<Location> getPoints(File gpxFile)
{
List<Location> points = null;
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
FileInputStream fis = new FileInputStream(gpxFile);
Document dom = builder.parse(fis);
Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("trkpt");
points = new ArrayList<Location>();
for(int j = 0; j < items.getLength(); j++)
{
Node item = items.item(j);
NamedNodeMap attrs = item.getAttributes();
NodeList props = item.getChildNodes();
Location pt = new Location("test");
pt.setLatitude(Double.parseDouble(attrs.getNamedItem("lat").getTextContent()));
pt.setLongitude(Double.parseDouble(attrs.getNamedItem("lon").getTextContent()));
for(int k = 0; k<props.getLength(); k++)
{
Node item2 = props.item(k);
String name = item2.getNodeName();
if(!name.equalsIgnoreCase("time")) continue;
try
{
pt.setTime((getDateFormatter().parse(item2.getFirstChild().getNodeValue())).getTime());
}
catch(ParseException ex)
{
ex.printStackTrace();
}
}
for(int y = 0; y<props.getLength(); y++)
{
Node item3 = props.item(y);
String name = item3.getNodeName();
if(!name.equalsIgnoreCase("ele")) continue;
pt.setAltitude(Double.parseDouble(item3.getFirstChild().getNodeValue()));
}
points.add(pt);
}
fis.close();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(ParserConfigurationException ex)
{
}
catch (SAXException ex) {
}
return points;
}
public static SimpleDateFormat getDateFormatter()
{
return (SimpleDateFormat)gpxDate.clone();
}
}
Hope this helps some people
with SAX:
GpxImportActivity.java
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
public class GpxImportActivity extends Activity {
private String fileName ="gpsTrack.gpx";
private File sdCard;
private List<Location> locationList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gpx_import);
locationList = new ArrayList<Location>();
sdCard = Environment.getExternalStorageDirectory();
if (!sdCard.exists() || !sdCard.canRead()) {
Log.d("GpxImportActivity", "SD-Card not available or not readable");
finish();
}
boolean availableFile = new File(sdCard, fileName).exists();
if (!availableFile) {
Log.d("GpxImportActivity", "File \"" +fileName+ "\" not available");
finish();
} else {
Log.d("GpxImportActivity", "File \"" +fileName+ "\" found");
}
try {
System.setProperty("org.xml.sax.driver","org.xmlpull.v1.sax2.Driver");
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
/*
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(false);
SAXParser saxParser = spf.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
*/
GpxFileContentHandler gpxFileContentHandler = new GpxFileContentHandler();
xmlReader.setContentHandler(gpxFileContentHandler);
FileReader fileReader = new FileReader(new File(sdCard,fileName));
InputSource inputSource = new InputSource(fileReader);
xmlReader.parse(inputSource);
locationList = gpxFileContentHandler.getLocationList();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.gpx_import, menu);
return true;
}
}
GpxFileContentHandler.java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import android.location.Location;
public class GpxFileContentHandler implements ContentHandler {
private String currentValue;
private Location location;
private List<Location> locationList;
private final SimpleDateFormat GPXTIME_SIMPLEDATEFORMAT = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");
public GpxFileContentHandler() {
locationList = new ArrayList<Location>();
}
public List<Location> getLocationList() {
return locationList;
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes atts) throws SAXException {
if (localName.equalsIgnoreCase("trkpt")) {
location = new Location("gpxImport");
location.setLatitude(Double.parseDouble(atts.getValue("lat").trim()));
location.setLongitude(Double.parseDouble(atts.getValue("lon").trim()));
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (localName.equalsIgnoreCase("ele")) {
location.setAltitude(Double.parseDouble(currentValue.trim()));
}
if (localName.equalsIgnoreCase("time")) {
try {
Date date = GPXTIME_SIMPLEDATEFORMAT.parse(currentValue.trim());
Long time = date.getTime();
location.setTime(time);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (localName.equalsIgnoreCase("trkpt")) {
locationList.add(location);
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
currentValue = new String(ch, start, length);
}
#Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
}
#Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
}
#Override
public void endPrefixMapping(String prefix) throws SAXException {
// TODO Auto-generated method stub
}
#Override
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
}
#Override
public void processingInstruction(String target, String data)
throws SAXException {
// TODO Auto-generated method stub
}
#Override
public void setDocumentLocator(Locator locator) {
// TODO Auto-generated method stub
}
#Override
public void skippedEntity(String name) throws SAXException {
// TODO Auto-generated method stub
}
#Override
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
// TODO Auto-generated method stub
}
}
Ready to use, open source, and fully functional java GpxParser (and much more) here
https://sourceforge.net/projects/geokarambola/
Details here
https://plus.google.com/u/0/communities/110606810455751902142
With the above library parsing a GPX file is a one liner:
Gpx gpx = GpxFileIo.parseIn( "SomeGeoCollection.gpx" ) ;
Getting its points, routes or tracks trivial too:
ArrayList<Route> routes = gpx.getRoutes( ) ;
Route route = routes.get(0) ; // First route.
Then you can iterate the route's points and get their lat/lon/ele directly
for(RoutePoint rtePt: route.getRoutePoints( ))
Location loc = new Location( rtePt.getLatitude( ), rtePt.getLongitude( ) ) ;

Categories

Resources