Note that there are some explanatory texts on larger screens.

plurals
  1. POError JSON Parser android app
    text
    copied!<p>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 : </p> <p><code>Error parsing data org.json.JSONException: Value Mail of type java.lang.String cannot be converted to JSONObject.</code></p> <p>It happens after having the Log.d(request!, starting)</p> <p>Here are the code.</p> <p>Activity.java:</p> <pre><code>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&lt;String, String, String&gt; { @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&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;(); 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(); } } } } </code></pre> <p>JSONParser.java :</p> <pre><code>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&lt;NameValuePair&gt; 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; } } </code></pre> <p>Thanks for any help.</p> <p>[Edit] Here is my web service :</p> <pre><code>&lt;?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' =&gt; $randome, ':user' =&gt; $_POST['username'] ); //time to run our query, and create the user try { $stmt = $db-&gt;prepare($query); $result = $stmt-&gt;execute($query_params); } catch (PDOException $ex) { // For testing, you could use a die and message. //die("Failed to run query: " . $ex-&gt;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"); //} ?&gt; </code></pre> <p>[EDIT2] I get : Mail Sent. {"success":0,"message":"Database Error2. Please Try Again !"} The problem is in my query I guess? Arnaud</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload