Android: Exception: Connection timeout - java

I keep getting this problem
Exception: Connection timeout
I am running my project on another device so i have to use the IP adress. So i change localhost:8080/lab/lab1.xml to http://192.168.1.5/lab/lab1.xml
Now after i run and it load for a while on the device after loading it then displays a
blank page. and when i checked Logcat it displays Exception: Connection timeout
Help me please. Thanks
So here is the MainActivity.java
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tvResponse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvResponse = (TextView) findViewById(R.id.tvResponse);
new PostAsync().execute();
}
class PostAsync extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
XMLHelper helper;
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(MainActivity.this, "by Es", "Loading", true, false);
}
#Override
protected Void doInBackground(Void... arg0) {
helper = new XMLHelper();
helper.get();
return null;
}
#Override
protected void onPostExecute(Void result) {
StringBuilder builder = new StringBuilder();
for(EventValue event : helper.events) {
builder.append("\nWhat: " + event.getWhat());
builder.append("\nWhen: " + event.getWhen());
builder.append("\nWhere: " + event.getWhere());
builder.append("\n");
}
tvResponse.setText(builder.toString());
pd.dismiss();
}
}
}
Here is the XMLHelper.java
import java.io.InputStream;
import java.net.URL;
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.util.Log;
public class XMLHelper extends DefaultHandler {
/**
* The URL to be parsed
*/
private String URL_MAIN = "http://192.168.1.5/lab/lab1.xml";
String TAG = "XMLHelper";
Boolean currTag = false;
String currTagVal = "";
public EventValue event = null;
public ArrayList<EventValue> events = new ArrayList<EventValue>();
public void get() {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser mSaxParser = factory.newSAXParser();
XMLReader mXmlReader = mSaxParser.getXMLReader();
mXmlReader.setContentHandler(this);
InputStream mInputStream = new URL(URL_MAIN).openStream();
mXmlReader.parse(new InputSource(mInputStream));
} catch(Exception e) {
// Exceptions can be handled for different types
// But, this is about XML Parsing not about Exception Handling
Log.e(TAG, "Exception: " + e.getMessage());
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if(currTag) {
currTagVal = currTagVal + new String(ch, start, length);
currTag = false;
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currTag = false;
if(localName.equalsIgnoreCase("what"))
event.setWhat(currTagVal);
else if(localName.equalsIgnoreCase("when"))
event.setWhen(currTagVal);
else if(localName.equalsIgnoreCase("where"))
event.setWhere(currTagVal);
else if(localName.equalsIgnoreCase("event"))
events.add(event);
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
Log.i(TAG, "TAG: " + localName);
currTag = true;
currTagVal = "";
if(localName.equals("event"))
event = new EventValue();
}
}
Here is the EventValue.java
public class EventValue {
String what, when, where;
public String getWhat() {
return what;
}
public void setWhat(String what) {
this.what = what;
}
public String getWhen() {
return when;
}
public void setWhen(String when) {
this.when = when;
}
public String getWhere() {
return where;
}
public void setWhere(String where) {
this.where = where;
}
}
Here is the xml file lab1.xml (localhost:8080/lab/lab1.xml)
<event>
<what>Summer</what>
<when>March1</when>
<where>--</where>
</event>
<event>
<what>asdasdas</what>
<when>March 2</when>
<where>asasas</where>
</event>
<event>
<what>asdasdq</what>
<when>asdasdx</when>
<where>asdasdf</where>
</event>

If you are using port 8080 then you should use that in the connection url:
http://192.168.1.5:8080/lab/lab1.xml
It would also be a good idea to check that you can access the url with a browser from another machine.

Related

identify incoming caller android and display in toast

I'm trying to build a simple phonebook application where I can perform a search and an API will return the information. So far this is the part that I've got working.
I also want incoming caller to be identified with the same API, that would require the incoming number from Broastcastreceiver to be put into the API query and the returned information should be displayed in a toast. This is the part I'm having problems with.
So far this is what I have. Apologize if its really messy, this is what I've been playing around with recently and made small adjustments. Also its alot of copy-paste, I'm a beginner at java/Android and trying to learn.
HttpHandler.java
package se.xx.api_test;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class HttpHandler extends PhoneCallReceiver {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
PhoneCallReceiver.java
package se.xx.api_test;
import java.util.Date;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;
import android.util.Log;
public class PhoneCallReceiver extends BroadcastReceiver {
//The receiver will be recreated whenever android feels like it. We need a static variable to remember data between instantiations
private static int lastState = TelephonyManager.CALL_STATE_IDLE;
private static Date callStartTime;
private static boolean isIncoming;
public static String savedNumber; //because the passed incoming is only valid in ringing
#Override
public void onReceive(Context context, Intent intent) {
//We listen to two intents. The new outgoing call only tells us of an outgoing call. We use it to get the number.
if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
savedNumber = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
}
else{
String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
int state = 0;
if(stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)){
state = TelephonyManager.CALL_STATE_IDLE;
}
else if(stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
state = TelephonyManager.CALL_STATE_OFFHOOK;
}
else if(stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)){
state = TelephonyManager.CALL_STATE_RINGING;
}
onCallStateChanged(context, state, number);
}
}
//Derived classes should override these to respond to specific events of interest
protected void onIncomingCallStarted(Context ctx, String number, Date start){}
protected void onOutgoingCallStarted(Context ctx, String number, Date start){}
protected void onIncomingCallEnded(Context ctx, String number, Date start, Date end){}
protected void onOutgoingCallEnded(Context ctx, String number, Date start, Date end){}
protected void onMissedCall(Context ctx, String number, Date start){}
//Deals with actual events
//Incoming call- goes from IDLE to RINGING when it rings, to OFFHOOK when it's answered, to IDLE when its hung up
//Outgoing call- goes from IDLE to OFFHOOK when it dials out, to IDLE when hung up
public void onCallStateChanged(Context context, int state, String number) {
if(lastState == state){
//No change, debounce extras
return;
}
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
isIncoming = true;
callStartTime = new Date();
savedNumber = number;
onIncomingCallStarted(context, number, callStartTime);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
//Transition of ringing->offhook are pickups of incoming calls. Nothing done on them
if(lastState != TelephonyManager.CALL_STATE_RINGING){
isIncoming = false;
callStartTime = new Date();
onOutgoingCallStarted(context, savedNumber, callStartTime);
}
break;
case TelephonyManager.CALL_STATE_IDLE:
//Went to idle- this is the end of a call. What type depends on previous state(s)
if(lastState == TelephonyManager.CALL_STATE_RINGING){
//Ring but no pickup- a miss
onMissedCall(context, savedNumber, callStartTime);
}
else if(isIncoming){
onIncomingCallEnded(context, savedNumber, callStartTime, new Date());
}
else{
onOutgoingCallEnded(context, savedNumber, callStartTime, new Date());
}
break;
}
lastState = state;
}
}
MainActivity.java
package se.xx.api_test;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.HashMap;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
public class MainActivity extends AppCompatActivity {
private TextView tv;
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
tv = (TextView) findViewById(R.id.textInput);
Button queryButton = (Button) findViewById(R.id.queryButton);
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
} catch (Exception e) {
// TODO: handle exception
}
contactList.clear();
new GetContacts().execute();
}
});
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//Toast.makeText(MainActivity.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
String id = tv.getText().toString();
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://10.0.2.2/api/api.php?id="+id;
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("data");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String namn = c.getString("namn");
String avdelning = c.getString("avdelning");
//String telnr = c.getString("telnr");
//JSONObject data = jsonObj.getJSONObject("data");
//String namn = data.getString("namn");
//String avdelning = data.getString("avdelning");
//String telnr = data.getString("telnr");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobil = phone.getString("mobil");
String telnr = phone.getString("telnr");
//String office = phone.getString("office");
// tmp hash map for single contact
//HashMap<String, String> contact = new HashMap<>();
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("namn", namn);
contact.put("avdelning", avdelning);
contact.put("mobil", mobil);
contact.put("telnr", telnr);
//contact.put("phone", phone);
//contact.put("namn", namn);
//contact.put("avdelning", avdelning);
//contact.put("telnr", telnr);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactList,
R.layout.list_item, new String[]{ "namn","avdelning","mobil", "telnr"},
new int[]{R.id.email, R.id.mobile, R.id.mobil, R.id.telnr});
lv.setAdapter(adapter);
}
}
}
CallReceiver.java (this is what I've been playing around with)
package se.xx.api_test;
import java.util.Date;
import java.util.HashMap;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.TextView;
import android.widget.RelativeLayout;
import android.view.ViewGroup;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import android.widget.ListAdapter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import java.lang.String;
import android.telephony.TelephonyManager;
public class CallReceiver extends PhoneCallReceiver {
#Override
public void onIncomingCallStarted(Context ctx, String number, Date start) {
final String phnr = String.valueOf(R.id.mobile);
Toast toast = Toast.makeText(ctx.getApplicationContext(), , Toast.LENGTH_SHORT);
ViewGroup group = (ViewGroup) toast.getView();
TextView messageTextView = (TextView) group.getChildAt(0);
messageTextView.setTextSize(25);
toast.show();
}
#Override
public void onOutgoingCallStarted(Context ctx, String number, Date start) {
}
#Override
protected void onIncomingCallEnded(Context ctx, String number, Date start, Date end) {
}
#Override
protected void onOutgoingCallEnded(Context ctx, String number, Date start, Date end) {
}
#Override
protected void onMissedCall(Context ctx, String number, Date start) {
}
private class APICall extends MainActivity {
String number = getIntent().getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
protected Void doInBackground(Void... arg0) {
String TAG = MainActivity.class.getSimpleName();
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://10.0.2.2/api/api.php?id="+number;
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("data");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
final String namn = c.getString("namn");
String avdelning = c.getString("avdelning");
//String telnr = c.getString("telnr");
//JSONObject data = jsonObj.getJSONObject("data");
//String namn = data.getString("namn");
//String avdelning = data.getString("avdelning");
//String telnr = data.getString("telnr");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobil = phone.getString("mobil");
String telnr = phone.getString("telnr");
//String office = phone.getString("office");
// tmp hash map for single contact
//HashMap<String, String> contact = new HashMap<>();
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("namn", namn);
contact.put("avdelning", avdelning);
contact.put("mobil", mobil);
contact.put("telnr", telnr);
//contact.put("phone", phone);
//contact.put("namn", namn);
//contact.put("avdelning", avdelning);
//contact.put("telnr", telnr);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
}
}
which part you got an error ?
with your Api ? or while receive you phone number from service ?
put your error to clarify the situation

Android Remote Service does not work on Real device

Remote Service
I'm doing a test for Android remote Service.
In the first app module, I make a service, complete as below:
AppService
package com.hqyj.dev.aidltest;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
public class AppService extends Service {
public AppService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return new IAppServiceRemoteBinder.Stub() {
#Override
public void basicTypes(
int anInt, long aLong,
boolean aBoolean, float aFloat,
double aDouble, String aString)
throws RemoteException {
}
#Override
public void setData(String data)
throws RemoteException {
setRealData(data);
}
#Override
public void registerCallback(IRemoteServiceCallback cb)
throws RemoteException {
AppService.this.callback = cb;
}
#Override
public void unregisterCallback(IRemoteServiceCallback cb)
throws RemoteException {
AppService.this.callback = null;
}
};
}
private IRemoteServiceCallback callback;
#Override
public void onCreate() {
super.onCreate();
System.out.println("Service started");
}
#Override
public void onDestroy() {
super.onDestroy();
System.out.println("Service stop");
}
public void setRealData(String data) {
this.data = data;
System.out.println("data = " + data);
try {
Thread.sleep(1000);
if (callback != null) {
callback.vlueChanged(data);
}
} catch (InterruptedException | RemoteException e) {
e.printStackTrace();
}
}
private String data = "default date";
}
And their are two AIDL files:
IAppServiceRemoteBinder.aild
// IAppServiceRemoteBinder.aidl
package com.hqyj.dev.aidltest;
// Declare any non-default types here with import statements
import com.hqyj.dev.aidltest.IRemoteServiceCallback;
interface IAppServiceRemoteBinder {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
void basicTypes(int anInt,
long aLong,
boolean aBoolean, float aFloat,
double aDouble, String aString);
void setData(String data);
void registerCallback(IRemoteServiceCallback cb);
void unregisterCallback(IRemoteServiceCallback cb);
}
IRemoteServiceCallback.aild
// IRemoteServiceCallback.aidl
package com.hqyj.dev.aidltest;
// Declare any non-default types here with import statements
interface IRemoteServiceCallback {
/**
* return from server
*/
void vlueChanged(String value);
}
And in AndroidManifest.xml, this Server decleared as below:
AndroidManifest.xml
<service
android:name="com.hqyj.dev.aidltest.AppService"
android:enabled="true"
android:exported="true"
android:process=":remote">
</service>
And then, the in second module, copies all these aidl files with package name, as below:
And in MainActivity in anotherapp, complete as below:
package com.hqyj.dev.anotherapp;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import com.hqyj.dev.aidltest.IAppServiceRemoteBinder;
import com.hqyj.dev.aidltest.IRemoteServiceCallback;
public class MainActivity extends AppCompatActivity
implements View.OnClickListener, ServiceConnection {
private final String TAG = MainActivity.class.getSimpleName();
private Intent intent;
private IAppServiceRemoteBinder binder;
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_start).setOnClickListener(this);
findViewById(R.id.btn_stop).setOnClickListener(this);
findViewById(R.id.btn_set).setOnClickListener(this);
intent = new Intent();
intent.setComponent(new
ComponentName("com.hqyj.dev.aidltest",
"com.hqyj.dev.aidltest.AppService"));
}
#SuppressLint("DefaultLocale")
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_start:
bindService(intent, this,
Context.BIND_AUTO_CREATE);
break;
case R.id.btn_set:
if (binder != null) {
try {
binder.setData(
String.format("the %d times",
++count));
} catch (RemoteException e) {
e.printStackTrace();
}
}
break;
case R.id.btn_stop:
try {
binder.unregisterCallback(callback);
} catch (RemoteException e) {
e.printStackTrace();
}
unbindService(this);
break;
}
}
#Override
public void onServiceConnected(
ComponentName name, IBinder service) {
binder =
IAppServiceRemoteBinder.Stub.asInterface(service);
Log.d(TAG, "onServiceConnected: " + 1);
try {
binder.registerCallback(callback);
} catch (RemoteException e) {
e.printStackTrace();
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
}
private IRemoteServiceCallback.Stub callback =
new IRemoteServiceCallback.Stub() {
#Override
public void
vlueChanged(String value) throws RemoteException {
Log.e(TAG, "vlueChanged: " + value);
}
};
}
As you see, I called the remote service by using bindService();
It works well, when I push these two apps into an emulator which using Android 7.0 as platform.
But
When I push these app into an real device(using Android 6.0), the flowing mistake happened:
AIDL failed!!
Why??

Auto Refresh Listview When Data in XML changed from server

This is my code that parsing XML from server and display in List view. I want auto refresh to display list view when data is changed from server.
package com.wafik;
import java.io.InputStream;
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.os.Handler;
import android.widget.ListView;
public class vctcs extends Activity {
/** Called when the activity is first created. */
private ListView listView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.listview);
bindDataToListing();
}
public void bindDataToListing() {
try {
SAXParserFactory saxparser = SAXParserFactory.newInstance();
SAXParser parser = saxparser.newSAXParser();
XMLReader xmlReader = parser.getXMLReader();
ParsingClass pc = new ParsingClass();
xmlReader.setContentHandler(pc);
URL url=new URL("my url");
InputStream is=url.openStream(); // Use this InputStream to parse
xmlReader.parse(new InputSource(is));
BindingData bindingData = new BindingData(this, pc.name,
pc.address, pc.qua,pc.qua2);
listView.setAdapter(bindingData);
} catch (Exception e) {
e.getMessage();
}
}
}
Parsing XML
package com.wafik;
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ParsingClass extends DefaultHandler {
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> address = new ArrayList<String>();
ArrayList<String> qua = new ArrayList<String>();
ArrayList<String> qua2 = new ArrayList<String>();
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if (localName.equalsIgnoreCase("time")) {
tempStore = "";
} else if (localName.equalsIgnoreCase("street_name")) {
tempStore = "";
} else if (localName.equalsIgnoreCase("intersection_no")) {
tempStore = "";
} else if (localName.equalsIgnoreCase("traffic_state")) {
tempStore = "";
}else{
tempStore = "";
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
if (localName.equalsIgnoreCase("time")) {
name.add(tempStore);
} else if (localName.equalsIgnoreCase("street_name")) {
address.add(tempStore);
} else if (localName.equalsIgnoreCase("intersection_no")) {
qua.add(tempStore);
}else if (localName.equalsIgnoreCase("traffic_state")) {
qua2.add(tempStore);
}
tempStore = "";
}
private String tempStore = "";
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
tempStore += new String(ch, start, length);
}
}
Binding Data
package com.wafik;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class BindingData extends BaseAdapter {
ArrayList<String> time;
ArrayList<String> street_name;
ArrayList<String> intersection_no;
ArrayList<String> traffic_state;
LayoutInflater inflater;
public BindingData() {
}
public BindingData(Activity act, ArrayList<String> name,
ArrayList<String> add, ArrayList<String> qua,ArrayList<String> qua2) {
this.time = name;
this.street_name = add;
this.intersection_no = qua;
this.traffic_state = qua2;
inflater = (LayoutInflater) act
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return time.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder;
if (convertView == null) {
holder = new Holder();
convertView = inflater.inflate(R.layout.listrow, null);
holder.txttime = (TextView) convertView.findViewById(R.id.name);
holder.txtstreet_name = (TextView) convertView.findViewById(R.id.address);
holder.txtintersection_no = (TextView) convertView.findViewById(R.id.quali);
holder.txttraffic_state = (TextView) convertView.findViewById(R.id.quali2);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
holder.txttime.setText(Html.fromHtml("<b>Time : </b>" + time.get(position)));
holder.txtstreet_name.setText(Html.fromHtml("<b>Street Name : </b>"
+ street_name.get(position)));
holder.txtintersection_no.setText(Html.fromHtml("<b>Intersection No : </b>"
+ intersection_no.get(position)));
holder.txttraffic_state.setText(Html.fromHtml("<b>Traffic State : </b>"
+ traffic_state.get(position)));
return convertView;
}
private class Holder {
TextView txttime, txtstreet_name, txtintersection_no,txttraffic_state;
}
}
First you need an object to hold all these values like time, streername, etc. then pass a list of that object, then make an add item method in your adapter that updates the list with new xml the call notifyDataSetChanged() to update your listview like this:
//Binding Data
public void addItem(YourItem item){
this.yourItemList.add(item);
notifyDataSetChanged();
}
//YourItem
public class YourItem{
private String time;
private String street_name;
private String intersection_no;
private String traffic_state;
public YourItem(String time, String street_name, String intersection_no, String traffic_state) {
this.time = time;
this.street_name = street_name;
this.intersection_no = intersection_no;
this.traffic_state = traffic_state;
}
//Getters and Setters for your object fields
}
you have to notify the list adapter that the data has changed if you want instance change in the list view, so every time the server data is changed you should call ...
bindingData.notifyDataSetChanged();

Facebook RSS Feed in Android app crashing

So I tried to set up an RSS feed for my Android application with the attached code, yet when I run it on the emulator, it crashes and I receive the attached errors in my LogCat. Any ideas for what could be wrong? Thanks in advance!!!
package com.fixed_gear_app;
import java.io.IOException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import javax.xml.parsers.ParserConfigurationException;
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;
public class RSSFeed extends Activity {
/** Called when the activity is first created. */
String rssResult = "";
boolean item = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rssfeed);
TextView rss = (TextView) findViewById(R.id.rss);
try {
URL rssUrl = new URL("https://www.facebook.com/feeds/page.php?format=rss20&id=619608694724497");
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
RSSHandler rssHandler = new RSSHandler();
xmlReader.setContentHandler(rssHandler);
InputSource inputSource = new InputSource(rssUrl.openStream());
xmlReader.parse(inputSource);
} catch (IOException e) {rss.setText(e.getMessage());
} catch (SAXException e) {rss.setText(e.getMessage());
} catch (ParserConfigurationException e) {rss.setText(e.getMessage());
}
rss.setText(rssResult);
}
/**public String removeSpaces(String s) {
StringTokenizer st = new StringTokenizer(s," ",false);
String t="";
while (st.hasMoreElements()) t += st.nextElement();
return t;
}*/
private class RSSHandler extends DefaultHandler {
public void startElement(String uri, String localName, String qName,
Attributes attrs) throws SAXException {
if (localName.equals("item"))
item = true;
if (!localName.equals("item") && item == true)
rssResult = rssResult + localName + ": ";
}
public void endElement(String namespaceURI, String localName,
String qName) throws SAXException {
}
public void characters(char[] ch, int start, int length)
throws SAXException {
String cdata = new String(ch, start, length);
if (item == true)
rssResult = rssResult +(cdata.trim()).replaceAll("\\s+", " ")+"\t";
}
}
}
You are attempting to do network communication on the main Activity thread. Android, by default, disallows this, (as you do not know how long it can take) so you will have to move your networking code to a class extending AsyncTask. Have a read of this, which shows you how to put it on an AsyncTask.

Error connection timeout in android

My app starts.. loads.. and when it is done loading it displays only a blank page. It doesnt crash just display a blank page.
And I noticed at the logcat there is this error: Exception localhost/127.0.0.1:8080 Connection Refused
I am playing my app on another device not in an emulator.
So i am thinking it has an error on the url "localhost:8080/lab/lab1.xml"
OR it has an error on my codes.
So here is the MainActivity.java
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tvResponse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvResponse = (TextView) findViewById(R.id.tvResponse);
new PostAsync().execute();
}
class PostAsync extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
XMLHelper helper;
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(MainActivity.this, "by Es", "Loading", true, false);
}
#Override
protected Void doInBackground(Void... arg0) {
helper = new XMLHelper();
helper.get();
return null;
}
#Override
protected void onPostExecute(Void result) {
StringBuilder builder = new StringBuilder();
for(EventValue event : helper.events) {
builder.append("\nWhat: " + event.getWhat());
builder.append("\nWhen: " + event.getWhen());
builder.append("\nWhere: " + event.getWhere());
builder.append("\n");
}
tvResponse.setText(builder.toString());
pd.dismiss();
}
}
}
Here is the XMLHelper.java
import java.io.InputStream;
import java.net.URL;
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.util.Log;
public class XMLHelper extends DefaultHandler {
/**
* The URL to be parsed
*/
private String URL_MAIN = "http://localhost:8080/lab/lab1.xml";
String TAG = "XMLHelper";
Boolean currTag = false;
String currTagVal = "";
public EventValue event = null;
public ArrayList<EventValue> events = new ArrayList<EventValue>();
public void get() {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser mSaxParser = factory.newSAXParser();
XMLReader mXmlReader = mSaxParser.getXMLReader();
mXmlReader.setContentHandler(this);
InputStream mInputStream = new URL(URL_MAIN).openStream();
mXmlReader.parse(new InputSource(mInputStream));
} catch(Exception e) {
// Exceptions can be handled for different types
// But, this is about XML Parsing not about Exception Handling
Log.e(TAG, "Exception: " + e.getMessage());
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if(currTag) {
currTagVal = currTagVal + new String(ch, start, length);
currTag = false;
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currTag = false;
if(localName.equalsIgnoreCase("what"))
event.setWhat(currTagVal);
else if(localName.equalsIgnoreCase("when"))
event.setWhen(currTagVal);
else if(localName.equalsIgnoreCase("where"))
event.setWhere(currTagVal);
else if(localName.equalsIgnoreCase("event"))
events.add(event);
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
Log.i(TAG, "TAG: " + localName);
currTag = true;
currTagVal = "";
if(localName.equals("event"))
event = new EventValue();
}
}
Here is the EventValue.java
public class EventValue {
String what, when, where;
public String getWhat() {
return what;
}
public void setWhat(String what) {
this.what = what;
}
public String getWhen() {
return when;
}
public void setWhen(String when) {
this.when = when;
}
public String getWhere() {
return where;
}
public void setWhere(String where) {
this.where = where;
}
}
Here is the xml file lab1.xml (localhost:8080/lab/lab1.xml)
<?xml version="1.0" encoding="utf-8"?>
<events>
<event>
<what>Summer</what>
<when>March1</when>
<where>--</where>
</event>
<event>
<what>asdasdas</what>
<when>March 2</when>
<where>asasas</where>
</event>
<event>
<what>asdasdq</what>
<when>asdasdx</when>
<where>asdasdf</where>
</event>
</events>
Please take a look at the codes. Thanks
EDIT-
it works now i am using computer IP adress but now the problem there is this new exception
Exception:Connection Timeout
Your error doesn't have anything to do with XML parsing. You have connection error. You are using localhost, which is the phone itself, of course it returns connection error. You probably meant your machine where you develop.
If you want to refer to the computer which is running the Android simulator, use the IP address 10.0.2.2 instead. You can read more from here.

Categories

Resources