2013-11-27 2 views
0

У меня небольшая проблема с моим кодом, и я не могу найти почему. Я получаю данные анализа ошибок для моего значения электронной почты. Точная ошибка:Ошибка JSON Parser android app

Error parsing data org.json.JSONException: Value Mail of type java.lang.String cannot be converted to JSONObject.

Это происходит после того, как в Log.d (запрос !, запуск)

Вот код.

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; 

    } 
} 

Спасибо за любую помощь.

[Edit] Вот мой веб-сервис:

<?php 
    try { 

     $to = $_POST['emailForgot']; 
     $subject = "Test mail"; 
     $message = "Hello! This is a simple email message."; 
     $from = "[email protected]"; 
     $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] я получаю: почта посланный. {«success»: 0, «message»: «Ошибка базы данных2. Попробуйте снова!»} Проблема в моем запросе, я думаю? Arnaud

+0

just chk weather ваша электронная почта json значение для объекта json –

+0

Попробуйте распечатать, какой ответ вы получили от HTTP-запроса. // Преобразуем данные строкового строба в фактическую строку. json = sb.toString(); '(при условии, что ответ является успешным). Еще раз проверьте ваш логарифм, получаете ли вы распечатки ошибок или нет – Rajeev

+0

результат 'jsonParser.makeHttpRequest ( REGISTER_URL,« POST », params)' не является 'JSONObject'.post ответ или проверить, является ли это' JSONArray' или нет –

ответ

0

Со стороны сервера, вам нужно отправить

{"success":0,"message":"Database Error2. Please Try Again !"}

вместо

Mail Sent. {"success":0,"message":"Database Error2. Please Try Again !"}

+0

Что за задница ****. Большое вам спасибо, было так просто! У меня все еще есть ошибка базы данных2, возможно, из-за моего запроса? Вы видите что-то не так? – ArnaudT

+0

@ArnaudT: посмотрите на значение, которое вы сохраняете в переменной message.may из-за ошибки в самом запросе. –

0

Я хотел высказать некоторые замечания, но я должен был иметь в списке 50 репутации !!! поэтому я должен дать свой ответ здесь ... У меня была такая же проблема с объектом json. используйте метод «GET» вместо «POST». попробовать ...

ИСПОЛЬЗОВАТЬ 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; 
} 
}