org.json.JSONException:值

时间:2015-03-21 20:31:41

标签: java php android json

早上好,我已经搜索了很多android和json论坛但是我找不到任何解决方案你能帮我吗!" ndroidhive.loginandregistration W / System.err:org.json。 JSONException:值

RegisterActivity.java

    import info.androidhive.loginandregistration.app.AppConfig;
    import info.androidhive.loginandregistration.app.AppController;
    import info.androidhive.loginandregistration.helper.SQLiteHandler;
    import info.androidhive.loginandregistration.helper.SessionManager;


    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() {
        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();
        }
        });

     }


       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(Method.POST,
            AppConfig.URL_REGISTER, new Response.Listener<String>() {

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

                    try {
                        JSONObject jObj = new JSONObject(response);
                        boolean error = jObj.getBoolean("error");
                        if (!error) {
                            // User successfully stored in MySQL
                            // Now store the user in sqlite
                            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();
  }
}

AppConfig.java

 package info.androidhive.loginandregistration.app;

  public class AppConfig {
 // Server user login url
    public static String URL_LOGIN =  "http://192.168.1.5/android_login_api/";

// Server user register url
  public static String URL_REGISTER =   "http://192.168.1.5/android_login_api/";
   }

myphpfile:index.php

 <?php
      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"] = "Unknow 'tag' value. It should be either      'login' or 'register'";
    echo json_encode($response);
    }
     } else {
     $response["error"] = TRUE;
     $response["error_msg"] = "Required parameter 'tag' is missing!";
     echo json_encode($response);
     }
       ?>

activity_register.xml

   <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:background="@color/bg_register"
  android:gravity="center"
  android:orientation="vertical"
  android:padding="10dp" >

  <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
      android:orientation="vertical"
      android:paddingLeft="20dp"
      android:paddingRight="20dp" >

      <EditText
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:background="@color/input_register_bg"
        android:hint="@string/hint_name"
        android:padding="10dp"
        android:singleLine="true"
        android:inputType="textCapWords"
        android:textColor="@color/input_register"
        android:textColorHint="@color/input_register_hint" />

      <EditText
        android:id="@+id/email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:background="@color/input_register_bg"
        android:hint="@string/hint_email"
        android:inputType="textEmailAddress"
        android:padding="10dp"
        android:singleLine="true"
        android:textColor="@color/input_register"
        android:textColorHint="@color/input_register_hint" />

     <EditText
        android:id="@+id/password"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:background="@color/input_register_bg"
        android:hint="@string/hint_password"
        android:inputType="textPassword"
        android:padding="10dp"
        android:singleLine="true"
        android:textColor="@color/input_register"
        android:textColorHint="@color/input_register_hint" />

      <!-- Login Button -->

      <Button
        android:id="@+id/btnRegister"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dip"
        android:background="#ea4c88"
        android:text="@string/btn_register"
        android:textColor="@color/white" />

       <!-- Link to Login Screen -->

         <Button
        android:id="@+id/btnLinkToLoginScreen"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dip"
        android:background="@null"
        android:text="@string/btn_link_to_login"
        android:textAllCaps="false"
        android:textColor="@color/white"
        android:textSize="15dp" />
    </LinearLayout>

  </LinearLayout>

0 个答案:

没有答案