I'm using below codes for downloading data from Google and getting a location keyword lat lng in my monodroid application:
public LatLng GetLatLng (String input)
{
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder ();
LatLng gp = null;
string str = null;
try {
StringBuilder sb = new StringBuilder (GEOCODER_API_BASE + OUT_JSON);
sb.Append ("?address=" + input + "&sensor=true");
/// "http://maps.googleapis.com/maps/api/geocode/json?address=Paris&sensor=true"
URL url = new URL (sb.ToString ());
conn = (HttpURLConnection)url.OpenConnection ();
Java.IO.InputStreamReader inp = new Java.IO.InputStreamReader (conn.InputStream);
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = inp.Read (buff)) != -1) {
jsonResults.Append (buff, 0, read);
}
str = jsonResults .ToString();
} catch (System.IO.IOException e) {
RltLog .HandleException (e, "\nError connecting to Places API\n");
return gp;
} finally {
if (conn != null) {
conn.Disconnect ();
}
}
try {
// Create a JSON object hierarchy from the results
JObject address = JObject .Parse (str);
JArray ja = (JArray)address ["results"];
JObject LocationJObejct = (JObject)ja [0] ["geometry"] ["location"];
gp = HelperMethods .executeLocationPoint (LocationJObejct ["lat"].ToString (),
LocationJObejct ["lng"].ToString ());
} catch (Exception e) {
RltLog .HandleException (e);
}
return gp;
}
But I keep getting these error:
Exception of type 'Java.IO.FileNotFoundException' was thrown.
I'm wondering what is the reason?
You should replace spaces with + in your request based on the google docs.
Related
I have a json file which contains only objects now i cant able to fetch all the object with iteration as here is no array.
Here is the code : That i have tried in my android studio & JSon Data Screenshot
#Override
protected String doInBackground(String... strings) {
try {
url = new URL("https://api.myjson.com/bins/r7dj6");
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line =" ";
while ((line = bufferedReader.readLine()) != null){
stringBuffer.append(line);
}
String fullfile = stringBuffer.toString();
JSONObject jsonObject = new JSONObject(fullfile);
JSONObject jsonObjectchild = jsonObject.getJSONObject("Apartment");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Here is a complete example. Works for me.
HttpURLConnection connection = null;
try {
URL url = new URL("https://api.myjson.com/bins/r7dj6");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder stringBuffer = new StringBuilder();
while ((line = reader.readLine()) != null){
stringBuffer.append(line);
}
JSONObject jsonObject = new JSONObject(stringBuffer.toString());
JSONObject apartmentObject = jsonObject.getJSONObject("Apartment");
Iterator<String> keys = apartmentObject.keys();
while (keys.hasNext()) {
String flatName = keys.next();
JSONObject flat = apartmentObject.getJSONObject(flatName);
String age = flat.getString("age");
String color = flat.getString("color");
String name = flat.getString("name");
String owner = flat.getString("owner");
String partner = flat.getString("partner");
Log.d("Flat", flatName + ": " + age + ", " + color + ", " + name + ", " + owner + ", " + partner);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
You can still iterate:
for (Iterator key=jsonObjectchild.keys();key.hasNext();) {
JSONObject flatName = json.get(key.next());
...
}
When lots of address be transformed to lat&lng by following code, sometimes the result is null.
I think that reason is using this url too much, so getting null value.
how do I solve this problem to get correct lat&lng?
String transformerUrl = "http://maps.google.com/maps/api/geocode/json?address=%s&language=zh-TW&sensor=false®ion=tw";
private String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public String[] getLocationInfoByAddress(String address)
throws IOException, JSONException {
String[] latLngStr = new String[2];
String encodeAddress = URLEncoder.encode(address, "Utf-8");
String formatAddress = String.format(transformerUrl, encodeAddress);
InputStream is = new URL(formatAddress).openConnection().getInputStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is,
Charset.forName("UTF-8")));
String jsonText = readAll(rd);
//System.out.println(jsonText);
try {
JSONArray arr = new JSONObject(jsonText)
.getJSONArray("results");
for (int i = 0; i < arr.length(); ++i) {
if (arr.getJSONObject(i).get("geometry") != null) {
Object lat = arr.getJSONObject(i).getJSONObject("geometry").getJSONObject("location").get("lat");
Object lng = arr.getJSONObject(i).getJSONObject("geometry").getJSONObject("location").get("lng") ;
latLngStr[0] = lat.toString();
latLngStr[1] = lng.toString();
break;
}
}
} catch (JSONException e) {
}
} finally {
is.close();
}
return latLngStr;
}
Check the returned Status before using the result.
The Google Maps Geocoding Web Service is subject to a quota and a rate limit. If you don't comply to those, you will get a status of OVER_QUERY_LIMIT.
If you aren't including a key in your URL (which I don't see in your question), adding a key to your request may allow you your own independent quota (only really applicable if you are on a shared server).
If that doesn't help, you need to throttle your requests to comply with quota/rate limit. There are questions on how to do that on StackOverflow.
I have a webservice that returnds a json response , the json response contains both plain text and base64 encoded images , I am consuming that service using android app so I implemented progress bar to indicate the progress .
Implementing progress bar forces me to use BufferedInputStream to read the response and update the progress based on what the app is reading .
The problem is that everything is working fine and the progress is updating correctly, but after collecting the response and exiting the while loop , I try to convert the string into json format using JSONObject.
Here is the code snippet
BufferedInputStream bis = new BufferedInputStream(responseEntity.getContent());
StringBuilder sb = new StringBuilder();
String line = null;
int total = 0 ;
int count = 0 ;
byte[] buffer = new byte[4096];
StringBuffer sBuffer = new StringBuffer();
StringWriter sw = new StringWriter();
String content = new String();
while((count = bis.read(buffer)) > 0){
content += new String(buffer,Charset.defaultCharset());
total += count;
publishProgress(""+(int )total*100/this.contentSize);
Log.i("updating",""+(int )total*100/this.contentSize);
}
bis.close();
// String content = new String(sb);
// Log.i("ServerRawresponse",content);
try {
Log.i("REsponse_Content",content.replaceAll("\"", ""));
responseString = new JSONObject(new JSONTokener(content.replaceAll("\"", "\\\"")));
//System.out.println(content);
} catch (JSONException e) {
e.printStackTrace();
}
Any help please
Try this methods works perfectly with me
HttpResponse WSresponse = httpclient.execute(httppost);
String response = getResponseBody(WSresponse.getEntity());
JSONObject jobj = new JSONObject(response);
public String getResponseBody(final HttpEntity entity) throws IOException, ParseException {
System.out.println("GEN START : " + Calendar.getInstance().getTimeInMillis());
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
if (instream == null) {
return "";
}
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException(
"HTTP entity too large to be buffered in memory");
}
StringBuilder buffer = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream, HTTP.UTF_8));
String line = null;
try {
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} finally {
instream.close();
reader.close();
}
return buffer.toString();
}
I am attempting to read a text file and create a JSONObject in an Android application, but after reading the text file into a string, I get a JSONException thrown when I try to construct a JSONObject using the string.
Here is the code I am using:
InputStream is = this.getResources().openRawResource(R.raw.quiz);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String jsString = "";
String line = null;
while((line = reader.readLine()) != null){
jsString += line;
}
is.close();
reader.close();
try {
return new JSONObject(jsString);
} catch (JSONException e) {
}
return null;
Here is the text file I am reading from, quiz.txt:
{"length":3,"questions":[{"questionText":"Is mayonaise an instrument?","answers":["Yes","no","no","no","no"],"correctAnswer":0},{"questionText":"10^2","answers":["1","10","100","1000","over 9000"],"correctAnswer":1},{"questionText":"Dogs Name?","answers":["Barky","Steve","Rex","Daisy","Wormy"],"correctAnswer":3}]}
Try using this method to read the file contents into a string.
public static String getJsonFromResource( int resource, Context context ) {
InputStream inputStream = context.getResources().openRawResource( resource );
BufferedReader r = new BufferedReader( new InputStreamReader( inputStream ) );
StringBuilder stringBuilder = new StringBuilder();
String line;
String jsonString = null;
try {
while (( line = r.readLine() ) != null) {
stringBuilder.append( line );
}
jsonString = stringBuilder.toString();
}
catch (Exception e) {
Log.e( "GetJsonFromResource", Log.getStackTraceString( e ) );
}
return jsonString;
}
I am getting a really long string as the response of the web service I am collecting it in the using the StringBuilder but I am unable to obtain the full value I also used StringBuffer but had no success.
Here is the code I am using:
private static String read(InputStream in ) throws IOException {
//StringBuilder sb = new StringBuilder(1000);
StringBuffer sb = new StringBuffer();
String s = "";
BufferedReader r = new BufferedReader(new InputStreamReader( in ), 1000);
for (String line = r.readLine(); line != null; line = r.readLine()) {
sb.append(line);
s += line;
} in .close();
System.out.println("Response from Input Stream Reader >>>" + sb.toString());
System.out.println("Response from Input S >>>>>>>>>>>>" + s);
return sb.toString();
}
Any help is appreciated.
You can also split the string in array of strings in order to see all of them
String delimiter = "put a delimiter here e.g.: \n";
String[] datas=sb.toString().split(delimiter);
for(String string datas){
System.out.println("Response from Input S >>>>>>>>>>>>" + string);
}
The String may not print entirely to the console, but it is actually there. Save it to a file in order to see it.
I do not think that your input is too big for a String, but only not shown to the console because it doesn't accept too long lines. Anyways, here is the solution for a really huge input as characters:
private static String[] readHugeStream(InputStream in) throws IOException {
LinkedList<String> dataList = new LinkedList<>();
boolean finished = false;
//
BufferedReader r = new BufferedReader(new InputStreamReader(in), 0xFFFFFF);
String line = r.readLine();
while (!finished) {
int lengthRead = 0;
StringBuilder sb = new StringBuilder();
while (!finished) {
line = r.readLine();
if (line == null) {
finished = true;
} else {
lengthRead += line.length();
if (lengthRead == Integer.MAX_VALUE) {
break;
}
sb.append(line);
}
}
if (sb.length() != 0) {
dataList.add(sb.toString());
}
}
in.close();
String[] data = dataList.toArray(new String[]{});
///
return data;
}
public static void main(String[] args) {
try {
String[] data = readHugeStream(new FileInputStream("<big file>"));
} catch (IOException ex) {
Logger.getLogger(StackoverflowStringLong.class.getName()).log(Level.SEVERE, null, ex);
} catch (OutOfMemoryError ex) {
System.out.println("out of memory...");
}
}
System.out.println() does not print all the characters , it can display only limited number of characters in console. You can create a file in SD card and copy the string there as a text document to check your exact response.
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Responsefromserver");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, "response.txt");
FileWriter writer = new FileWriter(gpxfile);
writer.append(totalResponse);
writer.flush();
writer.close();
}
catch(IOException e)
{
System.out.println("Error:::::::::::::"+e.getMessage());
throw e;
}