为什么它说它是一个字符串?

时间:2015-06-15 19:34:48

标签: java php android mysql json

我在Android应用程序开发方面非常新,我需要从我的本地xampp mysql数据库中获取数据。这些是我一直得到的错误信息。

06-15 15:12:31.472  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray
06-15 15:12:31.472  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at org.json.JSON.typeMismatch(JSON.java:111)
06-15 15:12:31.472  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at org.json.JSONArray.<init>(JSONArray.java:96)
06-15 15:12:31.472  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at org.json.JSONArray.<init>(JSONArray.java:108)
06-15 15:12:31.472  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at com.example.shirlyn.attendancesystem.StudentJSONParser.parseFeed(StudentJSONParser.java:18)
06-15 15:12:31.472  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at com.example.shirlyn.attendancesystem.MainActivity$ThreadClass.onPostExecute(MainActivity.java:111)
06-15 15:12:31.472  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at com.example.shirlyn.attendancesystem.MainActivity$ThreadClass.onPostExecute(MainActivity.java:95)
06-15 15:12:31.472  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at android.os.AsyncTask.finish(AsyncTask.java:636)
06-15 15:12:31.472  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at android.os.AsyncTask.access$500(AsyncTask.java:177)
06-15 15:12:31.472  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
06-15 15:12:31.473  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:102)
06-15 15:12:31.473  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at android.os.Looper.loop(Looper.java:135)
06-15 15:12:31.473  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5254)
06-15 15:12:31.473  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at java.lang.reflect.Method.invoke(Native Method)
06-15 15:12:31.473  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:372)
06-15 15:12:31.473  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
06-15 15:12:31.473  28252-28252/com.example.shirlyn.attendancesystem W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)  

这是我的php文件get_all_products.php

<?php // array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// get all products from products table
$result = mysql_query("SELECT * FROM student") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response = array();

while ($row = mysql_fetch_assoc($result)) {
    // temp user array
    $response[] = $row;
}
// success

// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No students found";

// echo no users JSON
header(‘Content-type: application/json’);
echo json_encode($response);
}
?>  

get_all_products.php的结果,如果我在浏览器上运行它似乎是正确的......

[{"student_id":"TP028616","student_name":"Shirlyn Hoe Yee Lyn","student_username":"lyn","student_password":"123"},{"student_id":"TP033500","student_name":"Ryan Teh Hoon Meng","student_username":"teh","student_password":"123"}]

这是我的Android应用程序StudentJSONParser.java中的java类

package com.example.shirlyn.attendancesystem;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

public class StudentJSONParser {
    public static List<Student> parseFeed(String content){

        try {
            System.out.println("begin parsing");
            JSONArray ar = new JSONArray(content);
            List<Student> studentList = new ArrayList<>();

            for(int i = 0 ; i < ar.length() ; i++){
                System.out.println("loop " + i);
                JSONObject obj = ar.getJSONObject(i);
                Student student = new Student(obj.getString("student_id"), obj.getString("student_name"), obj.getString("student_username"), obj.getString("student_password"));

                studentList.add(student);
                System.out.println("complete loop " + i);
            }
            System.out.println("complete parsing");

            return studentList;

        } catch (JSONException e) {
            e.printStackTrace();
            System.out.println("error parsing");

            return null;
        }

    }
}

这是.php文件没有返回jsonarrays的问题吗?或者我的应用程序的逻辑错了?感谢所有的回复。

这是我的asynctask类

public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private Button loginbtn;
private EditText usernameTxt, passwordTxt;
private ProgressBar pb;

private List<Student> studentslist;

public final static String readStudentphp = "http://192.168.0.103/webservice/get_all_products.php";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    OnClickButtonListener();
    initLogin();
    pb = (ProgressBar) findViewById(R.id.progressBar);
    pb.setVisibility(View.INVISIBLE);
}

private void initLogin(){
    usernameTxt = (EditText) findViewById(R.id.usernameTxt);
    passwordTxt = (EditText) findViewById(R.id.passwordTxt);
}

private void OnClickButtonListener(){
    loginbtn = (Button) findViewById(R.id.login);
    loginbtn.setOnClickListener(this);
}

private void requestData(String uri){
    ThreadClass t = new ThreadClass();
    t.execute(uri);
}

@Override
public void onClick(View v) {
    requestData(readStudentphp);
    //Intent intent = new Intent("com.example.shirlyn.attendancesystem.MainMenu");
    //startActivity(intent);
}

@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);
}

private class ThreadClass extends AsyncTask<String, String, String>{
    @Override
    protected void onPreExecute(){
        pb.setVisibility(View.VISIBLE);
    }

    @Override
    protected String doInBackground(String... params) {
        String content = HTTPManager.getData(params[0]);

        return content;
    }

    @Override
    protected void onPostExecute(String result){
        System.out.println("Before parsing");
        studentslist = StudentJSONParser.parseFeed(result);
        System.out.println("After parsing");
        if(studentslist != null && studentslist.size() > 0)
            System.out.println(studentslist.get(0).getStudent_name());
        pb.setVisibility(View.INVISIBLE);
    }
}

}

1 个答案:

答案 0 :(得分:1)

看起来您正在尝试将HTML解析为JSON(基于错误中的<br标记)。

<br of type java.lang.String cannot be converted to JSONArray

仔细检查您要解析的输出,以确保从终点返回JSON。可能是一个接受标题或类似的东西。