Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Developer
Posts: 149
Registered: ‎04-23-2011
My Device: BlackBerry 9700 Bold
My Carrier: Turkcell
Accepted Solution

Always getting the same JSON output

Hello,

 

A simple problem drives me mad, and I need your assistance... What I am doing is to get JSON data from a Web API (PHP) that lists nearby venues for a given GPS coordinate (longitude and latitude). Using the library provided by json.org, I managed to list the venues in an ObjectFieldList component. The problem is, I am always getting the same output. No matter what I try, I could not manage to pass the right coordinates. I am developing the application at home, so the ObjectListField always returns the nearby venues to my home. When my friend downloads the app OTA and runs the program, he gets the same venues (venues close to me). I cannot figure out what's wrong, and I need help. I am sure that the web API works, I tested it by writing a simple .NET program, it gets the correct venues...

 

Below is the code I'm using:

 

package com.buransoft;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.HttpConnection;
import org.json.me.JSONArray;
import org.json.me.JSONException;

import com.buransoft.HttpConnectionFactory.NoMoreTransportsException;

import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.ObjectListField;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.MainScreen;

public class MekanlarScreen extends MainScreen
{
	RichTextField rtfOutput = new RichTextField();
	final ObjectListField list = new ObjectListField();
	
	public MekanlarScreen()
	{
		rtfOutput.setText("Mekanlar alnıyor. Lütfen bekleyin...");
	    add(rtfOutput);
	        
	    MekanlariAl();
	 
	}
	
	private void MekanlariAl()
	{
		MekanlariAlThread t = new MekanlariAlThread();
		t.start();
		add(list);
	}
	
	private final class MekanlariAlThread extends Thread
	{
		public void run()
	    {	
			String result = null;
			HttpConnection connection = null;
			HttpConnectionFactory _factory = new HttpConnectionFactory(
					"http://popkop.letsimagine.net/Places/getVenues", HttpConnectionFactory.TRANSPORTS_ANY);
			
	        try
	        {       	
	        	//String postData = "lon=" + AnaEkranScreen.longitudeLabel.getText().trim();
	        	//String postData = "lon=" + AnaEkranScreen._longitude;
	        	String postData = "lon=29.227830";
				//postData += "&lat=" + AnaEkranScreen.latitudeLabel.getText().trim();
	        	//postData += "&lat=" + AnaEkranScreen._latitude;
				postData += "&lat=41.120569";
				
				try
				{
					connection = _factory.getNextConnection();
					try
					{
						connection.setRequestMethod( "POST" );
						OutputStream os = connection.openOutputStream();
						
						os.write(postData.getBytes());
						os.close();
						InputStream is = connection.openInputStream();					
						byte[] data = net.rim.device.api.io.IOUtilities.streamToBytes(is);
				        result = new String(data);
						is.close();
					}
					catch (IOException ioe)
				    {
				    	Dialog.inform(ioe.getMessage());
				    }
				}
				catch (NoMoreTransportsException e)
				{
					Dialog.inform(e.getMessage());
				}
				finally
				{
					try
					{
						connection.close();
					}
					catch (Exception e) {}
				}
	        }
	        catch (Exception e)
	        {
	        	Dialog.inform(e.getMessage());
	        }	        
	        showResponse(result);
	    }
		
		public void showResponse(final String result)
		{
			UiApplication.getUiApplication().invokeLater(new Runnable() 
		    {
				public void run() 
		        {
					try
					{
						JSONArray ja = new JSONArray(result);
						int len = ja.length();		
						String[] items = new String[len];
						for (int i = 0; i < len; i++)
						{
							items[i] = String.valueOf(ja.getJSONObject(i).get("name"));	
						}
						list.set(items);	
					} 
					catch (JSONException e) 
					{
						Dialog.alert(e.getMessage());
					}    
		        }
		    });
		}
	}
}

 

In this code above, I am passing a different coordinate, bu still getting the same venues. I cleared the simulator, restarted the device, without success. The app gets the GPS coordianates, but display always the same results... 

 

Any help would be appreciated. Thanks in advance...

 

P.S: BlackBerry Java Plug-in for Eclipse Version: 1.3.0, About - BlackBerry Smartphone Simulator 2.13.0.108
and real device is BlackBerry Bold 9700 with 5.0 software.

 

Contributor
Posts: 41
Registered: ‎08-19-2011
My Device: Bold 9000
My Carrier: Plus

Re: Always getting the same JSON output

[ Edited ]

Try to use this method:

public static void sendPostRequest(HttpConnection hc, String contType, String request) throws IOException {
hc.setRequestMethod(HttpConnection.POST);
hc.setRequestProperty("Content-type", contType);

OutputStreamWriter osw = new OutputStreamWriter(hc.openOutputStream(), "UTF-8");
osw.write(request);
osw.flush();
osw.close();
}

 As contType you can use: "application/x-www-form-urlencoded"

Developer
Posts: 149
Registered: ‎04-23-2011
My Device: BlackBerry 9700 Bold
My Carrier: Turkcell

Re: Always getting the same JSON output

Misiek06855, thank you. I used your code and it worked. Can you tell me what the cause was, using OutputStreamWriter instead of OutputStream, or calling the flush() method?

 

The application works now, however sometimes I am getting "A JSONArray test must start with '[' at character 1 of ..." and "Unterminated string at character ..." errors. What may be the reason?

 

Thanks again!

 

 

public class MekanlarScreen extends MainScreen
{
	RichTextField rtfOutput = new RichTextField();
	final ObjectListField list = new ObjectListField();
	
	public MekanlarScreen()
	{
		rtfOutput.setText("Mekanlar alınıyor. Lütfen bekleyin...");
	    add(rtfOutput);
	        
	    MekanlariAl();
	 
	}
	
	private void MekanlariAl()
	{
		MekanlariAlThread t = new MekanlariAlThread();
		t.start();
		add(list);
	}
	
	private final class MekanlariAlThread extends Thread
	{
		public void run()
	        {	
			
			String result = null;
			HttpConnection connection = null;
			HttpConnectionFactory _factory = new HttpConnectionFactory(
					"http://popkop.letsimagine.net/Places/getVenues", HttpConnectionFactory.TRANSPORTS_ANY);
			
	        try
	        {       	
	
	        	String postData = "lon=" + AnaEkranScreen._longitude;

	        	postData += "&lat=" + AnaEkranScreen._latitude;
			String contentType = "application/x-www-form-urlencoded";
				
				try
				{
					connection = _factory.getNextConnection();
					try
					{
						sendPostRequest(connection, contentType, postData);
						InputStream is = connection.openInputStream();					
						byte[] data = net.rim.device.api.io.IOUtilities.streamToBytes(is);
				                result = new String(data);
				        
						is.close();
					}

					catch (IOException ioe)
				        {
				    	    Dialog.inform(ioe.getMessage());
				        }
				}
				catch (NoMoreTransportsException e)
				{
					Dialog.inform(e.getMessage());
				}
				finally
				{
					try
					{
						connection.close();
					}
					catch (Exception e) {}
				}
	        }
	        catch (Exception e)
	        {
	        	Dialog.inform(e.getMessage());
	        }	        
	        showResponse(result);
	    }
		
		public void showResponse(final String result)
		{
			UiApplication.getUiApplication().invokeLater(new Runnable() 
		    {
				public void run() 
		        {
					try
					{
						JSONArray ja = new JSONArray(result);
						int len = ja.length();		
						String[] items = new String[len];
						for (int i = 0; i < len; i++)
						{
							items[i] = String.valueOf(ja.getJSONObject(i).get("name"));	
						}
						list.set(items);	
					} 
					catch (JSONException e) 
					{
						Dialog.alert(e.getMessage());
					}    
		        }
		    });
		}
		
		
	}
	
	public static void sendPostRequest(HttpConnection hc, String contType, String request) throws IOException 
	{		
		hc.setRequestMethod(HttpConnection.POST);		
		hc.setRequestProperty("Content-type", contType);		
		OutputStreamWriter osw = new OutputStreamWriter(hc.openOutputStream(), "UTF-8");		
		osw.write(request);		
		osw.flush();		
		osw.close();	
	}
}

 

Developer
Posts: 151
Registered: ‎01-20-2010
My Device: Blackberry Bold
My Carrier: Telefonica

Re: Always getting the same JSON output

I not sure, but when you get "A JSONArray test must start with '[' at character 1 of ..." or "Unterminated string at character ..." , maybe your JSON structure is not correct.

Look if you JSON structure is ok.

 

pd: Sorry for my english

Contributor
Posts: 41
Registered: ‎08-19-2011
My Device: Bold 9000
My Carrier: Plus

Re: Always getting the same JSON output

You're welcome

 

I think that useing OutputStreamWriter it's always better to write text, because you can define useing charset. Flush forces to write content of buffer, but the same should do close() method, it is possible that it works without flush. You can try.

 

  "A JSONArray test must start with '[' at character 1 - that seems to me, that your server respond isnt in json format, but I dont know where you getting this error.


I can't image to writting application useing web service  without net-sniffer. I recoment you "Wireshark", you can observe comunication with your app. and server. (but remember to set filtr on server ip adress)

 

"Unterminated string at character ..."  that tells nothing to me, maybe you can debug and tell me where you get this error.