【问题标题】:Storing multiple results from JSON从 JSON 存储多个结果
【发布时间】:2012-04-03 02:35:10
【问题描述】:

谁能建议一种方法来修改 JSONParser 的 getQuestionJSONFromUrl() 方法,以便它将每个问题作为自己的对象存储在 Android 中?通过 PHP JSON 从浏览器中的 SQL 表读取多个结果,如下所示:

{"category":"elections","id":"0","title":"Who will you vote for in November's Presidential election?","published":"2012-04-02","enddate":"2012-04-30","responsetype":"0"}

{"category":"elections","id":"2","title":"Question title, ladies and gents","published":"2012-04-02","enddate":"2012-04-30","responsetype":"1"}

目前,结果甚至不包括结束大括号和开始大括号之间的空格。但我可以添加到我的 php: echo "\n";当 JSON 读出时,这会给我两行之间的空间。所以现在显然是两行填充内容。最终,该 SQL 表中将包含真实的内容。

我希望能够将这些行分解为对象(我想可能是我的本地 SQLite db?),以便我可以使用它们在片段中将每个行显示为屏幕上的一个表行。我不太担心屏幕方面,但是将数据转换为可行的形式是一个问题。目前,我的代码仅将第一组大括号存储为 JSON 对象。以下是所有相关代码:

public UserFunctions(){
    jsonParser = new JSONParser();
}

public JSONObject getQuestions(String category) {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", question_tag));
    params.add(new BasicNameValuePair("category", category));
    JSONObject json = jsonParser.getQuestionJSONFromUrl(questionURL, params);
    return json;
}


public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static JSONObject[] jsonArray = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

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

        // Making HTTP request
    try {
            // defaultHttpClient
            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) {
                Log.v("while", line);
                sb.append(line + "\n");
                //Log.v("err", line);
            }
            is.close();
            json = sb.toString();


        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }

谁能建议一种方法来修改 JSONParser 的 getQuestionJSONFromUrl() 方法,以便它将每个问题作为自己的对象存储在 Android 中?我确实有一个本地 SQLite 数据库,我可以在其中添加一个或两个方法来添加第二个表等:

package library;

import java.util.HashMap;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHandler extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "android_api";

    // Login table name
    private static final String TABLE_LOGIN = "login";

    // Login Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    public static final String KEY_EMAIL = "email";
    private static final String KEY_UID = "uid";
    private static final String KEY_CREATED_AT = "created_at";

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
                + KEY_ID + " INTEGER PRIMARY KEY,"
                + KEY_NAME + " TEXT,"
                + KEY_EMAIL + " TEXT UNIQUE,"
                + KEY_UID + " TEXT,"
                + KEY_CREATED_AT + " TEXT" + ")";
        db.execSQL(CREATE_LOGIN_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);

        // Create tables again
        onCreate(db);
    }

    /**
     * Storing user details in database
     * */
    public void addUser(String name, String email, String uid, String created_at) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, name); // Name
        values.put(KEY_EMAIL, email); // Email
        values.put(KEY_UID, uid); // Email
        values.put(KEY_CREATED_AT, created_at); // Created At

        // Inserting Row
        db.insert(TABLE_LOGIN, null, values);
        db.close(); // Closing database connection
    }

    /**
     * Getting user data from database
     * */
    public HashMap<String, String> getUserDetails(){
        HashMap<String,String> user = new HashMap<String,String>();
        String selectQuery = "SELECT  * FROM " + TABLE_LOGIN;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        // Move to first row
        cursor.moveToFirst();
        if(cursor.getCount() > 0){
            user.put("name", cursor.getString(1));
            user.put("email", cursor.getString(2));
            user.put("uid", cursor.getString(3));
            user.put("created_at", cursor.getString(4));
        }
        cursor.close();
        db.close();
        // return user
        return user;
    }

    /**
     * Getting user login status
     * return true if rows are there in table
     * */
    public int getRowCount() {
        String countQuery = "SELECT  * FROM " + TABLE_LOGIN;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        int rowCount = cursor.getCount();
        db.close();
        cursor.close();

        // return row count
        return rowCount;
    }

    /**
     * Re crate database
     * Delete all tables and create them again
     * */
    public void resetTables(){
        SQLiteDatabase db = this.getWritableDatabase();
        // Delete All Rows
        db.delete(TABLE_LOGIN, null, null);
        db.close();
    }

}

【问题讨论】:

    标签: php android mysql android-asynctask


    【解决方案1】:

    使getQuestionJSONFromUrl 返回字符串。然后使用该字符串创建 JSONObject 并解析它。看下面的例子。

            JSONObject jsonobj=new JSONObject(str);
            String category=jsonobj.getString("category");
            String title=jsonobj.getString("title");
            int id=jsonobj.getInt("id");
            String published=jsonobj.getString("published");
            String enddate=jsonobj.getString("enddate");
            int responsetype=jsonobj.getInt("responsetype");
            System.out.println(category+" "+title +" "+id +" "+published +" "+enddate +" "+responsetype);
    

    【讨论】:

    • 这很有帮助,并且像宣传的那样工作 - 但如果方法 getQuestion... 只运行一次,并且有 20 个(任意数字,有时会更多,有时会更少)问题得到返回,该方法需要如何更改以容纳来自 SQL 的 20 个单独的行?
    • 使用 for 循环进行多次检索,例如 for(int i = 0; i
    • 我已经为此工作了一整天,但仍然无法正常工作。我能做的最好的事情是检测“}{”(两个 JSON 的结束/开始)并将第一部分放在字符串中并删除后半部分。我发现我需要的方法不存在。
    【解决方案2】:

    如果您的响应内容更多结果然后使用 for 循环检索所有数据,只需按照以下代码进行操作,希望它对您有用。

     JSONArray Arraylist = new JSONArray();
    Arraylist=new JSONObject(output).getJSONObject("category").getJSONArray("title");
    
    for (int i = 0; i < Arraylist.length(); i++)
    {
        JSONObject headObject = Arraylist.getJSONObject(i);
        String  Question_title= headObject.optString("Question title");
        String published=headObject.optString("published");
        String enddate=headObject.optString("enddate");
    
    }
    

    【讨论】:

    • 我可以看到所有这些代码是如何工作的,但是我有一个问题。我该如何解决: while ((line = reader.readLine()) != null) { ?这是服务器的 JSON 输出中显示的两组 {} {} 之间的自然断点(一个空空格)。如何编写一种方法来存储当前生成的字符串,然后在 null 停止它到达第二行输出之前重做 while 循环?
    【解决方案3】:

    这是使 PHP 脚本返回正确编码的 JSON 数据的解决方案。我目前仍在研究如何让 Android 将其解析为 JSONArray:https://stackoverflow.com/a/10019165/1231943

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-27
      • 2011-07-14
      • 2013-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多