如何使用baseadapter将获取的json数据显示到listview中

2023-12-24

我是 android 和 java 的新手。最近我在使用 baseadapter 将获取的 json 数据显示到 listview 时遇到问题。 起初我用过这段代码

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

   new TheTask().execute();
  }
     class TheTask extends AsyncTask<Void,Void,String>
  {

@Override
protected String doInBackground(Void... params) {
    String str = null;
    try
    {
      HttpClient httpclient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost("http://10.0.2.2/BSDI/show.php");
      HttpResponse response = httpclient.execute(httppost);
      str =  EntityUtils.toString(response.getEntity());     
    } 
    catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }

    return str;

  }



@Override
    protected void onPostExecute(String result) {

    super.onPostExecute(result);

    String response = result.toString();
    try {


        ArrayList<String> stringArray = new ArrayList<String>();

        JSONArray new_array = new JSONArray(response);

        for(int i = 0, count = new_array.length(); i< count; i++)
        {
            try {
                JSONObject jsonObject = new_array.getJSONObject(i);
                stringArray.add(jsonObject.getString("title").toString());


            }
            catch (JSONException e) {
                e.printStackTrace();
            }
        }




        ArrayAdapter<String> adapter = new ArrayAdapter<String>   (MainActivity.this,R.layout.test_tuh,stringArray);            
        ListView list= (ListView) findViewById(R.id.listView1);
        list.setAdapter(adapter);

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        //tv.setText("error2");
    } 


}
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
  }

此代码成功显示获取的 json 数据。但它只显示一行。我需要在列表视图中多于一(两)行。所以我尝试过这段代码 它不起作用,它显示空白屏幕。

我的代码如下,

 class TheTask extends AsyncTask<Void,Void,String>
  {

    @Override
    protected String doInBackground(Void... params) {
    String str = null;
    try
    {
      HttpClient httpclient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost("http://10.0.2.2/BSDI/show.php");
      HttpResponse response = httpclient.execute(httppost);
      str =  EntityUtils.toString(response.getEntity());     
    } 
    catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }

    return str;

  }


@Override
    protected void onPostExecute(String result) {


    // TODO Auto-generated method stub
    super.onPostExecute(result);

    String response = result.toString();
    try {
         arrayList=new ArrayList<get_set>();

        ArrayList<String> stringArray = new ArrayList<String>();

        JSONArray new_array = new JSONArray(response);



        for(int i = 0, count = new_array.length(); i< count; i++)
        {
            try {
                JSONObject jsonObject = new_array.getJSONObject(i);
                stringArray.add(jsonObject.getString("title").toString());


            }
            catch (JSONException e) {
                e.printStackTrace();
            }
        }



   ListView listView;
    adap= new BaseAdapter() {
        LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        @Override
        public View getView(int position, View view, ViewGroup viewgroup) {
            if (view==null) {
                view=inflater.inflate(R.layout.bsdi, null);
            }
            TextView title_tuh=(TextView) view.findViewById(R.id.title1);
            TextView notice_tuh=(TextView) view.findViewById(R.id.notice1);


            title_tuh.setText(arrayList.get(position).getTitle());
            notice_tuh=.setText(arrayList.get(position).getNotice());
            return view;
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return arrayList.get(position);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return arrayList.size();
        }
    };


    listView=(ListView) findViewById(R.id.listView1);
    listView.setAdapter(adap);


    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        //tv.setText("error2");
    } 


}

据我所知,问题就在这里

ArrayList<String> stringArray = new ArrayList<String>();

        JSONArray new_array = new JSONArray(response);



        for(int i = 0, count = new_array.length(); i< count; i++)
        {
            try {
                JSONObject jsonObject = new_array.getJSONObject(i);
                stringArray.add(jsonObject.getString("title").toString());


            }
            catch (JSONException e) {
                e.printStackTrace();
            }
        }

到目前为止,我猜测提取的 json 数据存储在字符串数组中,但稍后不会使用。如果我尝试像这样使用它,则会出现错误

title_tuh.setText(stringArray .get(position).getTitle());
notice_tuh=.setText(stringArray .get(position).getNotice());

如果我尝试不使用 ArrayList stringArray = new ArrayList();

and use
数组列表=新的数组列表();相反,像这样我也会收到错误。

    arrayList=new ArrayList<get_set>();


        JSONArray new_array = new JSONArray(response);


        //JSONArray jsonArray = new JSONArray();
        for(int i = 0, count = new_array.length(); i< count; i++)
        {
            try {
                JSONObject jsonObject = new_array.getJSONObject(i);
                arrayList.add(jsonObject.getString("title").toString());
               // String in = mInflater.inflate(R.layout.custom_row_view, null);

            }
            catch (JSONException e) {
                e.printStackTrace();
            }
        }

我不知道如何解决这个问题。我看过很多在线教程,但这些对我没有帮助。请帮我。


首先你需要创建row_listitem.xml文件如:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:background="@drawable/list_selector"
android:orientation="vertical"
android:padding="5dp" >

<ImageView
    android:id="@+id/iv_icon_social"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_centerVertical="true"
    android:background="@drawable/image_border"
    android:src="@drawable/sms_t"
    android:visibility="gone" />

<LinearLayout
    android:id="@+id/thumbnail"
    android:layout_width="fill_parent"
    android:layout_height="85dp"
    android:layout_marginRight="50dp"
    android:layout_marginTop="0dp"
    android:layout_toRightOf="@+id/iv_icon_social"
    android:gravity="center_vertical"
    android:orientation="vertical"
    android:padding="5dip"
    android:visibility="visible" >

    <TextView
        android:id="@+id/txt_ttlsm_row"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:text="Sample text"
        android:textSize="18dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/txt_ttlcontact_row2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="0dp"
        android:layout_marginTop="3dp"
        android:paddingLeft="10dp"
        android:maxEms="20"
        android:maxLines="2"
        android:singleLine="false"
        android:ellipsize="end"
        android:text="Sample text2"
        android:textColor="#808080"
        android:textSize="15dp"
        android:textStyle="normal"
        android:visibility="visible" />


</LinearLayout>

</RelativeLayout>

现在,你需要创建定制底座适配器 like:

  public class BaseAdapter2 extends BaseAdapter {

private Activity activity;
// private ArrayList&lt;HashMap&lt;String, String&gt;&gt; data;
private static ArrayList title,notice;
private static LayoutInflater inflater = null;

public BaseAdapter2(Activity a, ArrayList b, ArrayList bod) {
    activity = a;
    this.title = b;
    this.notice=bod;

    inflater = (LayoutInflater) activity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

public int getCount() {
    return title.size();
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    View vi = convertView;
    if (convertView == null)
        vi = inflater.inflate(R.layout.row_listitem, null);

    TextView title2 = (TextView) vi.findViewById(R.id.txt_ttlsm_row); // title
    String song = title.get(position).toString();
    title2.setText(song);


    TextView title22 = (TextView) vi.findViewById(R.id.txt_ttlcontact_row2); // notice
    String song2 = notice.get(position).toString();
    title22.setText(song2);

return vi;

}

}

现在,您可以设置您的主要活动 like:

public class MainActivity extends Activity {

ArrayList<String> title_array = new ArrayList<String>();
ArrayList<String> notice_array = new ArrayList<String>();
ListView list;
BaseAdapter2 adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    list = (ListView) findViewById(R.id.listView1);
    new TheTask().execute();
}

class TheTask extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
        String str = null;
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(
                    "http://10.0.2.2/BSDI/show.php");
            HttpResponse response = httpclient.execute(httppost);
            str = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return str;

    }



@Override
protected void onPostExecute(String result) {

    super.onPostExecute(result);

    String response = result.toString();
    try {


        JSONArray new_array = new JSONArray(response);

        for (int i = 0, count = new_array.length(); i < count; i++) {
            try {
                JSONObject jsonObject = new_array.getJSONObject(i);
                title_array.add(jsonObject.getString("title").toString());
                notice_array.add(jsonObject.getString("notice").toString());

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        adapter = new BaseAdapter2(MainActivity.this, title_array, notice_array);
        list.setAdapter(adapter);

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        // tv.setText("error2");
    }

}
}

 }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用baseadapter将获取的json数据显示到listview中 的相关文章

随机推荐

  • SQL Server 的 timestamp2 在 JDBC 中如何工作?

    我在尝试在 SQL Server 2008 中使用 timestamp2 而不是 Timestamp 时遇到了一些麻烦 显然 rs getTimestamp 在 timestamp 和 timestamp2 之间有非常不同的行为 但是 我找
  • 文字轮播交叉淡入淡出效果?

    我们正在尝试实现一个简单的文本轮播 用几个其他单词替换句子中的单个单词 它们将淡入 淡出 容器宽度应缩小 放大以容纳新单词 听起来很简单 但我们遇到了困难 应该像第二行一样工作www branch com http www branch c
  • Google App Engine (Java) 上的全文搜索

    关于这个主题有一些线索 但我认为我的用例有些不同 我想做的事 我的 GAE J 应用程序的全文搜索组件 索引大小较小 25 50MB左右 我不需要实时更新索引 定期重新索引就可以了 这是为了自动完成等 所以它需要非常快 我的印象是在数据存储
  • 在 Servlet 中使用 org.json 会导致 java.lang.ClassNotFoundException: org.json.JSONException

    我正在尝试开发一个 servlet 来发送一些 JSON 对象 但遇到几个异常 我相信我需要添加一些 jar 文件 但我不确定是哪个 这是 doGet 方法以及我导入的所有内容 import java io IOException impo
  • 更改导航栏按钮项目的标题

    let button UIButton button setImage UIImage named coin icon forState UIControlState Normal button addTarget self action
  • 在 docker 容器外部公开日志文件

    我有 net core 应用程序 其中 Serilog 作为日志框架 现在 Serilog 正在记录到文件 我想将此文件公开在容器外部 并像其他文件一样进行简单的访问 我根据 docker compose 参考尝试使用volume和volu
  • 如何将我的电子表格链接到应用制作工具?

    我是 App Maker 的新用户 刚刚开始使用 Google App Scripts 进行编码 所以基本上我对这个主题了解不多 今天我正在开发一个已经存在于 Google Sheets 中的应用程序 我必须使用应用程序制作工具重新创建它
  • 了解操作系统如何存储/检索 IO 设备输入

    我对键盘等 I O 设备如何存储输入以供操作系统或应用程序使用感到有点困惑 如果我有一台单处理器 单核CPU 的计算机 并且当前正在执行的进程是一个游戏 那么游戏如何能够 感知 键盘输入 即使按下按键会强制硬件中断 从而实现上下文切换 然后
  • 在海岸线附近的 ggplot 中选择栅格

    所以我有一张绘制加泰罗尼亚气压的地图 这是一个特写 我现在想选择气压高于 97 kPa 深蓝色 的所有观测值 并用它们创建一个新的数据框以供进一步分析 这是棘手的一点 我想选择符合高度过滤器 AAAAND 的观测值 并且位于地中海沿岸 大多
  • “AspNetUser”类型上的“Claims”属性不是导航属性

    我正在使用 ASP NET Identity 2 2 我正在将 ASP NET 旧成员资格迁移到新的身份系统 我正在按照中提到的步骤进行操作本文 http www asp net identity overview migrations m
  • 如何使用 Google Relyparty 禁用用户 Firebase?

    我想从我的应用程序中禁用 Firebase 用户 但 Firebase 文档只提供了删除用户的选项 我认为解决方案就像创建用户一样 https www googleapis com identitytoolkit v3 relyingpar
  • 用于 bash 补全的“have”关键字

    Is havebash 中的关键字 或者 bash 补全脚本使用非 bash 的语言吗 have gcc gcc 是很常见 看 grep have etc bash completion d 我找不到有关我见过的 bash 完成教程的任何信
  • 如何在 R 中为数据框着色

    我有以下类型的数据框 gt df V1 V2 V3 V4 V5 1 10 603 3 100 2 1 5 1 2 10 603 3 101 3 2 4 5 3 10 603 3 102 1 3 3 2 4 10 603 1 103 4 4
  • .NET 中是否存在与 UI 无关的 Point 结构?

    我认识几个Point NET 中的结构 System Drawing Point System Windows Point Sys UI Point 但它们都位于高级 UI 库 GDI WPF AJAX 中 我需要一个Point我不想将其与
  • CUDA/OpenCL 中的现实死锁示例

    对于我正在编写的教程 我正在寻找一个 现实 且简单的示例 说明由于不了解 SIMT SIMD 而导致的死锁 我想出了这个片段 这似乎是一个很好的例子 任何意见将不胜感激 int x threadID 2 if threadID gt x v
  • Python 中是否有已经制作好的字母表? [复制]

    这个问题在这里已经有答案了 我需要创建随机单词 名称random choice alphabet 对于我在 repl 中的许多游戏来说 但输入它并制作大写版本 仅辅音 元音等是很痛苦的 有没有一种内置的或可导入的方法来获取 python 中
  • 让 Bootstrap datetimepicker 在 ajax 加载后工作

    我有这个简单的脚本 可以正常形式工作 但是 如果我通过 ajax 将表单加载到 Bootstrap 3 模式中 时间和日期选择器不起作用 我知道问题是因为我通过 ajax 加载表单 那么如何为新加载的a
  • 简单的 Java 扫描器代码不起作用[重复]

    这个问题已经存在了 这是我为制作一个简单游戏而编写的一些基本代码的框架 Scanner in new Scanner System in String name String playing int age do System out pr
  • 如何从 iPhone 中的资源文件夹中获取文件夹和文件列表?

    我正在资源文件夹中执行文件夹结构 例如 Resource gt MyData gt S1 然后在S1 gt Name png data ppt 现在我想获取所有文件夹列表和文件名 这里 MyData 名称只是静态的 其他名称可能会更改 就像
  • 如何使用baseadapter将获取的json数据显示到listview中

    我是 android 和 java 的新手 最近我在使用 baseadapter 将获取的 json 数据显示到 listview 时遇到问题 起初我用过这段代码 Override protected void onCreate Bundl