Android的JSON服务器响应可能是无效的错误 [英] Android JSON Server Response might be invalid error

查看:458
本文介绍了Android的JSON服务器响应可能是无效的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开发和应用程序,并在我需要同步的本地数据库远程我的SQL数据库,以便为我已经在MySQL创建表,也写了一些脚本,这些都是我的脚本文件

 < PHP

类DB_Functions {

私人$分贝;

//把你的code在这里
//构造
功能__construct(){
    include_once'./db_connect.php;
    //连接到数据库
    $这个 - > DB =新DB_Connect();
    $这个 - > DB->连接();
}

//析构函数
功能__destruct(){

}

/ **
 *存储新用户
 *返回用户的详细信息
 * /
公共职能storeUser($名称,$电子邮件,$普农){
    //将用户存入数据库
    $结果= mysql_query(INSERT INTO游戏(姓名,电子邮件,PHNO)VALUES('$名字','$电子邮件,$普农));

    如果($结果){
        返回true;
    } 其他 {
        如果(mysql_errno()== 1062){
            //重复键 - 主键冲突
            返回true;
        } 其他 {
            //对于其他错误
            返回false;
        }
    }
}
 / **
 *让所有用户
 * /
公共职能getAllUsers(){
    $结果= mysql_query(选择的姓名,电子邮件,PHNO FROM游戏);
    返回$结果;
}
}

?>
 

这是我insertuser.php文件

 < PHP
include_once'./db_functions.php;
//创建对象的DB_Functions CLAS
$ DB =新DB_Functions();
//获取JSON发布的Andr​​oid应用程序
$ JSON = $ _ POST [usersJSON];
//删除斜杠
如果(get_magic_quotes_gpc()){
$ JSON =函数stripslashes($ JSON);
}
//德code JSON到一个数组
$数据= json_de code($ JSON);
//的Util阵列创建响应JSON
$ A =阵列();
$ B =阵列();
//循环遍历从JSON读入MySQL数据库的数组和插入数据
为($ i = 0; $ I<计数($的数据); $ I ++)
{
//存储用户到MySQL数据库
$水库= $ DB-> storeUser($数据[$ i]  - >用户名,$数据[$ i]  - > USEREMAIL,$数据[$ i]  - > userPhno);
//基于插入,创建JSON响应
如果($水库){
    $ B [名称] = $数据[$ i]  - >用户名;
    $ B [身份] ='是';
    array_push($ A,$ B);
}其他{
    $ B [名称] = $数据[$ i]  - >用户名;
    $ B [身份] ='不';
    array_push($ A,$ B);
}
}
//邮JSON响应返回给Android应用程序
  回声json_en code($ A);
  ?>
 

这是我DBController.java文件

 公共类DBController扩展SQLiteOpenHelper {

公共DBController(背景下的ApplicationContext){
    超(ApplicationContext中,syncscore.db,NULL,1);
}
//创建表
@覆盖
公共无效的onCreate(SQLiteDatabase数据库){
    查询字符串;
    查询=CREATE TABLE游戏(名文本,USEREMAIL TEXT,userPhno TEXT,udpateStatus文本);
    database.execSQL(查询);
}
@覆盖
公共无效onUpgrade(SQLiteDatabase数据库,诠释version_old,INT current_version){
    查询字符串;
    查询=DROP TABLE IF EXISTS游戏;
    database.execSQL(查询);
    的onCreate(数据库);
}
/ **
 *用户插入到的SQLite数据库
 * @参数queryValues
 * /
公共无效insertUser(HashMap的<字符串,字符串> queryValues​​){
    SQLiteDatabase数据库= this.getWritableDatabase();
    ContentValues​​值=新ContentValues​​();
    values​​.put(username的,queryValues​​.get(username的));
    values​​.put(USEREMAIL,queryValues​​.get(USEREMAIL));
    values​​.put(userPhno,queryValues​​.get(userPhno));
    values​​.put(udpateStatus,无);
    database.insert(游戏,空,价值观);
    database.close();
}

/ **
 *获取用户的列表,DB的SQLite作为数组列表
 * @返回
 * /
公众的ArrayList< HashMap的<字符串,字符串>> getAllUsers(){
    ArrayList的< HashMap的<字符串,字符串>>单词表;
    单词表=新的ArrayList< HashMap的<字符串,字符串>>();
    字符串selectQuery =SELECT * FROM游戏;
    SQLiteDatabase数据库= this.getWritableDatabase();
    光标光标= database.rawQuery(selectQuery,NULL);
    如果(cursor.moveToFirst()){
        做 {
             HashMap的<字符串,字符串>图=新的HashMap<字符串,字符串>();
            map.put(username的,cursor.getString(0));
            map.put(USEREMAIL,cursor.getString(1));
            map.put(userPhno,cursor.getString(2));
           wordList.add(图)
        }而(cursor.moveToNext());
    }
    database.close();
    返回词表;
}

/ **
 *撰写JSON出的SQLite记录
 * @返回
 * /
公共字符串composeJSONfromSQLite(){
    ArrayList的< HashMap的<字符串,字符串>>单词表;
    单词表=新的ArrayList< HashMap的<字符串,字符串>>();
    字符串selectQuery =SELECT * FROM游戏中udpateStatus ='+无+';
    SQLiteDatabase数据库= this.getWritableDatabase();
    光标光标= database.rawQuery(selectQuery,NULL);
    如果(cursor.moveToFirst()){
        做 {
            HashMap的<字符串,字符串>图=新的HashMap<字符串,字符串>();
            map.put(username的,cursor.getString(0));
            map.put(USEREMAIL,cursor.getString(1));
            map.put(userPhno,cursor.getString(2));
            wordList.add(图)
        }而(cursor.moveToNext());
    }
    database.close();
    GSON GSON =新GsonBuilder()创建()。
    //使用GSON序列化数组列表以JSON
    返回gson.toJson(单词表);
}

/ **
 *获取的SQLite的同步状态
 * @返回
 * /
公共字符串getSyncStatus(){
    弦乐味精= NULL;
    如果(this.dbSyncCount()== 0){
        味精=的SQLite和远程MySQL的DB是同步的!;
    }其他{
        味精=数据库同步所需的\ n;
    }
    返回味精;
}

/ **
 *获取SQLite的记录是没有被同步
 * @返回
 * /
公众诠释dbSyncCount(){
    诠释计数= 0;
    字符串selectQuery =SELECT * FROM游戏中udpateStatus ='+无+';
    SQLiteDatabase数据库= this.getWritableDatabase();
    光标光标= database.rawQuery(selectQuery,NULL);
    数= cursor.getCount();
    database.close();
    返回计数;
}

/ **
 *针对每个用户ID更新同步状态
 * @参数ID
 * @参数状态
 * /
公共无效updateSyncStatus(字符串名称,字符串状态){
    SQLiteDatabase数据库= this.getWritableDatabase();
    字符串updateQuery =更新游戏设置udpateStatus ='+状态+'其中username =+'+姓名+';
    Log.d(查询,updateQuery);
    database.execSQL(updateQuery);
    database.close();
}
 

}

这是我MainActivity.java文件

 公共类MainActivity延伸活动{
// DB类来执行数据库相关的操作
DBController控制器=新DBController(本);
//进度对话框对象
ProgressDialog prgDialog;

@覆盖
保护无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);
    //从SQLite的数据库用户记录
    ArrayList的< HashMap的<字符串,字符串>>用户列表= controller.getAllUsers();
    //
    如果(userList.size()!= 0){
        //设置用户数组列表中的ListView
        ListAdapter适配器=新SimpleAdapter(MainActivity.this,用户列表,R.layout.view_user_entry,新的String [] {用户id,username的},新的INT [] {R.id.userId,R.id.userName}) ;
        ListView控件myList上=(ListView控件)findViewById(android.R.id.list);
        myList.setAdapter(适配器);
        //显示的SQLite数据库的同步状态
        Toast.makeText(getApplicationContext(),controller.getSyncStatus(),Toast.LENGTH_LONG).show();
    }
    //初始化进度对话框性能
    prgDialog =新ProgressDialog(本);
    prgDialog.setMessage(假唱的SQLite数据与远程MySQL数据库,请稍候...);
    prgDialog.setCancelable(假);
}

@覆盖
公共布尔onCreateOptionsMenu(功能菜单){
    //充气菜单;这增加了项目操作栏,如果它是present。
    。getMenuInflater()膨胀(R.menu.main,菜单);
    返回true;
}

@覆盖
公共布尔onOptionsItemSelected(菜单项项){
    //处理动作栏项目点击这里。将操作栏
    //自动在主/向上按钮操作的点击,只要
    //你在AndroidManifest.xml中指定一个父活动。
    INT的id = item.getItemId();
    //当点击同步操作按钮
    如果(ID == R.id.refresh){
        //同步的SQLite数据库的数据到远程MySQL数据库
        syncSQLiteMySQLDB();
        返回true;
    }
    返回super.onOptionsItemSelected(项目);
}
//添加用户的方法获取调用上点击按钮(+)
公共无效ADDUSER(查看视图){
    意图objIntent =新的意图(getApplicationContext(),NewUser.class);
    startActivity(objIntent);
}

公共无效syncSQLiteMySQLDB(){
    //创建AsycHttpClient对象
    AsyncHttpClient客户端=新AsyncHttpClient();
    RequestParams PARAMS =新RequestParams();
    ArrayList的< HashMap的<字符串,字符串>>用户列表= controller.getAllUsers();
    如果(userList.size()!= 0){
        如果(controller.dbSyncCount()!= 0){
            prgDialog.show();
            params.put(usersJSON,controller.composeJSONfromSQLite());
            client.post(http://10.0.2.2/syncscore/viewusers.php,PARAMS,新AsyncHtt presponseHandler(){
                @覆盖
                公共无效的onSuccess(字符串响应){
                    的System.out.println(响应);
                    prgDialog.hide();
                    尝试 {
                        JSONArray ARR =新JSONArray(响应);
                        的System.out.println(arr.length());
                        的for(int i = 0; I< arr.length();我++){
                            JSONObject的OBJ =(的JSONObject)arr.get(我);
                            //System.out.println(obj.get("name));
                            //System.out.println(obj.get("status));
                            controller.updateSyncStatus(obj.get(姓名)的toString(),obj.get(身份)的toString());
                        }
                        Toast.makeText(getApplicationContext(),DB同步完成!,Toast.LENGTH_LONG).show();
                    }赶上(JSONException E){
                        // TODO自动生成的catch块
                        Toast.makeText(getApplicationContext()时出现错误[服务器的JSON响应可能无效]!,Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                }

                @覆盖
                公共无效onFailure(INT状态code,可抛出错误,
                    字符串的内容){
                    // TODO自动生成方法存根
                    prgDialog.hide();
                    如果(状态code == 404){
                        Toast.makeText(getApplicationContext(),请求的资源未找到,Toast.LENGTH_LONG).show();
                    }否则,如果(状态code == 500){
                        Toast.makeText(getApplicationContext(),出事了服务器端,Toast.LENGTH_LONG).show();
                    }其他{
                        Toast.makeText(getApplicationContext(),意外的错误occcured [最常见的错误:设备可能未连接到互联网]!,Toast.LENGTH_LONG).show();
                    }
                }
            });
        }其他{
            Toast.makeText(getApplicationContext(),的SQLite和远程MySQL DB位于同步!,Toast.LENGTH_LONG).show();
        }
    }其他{
            Toast.makeText(getApplicationContext()中的SQLite数据库没有数据,请不要输入用户名执行同步操作,Toast.LENGTH_LONG).show();
    }
}
 

}

在模拟器由用户输入的数据被存储在本地数据库中运行这个程序,如果我点击一个名为我的应用程序同步按钮,它是说,JSON服务器响应可能无效后。

任何一个可以请让我知道IAM错了..?得到了stucked这个2天,请帮忙解决这个 谢谢   请检查我的日志猫也

  08-22 00:28:31.790:W / System.err的(19929):org.json.JSONException:值小于; HTML>型的java.lang.String中不能转换到JSONArray
08-22 00:28:31.800:W / System.err的(19929):在org.json.JSON.typeMismatch(JSON.java:111)
08-22 00:28:31.800:W / System.err的(19929):在org.json.JSONArray< INIT>(JSONArray.java:96)
08-22 00:28:31.810:W / System.err的(19929):在org.json.JSONArray< INIT>(JSONArray.java:108)
08-22 00:28:31.810:W / System.err的(19929):在com.sathya.syncandroid.MainActivity $ 1.onSuccess(MainActivity.java:96)
08-22 00:28:31.810:W / System.err的(19929):在com.loopj.android.http.AsyncHtt presponseHandler.onSuccess(AsyncHtt presponseHandler.java:232)
08-22 00:28:31.810:W / System.err的(19929):在com.loopj.android.http.AsyncHtt presponseHandler.onSuccess(AsyncHtt presponseHandler.java:220)
08-22 00:28:31.810:W / System.err的(19929):在com.loopj.android.http.AsyncHtt presponseHandler.onSuccess(AsyncHtt presponseHandler.java:245)
08-22 00:28:31.810:W / System.err的(19929):在com.loopj.android.http.AsyncHtt presponseHandler.handleMessage(AsyncHtt presponseHandler.java:365)
08-22 00:28:31.810:W / System.err的(19929):在com.loopj.android.http.AsyncHtt presponseHandler $ ResponderHandler.handleMessage(AsyncHtt preS ponseHandler.java:135)
08-22 00:28:31.820:W / System.err的(19929):在android.os.Handler.dispatchMessage(Handler.java:102)
08-22 00:28:31.820:W / System.err的(19929):在android.os.Looper.loop(Looper.java:136)
 

解决方案

看着C时你的PHP $ C $似乎并不像你的反应是一个数组,它应该是一个JSONObject的,一直记录数据,并检查对象分析之前图:

  Log.d(mylog,JSON =+ response.toString());
 

更改你的PHP是这样的:

 < PHP
$响应=阵列():

如果(使用isset($ _ POST ['usersJSON'])){

尝试 {
    $ JSON = $ _ POST [usersJSON];
    include_once'./db_functions.php;
    $ DB =新DB_Functions();

    如果(get_magic_quotes_gpc()){
        $ JSON =函数stripslashes($ JSON);
    }

    // true传递给json_de code
    $记录= json_de code($ json的,真正的);

    $数据=阵列();
    的foreach($记录为$记录){
        $水库= $ DB-> storeUser($数据[用户名],$数据['USEREMAIL'],$数据['userPhno']);
        $数据['名称'] = $纪录[用户名];
        $数据['名称'] = $资源? '是不是';
        array_push($响应['数据'],$数据);
    }
    $响应['成功'] =真;
}赶上(异常$ E){
    $响应['成功'] = FALSE;
    $ respnose ['消息'] = $ E->的getMessage();
}


}其他{
    $响应['成功'] = FALSE;
    $ respnose ['消息'] ='缺少JSON数据;

}

回声json_en code($响应);
 

这样,你总是有一个回应,您有它不会给你一个答复,如果没有输入回路的方式

I have developed and app and in that i need to sync the local database to remote my sql database so for that i have created a table in mysql and also wrote some scripts for that these are my script files

<?php

class DB_Functions {

private $db;

//put your code here
// constructor
function __construct() {
    include_once './db_connect.php';
    // connecting to database
    $this->db = new DB_Connect();
    $this->db->connect();
}

// destructor
function __destruct() {

}

/**
 * Storing new user
 * returns user details
 */
public function storeUser($Name,$Email,$Phnum) {
    // Insert user into database
    $result = mysql_query("INSERT INTO              games(name,email,phno)VALUES('$Name','$Email',$Phnum)");

    if ($result) {
        return true;
    } else {
        if( mysql_errno() == 1062) {
            // Duplicate key - Primary Key Violation
            return true;
        } else {
            // For other errors
            return false;
        }            
    }
}
 /**
 * Getting all users
 */
public function getAllUsers() {
    $result = mysql_query("select name,email,phno FROM games");
    return $result;
}
}

?>  

And this is my insertuser.php file

 <?php
include_once './db_functions.php';
//Create Object for DB_Functions clas
$db = new DB_Functions(); 
//Get JSON posted by Android Application
$json = $_POST["usersJSON"];
//Remove Slashes
if (get_magic_quotes_gpc()){
$json = stripslashes($json);  
}
//Decode JSON into an Array
$data = json_decode($json);
//Util arrays to create response JSON
$a=array();
$b=array();
//Loop through an Array and insert data read from JSON into MySQL DB
for($i=0; $i<count($data) ; $i++)
{
//Store User into MySQL DB
$res = $db->storeUser($data[$i]->userName,$data[$i]->userEmail,$data[$i]->userPhno);
//Based on insertion, create JSON response
if($res){
    $b["name"] = $data[$i]->userName;
    $b["status"] = 'yes';
    array_push($a,$b);
}else{
    $b["name"] = $data[$i]->userName;
    $b["status"] = 'no';
    array_push($a,$b);
}
}
//Post JSON response back to Android Application
  echo json_encode($a);  
  ?>

And this is my DBController.java file

public class DBController  extends SQLiteOpenHelper {

public DBController(Context applicationcontext) {
    super(applicationcontext, "syncscore.db", null, 1);
}
//Creates Table
@Override
public void onCreate(SQLiteDatabase database) {
    String query;
    query = "CREATE TABLE games ( userName TEXT, userEmail TEXT,userPhno TEXT, udpateStatus TEXT)";
    database.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase database, int version_old, int current_version) {
    String query;
    query = "DROP TABLE IF EXISTS games";
    database.execSQL(query);
    onCreate(database);
}
/**
 * Inserts User into SQLite DB
 * @param queryValues
 */
public void insertUser(HashMap<String, String> queryValues) {
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put("userName", queryValues.get("userName"));
    values.put("userEmail", queryValues.get("userEmail"));
    values.put("userPhno", queryValues.get("userPhno"));
    values.put("udpateStatus", "no");
    database.insert("games", null, values);
    database.close();
}

/**
 * Get list of Users from SQLite DB as Array List
 * @return
 */
public ArrayList<HashMap<String, String>> getAllUsers() {
    ArrayList<HashMap<String, String>> wordList;
    wordList = new ArrayList<HashMap<String, String>>();
    String selectQuery = "SELECT  * FROM games";
    SQLiteDatabase database = this.getWritableDatabase();
    Cursor cursor = database.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        do {
             HashMap<String, String> map = new HashMap<String, String>();
            map.put("userName", cursor.getString(0));
            map.put("userEmail", cursor.getString(1));
            map.put("userPhno", cursor.getString(2));
           wordList.add(map);
        } while (cursor.moveToNext());
    }
    database.close();
    return wordList;
}

/**
 * Compose JSON out of SQLite records
 * @return
 */
public String composeJSONfromSQLite(){
    ArrayList<HashMap<String, String>> wordList;
    wordList = new ArrayList<HashMap<String, String>>();
    String selectQuery = "SELECT  * FROM games where udpateStatus = '"+"no"+"'";
    SQLiteDatabase database = this.getWritableDatabase();
    Cursor cursor = database.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        do {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("userName", cursor.getString(0));
            map.put("userEmail", cursor.getString(1));
            map.put("userPhno", cursor.getString(2));
            wordList.add(map);
        } while (cursor.moveToNext());
    }
    database.close();
    Gson gson = new GsonBuilder().create();
    //Use GSON to serialize Array List to JSON
    return gson.toJson(wordList);
}

/**
 * Get Sync status of SQLite
 * @return
 */
public String getSyncStatus(){
    String msg = null;
    if(this.dbSyncCount() == 0){
        msg = "SQLite and Remote MySQL DBs are in Sync!";
    }else{
        msg = "DB Sync needed\n";
    }
    return msg;
}

/**
 * Get SQLite records that are yet to be Synced
 * @return
 */
public int dbSyncCount(){
    int count = 0;
    String selectQuery = "SELECT  * FROM games where udpateStatus = '"+"no"+"'";
    SQLiteDatabase database = this.getWritableDatabase();
    Cursor cursor = database.rawQuery(selectQuery, null);
    count = cursor.getCount();
    database.close();
    return count;
}

/**
 * Update Sync status against each User ID
 * @param id
 * @param status
 */
public void updateSyncStatus(String name, String status){
    SQLiteDatabase database = this.getWritableDatabase();     
    String updateQuery = "Update games set udpateStatus = '"+ status +"' where userName="+"'"+ name +"'";
    Log.d("query",updateQuery);        
    database.execSQL(updateQuery);
    database.close();
}

}

And this is my MainActivity.java file

public class MainActivity extends Activity {
//DB Class to perform DB related operations
DBController controller = new DBController(this);
//Progress Dialog Object
ProgressDialog prgDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //Get User records from SQLite DB 
    ArrayList<HashMap<String, String>> userList =  controller.getAllUsers();
    //
    if(userList.size()!=0){
        //Set the User Array list in ListView
        ListAdapter adapter = new SimpleAdapter( MainActivity.this,userList, R.layout.view_user_entry, new String[] { "userId","userName"}, new int[] {R.id.userId, R.id.userName});
        ListView myList=(ListView)findViewById(android.R.id.list);
        myList.setAdapter(adapter);
        //Display Sync status of SQLite DB
        Toast.makeText(getApplicationContext(), controller.getSyncStatus(), Toast.LENGTH_LONG).show();
    }
    //Initialize Progress Dialog properties
    prgDialog = new ProgressDialog(this);
    prgDialog.setMessage("Synching SQLite Data with Remote MySQL DB. Please wait...");
    prgDialog.setCancelable(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.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();
    //When Sync action button is clicked
    if (id == R.id.refresh) {
        //Sync SQLite DB data to remote MySQL DB
        syncSQLiteMySQLDB();
        return true;
    }
    return super.onOptionsItemSelected(item);
}
//Add User method getting called on clicking (+) button
public void addUser(View view) {
    Intent objIntent = new Intent(getApplicationContext(), NewUser.class);
    startActivity(objIntent);
}

public void syncSQLiteMySQLDB(){
    //Create AsycHttpClient object
    AsyncHttpClient client = new AsyncHttpClient();
    RequestParams params = new RequestParams();
    ArrayList<HashMap<String, String>> userList =  controller.getAllUsers();
    if(userList.size()!=0){
        if(controller.dbSyncCount() != 0){
            prgDialog.show();
            params.put("usersJSON", controller.composeJSONfromSQLite());
            client.post("http://10.0.2.2/syncscore/viewusers.php",params ,new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(String response) {
                    System.out.println(response);
                    prgDialog.hide();
                    try {
                        JSONArray arr = new JSONArray(response);
                        System.out.println(arr.length());
                        for(int i=0; i<arr.length();i++){
                            JSONObject obj = (JSONObject)arr.get(i);
                            //System.out.println(obj.get("name"));
                            //System.out.println(obj.get("status"));
                            controller.updateSyncStatus(obj.get("name").toString(),obj.get("status").toString());
                        }
                        Toast.makeText(getApplicationContext(), "DB Sync completed!", Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Throwable error,
                    String content) {
                    // TODO Auto-generated method stub
                    prgDialog.hide();
                    if(statusCode == 404){
                        Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
                    }else if(statusCode == 500){
                        Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
                    }else{
                        Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]", Toast.LENGTH_LONG).show();
                    }
                }
            });
        }else{
            Toast.makeText(getApplicationContext(), "SQLite and Remote MySQL DBs are in Sync!", Toast.LENGTH_LONG).show();
        }
    }else{
            Toast.makeText(getApplicationContext(), "No data in SQLite DB, please do enter User name to perform Sync action", Toast.LENGTH_LONG).show();
    }
}

}

After running this app in the emulator the data entered by the user is storing in the local database and if i click a button called sync in my application it is saying that JSON Server Response might be invalid.

Can any one please let me know where iam wrong..?got stucked with this from 2 days please help to solve this Thanks Please check my Log cat also

08-22 00:28:31.790: W/System.err(19929): org.json.JSONException: Value <html> of type       java.lang.String cannot be converted to JSONArray
08-22 00:28:31.800: W/System.err(19929):    at org.json.JSON.typeMismatch(JSON.java:111)
08-22 00:28:31.800: W/System.err(19929):    at org.json.JSONArray.<init>(JSONArray.java:96)
08-22 00:28:31.810: W/System.err(19929):    at org.json.JSONArray.<init>(JSONArray.java:108)
08-22 00:28:31.810: W/System.err(19929):    at   com.sathya.syncandroid.MainActivity$1.onSuccess(MainActivity.java:96)
08-22 00:28:31.810: W/System.err(19929):    at     com.loopj.android.http.AsyncHttpResponseHandler.onSuccess(AsyncHttpResponseHandler.java:232    )
08-22 00:28:31.810: W/System.err(19929):    at        com.loopj.android.http.AsyncHttpResponseHandler.onSuccess(AsyncHttpResponseHandler.java:220    )
08-22 00:28:31.810: W/System.err(19929):    at com.loopj.android.http.AsyncHttpResponseHandler.onSuccess(AsyncHttpResponseHandler.java:245    )
08-22 00:28:31.810: W/System.err(19929):    at   com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java    :365)
08-22 00:28:31.810: W/System.err(19929):    at         com.loopj.android.http.AsyncHttpResponseHandler$ResponderHandler.handleMessage(AsyncHttpRes    ponseHandler.java:135)
08-22 00:28:31.820: W/System.err(19929):    at                  android.os.Handler.dispatchMessage(Handler.java:102)
08-22 00:28:31.820: W/System.err(19929):    at android.os.Looper.loop(Looper.java:136)

解决方案

Looking at your php code it does not seem like your response is an array, it should be a JSONObject, always log the data and check the object graph before parsing:

Log.d("mylog", "json = " + response.toString());

Change your php like this:

<?php
$response = array():

if(isset($_POST['usersJSON'])){

try {
    $json = $_POST["usersJSON"];
    include_once './db_functions.php';
    $db = new DB_Functions(); 

    if (get_magic_quotes_gpc()){
        $json = stripslashes($json);  
    }

    //pass true to json_decode
    $records = json_decode($json, true);

    $data = array();
    foreach($records as $record){
        $res = $db->storeUser($data['userName'],$data['userEmail'],$data['userPhno']);
        $data['name'] = $record['userName'];
        $data['name'] = $res ? 'yes' : 'no';
        array_push($response['data'], $data);   
    }
    $response['success'] = true;
} catch (Exception $e) {
    $response['success'] = false;
    $respnose['message'] = $e->getMessage();
}


}else{
    $response['success'] = false;
    $respnose['message'] = 'missing JSON data';

}

echo json_encode($response); 

This way you always have a response, the way you have it would not give you a response if the loop is not entered

这篇关于Android的JSON服务器响应可能是无效的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆