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.
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 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.
Recently i am developing Android applications
what i wanted to do is consume a web services
from .net WCF into my application
Here is my Client Code
import java.io.InputStream;<br>
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;<br>
import org.apache.http.HttpResponse;<br>
import org.apache.http.client.methods.HttpGet;<br>
import org.apache.http.impl.client.DefaultHttpClient;<br>
import org.json.JSONObject;<br>
import android.R.string;<br>
import android.os.Bundle;<br>
import android.app.Activity;<br>
import android.view.Menu;<br>
import android.view.View;<br>
import android.widget.TextView;<br>
public class MyPamIndex extends Activity {
private final static String SERVICE_URI = "http://172.30.2.95:9000/JSON/MyPam.svc";
private TextView NabVals;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_pam_index);
NabVals = (TextView)findViewById(R.id.textView2);
}
public void OnRefreshClick(View button)
{
try {
// Send GET request to <service>/GetVehicle/<plate>
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(SERVICE_URI + "/ProductID/" + "1");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
// Read response data into buffer
char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
JSONObject vehicle = new JSONObject(new String(buffer));
NabVals.setText(vehicle.getString("NabValue"));
// Populate text fields
} catch (Exception e) {
e.printStackTrace();
}
}
when i run the apps it have an error
in
HttpResponse response = httpClient.execute(request);
i have search the entire forum but found nothing
i already add my android manifest file but still does not working
please help me
this is my Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.core.mypam"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="anroid.permission.INTERNET"></uses-permission>
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.core.mypam.MyPamIndex"
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>
"http://172.30.2.95:9000" is not my machine IP but its located on other PC within same LAN
Please help me
You're making a network request on the UI thread. That is no longer allowed and, and will raise an exception. You need to move your code into an AsyncTask. Google NetworkOnMain for a plethora of examples.
I'm very inexperienced when it comes to developing Android Applications and I cannot code a lot of Java. I have been google'ing around for around 2 hours now, trying many different examples of how to send POST data to a HTTP web server page and getting the outputted data, but none work. I am using the Android SDK Version 4.0 (API 14), does anyone know how to do this? Just a simple post some data, and get the output.
Thanks.
EDIT: Here is my current code,
package me.babblebox.application;
import java.io.IOException;
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.view.View;
public class BabbleBoxActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void check_login() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://babblebox.me/android/test.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
public void check_login_button(View v) {
check_login();
}
}
manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="me.babblebox.application"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="14" /><application android:icon="#drawable/bb_launch_icon" android:label="#string/app_name" android:testOnly="false" android:name=".BabbleBox" android:enabled="true">
<activity android:label="#string/app_name" android:name=".BabbleBoxActivity">
<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" />
</manifest>
Button XML that calls the method:
<Button
android:id="#+id/Button_Login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:onClick="check_login_button"/>
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
Also you must add permissions to ApplicationManifest.xml to allow internet:
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>
EDIT:
Your problem is not in the POST code, but how you are calling the onClick method, try this to fix your problem:
public void buttonListener(View v) {
check_login();
}
And call make your layout XML look similar to this:
<Button
android:text="Calling From XML Layout"
android:id="#+id/Button04" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="buttonListener">
</Button>
You must add one parameter to Listener method that is the View.
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