I wrote the code below to get a simple message from a file php that send me a json object, I have no errors in my code and the PHP code work well, can you please help me to find what is the matter with my code :)
JAVA Code :
package com.example.httpclient;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView myListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//This is our textView element
myListView = (TextView) findViewById(R.id.textView1);
//Lets try to connect
try{
//Create a new client object
HttpClient httpclient = new DefaultHttpClient();
//Now post to your demo URL
HttpPost httppost = new HttpPost("http://goldengym.ma/test/test1.php");
//Execute the post and get the response
HttpResponse response = httpclient.execute(httppost);
//Get the message from the response
HttpEntity entity = response.getEntity();
//Get the content of the message
InputStream webs = entity.getContent();
//Convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(webs, "iso-8859-1"), 8);
//Read one line of the response
myListView.setText(reader.readLine());
//Slow our inputStream
webs.close();
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
}catch(Exception e){
Log.e("log_tag", "Error in http connection " + e.toString());
}
}catch (Exception e){
Log.e("log_tag", "Error " + e.toString());
}
}
}
And there is the PHP Code :
<?php
$result = 'TEST WORKED, WE GOT CONNECTION';
print json_encode($result);
?>
And there is my logcat :
03-03 12:35:02.918: I/ActivityManager(1995): Force stopping package com.example.httpclient uid=10118
03-03 12:35:04.518: W/PackageManager(1995): Code path for pkg : com.example.httpclient changing from /data/app/com.example.httpclient-2.apk to /data/app/com.example.httpclient-1.apk
03-03 12:35:04.518: I/ActivityManager(1995): Force stopping package com.example.httpclient uid=10118
03-03 12:35:04.518: W/PackageManager(1995): Resource path for pkg : com.example.httpclient changing from /data/app/com.example.httpclient-2.apk to /data/app/com.example.httpclient-1.apk
03-03 12:35:05.218: I/ActivityManager(1995): Force stopping package com.example.httpclient uid=10118
03-03 12:35:05.493: D/Launcher.LauncherModel(5871): --> package:com.example.httpclient
03-03 12:35:05.723: D/Launcher.LauncherModel(5871): --> update package com.example.httpclient
03-03 12:35:05.723: D/Launcher.LauncherModel(5871): --> package:com.example.httpclient
03-03 12:35:05.913: V/BackupManagerService(1995): updatePackageParticipantsLocked: com.example.httpclient
03-03 12:35:06.188: D/PackageBroadcastService(2465): Received broadcast action=android.intent.action.PACKAGE_REMOVED and uri=com.example.httpclient
03-03 12:35:06.523: V/BackupManagerService(1995): updatePackageParticipantsLocked: com.example.httpclient
03-03 12:35:07.598: W/DeepLinking(3458): no deep link install data found for com.example.httpclient
03-03 12:35:07.663: D/PackageBroadcastService(2465): Received broadcast action=android.intent.action.PACKAGE_ADDED and uri=com.example.httpclient
03-03 12:35:07.703: D/PackageAddedReceiver(2234): package added com.example.httpclient
03-03 12:35:08.048: D/PackageBroadcastService(2465): Received broadcast action=android.intent.action.PACKAGE_REPLACED and uri=com.example.httpclient
package com.example.httpclient;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.TargetApi;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView myListView;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//This is our textView element
myListView = (TextView) findViewById(R.id.tv);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
//Lets try to connect
try{
//Create a new client object
HttpClient httpclient = new DefaultHttpClient();
//Now post to your demo URL
HttpPost httppost = new HttpPost("http://10.0.2.2/testAndroid/test1.php");
//Execute the post and get the response
HttpResponse response = httpclient.execute(httppost);
//Get the message from the response
HttpEntity entity = response.getEntity();
//Get the content of the message
InputStream webs = entity.getContent();
//Convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(webs, "iso-8859-1"), 8);
//Read one line of the response
myListView.setText(reader.readLine());
//Slow our inputStream
webs.close();
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
}catch(Exception e){
Log.e("log_tag", "Error in http connection " + e.toString());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
PLz try this code, It is working fine. There should use
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
and Manifeast
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.httpclient"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.provider.testdemo.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Network calls made on the main Thread are disallowed (http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html)
Also, you need <uses-permission android:name="android.permission.INTERNET"/> in your AndroidManifest.xml file.
Never use Exception to handle your exceptions.
Also, I would try to avoid putting a try-catch into an other try-catch.
do it as follows:
public class MyAsyncTask extends AsyncTask<String, String, String> {
private TextView myListView;
public MyAsyncTask(TextView myListView){
this.myListView = myListView;
}
#Override
protected String doInBackground(String... params) {
String response = null;
HttpClient httpclient = new DefaultHttpClient();
//Now post to your demo URL
HttpPost httppost = new HttpPost(params[0]);
//Execute the post and get the response
HttpResponse response = httpclient.execute(httppost);
//Get the message from the response
HttpEntity entity = response.getEntity();
//Get the content of the message
InputStream webs = entity.getContent();
//Convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(webs, "iso-8859-1"), 8);
response = reader.readLine();
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}finally{
webs.close();
}
return response;
}
#Override
protected void onPostExecute(String result) {
if(result != null){
myListView.setText(result);
}
}
In onCreate() of your activity:
new MyAsyncTask(myListView).execute("http://goldengym.ma/test/test1.php");
The key method of AsyncTask is doInBackground(), which performs the lengthy operations on a separate thread, while onPostExecute works on the main thread. Refer AsyncTask documentation for more detail. Also, before making any call to server, you should always check first, whether internet is available. I had not posted that part here. Hope this helps.
You can not do the internet operations on main thread. It will give you mainThreadException.
You have to use Asynctask for doing these operations. Then only your able to fetch data from the web services.
http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html
You can use this link to understand how it works.
Related
Connect an Android Device To a Web Service on Local Host
Following my previous thread , im now able to connect my Android Device to my local host using wamp
But still i cannot connect to my symfony server and get my API datas
I sarted symfony's internal server :
"Server running on http://127.0.0.1:8000"
I used Internet permission on my AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
My MainActivity.java code
package com.example.cbmedandroid;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://192.168.43.13:8000/api/horaire.json");
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
EditText et = (EditText)findViewById(R.id.my_edit);
et.setText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}
}
When i launch the application and click to the button .
It load during 40 sec and i get this
"Connection to http://192.168.43.13:8000 refused"
192.168.43.13 is my pc adress
What should i do to fix this .
thanks.
FINALLY! i have found the solution to my problem
when running the built-in php server .
We need to specify this command
php bin/console server:run 0.0.0.0:8000
(8000 is my port , you can put yours)
so that Any device or host (ip) could access
if you put 127.0.0.1 only your localhost will be allowed
That's why i couldn't get the Api even i was connected to my localhost via wifi hotspot
It's ok now
Are you able to install this cURL App for Android?
Then use on your Android (is this a real phone or an emulator) open a cURL window and then enter:
cURL http://192.168.43.13:8000/
I tried this same kind of setup with a real Android phone and the above indicated cURL app and put in my Symfony web URL (on another PC), and the Android shows the correct html response back that I'm expecting.
At least this will help you verify functionality first.
Edit below this line:
Here is the code you might use since HttpClient was deprecated:
URL url = new URL("http://192.168.43.13:8000/api/horaire.json");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//conn.setRequestMethod("GET");
// read the response
System.out.println("Response Code: " + conn.getResponseCode());
InputStream in = new BufferedInputStream(conn.getInputStream());
String response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(response);
Not sure if you need to use the "setRequestMethod". But try out this change and see if that works for you.
I am developing a login application using MySQL database. I am using JSONParser from the database package to connect to the local mysql database I am getting the following error please some one help me. I googled for this error but what I got is to use the AsyncTask but I don't know where to use and how to use and what is the Mainthread also.
Please some one edit my code and explain or post relevant codes...
"android.os.NetworkonMainThreadException" is the error when I running the application from 4.2 genymotion emulator...
package com.android.database;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}``
Network Operations must be done in background.
You can use AsyncTask to accomplish this.
You are performing network operation on the UI thread and you can't do it. Consider using AsyncTask to do this kind operations, or an external library like this, which allows you to make Http request asynchronously in a very simple way.
I'm not sure if I understand your question correctly, and I would like to rather add a comment but am not allowed (too low rep) so here goes:
This class JSONParser i'm assuming is the "Activity" you are talking about. This is not an activity though, but a class, so you could rather create a new object of this class and use it from your calling activity:
JSONParser json = new JSONParser();
json.getJSONFromUrl(url,params);
Thing is, doing this parsing will take time and on the main UI thread this will probably pause the thread and might even let the app crash if the thread takes longer than 5 seconds to respond. This means you should use AsyncTask to run this JSONParser methods. A good place to start with learning AsyncTask is Vogella. He has some great tutorials on his site.
You will probably use doInBackground to run your getJSONFromUrl method and then update your UI thread from the onPostExecute method. So basically: Use AsyncTask
I'm new to android development n i'm trying to make HTTPConnection.
I make two files one is ParsingActivity.java(Main Activity File)and other one is XMLParser.java (For setting up the HTTPRClient Request).
ParserActivity.java
package ok.done;
import android.app.Activity;
import android.os.Bundle;
public class ParsingActivity extends Activity {
String URL = "http://api.androidhive.info/pizza/?format=xml";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.out.println("t1==========>"+URL);
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL);
System.out.println("t2==========>"+xml);
}
}
XMLParsing.java
package ok.done;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class XMLParser {
// constructor
public XMLParser() {
}
public String getXmlFromUrl(String url) {
String xml = null;
System.out.println("t3==========>"+xml);
System.out.println("t4==========>"+url);
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
System.out.println("t5==========>"+url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
System.out.println("t6==========>"+xml);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
}
I also add the permission in the AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ok.done"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name=".ParsingActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>
And the LogCat result for my System.out.println are
for t1==========>http://api.androidhive.info/pizza/?format=xml
t3==========>null
t4==========>http://api.androidhive.info/pizza/?format=xml
t5==========>null
t6==========>null
t2==========>null
but if everything is perfect in my this simple code thein for the result of t6,t2 is the xml file description.
Any one plz suggest me what should I do or any other links which will be helpful for me for creating XML parsing type application.
Thanks In Advance.
Are you sure that the http server gives a valid xml after firing. To make sure fire the url on web browser, if server gives the xml, you will get the xml content.
hi I am trying to fetch data from link as given below
http://abovestress.com/app_stress/fetch_all_detail.php?task=fetchtimefromdateanduserid&track_date=2011-08-09&tracker_user_id=374
but I can't get result my code is here
package com.JsonDemo;
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 JsonDemoActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<String> fetchsosfromID = new ArrayList<String>();
String result = "";
InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("track_date","2011-08-09"));
nameValuePairs.add(new BasicNameValuePair("tracker_user_id",""+374));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://abovestress.com/app_stress/fetch_all_detail.php?task=fetchtimefromdateanduserid&");
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();
Log.v("log_tag", "Append String " + result);
} 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);
fetchsosfromID.add(json_data.getString("track_time"));
Log.v("log_tag", "daily_data " + fetchsosfromID);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
}
and error comes like this
08-09 17:29:01.315: ERROR/log_tag(2291): Error in http connection java.net.UnknownHostException: abovestress.com
08-09 17:29:01.315: ERROR/log_tag(2291): Error converting result java.lang.NullPointerException
08-09 17:29:01.345: ERROR/log_tag(2291): Error parsing data org.json.JSONException: End of input at character 0 of
manifiest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.JsonDemo"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="9" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".JsonDemoActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-permission android:name="android.permission.INTERNET"/>
</application>
</manifest>
You've definitely added the
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
in your manifest, right?
Edit: Your <uses-permission> is in the wrong place. It should look like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.JsonDemo"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="9" />
<uses-permission android:name="android.permission.INTERNET"/>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".JsonDemoActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
you need to put permission tag put of application tag...
The exception you get points to a name resolution problem (getting abovestress.com ip address from DNS server). That is probably because your network is down.
A simple snippet to check if a network connection is up, where Context ctx is you Activity context:
public boolean checkConnection(Context ctx) {
ConnectivityManager conMgr =
(ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo i = conMgr.getActiveNetworkInfo();
if (i == null)
return false;
if (!i.isConnected())
return false;
if (!i.isAvailable())
return false;
return true;
}
EDIT:
if network in not your problem, have a look here and here
you may need to add (besides android.permission.INTERNET) other permissions:
android.permission.ACCESS_NETWORK_STATE
android.permission.READ_PHONE_STATE
and/or:
try {
InetAddress i = InetAddress.getByName(URLName);
} catch (UnknownHostException e1) {
e1.printStackTrace();
}
// ... actually using URL
EDIT 2: AND, as noted by others, uses-permission element goes inside manifest element, not application element
I'm was trying a tutorial to get data to android from a MySQL database that you can find here:
http://www.helloandroid.com/tutorials/connecting-mysql-database
So this is the table from where I'm trying to fetch data:
CREATE TABLE IF NOT EXISTS `pfc_db`.`capas` (
`id` VARCHAR(10) NOT NULL ,
`nombre` VARCHAR(50) NOT NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
This is the fragment of the php script where the query is performed:
$query = "select * from CAPAS";
$sql=mysql_query($query);
if (!$sql) {
die("The query ($query) could not be executed in the BD: " . mysql_error());
}
while( $row=mysql_fetch_array($sql)){
$output[]=$row;
if (isset($output)){
echo "yes ";
echo $output[0]['nombre'];
}
else{echo "no";}
}
print(json_encode($output));
mysql_close();
It works perfectly on the browser.
This is the android code:
package com.example.androidconn;
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;
import android.widget.LinearLayout;
import android.widget.TextView;
public class AndroidConnection extends Activity {
/** Called when the activity is first created. */
TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create a crude view - this should really be set via the layout resources
// but since its an example saves declaring them in the XML.
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
// Set the text and call the connect function.
txt.setText("Connecting...");
//call the method to run the data retreival
txt.setText(getServerData(KEY_121));
}
public static final String KEY_121 = "http://10.0.2.2/api/prueba.php"; //i use my real ip here
private String getServerData(String returnString) {
InputStream is = null;
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("nombre","Escuelas"));
//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.getString("id")+
", nombre: "+json_data.getString("nombre")
);
//Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}
}
And finally this is the logcat:
D/AndroidRuntime( 313): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
D/AndroidRuntime( 313): CheckJNI is ON
D/AndroidRuntime( 313): --- registering native functions ---
I/ActivityManager( 58): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.example.androidconn/.AndroidConnection }
D/AndroidRuntime( 313): Shutting down VM
D/dalvikvm( 313): Debugger has detached; object registry had 1 entries
I/AndroidRuntime( 313): NOTE: attach of thread 'Binder Thread #3' failed
E/log_tag ( 281): Error parsing data org.json.JSONException: Value yes of type java.lang.String cannot be converted to JSONArray
I/ActivityManager( 58): Displayed activity com.example.androidconn/.AndroidConnection: 1636 ms (total 1636 ms)
I've been reading the comments on the tutorial so that maybe someone had the same error but I didn't find it, which is a bit weird.
I checked similar posts here, but they didn't help. If this question is repeated please point me to the answer, and if it's not, any help would be appreciated!
I think your 'echo "yes " output is getting read before your print(json_encode($output)); output, then the Android JSON parser sees this:
yes
where it is expecting JSON, hence the error:
Value yes of type java.lang.String cannot be converted to JSONArray
Drop the echo debugging statements from your PHP and leave your while loop as just this:
while( $row=mysql_fetch_array($sql)){
$output[]=$row;
}
That should get you some valid JSON output at least.
The error is caused by this line:
JSONArray jArray = new JSONArray(result);
This happens because the data contained in result doesn't represent a JSON array. You should print the data in result to the log and see what is actually returned by the server.