【问题标题】:How To populate All Columns In ListView Android如何填充 ListView Android 中的所有列
【发布时间】:2017-01-08 16:08:31
【问题描述】:

我从mysql databasephp 获取数据,我获取了两个值,但适配器只显示一个。

这是我的 android getData() 函数,现在正在获取一列我想获取第二列,但我没有得到

public void getdata(){
    try {
        URL url=new URL(retri_url);
        try {
            HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            IS=new BufferedInputStream(httpURLConnection.getInputStream());

        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(IS));

        StringBuilder stringBuilder=new StringBuilder();
        while((line=bufferedReader.readLine())!=null){
            stringBuilder.append(line+"\n");    
        }
        IS.close();
       result=stringBuilder.toString();

    } catch (IOException e) {
        e.printStackTrace();
    }
    try{
        JSONArray jsonArray=new JSONArray(result);
        JSONObject jsonObject=null;
        data=new String[jsonArray.length()];

        for(int i=0;i<jsonArray.length();i++){

            jsonObject=jsonArray.getJSONObject(i);

            int id=Integer.parseInt(jsonObject.get("id").toString());
            String strI = String.valueOf(id);
            data[i] =strI;
            data[i]=jsonObject.getString("Name");    
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }  
}

【问题讨论】:

  • 因为你只在字符串数组中获取一列Address,所以使用 POJO 类
  • 你能举个例子吗
  • @PavneetSingh 我已经编辑了代码请检查只有一列正在获取.. 并非所有列都不起作用!
  • 发表您的回复
  • 我只得到一列,但日志猫没有错误

标签: php android mysql


【解决方案1】:

问题是代码在这里使用单个数组datanames 的数据覆盖到id

data[i] =strI;
data[i]=jsonObject.getString("Name");

我建议继续自定义适配器,但根据要求快速修复,这里是解决方案

1.) 创建三个数组

String[] names, data;
//        ^^        to store names        
//              ^^  to store re-presentable data like "pavneet   2122"  
int[] id ;
//   ^^  to store ids

2.) 初始化数组

data=new String[jsonArray.length()];
names=new String[jsonArray.length()];
id=new int[jsonArray.length()];

3.) 使用 optIntoptString ,将为您处理解析

JSONArray jsonArray=new JSONArray(result);
JSONObject jsonObject=null;
data=new String[jsonArray.length()];
names=new String[jsonArray.length()];
id=new int[jsonArray.length()];

for(int i=0;i<jsonArray.length();i++){

 jsonObject=jsonArray.getJSONObject(i);
    id[i]=jsonObject.optInt("id");
    name[i]=jsonObject.optString("Name");
    data[i]=id[i]+"\t\t"+name[i];

注意:\t\t 用于制表符空间,因此您可以将\n 用于两行格式

您可以使用此 data[i]=name[i]+"\t\t"+id[i]; 来显示姓名和 ID
`

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    相关资源
    最近更新 更多