I have been searching the web for a connection between my Android simulator and a MySQL db.
I've found that you can't connect directly but can via a web server. The web server will handle my request from my Android.
I found the following code on Hello Android, but I don't understand. If I run this code on the simulator, nothing happens; the screen stays black.
Where does Log.i land, in the Android screen, the error log, or somewhere else?
Can somebody help me with this code?
package app.android.ticket;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class fetchData extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//call the method to run the data retreival
getServerData();
}
public static final String KEY_121 = "http://www.jorisdek.nl/android/getAllPeopleBornAfter.php";
public fetchData() {
Log.e("fetchData", "Initialized ServerLink ");
}
private void getServerData() {
InputStream is = null;
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1980"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("id")+
", name: "+json_data.getString("name")+
", sex: "+json_data.getInt("sex")+
", birthyear: "+json_data.getInt("birthyear")
);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
Logging messages go in the Log cat. You could also use LogCat Reader.
Related
Good morning together from Germany!
I am trying to read a little json file from a webserver. When I start the app, I got the error message: android.os.NetworkOnMainThreadException.
The Target should be, that logcat is showing my json content:
{"first":"one","second":"two"}
Web server is working. When I access: 127.0.0.1/index.php, the browser shows me the upper line.
This is my Main:
package com.example.u0017007.jsonclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://127.0.0.1:80/index.php");
StringBuilder stringBuilder = new StringBuilder();
try {
HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
Log.i(this.getClass().getSimpleName(), stringBuilder.toString());
} else {
Log.e(this.getClass().getSimpleName(), "Fehler");
}
} catch (ClientProtocolException e) {
Log.e(this.getClass().getSimpleName(), e.getMessage());
} catch (IOException e) {
Log.e(this.getClass().getSimpleName(), e.getMessage());
}
}
}
That is the error log
FATAL EXCEPTION: main
Process: com.example.u0017007.jsonclient, PID: 16115
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.u0017007.jsonclient/com.example.u0017007.jsonclient.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:333)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
at java.net.Socket.connect(Socket.java:586)
at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:124)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:149)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:169)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:124)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:366)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470)
at com.example.u0017007.jsonclient.MainActivity.onCreate(MainActivity.java:29)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756
There are related questions that you can find and make use of them, but to give you the gist of the solutions available - you can solve them using any of the approaches given below:
You can refrain writing any Network related calls in your Main UI thread but use an AsyncTask to achieve what you want to, in it.
You can add the following code into your Main file by adding the following import as well.
The import:
import android.os.StrictMode;
The code:
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Hi guys I have a problem creating a JSON file from a google url that i have. This is my code that im using.
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadUrl {
public String readUrl(String strUrl) throws IOException, InterruptedException {
Log.d("URLS = ",strUrl);
Thread.sleep(2000);
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
Log.d("downloadUrl", data.toString());
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
}
It works fine when i throw a url that looks like this into it.
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.7207523,-73.383851&radius=4828&type=bar&key=MYKEY
But when i try and throw a url that looks like this into it.
https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJe3AmoGsr6IkRuWcK1LAh-DE&key=MYKEY
I get an error: D/GooglePlacesReadTask: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.InputStream.close()' on a null object reference
I dont know how i fix this. Any help?
Aah
you did not mention this is in android,
I presume this because you said ,
android.os.NetworkOnMainThreadException
in your comment
Android does not allow time consuming tasks on main thread,
use AsyncTask to call your function or use plain old java thread
Network on main thread exception comes when you run a networking operation on main thread .
Generally AsyncTask is used for these works but if you want to use the same code you written Just add..
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
I am trying to use the Java Bulk API for creating the documents in ElasticSearch. I am using a JSON file as the bulk input. When I execute, I get the following exception:
Exception in thread "main" NoNodeAvailableException[None of the configured nodes are available: []]
at org.elasticsearch.client.transport.TransportClientNodesService.ensureNodesAreAvailable(TransportClientNodesService.java:280)
at org.elasticsearch.client.transport.TransportClientNodesService.execute(TransportClientNodesService.java:197)
at org.elasticsearch.client.transport.support.TransportProxyClient.execute(TransportProxyClient.java:55)
at org.elasticsearch.client.transport.TransportClient.doExecute(TransportClient.java:272)
at org.elasticsearch.client.support.AbstractClient.execute(AbstractClient.java:347)
at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.java:85)
at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.java:59)
at bulkApi.test.App.main(App.java:92)
This is the java code.
package bulkApi.test;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args ) throws IOException, ParseException
{
System.out.println( "Hello World!" );
// configuration setting
Settings settings = Settings.settingsBuilder()
.put("cluster.name", "test-cluster").build();
TransportClient client = TransportClient.builder().settings(settings).build();
String hostname = "localhost";
int port = 9300;
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(hostname),port));
// bulk API
BulkRequestBuilder bulkBuilder = client.prepareBulk();
long bulkBuilderLength = 0;
String readLine = "";
String index = "testindex";
String type = "testtype";
String _id = null;
BufferedReader br = new BufferedReader(new InputStreamReader(new DataInputStream(new FileInputStream("/home/nilesh/Shiney/Learn/elasticSearch/ES/test/parseAccount.json"))));
JSONParser parser = new JSONParser();
while((readLine = br.readLine()) != null){
// it will skip the metadata line which is supported by bulk insert format
if (readLine.startsWith("{\"index")){
continue;
}
else {
Object json = parser.parse(readLine);
if(((JSONObject)json).get("account_number")!=null){
_id = String.valueOf(((JSONObject)json).get("account_number"));
System.out.println(_id);
}
//_id is unique field in elasticsearch
JSONObject jsonObject = (JSONObject) json;
bulkBuilder.add(client.prepareIndex(index, type, String.valueOf(_id)).setSource(jsonObject));
bulkBuilderLength++;
try {
if(bulkBuilderLength % 100== 0){
System.out.println("##### " + bulkBuilderLength + "data indexed.");
BulkResponse bulkRes = bulkBuilder.execute().actionGet();
if(bulkRes.hasFailures()){
System.out.println("##### Bulk Request failure with error: " + bulkRes.buildFailureMessage());
}
bulkBuilder = client.prepareBulk();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
br.close();
if(bulkBuilder.numberOfActions() > 0){
System.out.println("##### " + bulkBuilderLength + " data indexed.");
BulkResponse bulkRes = bulkBuilder.execute().actionGet();
if(bulkRes.hasFailures()){
System.out.println("##### Bulk Request failure with error: " + bulkRes.buildFailureMessage());
}
bulkBuilder = client.prepareBulk();
}
}
}
Couple of things to check:
Check that your cluster name is same as the one defined in
elastic.yml
Try creating the index with the index name
('testindex' in your case) with PUT api from any REST Client
(ex:AdvancedRestClient) http://localhost:9200/testindex (Your
request has to be successful i.e status code==200 )
Run your program after you create the index with the above PUT request.
I am trying to use the Google Place Actions API, specifically the events and I cannot get a valid post for the life of me.
Here is the URL I am using:
https://maps.googleapis.com/maps/api/place/event/add/json?sensor=false&key=placesApiKey&duration=26000&reference=CjQwAAAAv4TTQ3ySXiGhOElWFNAQ-roLOfgwo215yRTk1Bmhg0jSJ-sAdz9nHgNgnGBAmqP7EhC7K0AjTfFcZgCUh68c2yNtGhRkmynXvE5d4XA5ZfyBqAxlNdsAIg&summary=this is going to be something fun
The reference is to Tempe, AZ. I keep getting a 404 back saying that it is an illegal request. Any help would be great! I really don't know what I am doing wrong.
I have tried three different ways both with the same results:
HttpClient client = new HttpClient();
client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
String url = "https://maps.googleapis.com/maps/api/place/event/add/json?sensor=false&key=" + googlePlacesAPIKey;
PostMethod post = new PostMethod(url);
NameValuePair[] data = {
new NameValuePair("duration", Long.toString(duration)),
new NameValuePair("reference", reference),
new NameValuePair("summary", summary)
};
post.setRequestBody(data);
and
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://maps.googleapis.com/maps/api/place/event/add/json?sensor=false&key=" + googlePlacesAPIKey);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("duration", Long.toString(duration)));
nameValuePairs.add(new BasicNameValuePair("reference", reference));
nameValuePairs.add(new BasicNameValuePair("summary", summary));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
}
and
URL url = new URL("https://maps.googleapis.com/maps/api/place/event/add/json?sensor=false&key="+googlePlacesAPIKey+"&duration="+duration+"&reference="+reference+"&summary="+summary);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
OutputStreamWriter out = new OutputStreamWriter( httpCon.getOutputStream());
System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage()); out.close();
and
HttpPost post = new HttpPost("https://maps.googleapis.com/maps/api/place/event/add/json?sensor=false&key=" + googlePlacesAPIKey);
post.setHeader("Content-type", "application/json");
JSONObject object = new JSONObject();
object.put("duration", Long.toString(duration));
object.put("reference", reference);
object.put("summary", summary);
String message = object.toString();
post.setEntity(new StringEntity(message));
HttpResponse response = client.execute(post);
Here is the link to the API for those that are curious:
https://developers.google.com/places/documentation/actions#event_add
In python, you can do like this:
#!/usr/bin/python
# coding: utf8
import sys
import urllib
parameters = urllib.urlencode({
'key' : "YOUR_API_KEY",
'sensor' : 'false'
})
url = "https://maps.googleapis.com/maps/api/place/event/add/json?%s" % (parameters)
#The reference
reference = "CoQBdgAAAN4u...YKmgQ"
#Add event
postdata = '''
{
"duration": 86400,
"language": "ja",
"reference": "%s",
"summary": "Event Name!",
"url" : "http://hogehoge.com/test_page"
}
''' % (reference)
f = urllib.urlopen(url, postdata)
print f.read()
Ok, I'm not good for Java though, I created an example code for Android Java.
[MainActivity.java]
package com.example.placeseventtest;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private final String API_KEY = "YOUR_API_KEY";
private PlacesHTTP myUtil;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView resTxtView = (TextView) findViewById(R.id.responseText);
myUtil = new PlacesHTTP(API_KEY, resTxtView);
Button currentPosBtn = (Button) this.findViewById(R.id.currentPosBtn);
currentPosBtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
JSONObject params = new JSONObject();
JSONObject location = new JSONObject();
JSONArray types = new JSONArray();
try {
location.put("lat", 123.4556);
location.put("lng", 123.4556);
params.put("location", location);
params.put("accuracy", 20);
params.put("name", "Event Name");
//only one type is available.
types.put("parking");
params.put("types", types);
params.put("language", "en");
} catch (Exception e) {}
// Show the request JSON data.
TextView reqTxtView = (TextView) findViewById(R.id.requestText);
try {
reqTxtView.setText(params.toString(2));
} catch (Exception e) {}
// POST to Google Server
myUtil.execute(params);
}
});
}
}
[PlacesHTTP.java]
package com.example.placeseventtest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.widget.TextView;
public class PlacesHTTP extends AsyncTask<JSONObject, Void, HttpResponse>{
private HttpPost post;
private HttpClient httpClient;
private String url;
private TextView txtView;
public PlacesHTTP(String api_key, TextView resultView) {
url = String.format("https://maps.googleapis.com/maps/api/place/add/json?sensor=false&key=%s", api_key);
txtView = resultView;
}
protected void onPreExecute() {
httpClient = new DefaultHttpClient();
post = new HttpPost(url);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
}
#Override
protected HttpResponse doInBackground(JSONObject... params) {
//Send data as JSON format
JSONObject opts = params[0];
StringEntity strEntity;
HttpResponse response = null;
try {
strEntity = new StringEntity(opts.toString());
post.setEntity(strEntity);
response = httpClient.execute(post);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
protected void onPostExecute(HttpResponse result) {
if (result != null) {
// Display the result
try {
txtView.setText(EntityUtils.toString(result.getEntity()));
} catch (Exception e) {
e.printStackTrace();
}
} else {
txtView.setText("null");
}
}
}
I got this result:
I was starting out with google map Api's. Following some examples on the internet.I came up with these code. I was able to get the Json code quite easily by crating HttpURLCOnnection but somehow I am getting a runtime error.Somehow i am unable to create a Json Object.I searched quite a bit,but didn't find any relation between JSONObject and Runtimeerror
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
public class Parser {
public static void main(String args[])
{
String response="";
int lat1=20270000,lon1=85520000,lat2=20264500,lon2=85835500;
String urlString="https://maps.googleapis.com/maps/api/directions/json?origin="+Double.toString((double)lat1/1E6)+","+Double.toString((double) lon1/1E6)+"&destination="+Double.toString((double)lat2/1E6)+","+Double.toString((double) lon2/1E6)+"&sensor=true";
HttpURLConnection urlConnection= null;
URL url = null;
try{
url = new URL(urlString.toString());
urlConnection=(HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
InputStream inStream = urlConnection.getInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
String temp;
while((temp = bReader.readLine()) != null){
response += temp;
}
System.out.println(response);
bReader.close();
inStream.close();
urlConnection.disconnect();
}
catch(Exception e){}
ArrayList<Bundle> list = new ArrayList<Bundle>();
try {
System.out.println(response.toString()); // uptil here every thing is fine..... I am getting correct Json text.
JSONObject jsonObject = new JSONObject(response); //I am getting a runtime error in this line. Can't figure out the reason
System.out.println(jsonObject);
JSONArray routesArray= jsonObject.getJSONArray("routes");
JSONObject route = routesArray.getJSONObject(0);
JSONArray legs = route.getJSONArray("legs");
JSONObject leg = legs.getJSONObject(0);
JSONObject durationObject = leg.getJSONObject("duration");
String duration = durationObject.getString("text");
System.out.println("egferg"+duration);
}
catch(Exception e1){e1.printStackTrace();}
}
}