Android studio http response returns caught exception - java

I want to get response from url but it returns caught exception.
In detail, I created activity which will get two input variable emailid and password.
There is one login button, clicking on the login button will invoke the getquizzes function.
Here is the code that I am using:
public void getquizzes(View view) {
emailid = (EditText) findViewById(R.id.email);
ipassword = (EditText) findViewById(R.id.password);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.TOP | Gravity.LEFT, 10, 10);
// Toast toast = Toast.makeText(context, text, duration);
// toast.makeText(LoginActivity.this, emailid.getText(), toast.LENGTH_SHORT).show();
String rurl = "http://www.savsoftquiz.com/quizdemo/index.php/verifylogin/api_login/" + emailid.getText() + "/" + ipassword.getText();
Toast.makeText(this, verifylogin(rurl), Toast.LENGTH_LONG).show();
}
private String verifylogin(String rurl){
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(rurl);
try {
HttpResponse response = httpclient.execute(httpget);
if(response != null) {
String line = "";
InputStream inputstream = response.getEntity().getContent();
line = convertStreamToString(inputstream);
return line;
} else {
return "Unable to complete your request";
}
} catch (ClientProtocolException e) {
return "Caught ClientProtocolException";
} catch (IOException e) {
return "Caught IOException";
} catch (Exception e) {
return "Caught Exception";
}
}
private String convertStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (Exception e) {
Toast.makeText(this, "Stream Exception", Toast.LENGTH_SHORT).show();
}
return total.toString();
}

Use this format. Also store your edit text value in string variable.
class Login extends AsyncTask<String, String, String> {
String email ;
String pass ;
JSONObject json=null;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
List<NameValuePair> parametres = new ArrayList<NameValuePair>();
// getting JSON string from URL
parametres.add(new BasicNameValuePair("email", email));
parametres.add(new BasicNameValuePair("password", pass));
JSONObject json = jsonParser.makeHttpRequest(url,
"GET", parametres);
try {
// Checking for SUCCESS TAG
int success = json.getInt(KEY_SUCCESS);
if (success == 1) {
//yourcode
}
return json.getString(TAG_MESSAGE);
} else {
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
}
json parser
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// 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();
System.out.println(is + "post");
}else if(method == "GET"){
System.out.println("1");
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
System.out.println("2");
String paramString = URLEncodedUtils.format(params, "utf-8");
System.out.println("3");
url += "?" + paramString;
System.out.println("4");
HttpGet httpGet = new HttpGet(url);
System.out.println("5");
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("6");
HttpEntity httpEntity = httpResponse.getEntity();
System.out.println("7");
is = httpEntity.getContent();
System.out.println(is + "get");
}
} 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.i("TagCovertS", "["+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;
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
/**
* Getting XML DOM element
* #param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/** Getting node value
* #param elem element
*/
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}

Related

How To Receive data from website using JSON for android?

I created a class for my android application that connects to mysql database using json.. note that the php code getNews.php is tested and it responds with the required data in json format properly. And note that i only want to get an array containing the data with this class ArrayReceiver.java ... it isn't working though... can anyone check the code please.
ArrayReceiver.java
package com.example.batoul.uptodate4;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ArrayReceiver extends AsyncTask<String, Integer, String> {
List<Article> a=new ArrayList<Article>();
String url="192.168.11.8/utd/getNews.php";
Boolean error = false;
private ProgressDialog pDialog;
Boolean success = false;
String msg = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
public List<Article> getA() {
return a;
}
#Override
protected String doInBackground(String... arg) {
publishProgress(2);
// agendaArrayList = new ArrayList<>();
List<NameValuePair> params = new ArrayList<>();
try {
// params.add(new BasicNameValuePair("notActivated", "false"));
ServiceHandler serviceClient = new ServiceHandler();
String json = serviceClient.makeServiceCall(url,
ServiceHandler.POST, params);
// Log.e("aaa ", "> " + ServiceHandler.url);
// Log.d("Create Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
//int catObj22 = jsonObj.getInt("success");
// if (catObj22 == 1) {
JSONArray titles = jsonObj.getJSONArray("title");
for (int i = 0; i < titles.length(); i++) {
String catObj = (String) titles.get(i);
Article obj = new Article(0,"");
obj.setTitle(catObj);
a.add(obj);
}
success = true;
} else {
success = false;
}
// }
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
} catch (Exception e) {
error = true;
return null;
}
Log.e("aaa ", " success");
return "success";
}
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// if (pDialog.isShowing()) {
// pDialog.dismiss();
// }
// Toast.makeText(TravelsActivity.this, s, Toast.LENGTH_LONG).show();
if (success) {
// for (int i = 0; i < travelsArr.size(); i++) {
// new getPic().execute("" + i);
// }
//ListAdapterClass adapter = new ListAdapterClass( ArticleArr,view.getContext());
//SubjectListView.setAdapter(adapter);
}
}
}
ServiceHandler.java
package com.example.batoul.uptodate4;
import android.util.Log;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
public class ServiceHandler {
static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public static String url ,u;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
this.url =url +"?" + paramString;
}
HttpGet httpGet = new HttpGet(this.url);
httpResponse = httpClient.execute(httpGet);
}
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, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
response = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error: " + e.toString());
}
return response;
}
}
getNews.php :
<?php
$response = array();
$db = mysqli_connect('localhost', 'root', '', 'utd1_db');
$query = " SELECT * FROM `article`";// need change
$result = $db->query($query);
if ($result->num_rows > 0) {
$title = array();
while ($row = $result->fetch_assoc()) {
array_push($title, $row["title"]);// need change
}
$response["success"] = 1;
$response["title"] = $title;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Nothing found";
echo json_encode($response);
}
?>

JSONParser from androidhive tutorial, NoSuchMethodError in DefaultHttpClient

I'm following this tutorial, and getting this error:
Caused by: java.lang.NoSuchMethodError: No virtual method execute(Lorg/apache/http/client/methods/HttpUriRequest;)Lorg/apache/http/client/methods/CloseableHttpResponse; in class Lorg/apache/http/impl/client/DefaultHttpClient; or its super classes (declaration of 'org.apache.http.impl.client.DefaultHttpClient' appears in /system/framework/ext.jar)
at info.androidhive.materialtabs.adpater.JSONParser.makeHttpRequest(JSONParser.java:52)
at info.androidhive.materialtabs.UserFunctions.loginUser(UserFunctions.java:37)
at info.androidhive.materialtabs.activity.MainActivity$Login.doInBackground(MainActivity.java:551)
at info.androidhive.materialtabs.activity.MainActivity$Login.doInBackground(MainActivity.java:519)
Here is the JSONParser class that I'm using:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// 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();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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();
} 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;
}
}
DefaultHttpClient was deprecated in api level 22, and removed in api level 23.
The documentation was even removed from the Android documentation, here is the link to where the documentation was previously, and you can see where it re-directs to:
http://developer.android.com/reference/org/apache/http/impl/client/DefaultHttpClient.html
Quote just in case the re-direct changes:
Android 6.0 release removes support for the Apache HTTP client. If
your app is using this client and targets Android 2.3 (API level 9) or
higher, use the HttpURLConnection class instead. This API is more
efficient because it reduces network use through transparent
compression and response caching, and minimizes power consumption.
I created an updated version of the JSONParser class that you're using, here it is:
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
public class JSONParser {
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
public JSONObject makeHttpRequest(String url, String method,
HashMap<String, String> params) {
sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
if (method.equals("POST")) {
// request method is POST
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", charset);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
paramsString = sbParams.toString();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
}
Example AsyncTask for Post:
class PostAsync extends AsyncTask<String, String, JSONObject> {
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String LOGIN_URL = "http://www.example.com/testPost.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
try {
HashMap<String, String> params = new HashMap<>();
params.put("name", args[0]);
params.put("password", args[1]);
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
int success = 0;
String message = "";
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
if (json != null) {
Toast.makeText(MainActivity.this, json.toString(),
Toast.LENGTH_LONG).show();
try {
success = json.getInt(TAG_SUCCESS);
message = json.getString(TAG_MESSAGE);
} catch (JSONException e) {
e.printStackTrace();
}
}
if (success == 1) {
Log.d("Success!", message);
}else{
Log.d("Failure", message);
}
}
}
Example AsyncTask for Get:
class GetAsync extends AsyncTask<String, String, JSONObject> {
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String LOGIN_URL = "http://www.example.com/testGet.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
try {
HashMap<String, String> params = new HashMap<>();
params.put("name", args[0]);
params.put("password", args[1]);
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "GET", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
int success = 0;
String message = "";
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
if (json != null) {
Toast.makeText(MainActivity.this, json.toString(),
Toast.LENGTH_LONG).show();
try {
success = json.getInt(TAG_SUCCESS);
message = json.getString(TAG_MESSAGE);
} catch (JSONException e) {
e.printStackTrace();
}
}
if (success == 1) {
Log.d("Success!", message);
}else{
Log.d("Failure", message);
}
}
}
For more details, here's my blog post about this code: http://danielnugent.blogspot.com/2015/06/updated-jsonparser-with.html

json post request java not send data to server

I try to Create a class which is unique to all json request and try to send json request from it to server. It takes only request url and json StringEntity only. Request send but problem is when i try to access data from server can't find that post data.
JSONClinet.java
package info.itranfuzz.service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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 android.util.Log;
public class JSONClient {
private final HttpClient httpClient;
private HttpPost httpPost;
private HttpResponse httpResponse;
public JSONClient() {
httpClient = new DefaultHttpClient();
}
public String doPost(String url, StringEntity se) {
InputStream inputStream = null;
String result = "";
httpPost = new HttpPost(url);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
httpPost.setEntity(se);
try {
httpResponse = httpClient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
Server accss code is here.
There email and lat and lng to send to server.
<?php
//set content type to json
header('Content-type: application/json');
$email = $this->input->post("email");
$lat = $this->input->post('lat');
$lng = $this->input->post('lng');
$status = array("STATUS"=>"false");
if($this->donor->updateLocationByEmail($email,$lat,$lng)){
$status = array("STATUS"=>"true");
}
array_push($status, array("email"=>$email,"lat"=>$lat,"lng"=>$lng));
echo json_encode($status);
?>
My calling method is this
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
JSONClient jClient = new JSONClient();
Location loc = new Location(LocationService.this);
LatLng p = loc.getLocation();
if (p != null) {
String json = "";
try {
JSONObject jsonObject = new JSONObject();
// jsonObject.accumulate("email", WebLoad.STORE.getEmail());
jsonObject.put("email", "b#gmail.com");
jsonObject.put("lat", p.getLat());
jsonObject.put("lng", p.getLng());
json = jsonObject.toString();
System.out.println(jClient.doPost(WebLoad.ROOTURL
+ "/donor_controller/updatelocation", new StringEntity(
json)));
} catch (JSONException e) {
System.out.println("Json exception occur");
} catch (UnsupportedEncodingException e) {
System.out.println("Unsupported ecodding exception occur");
}
}
return super.onStartCommand(intent, flags, startId);
}
//import packages
public class DBConnection {
static InputStream is = null;
static JSONObject jsonObject = null;
static String json = "";
// This is a constructor of this class
public DBConnection() {
}
/*
* function get jsonObject from URL by making HTTP POST or GET method.
*/
public JSONObject createHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST and making default client.
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();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
} catch (ClientProtocolException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.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.w("Error" ,"My Error" + json);
} catch (Exception ex) {
Log.e("Buffer Error", "Error converting result " + ex.toString());
}
// try to parse the string to a JOSN object
try {
Log.w("sub",json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
jsonObject = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return new object
return jsonObject;
}
}
please , you try this manner to make request.
$email = $this->input->$_POST('email')
use this way any try to do . change post to $_POST['variable name']. as i tell this , you write to server side PHP. in PHP get and post method we access $_GET and $_POST.

Error JSON Parser android app

I have a small problem with my code and I can't find why. I get the error parsing data for my email value.
The exact error is :
Error parsing data org.json.JSONException: Value Mail of type java.lang.String cannot be converted to JSONObject.
It happens after having the Log.d(request!, starting)
Here are the code.
Activity.java:
package com.example.mysqltest;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class ForgotPassword extends Activity implements OnClickListener{
private EditText email;
private Button mForgotPassword;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php register script
private static final String REGISTER_URL = "test";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forgot_password);
email = (EditText)findViewById(R.id.emailforf);
mForgotPassword = (Button)findViewById(R.id.forgotPassword);
mForgotPassword.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new ForgotPass().execute();
}
class ForgotPass extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ForgotPassword.this);
pDialog.setMessage("Retrieving password...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String emails = email.getText().toString();
if (emails instanceof String){
Log.d("lol","ok");
}else{
Log.d("lol","not ok");
}
try {
// Building Parameters
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ForgotPassword.this);
String userpref = prefs.getString("username","arnaud");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("emailForgot", emails));
Log.d(userpref,"lol");
params.add(new BasicNameValuePair("username", userpref));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
REGISTER_URL, "POST", params);
// full json response
Log.d("Registering attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Registering Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(ForgotPassword.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
JSONParser.java :
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
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(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to 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 the JSON Object.
return jObj;
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// 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();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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();
} 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;
}
}
Thanks for any help.
[Edit] Here is my web service :
<?php
try {
$to = $_POST['emailForgot'];
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "track_my_mate#example.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
$randome = 'pierre';
$query = "UPDATE 'users' SET 'password' = ? WHERE 'id' = ? ";
//Again, we need to update our tokens with the actual data:
$query_params = array(
':pass' => $randome,
':user' => $_POST['username']
);
//time to run our query, and create the user
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one:
$response["success"] = 0;
$response["message"] = "Database Error2. Please Try Again!";
die(json_encode($response));
}
} catch (Exception $e) {
$response["success"] = 0;
$response["message"] = "Please Try Again!";
}
//If we have made it this far without dying, we have successfully added
//a new user to our database. We could do a few things here, such as
//redirect to the login page. Instead we are going to echo out some
//json data that will be read by the Android application, which will login
//the user (or redirect to a different activity, I'm not sure yet..)
$response["success"] = 1;
$response["message"] = "Password Successfully Changed!";
try {
echo json_encode($response);
} catch (Exception $e) {
echo ("pierre");
}
//for a php webservice you could do a simple redirect and die.
//header("Location: login.php");
//die("Redirecting to login.php");
//}
?>
[EDIT2] I get : Mail Sent. {"success":0,"message":"Database Error2. Please Try Again !"} The problem is in my query I guess?
Arnaud
From server side,
you need to send
{"success":0,"message":"Database Error2. Please Try Again !"}
instead of
Mail Sent. {"success":0,"message":"Database Error2. Please Try Again !"}
get JSONException: Value of type java.lang.String cannot be converted to JSONObject when parsing a JSON response
Likely that your web service is not returning correct JSON.
i wanted to put some comment but i should have at list 50 reputation!!! so i should give my answer here... i had same problem with json object. use "GET" method instead of "POST". try it...
USE THIS JSON PARSER
public class JSONParser extends Activity{
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// 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();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
Log.e("JSON PARSER", "GET OR POST");
Toast.makeText(getApplicationContext(), "Something is wrong with network!", Toast.LENGTH_LONG).show();
json="";
create_JSon_Object();
} catch (ClientProtocolException e) {
Toast.makeText(getApplicationContext(), "Something is wrong with network!", Toast.LENGTH_LONG).show();
Log.e("JSON PARSER", "GET OR POST");
json="";
return create_JSon_Object();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Something is wrong with network!", Toast.LENGTH_LONG).show();
Log.e("JSON PARSER IO ERROR", "GET OR POST");
json="";
return create_JSon_Object();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Something is wrong with network!", Toast.LENGTH_LONG).show();
Log.e("JSON PARSER Buffer Error", "Error converting result ");
json="";
return create_JSon_Object();
}
return create_JSon_Object();
}
private JSONObject create_JSon_Object() {
// try parse the string to a JSON object
try {
//jObj = new JSONObject(json);
jObj = new JSONObject(json);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Something is wrong with network!", Toast.LENGTH_LONG).show();
Log.e("JSON Parser", "Error parsing data " + e.toString());
return jObj;
}
// return JSON String
return jObj;
}
}

Json parse from URL

I am getting java.lang.NullPointerException when I run this. Does anyone know why this is happening and how I can fix it?
Please take a look at my code and let me know if you have any suggestions.
{"begin":[{"id":1,"name":"Andy","size":1}],"open":[{"id":1,"name":"Tom","size":2}]}
Fragment
public class MainFragment extends Fragment {
public MainFragment() {}
//URL to get JSON Array
private String url = "URL...";
//JSON Node Names
private static final String TAG_BEGIN = "begin";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_SIZE = "size";
JSONArray begin = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
new JSONParse().execute();
return rootView;
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(HomeActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
begin = json.getJSONArray(TAG_BEGIN);
JSONObject c = begin.getJSONObject(0);
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String size = c.getString(TAG_SIZE);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser
import android.util.Log;
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.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
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();
} 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;
}
}
Error:
E/JSON Parserīš• Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
FATAL EXCEPTION: main
java.lang.NullPointerException
at
...$MainFragment$JSONParse.onPostExecute(MainActivity.java:399)
at
...$MainFragment$JSONParse.onPostExecute(MainActivity.java:373)
Which is...
begin = json.getJSONArray(TAG_BEGIN);
and...
private class JSONParse extends AsyncTask<String, String, JSONObject> {
EDIT (Answer)
JSONParser
Inside of JSONParser I changed my code to this:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpUriRequest request = new HttpGet(url);
request.setHeader("Accept", "application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity httpEntity = response.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();
} 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;
}
}
Inside of onPostExecute
JSONArray begin = json.getJSONArray(TAG_BEGIN);
for (int i = 0; i < begin(); i++) {
try {
JSONObject b = = begin(i);
String id = b.getString(TAG_ID);
String name = b.getString(TAG_NAME);
String size = b.getString(TAG_SIZE);
} catch (JSONException e) {
e.printStackTrace();
}
}
First make sure your JSONObject is not null. Then slowly transverse line by line based off the type.
JSONArray begin = json.getJSONArray(TAG_BEGIN);
Then possibly do something like this?
for(int n = 0; n < begin.length(); n++)
{
JSONObject object = begin.getJSONObject(n);
// query through the array
String id = object.getString(TAG_ID);
String name = object.getString(TAG_NAME);
String size = object.getString(TAG_SIZE);
//Now do something with the strings
}
Of course you'd do the same thing with the TAG_OPEN. Let me know if this works, I'll gladly help as much as possible.
the error shows that the return string of you http request is not only the json data
something like <!DOCTYPE are includeed
please check you are request the right url, and the server handle the request correctly
you can use your browser visit the url you request and check the return result
I am not using a fragment but here is similar solution.
Change your url and key values for retrieving values from json. I didn't have your url so i used some other. Please check it out. Same concept except i am not using fragments but this json parsing code works just fine.
First of all, you have to deal with the network on main thread exception
Add:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
in your class,
and
ADD this to ManiFestFile:
<uses-permission android:name="android.permission.INTERNET"/>
MainActivity.Java
package com.example.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Making HTTP request
String url = "http://api.androidhive.info/contacts/";
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
JSONArray begin = json.getJSONArray("contacts");
JSONObject c = begin.getJSONObject(0);
// Storing JSON item in a Variable
String id = c.getString("id");
String name = c.getString("name");
String size = c.getString("email");
} catch (JSONException e) {
e.printStackTrace();
}
}
#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;
}
}
JSONParser.Java
package com.example.test;
import android.os.StrictMode;
import android.util.Log;
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.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
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();
} 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;
}
}

Categories

Resources