jjzjj

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

coder 2023-12-17 原文

我尝试开发一个 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

最佳答案

在您的 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/

有关java.lang.String 无法从 Android 转换为 JSONObject的更多相关文章

  1. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  4. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  5. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  6. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  7. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  8. ruby-on-rails - 无法在centos上安装therubyracer(V8和GCC出错) - 2

    我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e

  9. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  10. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

随机推荐