Trying to parse a HTML page using JSoup parser in Android? - android

So far I've tried this example which I just took from this site but it is not working in my case and I don't know why?! Is there anyone who can tell me how can I solve this problem, here is the code: this code shows me NullExceptionPointer
And i tried to print the doc.select() it shows me error :s null excetptionpointer.
URL url = null;
try {
url = new URL("http://www.nseindia.com/content/equities/niftysparks.htm");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Document doc = null;
try {
doc = Jsoup.parse(url, 3000);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Element table = doc.select("table[class=niftyd]").first();
Iterator<Element> ite = table.select("td[width=65]").iterator();
ite.next(); // first one is image, skip it
System.out.println("Value 1: " + ite.next().text());
System.out.println("Value 2: " + ite.next().text());
System.out.println("Value 3: " + ite.next().text());
System.out.println("Value 4: " + ite.next().text());
Any help I would really appreciate it, I'm fighting for the whole day and I cant solve it! :s

The problem is doc.select("table[class=niftyd]") returns null. When your call first on it you get the null pointer exception. You're trying to call a method on an object that is actually null. You need make sure what doc.select() returns isn't null.

Related

Android Get XML from URL as string

I am very new to Android Development and Java,
I have C# experience
anyway
I am trying to get XML from a URL
I tried every possible thing but non is working.
Always get crash or no result.
I just want a simple XML result, I found some JSON and PHP code, that i do not want to connect to MySQL.
is there any simple function to retrieve the XML as string from a URL
this is one of my traials
`
lbl1 = (TextView) findViewById(R.id.lbl1);
try {
InputStream is = new URL("http://api.androidhive.info/pizza/?format=xml").openConnection().getInputStream();
String strxml = is.toString();
lbl1.setText(strxml);
}
catch (MalformedURLException e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}
catch (IOException e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}`
any help will be much appreciated. Thanks
How would you do it in C#?
URL.toString() and (in c#) Request.Url.ToString() are alike. Both behave the same way: creating a string of the URL.
(Like in C#) you would need a HTTP client: http://android-developers.blogspot.de/2011/09/androids-http-clients.html

Eclipse - Functions issue [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm trying to get text from server and then check it a to know what actions to take with the text adopted. The problem is that when I try to check if the received text for example is "Exited" the query always return the value "false" when the received text is really "Exited".
Here is the code :
class Get_Message_From_Server implements Runnable
{
public void run()
{
InputStream iStream = null;
try
{
iStream = Duplex_Socket_Acceptor.getInputStream();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//Create byte array of size image
byte[] Reading_Buffer = null;
try
{
Reading_Buffer = new byte [Duplex_Socket_Acceptor.getReceiveBufferSize()];
//New_Buffer = new byte [100];
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] Byte_Char_1 = new byte[1];
int Byte_String_Lenght = 0;
//read size
try
{
iStream.read(Reading_Buffer);
String Reading_Buffer_Stream_Lenghtor = new String(Reading_Buffer);
//System.out.println("full : " + Reading_Buffer_Stream_Lenghtor);
Byte_String_Lenght = Reading_Buffer_Stream_Lenghtor.indexOf(new String(Byte_Char_1));
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//Convert to String
Meassage = new String(Reading_Buffer);
Meassage = Meassage.substring(0, Byte_String_Lenght);//The text that received
Message_Getted = 1;
}
}
The query :
if(Message_1 != "Exited")//the message query
{
System.out.println("Continued 253");
continue;
}
Its always return the value - false
its important to know that the message is in Utf - 8 encoding
so how i can to fix the issue ?
If you compare strings by using oparators, Java will not look at the contents of the string but at the reference in memory. To compare String content in Java, you should use the following:
String Message_1; // Hopefully has a value sent by the server
if(Message_1.equals("Exited")) {
// Do stuff when exited
} else {
// Do stuff when not exited
}
String is a variable - and variables should start with lower Case letter - Please read Java Code conventions. Also to check if your message contains string you thing it should just do System.out.println(Message_1); and if the message contains what you expect you compare string doing
if(Message_1.equals("Exited")) {
System.out.println("Yes they are equal");
} else {
System.out.println("No they are not");
}
If this will print "No they are not" that simply means that your variable Message_1 is not what you think it is.. As simple as that. There is no such a thing as .equals method does not work. Its your variable that doesn't ;)

Type mismatch: cannot convert from Object to JSONObject

I'm relatively new to Android development and am writing my first REST-based app. I've opted to use the Android Asynchronous HTTP Client to make things a bit easier. I'm currently just running through the main "Recommended Usage" section on that link, essentially just creating a basic static HTTP client. I'm following the code given, but changing it around to refer to a different API. Here's the code in question:
public void getFactualResults() throws JSONException {
FactualRestClient.get("q=Coffee,Los Angeles", null, new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONArray venues) {
// Pull out the first restaurant from the returned search results
JSONObject firstVenue = venues.get(0);
String venueName = firstVenue.getString("name");
// Do something with the response
System.out.println(venueName);
}
});
}
The String venueName = firstVenue.getString("name"); line is currently throwing an error in Eclipse: "Type mismatch: cannot convert from Object to JSONObject". Why is this error occurring? I searched other threads which led me to try using getJSONObject(0) instead of get(0) but that led to further errors and Eclipse suggesting using try/catch. I haven't changed any of the code on the tutorial, save for the variable names and URL. Any thoughts/tips/advice?
Thanks so much.
EDIT:
Here is the onSuccess method, modified to include the try/catch blocks suggested. Eclipse now shows the "local variable may not have been initialized" for firstVenue here: venueName = firstVenue.getString("name"); and for venueName here: System.out.println(venueName); Even if I initialize String venueName; directly after JSONObject firstVenue; I still get the same error. Any help in resolving these would be greatly appreciated!
public void onSuccess(JSONArray venues) {
// Pull out the first restaurant from the returned search results
JSONObject firstVenue;
try {
firstVenue = venues.getJSONObject(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String venueName;
try {
venueName = firstVenue.getString("name");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Do something with the response
System.out.println(venueName);
}
You can try to convert object you are getting from querying to String and then use
final JSONObject jsonObject = new JSONObject(stringresult);
I was getting same error earlier, it worked for me.
Yes, you should be using getJSONObject to ensure that the value you obtain is a JSON object. And yes, you should catch the possible JSONException which is thrown if that index in the array doesn't exist, or does not contain an object.
It'll look something like this:
JSONObject firstVenue;
try {
firstVenue = venues.get(0);
} catch (JSONException e) {
// error handling
}
convert obj to json Object:
Object obj = JSONValue.parse(inputParam);
JSONObject jsonObject = (JSONObject) obj;
The solution provided by Shail Adi only worked for me by setting the initial values of firstVenue and venueName to null. Here's my code:
JSONObject firstVenue = null;
try {
firstVenue = (JSONObject)venues.get(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String venueName = null;
try {
venueName = firstVenue.getString("name");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Do something with the response
System.out.println(venueName);

Data being lost between Android device and python server using TCP

I'm somewhat new to network programming and am having some trouble. I am creating a JSON object on an Android device, connecting to a python server via TCP, and sending the JSON string. The connection gets accepted, but I keep losing the end of the string, so
json.loads(json_string)
is failing.
Here is the relevant Android code:
private class Worker implements Runnable
{
#Override
public void run()
{
//create the network socket
try
{
socket = new Socket(address, 4242);
Log.i(TAG, "timeout: " + socket.getSoTimeout());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
packets = new ArrayList<JSONObject>();
for (jobs.moveToFirst(); jobs.isAfterLast() == false; jobs.moveToNext())
{
String jobName = jobs.getString(jobs.getColumnIndex(JobMetaData.JobTableMetaData.JOB));
Uri.Builder updated = new Uri.Builder();
updated.scheme("content");
updated.authority(JobMetaData.AUTHORITY);
updated.appendPath(jobName);
updated.appendPath("member");
updated.appendPath(JobMetaData.MemberTableMetaData.CHANGED);
updated.appendPath("true");
Cursor changed = getContentResolver().query(updated.build(), null, null, null, null);
Log.d(TAG, "number of members " + changed.getCount());
//create a JSON object out of the editable properties
for (changed.moveToFirst(); changed.isAfterLast() == false; changed.moveToNext())
{
JSONObject json = new JSONObject();
for (String att : changed.getColumnNames())
{
if (ListMetaData.validAtts.contains(att))
{
try
{
json.put(att, changed.getString(changed.getColumnIndex(att)));
}
catch (JSONException e)
{
// TODO Auto-generated catch block
Log.d(TAG, "JSON exception in DatagramService");
e.printStackTrace();
}
}
}
//include the GUID and job name
//for identification
try
{
json.put(JobMetaData.MemberTableMetaData.GUID,
changed.getString(changed.getColumnIndex(JobMetaData.MemberTableMetaData.GUID)));
json.put(JobMetaData.JobTableMetaData.JOB, jobName);
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
packets.add(json);
}
changed.close();
}
Log.d(TAG, "entering send loop");
try
{
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.flush();
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
for (JSONObject packet : packets)
{
Log.d(TAG, "supposedly sending");
try
{
//now write the data
Log.d(TAG, "packet string: " + packet.toString());
out.write(packet.toString());
out.flush();
}
catch (IOException e)
{
}
}
try
{
out.write("Done");
out.flush();
out.close();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
stopSelf();
}
And the test server that I am using (written in python):
#!/usr/bin/env python
import SocketServer
import json
class MemberUpdateHandler(SocketServer.BaseRequestHandler):
def setup(self):
print self.client_address, "connected"
def handle(self):
while True:
self.JSONString = self.request.recv(8192).strip()
if self.JSONString == "Done":
return
self.handleJSON()
self.update()
def handleJSON(self):
JSONMember = json.loads(self.JSONString)
print "GUID:", JSONMember['ManufacturingGUID']
print "Weight:", JSONMember['Weight']
def update(self):
print "do something here"
if __name__ == "__main__":
ADDRESS = ''
PORT = 4242
HOST = (ADDRESS, PORT)
s = SocketServer.ThreadingTCPServer(HOST, MemberUpdateHandler)
s.serve_forever()
Here is the string that is being sent (it is long):
{"DetailCheckedBy":"","SketchRight":"","DetailLength":"142.75","DetailedDate":"**NOT SET**","EngineerVerifiedBothConns":"False","HoldStatus":"Not held","RevisionLevel":"No Revision","MemberNumber":"28","RequestVerifySectionSize":"False","TieForcesRight":"False","InputBy":"","IFCFinishDate_4":"**NOT SET**","IFCFinishDate_5":"**NOT SET**","Weight":"438.408","IFCTaskUID_1":"","IFCFinishDate_1":"**NOT SET**","ErectorOrder":"","IFCFinishDate_2":"**NOT SET**","IFCFinishDate_3":"**NOT SET**","IFCTaskUID_4":"","IFCTaskUID_5":"","IFCTaskUID_2":"","SketchLeft":"","IFCTaskUID_3":"","ErectorSequences":"","ReasonRejected":"","MemberCategory":"","EngineerVerifiedLeftConn":"False","BarcodeId":"","ManufacturingGUID":"42bbf9cc-52da-4712-a5fc-e37c5a544c14","aess":"False","FabricationComplete":"**NOT SET**","UserComment2":"","UserComment3":"","LoadNumber":"","UserComment1":"","ErectionBolted":"**NOT SET**","RequestVerifyLength":"False","RequestVerifyGrade":"False","Painted":"False","HeatCertNumber":"","Route1Description":"","IsExisting":"No","ReceivedFromApproval":"**NOT SET**","BackCheckedBy":"","BatchNumber":"","CostCodeReference":"","PONumber":"","Piecemark":"B_25","ReleasedForFabrication":"**NOT SET**","MemberDescription":"BEAM","EngineerVerifiedMemberReady":"False","IFCTaskName_2":"","IFCTaskName_1":"","IFCTaskName_4":"","RequestVerifyMemberPosition":"False","IFCTaskName_3":"","Erected":"**NOT SET**","RevisionCheckedBy_3":"","IFCTaskName_5":"","RevisionCheckedBy_2":"","RevisionCheckedBy_1":"","EngineerVerifiedLeftComments":"","RequestVerifyLeftConnMaterial":"False","RequestEngineerVerify":"False","RevisionCheckedDate_3":"**NOT SET**","RevisionCheckedDate_2":"**NOT SET**","RevisionCheckedDate_1":"**NOT SET**","EngineerVerifiedLength":"False","BackCheckedDate":"**NOT SET**","SubmittedForApproval":"**NOT SET**","EngineerVerifiedSpecial":"False","CostCodeDescription":"","IFCStartDate_5":"**NOT SET**","TieForcesLeft":"False","Fireproofed":"False","ErectorAvailable":"False","RequestVerifyRightConnMaterial":"False","DetailCheckedDate":"**NOT SET**","ErectorNonSteelSupported":"False","BeamPent":"False","StockStatus":"","Sequence":"1","RequestVerifyLeftLoad":"False","DetailFinalCheckDate":"**NOT SET**","ErectorMemberPlaced":"**NOT SET**","InstanceStatus":"","EngineerVerifiedRightConn":"False","DateReceived":"**NOT SET**","MemberType":"Beam","ModelCheckDate":"**NOT SET**","ReasonForHold":"","EngineerVerifiedRightComments":"","ReceivedOnJobSite":"**NOT SET**","RequestVerifyRightLoad":"False","CostCodePrice":"0.0","NestStatus":"","DateDue":"**NOT SET**","ShopSequence":"","EngineerVerifiedSectionSize":"False","ActualLength":"144","InputDate":"**NOT SET**","ErectorCity":"Unknown","EngineerVerifiedSpecial_comments":"","Route4Description":"","EngineerVerifiedGrade":"False","RightLocation":"0.0xx144.0xx156.0xx","IFCFinishTime_2":"","IFCFinishTime_1":"","IFCFinishTime_4":"","Route3Description":"","IFCFinishTime_3":"","LoadStatus":"","ErectorLongitude":"","DateModelCompleted":"61299957600000","Grade":"##SEKRIT KODE!!##","IFCFinishTime_5":"","Route2Description":"","RequestVerifyCamber":"False","ProjectedFabricationComplete":"**NOT SET**","DetailedBy":"","DetailFinalCheckBy":"","Description":"W8x35","ProjectedShippedDate":"**NOT SET**","NestName":"","IFCStartDate_2":"**NOT SET**","IFCStartTime_1":"","IFCStartDate_1":"**NOT SET**","IFCStartDate_4":"**NOT SET**","IFCStartDate_3":"**NOT SET**","IFCStartTime_5":"","IFCStartTime_4":"","IFCStartTime_3":"","DateHeld":"**NOT SET**","IFCStartTime_2":"","LeftLocation":"0.0xx0.0xx156.0xx","Job":"Mobile_x_x_x_x_Demo_x_x_x_x_IN_x_x_x_x_2011","SpecialCutWeld":"False","RejectedBy":"","ErectionWelded":"**NOT SET**","RequestVerifyRightConnConfig":"False","Vendor":"","PackageNumber":"","RejectedByErector":"**NOT SET**","ModelCheckedBy":"","ApprovalStatus":"Not reviewed","RequestVerifyLeftConnConfig":"False","ErectorLatitude":"","LotName":"","ActualShipDate":"**NOT SET**","NestId":""}
This is the error I get from the python server:
ValueError: Unterminated string starting at: line 1 column 1435 (char 1435)
which means that the string has been truncated to:
{"DetailCheckedBy":"","SketchRight":"","DetailLength":"142.75","DetailedDate":"**NOT SET**","EngineerVerifiedBothConns":"False","HoldStatus":"Not held","RevisionLevel":"No Revision","MemberNumber":"28","RequestVerifySectionSize":"False","TieForcesRight":"False","InputBy":"","IFCFinishDate_4":"**NOT SET**","IFCFinishDate_5":"**NOT SET**","Weight":"438.408","IFCTaskUID_1":"","IFCFinishDate_1":"**NOT SET**","ErectorOrder":"","IFCFinishDate_2":"**NOT SET**","IFCFinishDate_3":"**NOT SET**","IFCTaskUID_4":"","IFCTaskUID_5":"","IFCTaskUID_2":"","SketchLeft":"","IFCTaskUID_3":"","ErectorSequences":"","ReasonRejected":"","MemberCategory":"","EngineerVerifiedLeftConn":"False","BarcodeId":"","ManufacturingGUID":"42bbf9cc-52da-4712-a5fc-e37c5a544c14","aess":"False","FabricationComplete":"**NOT SET**","UserComment2":"","UserComment3":"","LoadNumber":"","UserComment1":"","ErectionBolted":"**NOT SET**","RequestVerifyLength":"False","RequestVerifyGrade":"False","Painted":"False","HeatCertNumber":"","Route1Description":"","IsExisting":"No","ReceivedFromApproval":"**NOT SET**","BackCheckedBy":"","BatchNumber":"","CostCodeReference":"","PONumber":"","Piecemark":"B_25","ReleasedForFabrication":"**NOT SET**","MemberDescription":"BEAM","EngineerVerifiedMemberReady":"False","IFCTaskName_2":"","IFCTaskName_1":"","IFCTaskName_4":"","RequestVerifyMemberPosition":"False","IFCTaskName_3":"","Erected":"**NOT SET**","RevisionCheckedBy_3":"","IFCTaskName_
Any help would be greatly appreciated. Thanks in advance.
UPDATE:
I have updated the code to reflect my tinkering. The string received by the server is now
{"DetailCheckedBy":"","SketchRight":"","DetailLength":"142.75","DetailedDate":"**NOT SET**","EngineerVerifiedBothConns":"False","HoldStatus":"Not held","RevisionLevel":"No Revision","MemberNumber":"28","RequestVerifySectionSize":"False","TieForcesRight":"False","InputBy":"","IFCFinishDate_4":"**NOT SET**","IFCFinishDate_5":"**NOT SET**","Weight":"438.408","IFCTaskUID_1":"","IFCFinishDate_1":"**NOT SET**","ErectorOrder":"","IFCFinishDate_2":"**NOT SET**","IFCFinishDate_3":"**NOT SET**","IFCTaskUID_4":"","IFCTaskUID_5":"","IFCTaskUID_2":"","SketchLeft":"","IFCTaskUID_3":"","ErectorSequences":"","ReasonRejected":"","MemberCategory":"","EngineerVerifiedLeftConn":"False","BarcodeId":"","ManufacturingGUID":"42bbf9cc-52da-4712-a5fc-e37c5a544c14","aess":"False","FabricationComplete":"**NOT SET**","UserComment2":"","UserComment3":"","LoadNumber":"","UserComment1":"","ErectionBolted":"**NOT SET**","RequestVerifyLength":"False","RequestVerifyGrade":"False","Painted":"False","HeatCertNumber":"","Route1Description":"","IsExisting":"No","ReceivedFromApproval":"**NOT SET**","BackCheckedBy":"","BatchNumber":"","CostCodeReference":"","PONumber":"","Piecemark":"B_25","ReleasedForFabrication":"**NOT SET**","MemberDescription":"BEAM","EngineerVerifiedMemberReady":"False","IFCTaskName_2":"","IFCTaskName_1":"","IFCTaskName_4":"","RequestVerifyMemberPosition":"False","IFCTaskName_3":"","Erected":"**NOT SET**","RevisionCheckedBy_3":"","IFCTaskName_5":"","RevisionCheckedBy_2":"","RevisionCheckedBy_1":"","EngineerVerifiedLeftComments":"","RequestVerifyLeftConnMaterial":"False","RequestEngineerVerify":"False","RevisionCheckedDate_3":"**NOT SET**","RevisionCheckedDate_2":"**NOT SET**","RevisionCheckedDate_1":"**NOT SET**","EngineerVerifiedLength":"False","BackCheckedDate":"**NOT SET**","SubmittedForApproval":"**NOT SET**","EngineerVerifiedSpecial":"False","CostCodeDescription":"","IFCStartDate_5":"**NOT SET**","TieForcesLeft":"False","Fireproofed":"False","ErectorAvailable":"False","RequestVerifyRightConnMaterial":"False","DetailCheckedDate":"**NOT SET**","ErectorNonSteelSupported":"False","BeamPent":"False","StockStatus":"","Sequence":"1","RequestVerifyLeftLoad":"False","DetailFinalCheckDate":"**NOT SET**","ErectorMemberPlaced":"**NOT SET**","InstanceStatus":"","EngineerVerifiedRightConn":"False","DateReceived":"**NOT SET**","MemberType":"Beam","ModelCheckDate":"**NOT SET**","ReasonForHold":"","EngineerVerifiedRightComments":"","ReceivedOnJobSite":"**NOT SET**","RequestVerifyRightLoad":"False","CostCodePrice":"0.0","NestStatus":"","DateDue":"**NOT SET**","ShopSequence":"","EngineerVerifiedSectionSize":"False","ActualLength":"144","InputDate":"**NOT SET**","ErectorCity":"Unknown","EngineerVerifiedSpecial_comments":"","Route4Description":"","EngineerVerifiedGrade":"False","RightLocation":"0.0xx144.0xx156.0xx","IFCFinishTime_2":"","IFCFinishTime_1":"","IFCFinishTime_4":"","Route3Description":"","IFCFinishTime_3":"","LoadStatus":"","ErectorLongitude":"","DateModelCompleted":"61299957600000","Grade":"##SEKRIT KODE!!##","IFCFinishTime_5":"","Route2Description":"","RequestVerifyCamber":"False","ProjectedFabricationComplete":"**NOT SET**","DetailedBy":"","DetailFinalCheckBy":"","Description":"W8x35","ProjectedShippedDate":"**NOT SET**","NestName":"","IFCStartDate_2":"**NOT SET**","IFCStartTime_1":"","IFCStartDate_1":"**NOT SET**","IFCStartDate_4":"**NOT SET**","IFCStartDate_3":"**NOT SET**","IFCStartTime_5":"","IFCStartTime_4":"","IFCStartTime_3":"","DateHeld":"**NOT SET**","IFCStartTime_2":"","LeftLocation":"0.0xx0.0xx156.0xx","Job":"Mobile_x_x_x_x_Demo_x_x_x_x_IN_x_x_x_x_2011","SpecialCutWeld":"False","RejectedBy":"","ErectionWelded":"**NOT SET**","RequestVerifyRightConnConfig":"False","Vendor":"","PackageNumber":"","RejectedByErector":"**NOT SET**","ModelCheckedBy":"","ApprovalStatus":"Not reviewed","RequestVerifyLeftConnConfig":"False","ErectorLatitude":"","LotName":"","ActualShipDate":"**NOT SET**","NestId":""}Done
followed by a mess of whitespace. Enough that gedit has trouble loading it all. One step forward two steps back. :/
sizeof(int) may not be the same on both devices. So you probably should hardcode something if you want to pass a binary integer.
If you evaluate int('\001\002\003\004\005\006\007\010'), you're unlikely to get what you want, and I believe that's close to what you're doing in your Python code. For one thing, the endianness of the two devices might be different, and for another, int() wants to evaluate ASCII or some other encoding, not raw endian-dependent integers.
On the python side, you might find this useful:
http://stromberg.dnsalias.org/~strombrg/bufsock.html
I'm not sure about the out.write() you're using, but at the lower level of send(), there's no guarantee that your entire buffer will be written in a single send() - it's allowed to stop early and just return how much was sent. Hopefully, java protects you from that detail the way bufsock does for python.
Why are you "assuming" that the string has been truncated? print it and see what it actually is.
Also, the string that is being sent (as you posted it) is not enclosed in {}, which means it is not proper JSON... I tried to copy/paste it in the interpreter, this raises a ValueError:
ValueError: Extra data: line 1 column 17 - line 1 column 3952 (char 17 - 3952)
I enclosed it in {} and it worked. You should try to see what the string you are receiving actually is on the python side, and then you can really see what's happening. I assume also, that since you are seeing the "Done" sent, then the content should have been sent completely.

Android: Need help, trying to parse a HTML page using JSoup parser

Here is the code so far I am trying but it is showing me error:
URL url = null;
try {
url = new URL("http://wap.nastabuss.se/its4wap/QueryForm.aspx?hpl=Teleborg+C+(V%C3%A4xj%C3%B6)");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("1");
Document doc = null;
try {
System.out.println("2");
doc = Jsoup.parse(url, 3000);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("3");
Element table = doc.select("table[title=Avgångar:]").first();
System.out.println("4");
Iterator<Element> it = table.select("td").iterator();
//we know the third td element is where we wanna start so we call .next twice
it.next();
it.next();
while(it.hasNext()){
// do what ever you want with the td element here
System.out.println(it.next());
//iterate three times to get to the next td you want. checking after the first
// one to make sure
// we're not at the end of the table.
it.next();
if(!it.hasNext()){
break;
}
it.next();
it.next();
}
It prints System.out.println("3");
then it stops in this line
Element table = doc.select("table[title=Avgångar:]").first();
How can i solve this problem,
Thanks
It looks like the website you're trying to parse the HTML from has an error and doesn't have any tables on it. This is what's causing the null pointer exception. doc.select("table[title=Avgångar:]") isn't returning an element and then you're trying to call a method on it. To prevent this error from happening again, you could do something like this:
Elements foundTables = doc.select("table[title=Avgångar:]");
Element table = null;
if(!foundTables.isEmpty()){
table = tables.first();
}
Now, if any table was found, the table variable won't be null. You'll just have to alter the code to adapt in case no tables are found.
You're not checking the result of doc.select() before calling .first(). If there are no elements in the document that match the specified query, doc.select() could return null. Then you are calling .first() on a null pointer which, of course, will throw an exception. There is no table tag with the title you have specified in the document that you are using in your example. So, the result is not surprising.

Categories

Resources