简体   繁体   中英

java.lang.String cannot be converted to JSONObject from Android

I try to develop an android application that can register a profile using JSON Parser to the web hosting. I successfully create the login function. But I get this error message saying that the return object from the database is not a JSON Object. I think that my php file is the problem.

Whenever I try run the app, and click the button, it will display that the profile is already exist. I've tried compare with other post but neither it really solved my problem.

Here is my register.java. package com.teradata.sb186103.cbet;

 import android.content.Intent;
 import android.os.Bundle;
 import android.os.StrictMode;
 import android.support.v7.app.AppCompatActivity;
 import android.util.Log;
 import android.view.Menu;
 import android.view.MenuItem;
 import android.view.View;
 import android.widget.EditText;
 import android.widget.Toast;

 import org.apache.http.NameValuePair;
 import org.apache.http.message.BasicNameValuePair;
 import org.json.JSONObject;

 import java.util.ArrayList;
 import java.util.List;

public class RegisterActivity extends AppCompatActivity {

private JSONParser jsonParser;
private static String KEY_SUCCESS = "success";
String id;
private EditText consName;
private EditText consEmail;
private EditText password;

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


    consName = (EditText) findViewById(R.id.ETusername);
    consEmail = (EditText) findViewById(R.id.ETemail);
    password = (EditText) findViewById(R.id.ETpassword);

}

public void Register(View v) {
    try {

        String username = consName.getText().toString();
        String email = consEmail.getText().toString();
        String pass = password.getText().toString();

        //CHECK IF PROFILE ALREADY EXIST
        Boolean exist = CheckProfile(username, email, pass);
        if(exist==true){
            Toast.makeText(getApplicationContext(), "PROFILE ALREADY EXIST!", Toast.LENGTH_SHORT).show();
            return;
        }

        Boolean register = RegisterProfile(id, username, email, pass);
        if(register==true){
            Toast.makeText(getApplicationContext(), "PROFILE HAS BEEN UPDATED", Toast.LENGTH_SHORT).show();

            Intent intent = new Intent(v.getContext(), ViewProfileActivity.class);
            startActivity(intent);
        }


    } catch (Exception e) {
        e.printStackTrace();
    }


}

 /*   public void Cancel(View v) {

    Intent intent = new Intent(v.getContext(), MenuActivity.class);
    startActivity(intent);

   }*/

  public boolean CheckProfile(String consEmail, String consName, String password) throws Exception{
     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    String URL = JSONParser.serverURL;
    String tag = "CheckProfile";

    jsonParser = new JSONParser();
    List<NameValuePair> params = new ArrayList<NameValuePair>();

    String value = consEmail + "<@>" + consName + "<@>" + password;
    params.add(new BasicNameValuePair("tag", tag));
    params.add(new BasicNameValuePair("value", value));

    JSONObject json = jsonParser.getJSONFromUrl(URL, params);

    if (json != null && json.getString(KEY_SUCCESS) != null){
        return true;
    }else return false;



}

public boolean RegisterProfile(String id, String consName, String consEmail, String password) throws Exception{
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    String URL = JSONParser.serverURL;
    String tag = "RegisterProfile";

    jsonParser = new JSONParser();
    List<NameValuePair> params = new ArrayList<NameValuePair>();

    String value = id + "<@>" + consName + "<@>" + consEmail + "<@>" + password;
    params.add(new BasicNameValuePair("tag", tag));
    params.add(new BasicNameValuePair("value", value));

    JSONObject json = jsonParser.getJSONFromUrl(URL, params);

    String res = json.getString(KEY_SUCCESS);
    if (Integer.parseInt(res) == 1){
        return true;
    }
    else {
        return false;
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
   }
}

This is my index.php The part intended for register.java is the //Check Profile and //Register Profile

  <?php

  require_once ('database.php');
  date_default_timezone_set('Asia/Kuala_Lumpur'); 

   if (isset($_POST['tag']) && $_POST['tag'] != '') {

$tag = $_POST['tag'];  
$response = array("tag" => $tag, "success" => 0); 

//LOGIN
if ($tag == 'consumerLogin') {
    $value = $_POST['value'];
    $array = explode("<@>", $value);
    $consEmail = $array[0];
    $password = $array[1];

    $query = "select * from consumer where consEmail='$consEmail' and password='$password'";    
    $result = mysql_query($query);
    $row = mysql_fetch_array($result);
    if($row[0] != null)
        $response["success"] = 1;
    else
        $response["success"] = 0;
    echo json_encode($response);
    return;         

}

//GET ROW ID
else if ($tag == 'getID') {
    $value = $_POST['value'];
    $array = explode("<@>", $value);
    $table = $array[0];
    $column = $array[1];
    $val = $array[2];       

    $query = "select id from $table where $column = '$val'";    
    $result = mysql_query($query);
    $row = mysql_fetch_array($result);
    if($row[0] != null) {
        $response["value"] = $row[0];
        $response["success"] = 1;
    }
    else {
        $response["success"] = 0;
    }
    echo json_encode($response);
    return;         

}


//CHECK PROFILE
else if ($tag == 'CheckProfile') {
    $value = $_POST['value'];
    $array = explode("<@>", $value);
    $id= $array[0];
    $consName = $array[1];
    $consEmail = $array[2];
    $password = $array[3];                  


    $query = "select * from consumer where consName=$consName and consEmail='$consEmail' and password=$password" and id <> $id";
    $result = mysql_query($query);  
    $row = mysql_fetch_array($result);  
    $found=false;
    if($row[0]!=null)
        $found=true;

    if($found==true) {          
        $response["success"] = 1;
    }
    else {
        $response["success"] = 0;
    }

    echo json_encode($response);
    return;     

}

//REGISTER PROFILE
else if ($tag == 'RegisterProfile') {
    $value = $_POST['value'];
    $array = explode("<@>", $value);
    $id= $array[0];
    $consName = $array[1];
    $consEmail = $array[2];
    $password = $array[3];                  



    $query = "insert into consumer values(null,$consName,$consEmail,'$password')";
    $result = mysql_query($query);  

    $response["success"] = 1;                       
    echo json_encode($response);
    return;     

}

else {
    echo "Error Message: Invalid Request";      
   }
}
 else {
     echo "Error Message: Anynomous Access Denied"; 

 }



 ?>

This is my JSONParser

 package com.teradata.sb186103.cbet;



  import java.io.IOException;
  import android.util.Log;
  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.HttpPost;



  import org.apache.http.impl.client.DefaultHttpClient;
  import org.json.JSONException;
   import org.json.JSONObject;

     import java.io.BufferedReader;
  import java.io.InputStream;
    import java.io.InputStreamReader;
      import java.io.UnsupportedEncodingException;
    import java.util.List;

  public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
static String serverURL = "http://tdcbet.******/index.php";

public JSONParser() {

}

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {


    try {

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

    } 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();
        Log.e("JSON", json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }


    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }


    return jObj;



  }
}

logcat

  09-23 07:32:04.923 4311-4311/com.teradata.sb186103.cbet E/JSON Parser: Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject
  09-23 07:32:06.935 4311-4517/com.teradata.sb186103.cbet E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb4055100
  09-23 07:32:08.580 4311-4311/com.teradata.sb186103.cbet E/JSON: <br><table border='1' cellpadding='2' bgcolor='#FFFFDF' bordercolor='#E8B900' align='center'><tr><td><font face='Arial' size='1' color='#000000'>
        <b>PHP Error Message</b></font></td></tr></table><br /><b>Warning</b>:  mysql_fetch_array(): supplied argument is not a valid MySQL result resource in <b>/home/a6410240/public_html/index.php</b> on line 
        <b>65</b><br /><br><table border='1' cellpadding='2' bgcolor='#FFFFDF' bordercolor='#E8B900' align='center'><tr><td><div align='center'>
        <a href='http://www.000webhost.com/'><font face='Arial' size='1' color='#000000'>Free Web Hosting</font></a></div></td></tr>
   </table>{"tag":"CheckProfile","success":0}<!-- Hosting24 Analytics Code --> 
       <script type="text/javascript" src="http://stats.hosting24.com/count.php"></script><!-- End Of Analytics Code -->
  09-23 07:32:08.580 4311-4311/com.teradata.sb186103.cbet E/JSON Parser: Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject
  09-23 07:32:10.586 4311-4517/com.teradata.sb186103.cbet E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb4055170
  09-23 07:32:12.177 4311-4517/com.teradata.sb186103.cbet E/Surface: getSlotFromBufferLocked: unknown buffer: 0xa2d182a0
  09-26 01:31:21.886 2906-2906/com.teradata.sb186103.cbet E/JSON Parser: Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject
  09-26 01:31:21.886 2906-2906/com.teradata.sb186103.cbet W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference
 09-26 01:31:21.886 2906-2906/com.teradata.sb186103.cbet W/System.err:     at com.teradata.sb186103.cbet.RegisterActivity.RegisterProfile(RegisterActivity.java:120)
 09-26 01:31:21.886 2906-2906/com.teradata.sb186103.cbet W/System.err:     at com.teradata.sb186103.cbet.RegisterActivity.Register(RegisterActivity.java:57)
 09-26 01:31:21.886 2906-2906/com.teradata.sb186103.cbet W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
 09-26 01:31:21.886 2906-2906/com.teradata.sb186103.cbet W/System.err:     at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
 09-26 01:31:21.886 2906-2906/com.teradata.sb186103.cbet W/System.err:     at android.view.View.performClick(View.java:5198)
 09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet W/System.err:     at android.view.View$PerformClick.run(View.java:21147)
 09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
 09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
 09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet W/System.err:     at android.os.Looper.loop(Looper.java:148)
 09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
 09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
 09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
  09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet I/Choreographer: Skipped 71 frames!  The application may be doing too much work on its main thread.
 09-26 01:37:11.337 2906-2912/com.teradata.sb186103.cbet W/art: Suspending all threads took: 13.723ms

这是我的数据库表

In your PHP code you have the following lines,

else {
    echo "Error Message: Invalid Request";      
   }
}
 else {
     echo "Error Message: Anynomous Access Denied"; 
 }
 echo "masuk";

In case some error occurred this code will be working.

You are trying to parse this String to a JSONObject in your Android code.

EDIT

In case of CheckProfile you have 3 values in value variable.

String value = consEmail + "<@>" + consName + "<@>" + password;

In your PHP you are taking 4 values. There is no value at index 3. Also you are not passing the id variable.

$value = $_POST['value'];
$array = explode("<@>", $value);
$id= $array[0];
$consName = $array[1];
$consEmail = $array[2];
$password = $array[3];                  

Try this in PHP for CheckProfile ,

$consEmail= $array[0];
$consName = $array[1];
$password = $array[2];

$query = "select * from consumer where consEmail='$consEmail'";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM