2012-04-03 61 views
0

多個結果,任何人都可以提出一個方法)來修改JSONParser的getQuestionJSONFromUrl(方法,這樣它存儲每一個問題作爲自己的Android對象?通過從SQL表看起來像這樣在瀏覽器PHP JSON返回讀取多個結果:存儲從JSON

{"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:回聲「\ n」;當JSON讀出時,這會給我兩行之間的空間。所以現在顯然是兩排填充物。最終會在該SQL表中存在真實的內容。

我希望能夠將這些行分解成對象(可能是我本地的SQLite數據庫我想?),以便我可以使用它們在屏幕上顯示每個片段作爲片段。我並不太擔心屏幕方面的問題,但將數據轉換爲可行的形式是一個問題。目前,我的代碼只將第一組大括號存儲爲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(); 
    } 

} 

回答

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); 
+0

這是非常有用的,並且可以像廣告一樣工作 - 但是如果方法getQuestion ...只運行一次,並且有20個(任意數字,有時會更多,有時它會更少)得到返回的問題,請問該方法需要改變,以適應從SQL 20個分開行? – Davek804 2012-04-03 04:04:57

+0

使用for循環,用於檢索一個以上的時間,如對於 (INT I = 0; I wolverine 2012-04-03 04:16:50

+0

我花了一整天在這方面的工作,我仍然不能得到它的工作。我已經能夠做的最好的是檢測「} {」(二JSON結束/開始),並放置在一個字符串的第一部分,並刪除了下半場。我發現我需要的方法不在那裏。 – Davek804 2012-04-04 03:58:43

1

如果您迴應的內容更多的結果,那麼使用循環來獲取所有數據,只需按照下面的代碼,希望它會爲你的作品。

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"); 

} 
+0

我可以看到所有這些代碼如何工作,但我遇到了問題。我如何解決:while((line = reader.readLine())!= null){?這是服務器JSON輸出中顯示的兩組{} {}之間的自然斷點(空間)。我如何編寫一個方法來存儲被成爲當前字符串,然後重做while循環當空停止其到達輸出的第二行之前? – Davek804 2012-04-03 06:30:18