2013-11-27 42 views
0

我的代码有一个小问题,我无法找到原因。我得到了我的电子邮件值的错误解析数据。 确切的错误是:错误JSON解析器android应用程序

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; 

    } 
} 

感谢您的帮助。

[编辑]这里是我的web服务:

<?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”:“Database Error2。Please Try Again!”}问题出在我的查询中,我猜? 阿尔诺

+0

只是chk天气您的电子邮件是json对象的json值 –

+0

尝试打印您从HTTP请求收到的回复。 '//将字符串构建器数据转换为实际的字符串。 json = sb.toString();'(假设响应成功)。否则检查你的logcat是否得到错误打印 – 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

什么是屁股****。非常感谢你,太容易了!我仍然有一个数据库error2,可能是由于我的查询?你看到有什么问题吗? – ArnaudT

+0

@ArnaudT:看看你在消息变量中保存的值,可能是由于查询本身的错误。 –

0

我想提出一些意见,但我应该在名单50声誉!所以我应该在这里给我答案...我与json对象有同样的问题。使用“GET”方法而不是“POST”。试试吧......

使用本JSON分析器

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; 
} 
}