java.lang.String 无法从 Android 转换为 JSONObject

标签 java php android json

我尝试开发一个 android 应用程序,它可以使用 JSON Parser 将配置文件注册到网络托管。我成功创建了登录功能。但是我收到此错误消息,指出从数据库返回的对象不是 JSON 对象。我认为我的 php 文件有问题。

每当我尝试运行应用程序并单击按钮时,它都会显示配置文件已存在。我试过与其他帖子进行比较,但都没有真正解决我的问题。

这是我的 register.java。 包 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);
   }
}

这是我的index.php 用于 register.java 的部分是//Check Profile 和//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"; 

 }



 ?>

这是我的 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;



  }
}

日志

  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

this is my database table

最佳答案

在您的 PHP 代码中,您有以下几行,

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

如果发生错误,此代码将起作用。

您正在尝试将此 String 解析为 Android 代码中的 JSONObject

编辑

CheckProfile 的情况下,您在 value 变量中有 3 个值。

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

在您的 PHP 中,您采用了 4 个值。索引 3 处没有值。您也没有传递 id 变量。

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

在 PHP 中为 CheckProfile 尝试这个,

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

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

关于java.lang.String 无法从 Android 转换为 JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39655347/

相关文章:

php - 如何使用 laravel 6 在我的包中使用 auth 进行自定义保护?

php - 如何使用 php 在 td 中发送 contenteditable 值

java - 生成项目时,如何有条件地从原型(prototype)中包含或排除文件?

java - 在异步任务前/后执行方法中使用 ProgressDialog

php - EC2 Mod Rewrite 将 AllowOverRide None 更改为 All

java - 如何在字符串中的 "| "之后在新行中打印数据

javascript - 未捕获的类型错误 : Object #<Object> has no method 'exec' at file:///android_asset/www/index. html

android - WebView setJavaScriptEnabled 和 JavaScript 现场

java - 使用对象访问 List 的 EL 语法是什么?

java - 将共享/安装的 block 存储与 Xodus 一起使用