Fetching data from a url in android - android

I'm new to android. My applcation will query to a url and will receive the json response.
But I am unable to fetch the data from the url. I am behind the proxy server ..so have updated the APN settings in the emulator and the built-in browser working fine.
I am using the following code for getting the data...:
package com.android.urlfetch;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
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 android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
public class UrlfetchActivity extends Activity {
Button but1;
String result ;
private TextView text;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
result = getStringContent("http://www.google.com");
}catch (Exception e) {
// TODO: handle exception
result = "Error";
}
text = (TextView)findViewById(R.id.text);
text.setText(result);
}
url=http://voxpopis.com");
public static String getStringContent(String uri) throws Exception {
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(uri));
HttpResponse response = client.execute(request);
InputStream ips = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader (ips,"UTF-8"));
StringBuilder sb = new StringBuilder();
String s;
while(true )
{
s = buf.readLine();
if(s==null || s.length()==0)
break;
sb.append(s);
}
buf.close();
ips.close();
return sb.toString();
}
finally {
}
}
}
I tried to get the anser in stack overflow's similar questions but dint get any answer. Any help will be appreciated.
My logcat response is :
06-30 15:14:08.820: WARN/InputManagerService(58): Got RemoteException sending setActive(false) notification to pid 601 uid 10037
06-30 15:14:10.800: WARN/PackageManager(58): Code path for pkg : com.android.urlfetch changing from /data/app/com.android.urlfetch-1.apk to /data/app/com.android.urlfetch-2.apk
06-30 15:14:10.800: WARN/PackageManager(58): Resource path for pkg : com.android.urlfetch changing from /data/app/com.android.urlfetch-1.apk to /data/app/com.android.urlfetch-2.apk
06-30 15:14:12.250: WARN/RecognitionManagerService(58): no available voice recognition services found
06-30 15:14:25.629: WARN/ActivityManager(58): Launch timeout has expired, giving up wake lock!
06-30 15:14:26.257: WARN/ActivityManager(58): Activity idle timeout for HistoryRecord{44fd4af8 com.android.urlfetch/.UrlfetchActivity}
06-30 15:14:36.911: WARN/IInputConnectionWrapper(539): showStatusIcon on inactive InputConnection
This code is working fine in direct connection ....but I am in a proxy network ...its not working in proxy network.What settings I should do to work in a proxy net?

For fetching the data from the web very comfortably you can use Jsoup.To see how to work with this in android with the emulator click here

Related

Connection Refused for Android Device Web Service SYMFONY 3

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.

Getting the response code 200 while sending message to gcm server but the result displays error

I have created the application server that sends the message to the gcm server via http post. After executing the code i get the response code of 200 but the result displayed is Error=MissingRegistration .
I am not able to understand the that why is the registration id missing. I have successfully obtained the registration id of the emulator by creating google account on it. I have verified my project id and the keys and have also used gcm-server.jar to create server. I have also tried using server key instead of browser key but still getting the same result.
Here is the code of my application server that sends the message through http post to gcm server.
package com.example.gcmserver;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
public class Server {
public static void main(String[] args) throws IOException {
DefaultHttpClient client = new DefaultHttpClient();
client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("username", "password"));
client.addRequestInterceptor(new HttpRequestInterceptor() {
#Override
public void process(HttpRequest arg0, HttpContext context)
throws HttpException, IOException {
// TODO Auto-generated method stub
AuthState state = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
if (state.getAuthScheme() == null) {
BasicScheme scheme = new BasicScheme();
CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
Credentials credentials = credentialsProvider.getCredentials(AuthScope.ANY);
if (credentials == null) {
throw new HttpException();
}
state.setAuthScope(AuthScope.ANY);
state.setAuthScheme(scheme);
state.setCredentials(credentials);
}}
}, 0);
HttpPost httppost = new HttpPost("https://android.googleapis.com/gcm/send");
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("data.registration id","APA91bERSCmbVV-diaS7OkA6nQlatuq1e8whUhjN54WcsfasiY3PSlby2_DtSq7Gjs_rXcOuUPTj8obnvnD55VbXJiWvWgXGj71oRFw_0yP4uz9JGDTax5dY-DKhnk6tK2gEFy50bDuKebQoRnUo9CYfSSW3AAtqV4tJDKv4GYwtUI0vIUliSJM"));
urlParameters.add(new BasicNameValuePair("data.title", "e-pass application"));
urlParameters.add(new BasicNameValuePair("data.message", "Your code is 13133"));
httppost.setHeader("Authorization",
"key=mybrowserkey");
httppost.setHeader("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
httppost.setHeader("Sender_ID", "myprojectid");
httppost.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8"));
HttpResponse response = client.execute(httppost);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
System.out.println("Getting the contents of the message");
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println("the result is:"+result);
}
}
I have referred to this link to create the server:
Trying to HTTP-POST to GCM from Java
Thanks a lot in advance for the help.
No need to prefix registration ID with "data.". The key-value pair should be: registration_ids, array containing the registration ID

POST data to login a https webpage using httpclient

This is what i basically how my app function.
this is an app to login to my university website and view student detail.
username and password will post to the login url.
after successful login, i will able to view the student detail in the webView.
I having some problem with my code. i insert the correct username and id but it failed to post the data. i tried some different method but it still not working. Can i know why?
package com.project;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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 android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class AndroidLogin extends Activity implements OnClickListener {
Button ok,back,exit;
TextView result;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Login button clicked
ok = (Button)findViewById(R.id.btn_login);
ok.setOnClickListener(this);
result = (TextView)findViewById(R.id.lbl_result);
}
public void postLoginData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
/* returns true if username and password is correct */
HttpPost httppost = new HttpPost("https://icems.mmu.edu.my/sic/vlogin.jsp");
try {
// Add user name and password
EditText uname = (EditText)findViewById(R.id.txt_username);
String username = uname.getText().toString();
EditText pword = (EditText)findViewById(R.id.txt_password);
String password = pword.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("form_loginUsername", username));
nameValuePairs.add(new BasicNameValuePair("login-password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("MMU", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent()).toString();
Log.w("MMU", str);
if(str.toString().equalsIgnoreCase("true"))
{
Log.w("MMU", "Login success");
}else
{
Log.w("MMU", "Login fail");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
#Override
public void onClick(View view) {
if(view == ok){
postLoginData();
WebView AchievementWeb = (WebView) findViewById(R.id.webViewAchievement);
AchievementWeb.loadUrl("https://icems.mmu.edu.my/sic/vaas/vaas_main.jsp");
}
}
}
This is the logcat
02 03:38:11.502: D/dalvikvm(800): GC_FOR_ALLOC freed 86K, 8% free 2934K/3180K, paused 130ms, total 133ms
01-02 03:38:12.062: D/(800): HostConnection::get() New Host Connection established 0x2a207598, tid 800
01-02 03:38:13.202: E/cutils-trace(800): Error opening trace file: No such file or directory (2)
01-02 03:38:13.582: D/TilesManager(800): Starting TG #0, 0x2a2ea4c0
01-02 03:38:39.863: D/InputEventConsistencyVerifier(800): KeyEvent: ACTION_UP but key was not down.
01-02 03:38:39.863: D/InputEventConsistencyVerifier(800): in android.widget.EditText{417107b8 VFED..CL .F....I. 102,114-252,162 #7f050004 app:id/txt_password}
01-02 03:38:39.863: D/InputEventConsistencyVerifier(800): 0: sent at 172536000000, KeyEvent { action=ACTION_UP, keyCode=KEYCODE_TAB, scanCode=15, metaState=0, flags=0x8, repeatCount=0, eventTime=172536, downTime=172448, deviceId=0, source=0x101 }
01-02 03:38:43.723: W/MMU(800): Execute HTTP Post Request
01-02 03:38:44.943: D/dalvikvm(800): GC_FOR_ALLOC freed 339K, 14% free 3108K/3608K, paused 39ms, total 42ms
01-02 03:38:45.163: W/MMU(800): <HTML><HEAD><TITLE>500 Internal Server Error</TITLE></HEAD><BODY><H1>500 Internal Server Error</H1><PRE>java.lang.NullPointerException<br></PRE></BODY></HTML>
01-02 03:38:45.163: W/MMU(800): Login fail
01-02 03:38:46.123: E/chromium_net(800): external/chromium/net/disk_cache/block_files.cc:81: [0102/033846:ERROR:block_files.cc(81)] Failing CreateMapBlock
01-02 03:38:46.132: E/chromium_net(800): external/chromium/net/disk_cache/entry_impl.cc:904: [0102/033846:ERROR:entry_impl.cc(904)] Failed to save user data
01-02 03:38:46.483: E/chromium_net(800): external/chromium/net/disk_cache/rankings.cc:762: [0102/033846:ERROR:rankings.cc(762)] Inconsistent LRU.
01-02 03:38:46.483: E/chromium_net(800): external/chromium/net/disk_cache/backend_impl.cc:1107: [0102/033846:ERROR:backend_impl.cc(1107)] Critical error found -8
01-02 03:38:46.483: W/chromium_net(800): external/chromium/net/disk_cache/storage_block-inl.h:119: [0102/033846:WARNING:storage_block-inl.h(119)] Failed data load.
01-02 03:38:46.513: W/chromium_net(800): external/chromium/net/disk_cache/storage_block-inl.h:119: [0102/033846:WARNING:storage_block-inl.h(119)] Failed data load.
01-02 03:38:46.533: W/chromium_net(800): external/chromium/net/disk_cache/storage_block-inl.h:119: [0102/033846:WARNING:storage_block-inl.h(119)] Failed data load.
01-02 03:38:46.553: D/chromium(800): Unknown chromium error: -401
You should post your error message to solve your problem. But i think you get a "NetworkOnMainThreadException" because you are trying to perform a network operation on your applications main thread. You can use Async Task.
You can check this to solve your problem.
How to fix android.os.NetworkOnMainThreadException?
If you get a different error please post error message.
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"enterwebsite");
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
// httppost.setHeader("Content-Type",
// "application/x-www-form-urlencoded");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("oauth_uid", oauth_uid));
nameValuePairs.add(new BasicNameValuePair("group_id", group_id));
nameValuePairs.add(new BasicNameValuePair("user_id", user_id));
HttpResponse mresponce;
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
mresponce = client.execute(httppost);
HttpEntity mentity = mresponce.getEntity();
mstream = mentity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
mstream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
String json = sb.toString();
Log.v("JOIN", json);
mList = new ArrayList<GetterSetteList>();
Object obj = new JSONTokener(json).nextValue();
if (obj instanceof JSONObject) {
JSONObject objs = new JSONObject(json);
messagex = (String) objs.opt("message");
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.v("ERROR", "API_JoinGroup" + e.toString());
flag = 1;
e.printStackTrace();
Log.v("JOIN", e.toString());
}
As others have mentioned you should wrap your call to "postLoginData()" in a asynctask otherwise this call will give you a NetworkOnMainThreadException". However from the logs you pasted I see this being printed.
> 01-02 03:38:45.163: W/MMU(800): <HTML><HEAD><TITLE>500 Internal Server
> Error</TITLE></HEAD><BODY><H1>500 Internal Server
> Error</H1><PRE>java.lang.NullPointerException<br></PRE></BODY></HTML>
Are you sure the URL that you are using "https://icems.mmu.edu.my/sic/vlogin.jsp" and the query-params "form_loginUserName" and "login-password" correct?
Does it work from a normal POST client or anywhere else?

Unable to find com.google.api.client.htpp.javanet.NetHttpTransport in Android Application

I am trying to implement http://codify.freebaseapps.com/?request=https%3A%2F%2Fwww.googleapis.com%2Ffreebase%2Fv1%2Fsearch%3Fquery%3DBlue%2BBottle&title=Simple%20Search inside an android application. I have the correct api key installed and matched to the google api service and have imported the appropriate jar files under Referenced Libraries.
My code however keeps throwing a could not find class - 'com.google.api.client.http.javanet.NetHttpTransport' error every time it is run on the emulator. Any suggestions or feedback ?
You must add library into project.
right click project
Properties
Java Build Path
Add External JARs
please read this post: Android and Google client API NetHttptransport Class not found
When I built the Codify app that you linked to I didn't test it against Android so there may be an easier way to do it in Android.
Here's another way to do it using Apache HttpClient and json.org which are included in the Android SDK.
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
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 org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
public class FreebaseSearchTask extends AsyncTask<String, Void, JSONObject> {
protected JSONObject getJsonContentFromEntity(HttpEntity entity)
throws IllegalStateException, IOException, JSONException {
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));
}
JSONObject jObject = new JSONObject(out.toString());
return jObject;
}
#Override
protected JSONObject doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
String query = params[0];
JSONObject result = null;
try {
HttpGet httpGet = new HttpGet("https://www.googleapis.com/freebase/v1/search?query=" + URLEncoder.encode(query, "utf-8"));
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
result = getJsonContentFromEntity(entity);
} catch (Exception e) {
Log.e("error", e.getLocalizedMessage());
}
return result;
}
protected void onPostExecute(JSONObject result) {
doSomething(result);
}
}

Can't find the JSON parsing error that the logcat is complaining about

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.

Categories

Resources