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
Related
Here is the answer I'm using How to implement Login with HttpURLConnection and PHP server in Android
Here is my JSONParser.java:
package com.example.android.simplejson;
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; // Connection
DataOutputStream wr; // Write
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("my_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
try {
urlObj = new URL("my_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("Response: ", "> " + line); //here you'll get the whole response
}
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;
}
}
Here is a snippet of my MainActivity.java:
class checkLogin extends AsyncTask<String, String, JSONObject> {
JSONParser jsonParser = new JSONParser();
private ProgressDialog pd;
private static final String LOGIN_URL = "my_url";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Attempting login...");
pd.setIndeterminate(false);
pd.setCancelable(true);
pd.show();
}
protected JSONObject doInBackground(String... params) {
try {
HashMap<String, String> credentials = new HashMap<>();
credentials.put("username", params[0]);
credentials.put("password", params[1]);
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", credentials);
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 (pd != null && pd.isShowing()) {
pd.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);
}
}
}
}
It gets a JSONArray from the server [{"AuthStatus":true,"AuthMessage":"This is my sample message","username":"username=&password="}]
My problem is the JSONArray can't be converted to JSONObject. So what can I change in my code to return the JSONArray as jObj? My ultimate goal is to set the text in my main activity as [{"AuthStatus":true,"AuthMessage":"This is my sample message","username":"username=&password="}].
Thanks!
You can't parse a JSON array as a JSON object. First you have to parse the payload as an array and then get the object from it.
public JSONObject makeHttpRequest(String url, String method,
HashMap<String, String> params) {
// ...
try {
JSONArray jArr = new JSONArray(result.toString());
jObj = jArr.getJSONObject(0);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
Refer the below exampe :
String str = {"xyz":[{"name":"apple","email_id":"apple#apple.com"}]};
JSONObject json = JSONObject.fromObject(str);
So essentially your response is in format of a JSONArray [{"AuthStatus":true,"AuthMessage":"This is my sample message","username":"username=&password="}]'
where it should have been something like
{"response": [{"AuthStatus":true,"AuthMessage":"This is my sample message","username":"username=&password="}]}
or simply
{"AuthStatus":true,"AuthMessage":"This is my sample message","username":"username=&password="}
depending on your preference. If you are always going to return a single JSONObject (probably as this is a login service response) there is no need to use the square braces which makes it a JSONArray.
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));
}
}
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.
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;
}
}
In order to avoid executing the http relating things in the UI thread, i migrated my code inside asynctask, before that, it was working fine on versions before 3.0 -- however, after literally copy pasting the code inside asynctask, it started to giving the invalid index, size is 0 exception. Whenever I need to use the method I am applying the call --
new dataRetrievalViaAsyncTask().execute(url, null, null); --
Whats wrong down there ?
class dataRetrievalViaAsyncTask extends AsyncTask<String, Void, Void>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(String... f_url)
{
Log.i("tag", "inside doInBackground");
String url2 = f_url[0];
Log.i("tag", url2);
HttpClient httpclient = new DefaultHttpClient();
Log.i("tag", "done : HttpClient httpclient = new DefaultHttpClient();");
HttpPost httppost = new HttpPost(url2);
Log.i("tag", "done : HttpPost httppost = new HttpPost(url);");
try
{
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.i("tag", "done : httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));");
HttpResponse response = httpclient.execute(httppost);
Log.i("tag", "done : HttpResponse response = httpclient.execute(httppost);");
HttpEntity entity = response.getEntity();
Log.i("tag", "done : HttpEntity entity = response.getEntity();");
is = entity.getContent();
Log.i("tag", "after : is = entity.getContent();");
} catch (Exception e)
{
Log.e("log_tag", "Error in http connection", e);
}
// convert response to string
return null;
}
protected void onPostExecute()
{
try
{
Log.i("tag","before : BufferedReader reader = new BufferedReader(new Inp");
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e)
{
Log.e("log_tag", "Error in http connection", e);
}
try
{
Log.i("tag", "before : jsons ");
jArray = new JSONArray(result);
JSONObject json_data = null;
Log.i("tag", Integer.toString(jArray.length()));
for (int i = 0; i < jArray.length(); i++)
{
json_data = jArray.getJSONObject(i);
uid = json_data.getInt("uid");
item1= json_data.getString("item1");
item2 = json_data.getString("item2");
item3 = json_data.getString("item3");
item4 = json_data.getString("item4");
item5 = json_data.getString("item5");
item6 = json_data.getString("item6");
favorited = json_data.getString("favorited");
currentList.add(new itemClass(uid, item1 item2)); //there is a constructor for this in the itemClass
itemClass toSendToOffline = new itemsClass(uid, item1, item2, item3, item4, item5, item6, favorited);
myDBHelper.insertFromOnlineToDBtoSendToOffline();
}
} catch (JSONException e1)
{
Toast.makeText(getBaseContext(), "Not Found", Toast.LENGTH_LONG).show();
} catch (ParseException e1)
{
e1.printStackTrace();
}
super.onPostExecute(null);
}
}
(mainly the code is stopping at --
HttpResponse response = httpclient.execute(httppost);
I can not see nameValuePairs variable initialized anywhere, which is actually causing problem.
class dataRetrievalViaAsyncTask extends AsyncTask<Void, Void, String>
{
String URL = "";
public dataRetrievalViaAsyncTask( String url )
{
URL = url;
}
#Override
protected void onPreExecute()
{
}
#Override
protected String doInBackground(Void... f_url)
{
String result="";
try
{
result=fetchdataFromServer(URL);
}
catch (JSONException e)
{
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result)
{
// See your results as string //result
}
public JSONObject getJsonObjectToRequestToServer(String plid) throws JSONException
{
JSONObject parms = new JSONObject();
parms.put("user_id", "");
parms.put("app_key", "xyz");
parms.put("secret", "abc");
parms.put("token", "");
parms.put("playurl", "1");
parms.put("mode", "playlistdetail");
parms.put("playlist_id", plid);
return parms;
}
public String fetchdataFromServer(String url) throws JSONException
{
String stringresponce = null;
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
JSONObject parms = getJsonObjectToRequestToServer("1");
StringEntity se;
se = new StringEntity(parms.toString());
httpPost.setEntity(se);
httpPost.setHeader("Content-type", "application/json");
#SuppressWarnings("rawtypes")
ResponseHandler responseHandler = new BasicResponseHandler();
stringresponce = httpClient.execute(httpPost, responseHandler);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return stringresponce;
}
}
put this code in your code and pass arguments ass you need this is the way how i request to server and get json response as string from result variable pass arguments to your url as i passed by making json object then convert them to string
then execute like this............
dataRetrievalViaAsyncTask asyncTask=new dataRetrievalViaAsyncTask(Yoururl);
asyncTask.execute();
hope this will help if you have some issues please post here thanks......