2011-12-25 73 views
0

我正在嘗試編寫一個應用程序,它將連接到數據庫,提取數據並在手機上顯示該數據。儘管我遇到了一個問題。在ListView中顯示JsonArray

我連接到使用數據庫:

try {   
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("http://74.208.131.62/Androidtest/testscript.php"); 
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
    HttpResponse response = httpclient.execute(httppost); 
    HttpEntity entity = response.getEntity(); 
    is = entity.getContent(); 
    Log.d("Connection Success","Connected To Database"); 
} catch(Exception e) { 

} 

test.php的是一個SQL將返回值:ITEM_ID(auto_inc_int),OtherTerms(字符串)。

然後,我把它轉換爲字符串:

BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); 
sb = new StringBuilder(); 
sb.append(reader.readLine() + "\n"); 
String line = "0"; 

while ((line = reader.readLine()) != null) { 
    sb.append(line + "\n"); 
    is.close(); 
    result = sb.toString(); 
} 

然後我用這部分,我不明白,我只是從網上抄了一遍:

int Item_id; 
String Item_name; 
String populate = new String(); 

try {  
    jArray = new JSONArray(result); 
    JSONObject json_data = null; 
    for(int i = 0; i < jArray.length(); i++) { 
     json_data = jArray.getJSONObject(i); 
     Item_id = json_data.getInt("id"); 
     Item_name = json_data.getString("item"); 
    } 
... 

然而,我收到消息「沒有找到物品」。我嘗試更改數據庫的名稱,但LogCat中沒有出現「連接錯誤」,而是「找不到任何項目」。

我不知道我的應用程序是否成功連接到數據庫。我需要將結果插入到ListView對象中。我究竟做錯了什麼?

(另外,節日快樂給大家!)

回答

2

我在一個應用程序,不正是你正在嘗試做的工作。

繼承人我的代碼:

這是主要活動。在這裏你連接到php文件並從JSON結果創建一個數組。

public class mainActivity extends Activity { 



@Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.menu); 

    ArrayList<List> menuitems = getItems("android", 1); //Call to function to get results from web, you can put variables to pass here 

    ListView listView = (ListView) findViewById(R.id.Menu); 
    listView.setAdapter(new ListAdapter(this, R.layout.categorymenu, menuitems)); 

    listView.setOnItemClickListener(new OnItemClickListener() { 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) {    
      ON CLICK ACTIVITY GOES HERE 




     } 
    }); 
} 

public ArrayList<List> getItems(String searchTerm, int page) { 
    String searchUrl = "URL TO YOUR PHP FILE GOES HERE"; 

    ArrayList<List> lists = new ArrayList<List>(); 

    HttpClient client = new DefaultHttpClient(); 
    HttpGet get = new HttpGet(searchUrl); 

    ResponseHandler<String> responseHandler = new BasicResponseHandler(); 

    String responseBody = null; 
    try{ 
     responseBody = client.execute(get, responseHandler); 
    }catch(Exception ex) { 
     ex.printStackTrace(); 
    } 

    JSONObject jsonObject = null; 
    JSONParser parser=new JSONParser(); 

    try { 
     Object obj = parser.parse(responseBody); 
     jsonObject=(JSONObject)obj; 

    }catch(Exception ex){ 
     Log.v("TEST","Exception: " + ex.getMessage()); 
    } 

    JSONArray arr = null; 

    try { 
     Object j = jsonObject.get("results"); 
     arr = (JSONArray)j; 
    }catch(Exception ex){ 
     Log.v("TEST","Exception: " + ex.getMessage()); 
    } 

    for(Object t : arr) { 
     List list = new List(
       ((JSONObject)t).get("categories_name").toString(), 
       ((JSONObject)t).get("categories_id").toString() 
       ); 
     lists.add(list); 
    } 

    return lists; 


} 

/** Classes **/ 

public class List { 
    public String name; 
    public String message; 
    public Boolean usernameSet = false; 
    public Boolean messageSet = false; 

    public List(String username, String message) { 
     this.name = username; 
     this.message = message; 
    } 
} 

} 

然後我用menuListAdapater類創建列表視圖:

public class menuListAdapter extends ArrayAdapter<List> { 
private ArrayList<List> lists; 
    private Activity activity; 


public menuListAdapter(Activity a, int textViewResourceId, ArrayList<List> lists) { 
    super(a, textViewResourceId, lists); 
    this.lists = lists; 
    activity = a; 

} 

public static class ViewHolder{ 
    public TextView name; 
    public TextView message; 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    View v = convertView; 
    ViewHolder holder; 
    if (v == null) {   
     LayoutInflater vi = 
      (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     v = vi.inflate(R.layout.categorymenu, null); 
     holder = new ViewHolder(); 
     holder.name = (TextView) v.findViewById(R.id.categoryname); 
     holder.message = (TextView) v.findViewById(R.id.message); 
     v.setTag(holder); 
    } 
    else 
     holder=(ViewHolder)v.getTag(); 

    final List list = lists.get(position); 
    if (list != null) { 
     holder.name.setText(list.name); 
     holder.message.setText(list.message); 
    } 

    return v; 
} 

} 

我強烈建議你測試你的PHP文件的輸出在一個瀏覽器,以確保您的查詢,並連接到數據庫正常工作。

祝你好運!

+0

所以,你的意思是沒有listadapter我不能完成這個? (我只通過使用JsonObject試過它..非常感謝你的答覆!它幫助了很多! – Beetle 2011-12-27 18:11:42

+0

我試圖理解你給我的代碼。我有一個小問題搞清楚R.layout.catagorymenu。什麼是這個對象?一個列表視圖? – Beetle 2012-01-11 02:19:56