2015-08-20 86 views
0

我正在开发一个使用php api和mysql的android注册和登录表单。我得到预期的JSON结果中的logcat但结果没有显示在我的app.Here是我的代码:JSonException:无法将类型java.lang.string的值转换为JSonObject

<?php 

/** 
* File to handle all API requests 
* Accepts GET and POST 
* 
* Each request will be identified by TAG 
* Response will be JSON data 

/** 
* check for POST request 
*/ 
if (isset($_POST['tag']) && $_POST['tag'] != '') { 
// get tag 
$tag = $_POST['tag']; 

// include db handler 
require_once 'include/DB_Functions.php'; 
$db = new DB_Functions(); 

// response Array 
$response = array("tag" => $tag, "error" => FALSE); 

// check for tag type 
if ($tag == 'login') { 
    // Request type is check Login 
    $email = $_POST['email']; 
    $password = $_POST['password']; 

    // check for user 
    $user = $db->getUserByEmailAndPassword($email, $password); 
    if ($user != false) { 
     // user found 
     $response["error"] = FALSE; 
     $response["uid"] = $user["unique_id"]; 
     $response["user"]["name"] = $user["name"]; 
     $response["user"]["email"] = $user["email"]; 
     $response["user"]["created_at"] = $user["created_at"]; 
     $response["user"]["updated_at"] = $user["updated_at"]; 
     echo json_encode($response); 
    } else { 
     // user not found 
     // echo json with error = 1 
     $response["error"] = TRUE; 
     $response["error_msg"] = "Incorrect email or password!"; 
     echo json_encode($response); 
    } 
} else if ($tag == 'register') { 
    // Request type is Register new user 
    $name = $_POST['name']; 
    $email = $_POST['email']; 
    $password = $_POST['password']; 

    // check if user is already existed 
    if ($db->isUserExisted($email)) { 
     // user is already existed - error response 
     $response["error"] = TRUE; 
     $response["error_msg"] = "User already existed"; 
     echo json_encode($response); 
    } else { 
     // store user 
     $user = $db->storeUser($name, $email, $password); 
     if ($user) { 
      // user stored successfully 
      $response["error"] = FALSE; 
      $response["uid"] = $user["unique_id"]; 
      $response["user"]["name"] = $user["name"]; 
      $response["user"]["email"] = $user["email"]; 
      $response["user"]["created_at"] = $user["created_at"]; 
      $response["user"]["updated_at"] = $user["updated_at"]; 
      echo json_encode($response); 
     } else { 
      // user failed to store 
      $response["error"] = TRUE; 
      $response["error_msg"] = "Error occured in Registartion"; 
      echo json_encode($response); 
     } 
    } 
    } else { 
    // user failed to store 
    $response["error"] = TRUE; 
    $response["error_msg"] = "Unknown 'tag' value.should be either'or; 
    echo json_encode($response); 
} 
} else { 
$response["error"] = TRUE; 
$response["error_msg"] = "Required parameter 'tag' is missing!"; 
echo json_encode($response); 
} 
?> 

它处理从登录和注册活动所有请求。下面我张贴那些为well.This是RegisterActivity:

package com.indiainhand.iih; 

import android.annotation.TargetApi; 
import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.os.Build; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 

    import com.android.volley.Request; 
    import com.android.volley.Response; 
import com.android.volley.VolleyError; 
    import com.android.volley.toolbox.StringRequest; 

import org.json.JSONException; 
import org.json.JSONObject; 

import java.util.HashMap; 
import java.util.Map; 


public class RegisterActivity extends Activity { 
private static final String TAG = RegisterActivity.class.getSimpleName(); 
private Button btnRegister; 
private Button btnLinkToLogin; 
private EditText inputFullName; 
private EditText inputEmail; 
private EditText inputPassword; 
private ProgressDialog pDialog; 
private SessionManager session; 
private SQLiteHandler db; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_register); 

    inputFullName = (EditText) findViewById(R.id.name); 
    inputEmail = (EditText) findViewById(R.id.email); 
    inputPassword = (EditText) findViewById(R.id.password); 
    btnRegister = (Button) findViewById(R.id.btnRegister); 
    btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen); 

    // Progress dialog 
    pDialog = new ProgressDialog(this); 
    pDialog.setCancelable(false); 

    // Session manager 
    session = new SessionManager(getApplicationContext()); 

    // SQLite database handler 
    db = new SQLiteHandler(getApplicationContext()); 

    // Check if user is already logged in or not 
    if (session.isLoggedIn()) { 
     // User is already logged in. Take him to main activity 
     Intent intent = new Intent(RegisterActivity.this, 
       MainActivity.class); 
     startActivity(intent); 
     finish(); 
    } 

    // Register Button Click event 
    btnRegister.setOnClickListener(new View.OnClickListener() { 
     @TargetApi(Build.VERSION_CODES.GINGERBREAD) 
     public void onClick(View view) { 
      String name = inputFullName.getText().toString(); 
      String email = inputEmail.getText().toString(); 
      String password = inputPassword.getText().toString(); 

     if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty())  { 
       registerUser(name, email, password); 
      } else { 
       Toast.makeText(getApplicationContext(), 
         "Please enter your details!", Toast.LENGTH_LONG) 
         .show(); 
      } 
     } 
    }); 

    // Link to Login Screen 
    btnLinkToLogin.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View view) { 
      Intent i = new Intent(getApplicationContext(), 
        LoginActivity.class); 
      startActivity(i); 
      finish(); 
     } 
    }); 

    } 

    /** 
* Function to store user in MySQL database will post params(tag, name, 
* email, password) to register url 
* */ 
    private void registerUser(final String name, final String email, 
          final String password) { 
    // Tag used to cancel the request 
    String tag_string_req = "req_register"; 

    pDialog.setMessage("Registering ..."); 
    showDialog(); 

StringRequest strReq = new StringRequest(Request.Method.POST,AppConfig.URL_REGISTER, new Response.Listener<String>() { 

     @Override 
     public void onResponse(String response) { 
      Log.d(TAG, "Register Response: " + response); 
      showDialog(); 

      try { 
       JSONObject jObj = new JSONObject(response); 
       boolean error = jObj.getBoolean("error"); 
       if (!error) { 
        // User successfully stored in MySQL 
        // Now store the user in sqlite 
        pDialog.setMessage("Registration Successfull"); 
        showDialog(); 
        String uid = jObj.getString("uid"); 

        JSONObject user = jObj.getJSONObject("user"); 
        String name = user.getString("name"); 
        String email = user.getString("email"); 
        String created_at = user 
          .getString("created_at"); 

        // Inserting row in users table 
        db.addUser(name, email, uid, created_at); 


        // Launch login activity 
        Intent intent = new Intent(
          RegisterActivity.this, 
          LoginActivity.class); 
        startActivity(intent); 
        finish(); 
       } else { 

        // Error occurred in registration. Get the error 
        // message 
        String errorMsg = jObj.getString("error_msg"); 
        Toast.makeText(getApplicationContext(), 
          errorMsg, Toast.LENGTH_LONG).show(); 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

     } 
    }, new Response.ErrorListener() { 

     @Override 
     public void onErrorResponse(VolleyError error) { 
      Log.e(TAG, "Registration Error: " + error.getMessage()); 
      Toast.makeText(getApplicationContext(), 
        error.getMessage(), Toast.LENGTH_LONG).show(); 
      hideDialog(); 
     } 
    }) { 

     @Override 
     protected Map<String, String> getParams() { 
      // Posting params to register url 
      Map<String, String> params = new HashMap<String, String>(); 
      params.put("tag", "register"); 
      params.put("name", name); 
      params.put("email", email); 
      params.put("password", password); 

      return params; 
     } 

    }; 

    // Adding request to request queue 
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req); 
} 

private void showDialog() { 
    if (!pDialog.isShowing()) 
     pDialog.show(); 
} 

private void hideDialog() { 
    if (pDialog.isShowing()) 
     pDialog.dismiss(); 
} 
} 

那是什么就是我facing.Please帮助我,谢谢你在前进:)

+0

您应该发布堆栈跟踪。它比仅仅错误类型更有用。 – d0nut

+0

此外,在你的PHP中,你错过了字符串''未知'标签'value.should ...'的结尾引号'' – d0nut

+0

是的,你是对的,但这不是这个错误的原因 –

回答

0

首先,确保你的PHP代码有问题返回正确的JSON,尝试通过将您的POST变量更改为GET变量来模拟API调用,并尝试浏览器中的代码。 我认为php代码正在工作,但在您的android代码中,您在请求JsonObjectRequest时请求StringResponse。 尝试更改并反馈。

+0

Thankyou为您的答复。我不知道你告诉我,这里是代码:'JsonObjectRequest strReq = new''JsonObjectRequest(Request.Method.POST,AppConfig.URL,''newResponse.Listener ()''public void onResponse(JSONObject response) {''JSONObject jObj = new JSONObject(response);'我只改变了整个代码的上面几行,并且出现'无法解析构造函数org.json.jsonobject'的错误'JSONObject jObj = new JSONObject (response);'at response parameter。 –

+0

不需要onResponse中的las行代码,而是将'response'传递给另一个将执行解析的方法, E.G. 'public void onResponse(JSONObject response){ parseResponse(response); }' 然后在该方法中,你可以提取你的东西从JSON就像这样: '公共无效parseResponse(JSONObject的响应){ 尝试{ 字符串usernameFromJson = response.getString( “用户名”); //用usernameFromJson做些事 } catch(JSONException e){ Log.e(“Error”,“Parsing error”+ e.toString()); } } ' –

+0

@ R.Rohilla,如果回答你的问题,请选择它 –

相关问题