Request the web page one page every 2 seconds Volley Android - Android Studio

I want to make a request to a web page every 2 seconds. I found a tutorial on google about this and I tried to make an example code but unfortunately it doesn't work ....
When I try to make a simple request without loop then it works perfectly but when I try with loop then it already writes error ....
Here is the code I try to run:
public void run1(){
try {
while(true) {
Log.d(TAG, "test");
RequestQueue queue = Volley.newRequestQueue(this);
String url = "xxxx";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@override
public void onResponse(String response) {
Log.d(TAG, "=============response=============");
//check response its is ok
if(response.length() > 0){
textView.setText( response);
}else{
Log.d(TAG, "NU am mesaj de trimis!");
}
}
}, new Response.ErrorListener() {
@override
public void onErrorResponse(VolleyError error) {
textView.setText("IMI PARE RAU CEVA NU A MERS!!");
}
});
queue.add(stringRequest);
Thread.sleep(2000); //1000 milliseconds is one second.
}
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
number = "0770162059";
message = "test";
send = findViewById(R.id.send);
final TextView textView = (TextView) findViewById(R.id.text);
send.setEnabled(false);
if(checkPermission(Manifest.permission.SEND_SMS)){
send.setEnabled(true);
}else{
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS}, SEND_SMS_PERMISSION_REQUEST_CODE);
}
if(checkPermission(Manifest.permission.INTERNET)){
Log.d(TAG, "======Internet permission ready=======");
}else{
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.INTERNET}, INTERNET_PERMISSION_REQUEST_CODE);
}
run1();
}
And the error of what I think it shows in LogCat is:
02-02 11:09:26.763 6563-6563/com.example.send_sm_test D/MainActivity: test 02-02 11:09:26.763 6563-6590/com.example.send_sm_test I/qtaguid: Tagging socket 49 with tag 56062fc900000000(-704237623) for uid -1 failed errno=-2 02-02 11:09:26.763 6563-6590/com.example.send_sm_test I/NetworkManagementSocketTagger: tagSocketFd(49, -704237623, -1) failed with errno-2 02-02 11:09:26.763 6563-6590/com.example.send_sm_test I/qtaguid: Tagging socket 50 with tag 56062fc900000000(-704237623) for uid -1 failed errno=-2 02-02 11:09:26.763 6563-6590/com.example.send_sm_test I/NetworkManagementSocketTagger: tagSocketFd(50, -704237623, -1) failed with errno-2 02-02 11:09:26.793 6563-6567/com.example.send_sm_test D/dalvikvm: GC_CONCURRENT freed 361K, 4% free 18869K/19463K, paused 1ms+1ms 02-02 11:09:26.833 6563-6590/com.example.send_sm_test I/qtaguid: Untagging socket 50 failed errno=-2 02-02 11:09:26.833 6563-6590/com.example.send_sm_test W/NetworkManagementSocketTagger: untagSocket(50) failed with errno -2
UPDATE:
Code:
public void run1(){
try {
while(true) {
Log.d(TAG, "test");
RequestQueue queue = Volley.newRequestQueue(this);
String url = "xxx";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
[user=439709]@override[/user]
public void onResponse(String response) {
Log.d(TAG, "=============response=============");
//check response its is ok
if(response.length() > 0){
textView.setText( response);
}else{
Log.d(TAG, "NU am mesaj de trimis!");
}
}
}, new Response.ErrorListener() {
[user=439709]@override[/user]
public void onErrorResponse(VolleyError error) {
textView.setText("IMI PARE RAU CEVA NU A MERS!!");
}
});
stringRequest.setTag(RequestTAG);
queue.add(stringRequest);
if(queue != null){
queue.cancelAll(RequestTAG);
}
Thread.sleep(9000); //1000 milliseconds is one second.
}
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
I introduced TAG to close each previous connection but it seems that this solved only the errors that were created but did not solve my request to the site. Next, the request submission does not work, but it does not cause any error ...

Related

[Q] connect to bluetooth keyboard from android application problems

I wrote a simple application to connect to a bluetooth mini keyboard but am having trouble with the BluetoothDevice.connect() call.
it gives discovery service failed. I have no problem using the bluetooth pairing and connect from the bluetooth settings menu. The same code works with a bluesnap serial to bluetooth device.
Am I missing something obvious?
I'm on galaxy tab froyo.
The code is:
Code:
package test.com;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.UUID;
//import test.com.connect.ClientConnectThread;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Toast;
import android.bluetooth.*;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class connect extends Activity {
static final int ALERT_DIALOG_ID = 1;
private BtReceiver btReceiver;
private BluetoothAdapter btAdapter;
private final Handler handler = new Handler();
private static final UUID SIMPLE_BT_APP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private ClientConnectThread clientConnectThread;
private BluetoothDataCommThread bluetoothDataCommThread;
private BluetoothDevice remoteDevice;
private BluetoothSocket activeBluetoothSocket;
private final String deviceAddress="98:9A:10:12:03:6E";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btAdapter=BluetoothAdapter.getDefaultAdapter();
if(btAdapter==null)
{
Toast.makeText(getApplicationContext(), "No Bluetooth Available",Toast.LENGTH_LONG ).show();
}else
{
if(!btAdapter.isEnabled())
{
Intent enableBtIntent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//REQUEST_ENABLE_BT is supposed to be 2 so
startActivityForResult(enableBtIntent, 2);
}
// we need a broadcast receiver now
btReceiver = new BtReceiver();
// register for state change broadcast events
IntentFilter stateChangedFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(btReceiver, stateChangedFilter);
// register for discovery events
IntentFilter actionFoundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(btReceiver, actionFoundFilter);
// check current state
int currentState = btAdapter.getState();
if (currentState == BluetoothAdapter.STATE_ON) {
findDevices();
}
}
}
public void findDevicesHandler(View view){
int currentState = btAdapter.getState();
if (currentState == BluetoothAdapter.STATE_ON) {
Toast.makeText(getApplicationContext(), "Finding devices",Toast.LENGTH_LONG ).show();
findDevices();
}
else
{
Toast.makeText(getApplicationContext(), "Adapter is off",Toast.LENGTH_LONG ).show();
}
}
protected void onActivityResult(int request,int result,Intent data)
{
if(result==RESULT_OK)
{
Toast.makeText(getApplicationContext(), "TURNING ON BLUETOOTH",Toast.LENGTH_LONG ).show();
}
}
public class BtReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
setStatus("Broadcast: Got ACTION_STATE_CHANGED");
int currentState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF);
if (currentState == BluetoothAdapter.STATE_ON) {
findDevices();
}
} else if (action.equals(BluetoothDevice.ACTION_FOUND)) {
setStatus("Broadcast: Got ACTION_FOUND");
BluetoothDevice foundDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
setStatus("Device: " + foundDevice.getName() + "@" + foundDevice.getAddress());
remoteDevice=foundDevice;
if(remoteDevice.getAddress().equals(deviceAddress))
{
takeAction();
}
}
}
}
private void setStatus(String string){
Toast.makeText(getApplicationContext(), string,Toast.LENGTH_LONG ).show();
}
private void findDevices() {
Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
for (BluetoothDevice pairedDevice : pairedDevices) {
if (pairedDevice.getAddress().equals(deviceAddress)) {
setStatus("Found device: " + pairedDevice.getName() + "@" + deviceAddress);
remoteDevice = pairedDevice;
}
}
if (remoteDevice == null) {
setStatus("Starting discovery...");
if (btAdapter.startDiscovery()) {
setStatus("Discovery started...");
}
}
else
{
setStatus("Remote Device Address:"+remoteDevice.getAddress());
takeAction();
}
}
private void takeAction()
{
Toast.makeText(getApplicationContext(), "GETTING READY",Toast.LENGTH_LONG).show();
clientConnectThread = new ClientConnectThread(remoteDevice);
clientConnectThread.run();
}
@Override
protected void onDestroy() {
if (clientConnectThread != null) {
clientConnectThread.stopConnecting();
}
if (bluetoothDataCommThread != null) {
bluetoothDataCommThread.disconnect();
}
if (activeBluetoothSocket != null) {
try {
activeBluetoothSocket.close();
} catch (IOException e) {
//Log.e(DEBUG_TAG, "Failed to close socket", e);
Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG ).show();
}
}
btAdapter.cancelDiscovery();
this.unregisterReceiver(btReceiver);
super.onDestroy();
}
public void doStartDataCommThread() {
if (activeBluetoothSocket == null) {
setStatus("Can't start datacomm");
} else {
setStatus("Data comm thread starting");
bluetoothDataCommThread = new BluetoothDataCommThread(activeBluetoothSocket);
bluetoothDataCommThread.start();
}
}
private void setLastUsedRemoteBTDevice(String name) {
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
Editor edit = prefs.edit();
edit.putString("LAST_REMOTE_DEVICE_ADDRESS", name);
edit.commit();
}
// client thread: used to make a synchronous connect call to a device
private class ClientConnectThread extends Thread {
private final BluetoothDevice remoteDevice;
private BluetoothSocket clientSocket;
public ClientConnectThread(BluetoothDevice remoteDevice) {
this.remoteDevice = remoteDevice;
clientSocket = null;
}
public void run() {
boolean success = false;
//success=true;
try {
btAdapter.cancelDiscovery();
//Method m = remoteDevice.getClass().getMethod("createRfcommSocket",new Class[] { int.class});
//Method m = remoteDevice.getClass().getMethod("createScoSocket",new Class[] { int.class});
//Method m = remoteDevice.getClass().getMethod("createInsecureRfcommSocket",new Class[] { int.class});
//clientSocket=(BluetoothSocket)m.invoke(remoteDevice,0);
clientSocket = remoteDevice.createRfcommSocketToServiceRecord(SIMPLE_BT_APP_UUID);
clientSocket.connect();
success = true;
} catch (IOException e) {
Toast.makeText(getApplicationContext(),"CONNECT:"+ e.toString(),Toast.LENGTH_LONG ).show();
try {
clientSocket.close();
} catch (IOException e1) {
Toast.makeText(getApplicationContext(),"CLOSE:"+ e.toString(),Toast.LENGTH_LONG ).show();
}
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(),"CONNECT:"+ e.toString(),Toast.LENGTH_LONG ).show();
} catch (NoSuchMethodException e) {
Toast.makeText(getApplicationContext(),"CONNECT:"+ e.toString(),Toast.LENGTH_LONG ).show();
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(),"CONNECT:"+ e.toString(),Toast.LENGTH_LONG ).show();
} /*catch (IllegalAccessException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(),"CONNECT:"+ e.toString(),Toast.LENGTH_LONG ).show();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(),"CONNECT:"+ e.toString(),Toast.LENGTH_LONG ).show();
}*/
final String status;
if (success) {
status = "Connected to remote device";
activeBluetoothSocket = clientSocket;
// we don't need to keep listening
//serverListenThread.stopListening();
} else {
status = "Failed to connect to remote device";
activeBluetoothSocket = null;
}
handler.post(new Runnable() {
public void run() {
setStatus(status);
setLastUsedRemoteBTDevice(remoteDevice.getAddress());
doStartDataCommThread();
}
});
}
public void stopConnecting() {
try {
clientSocket.close();
} catch (Exception e) {
//Log.e(DEBUG_TAG, "Failed to stop connecting", e);
Toast.makeText(getApplicationContext(), "CLOSE2:"+e.toString(),Toast.LENGTH_LONG ).show();
}
}
}
private class BluetoothDataCommThread extends Thread {
private final BluetoothSocket dataSocket;
private final InputStream inData;
public BluetoothDataCommThread(BluetoothSocket dataSocket) {
this.dataSocket = dataSocket;
InputStream inData = null;
try {
inData = dataSocket.getInputStream();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG ).show();
}
this.inData = inData;
}
public void run() {
byte[] readBuffer = new byte[64];
int readSize = 0;
try {
while (true) {
readSize=inData.read(readBuffer, 0, 24);
final String inStr = new String(readBuffer, 0, readSize);
handler.post(new Runnable() {
public void run() {
doHandleReceivedCommand(inStr);
}
});
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG ).show();
}
}
public void disconnect() {
try {
dataSocket.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG ).show();
}
}
}
public void doHandleReceivedCommand(String rawCommand) {
String command = rawCommand.trim();
setStatus("Got: "+ command);
}
}
www.code.google.com
so it is right that not all bluetooth keyboard might work properly with any kind of android handheld....as yesterday i just read it in one of bluetooth keyboard

Problem with context

Hi, I have code:
Code:
Class<?> pm =
XposedHelpers.findClass(packageManagerService, null);
hookAllConstructors(pm, packageManagerServiceHook);
packageManagerServiceHook = new XC_MethodHook() {
@Override
protected void afterHookedMethod(final MethodHookParam param) throws Throwable {
Context context = (Context) XposedHelpers.getObjectField(
param.thisObject, "mContext");
if (context == null && param.args.length != 0) {
context = (Context) param.args[0];
}
XposedBridge.log(context==null? "null" : "not null");
if (context != null) {
mContext = context;
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ACTION_ENABLE_SIGNATURE_CHECK);
intentFilter.addAction(ACTION_DISABLE_SIGNATURE_CHECK);
mContext.registerReceiver(mBroadcastReceiver, intentFilter);
}
}
};
I get "not null" but then, I get NPE on line mContext.registerReceiver(mBroadcastReceiver, intentFilter); Any solution?
I'd check if mBroadcastReceiver is null, I don't see you assigning that. Otherwise post the full log.

Hook parcel readString, IBinder transact

Hello. I have this code.
Code:
public String getId() throws RemoteException {
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
String id;
try {
data.writeInterfaceToken("com.google.android.gms.ads.identifier.internal.IAdvertisingIdService");
binder.transact(1, data, reply, 0);
reply.readException();
id = reply.readString();
} finally {
reply.recycle();
data.recycle();
}
return id;
}
How i can hook " id = reply.readString();" when a don't know method name like "getId()". Thanks.
PS: Sorry for my bad English.
Now i can hook "transact" method like this:
Code:
XposedHelpers.findAndHookMethod("android.os.BinderProxy", loadPackageParam.classLoader, "transact", int.class, Parcel.class, Parcel.class, int.class, new XC_MethodHook() {
protected void afterHookedMethod(XC_MethodHook.MethodHookParam param) throws Throwable {
super.afterHookedMethod(param);
IBinder binder = (IBinder) param.thisObject;
String interfaceBinder = binder.getInterfaceDescriptor();
if (interfaceBinder.equals("com.google.android.gms.ads.identifier.internal.IAdvertisingIdService")) {
// change result for readString
}
}
});
But i cant override "readString" result for Parcel (args[2]) object. How can i do this? Thanks.

Adding a Spinner and posting the data to database [volley]

public class MainActivity extends Activity {
EditText name, phonenumber, address;
Button insert;
RequestQueue requestQueue;
String insertUrl = "localhosti/insertCustomer.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* CHECK INTERNET CONNECTION */
boolean mobileNwInfo = false;
ConnectivityManager conxMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
try { mobileNwInfo = conxMgr.getActiveNetworkInfo().isConnected(); }
catch (NullPointerException e) { mobileNwInfo = false; }
if ( mobileNwInfo == false ) {
Toast.makeText(this, "No Network, please check your connection. ", Toast.LENGTH_LONG).show();
}
/* CHECK INTERNET CONNECTION PROCEDURE DONE */
name = (EditText) findViewById(R.id.editText);
phonenumber= (EditText) findViewById(R.id.editText2);
address = (EditText) findViewById(R.id.editText3);
insert = (Button) findViewById(R.id.insert);
requestQueue = Volley.newRequestQueue(getApplicationContext());
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final ProgressDialog pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Booking Service ....");
pd.show();
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
pd.hide();
System.out.println(response.toString());
name.setText("");
phonenumber.setText("");
address.setText("");
Toast.makeText(getApplicationContext(), "Service successfully booked !!", Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
pd.hide();
Toast.makeText(getApplicationContext(), "Error: Please try again later.", Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("name", name.getText().toString());
parameters.put("phonenumber", phonenumber.getText().toString());
parameters.put("address", address.getText().toString());
return parameters;
}
};
requestQueue.add(request);
}
});
}
}
Click to expand...
Click to collapse
how can i fetch the data from a spinner and post it to my db along with the current data ?

Xml Parsing issue

Hi Folks.
I am new to android studio and object oriented programming in general so apologies if this is obvious but I cannot get my head round it. I have a small xml web server and I can connect to it and send data to it and I can also read it back and view it in the monitor. I want to do xml parsing on it but cannot get it to work.
Below is the xml server being displayed in the android monitor and is from the line "System.out.println(output);"
The response is saved from a string but I think I need it in a different format to do a pull parser on it. The program basically prints this string and then crashes. What is the best way to parse my data? Any help would be really appreciated.
<TITLE>GET test page</TITLE>
05-16 20:19:50.499 13394-14092/com.example.mark.gps_to_server I/System.out: </HEAD>
05-16 20:19:50.499 13394-14092/com.example.mark.gps_to_server I/System.out: <BODY>
05-16 20:19:50.499 13394-14092/com.example.mark.gps_to_server I/System.out: <H1>LED Control</H1>
05-16 20:19:50.499 13394-14092/com.example.mark.gps_to_server I/System.out: <a href="/?nnn" >ON</a>
05-16 20:19:50.499 13394-14092/com.example.mark.gps_to_server I/System.out: <a href="/?fff" >OFF</a>
05-16 20:19:50.499 13394-14092/com.example.mark.gps_to_server I/System.out: <IFRAME name=inlineframe style="display:none" >
05-16 20:19:50.519 13394-14092/com.example.mark.gps_to_server I/System.out: </IFRAME>
05-16 20:19:50.519 13394-14092/com.example.mark.gps_to_server I/System.out: <H1>Status On Now</H1>
05-16 20:19:50.529 13394-14092/com.example.mark.gps_to_server I/System.out: <H2> test</H2>
Click to expand...
Click to collapse
The code:
Code:
public class HTTPRequestTask extends AsyncTask<String , Void, String > {
@Override
protected String doInBackground(String... args) {
String IP = args[0];
System.out.println(IP);
try {
URL url = new URL(IP);
XmlPullParser recievedData = XmlPullParserFactory.newInstance().newPullParser();
recievedData.setInput(url.openStream(),null);
System.setProperty("http.keepAlive", "false");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
XmlPullParser parser = Xml.newPullParser();
parser.setInput(new StringReader(output));
System.out.println("doc");
System.out.println(parser);
System.out.println("Disconnecting\n");
conn.disconnect();
//System.out.println(recievedData);
processRecievedData(recievedData);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
return null;
}
private int processRecievedData(XmlPullParser xmlData) {
int recordsFound = 0; // Find values in the XML records
int eventType = -1;
String appId = ""; // Attributes
String itemId = "";
String timeStamp = ""; String data = ""; // Text int eventType = -1;
while (eventType != XmlResourceParser.END_DOCUMENT) {
String tagName = xmlData.getName();
switch (eventType) {
case XmlResourceParser.START_TAG: // Start of a record, so pull values encoded as attributes.
if (tagName.equals("Version")) {
System.out.println("yes");
appId = xmlData.getAttributeValue(null, "Model");
itemId = xmlData.getAttributeValue(null, "vendor_id");
timeStamp = xmlData.getAttributeValue(null, "timestamp");
data = "";
}
System.out.println("no");
break;
// Grab data text (very simple processing)
// NOTE: This could be full XML data to process.
case XmlResourceParser.TEXT:
data += xmlData.getText();
break;
case XmlPullParser.END_TAG:
if (tagName.equals("record")) {
recordsFound++;
//publishProgress(appId, itemId, data, timeStamp);
}
break;
}
//eventType = xmlData.next();
}
// Handle no data available: Publish an empty event.
if (recordsFound == 0) { publishProgress();
}
Log.i(TAG, "Finished processing "+recordsFound+" records.");
return recordsFound;
}
protected void onProgressUpdate(String... values) {
if (values.length == 0) {
Log.i(TAG, "No data downloaded");
}
if (values.length == 4) {
String appId = values[0];
String itemId = values[1];
String data = values[2];
String timeStamp = values[3];
// Log it
Log.i(TAG, "AppID: " + appId + ", Timestamp: " + timeStamp);
Log.i(TAG, " ItemID: " + itemId + ", Data: " + data);
// Pass it to the application handleNewRecord(itemId, data); }
//super.onProgressUpdate(values);
}
}
Thanks.
Probably you should use 3rd party library to parse XML from your web server. This will significantly reduce the code and improve performance. Of course, before parsing xml, you should download the data.
Personal prefference
I prefer the document (DOM) parsing. I think DOM parsing is more object oriented.
Whats the error in the log?
this works for me:
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
} catch (IOException e) {
e.printStackTrace();
}
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
String sb_string = sb.toString();
Document return_doc = null;
if(sb_string.equals(0))
{
}
else {
DocumentBuilder db = null;
try {
db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(sb_string));
try {
return_doc = db.parse(is);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Please note! It took me a while before i could get attributes and knew the difference between nodes and elements.
this line of thought will require you to gain more information how to work with documents which might get frustration but in the end it might be beneficial.

Categories

Resources