public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView listView = (ListView) findViewById(R.id.listview); MainAdapter
adapter = new MainAdapter(getData(), getBaseContext()); listView.setAdapter(adapter); } public String readTextFile(InputStream inputStream) { StringBuilder stringBuilder = new StringBuilder(); BufferedReader bufferedReader = null; try { bufferedReader = new
BufferedReader(new InputStreamReader(inputStream, "UTF-8")); String tempt; while ((tempt = bufferedReader.readLine()) != null) { stringBuilder.append(tempt); } bufferedReader.close(); inputStream.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace();
} catch (IOException e) { e.printStackTrace(); } return stringBuilder.toString(); } private List<Map> getData() { List<Map> list = new ArrayList<>(); Map map = new HashMap<>(); try { InputStream open = getAssets().open("demo.json"); String json = readTextFile(open);
JSONArray jsonArray = new JSONArray(json); for (int i = 0; i < jsonArray.length(); i++) { map = new HashMap<>(); map.put("name", jsonArray.getJSONObject(i).get("name")); map.put("age", jsonArray.getJSONObject(i).get("age")); list.add(map); } } catch (IOException
| JSONException e) { e.printStackTrace(); } return list; } public class MainAdapter extends BaseAdapter { private final Context context; private final List list; public MainAdapter(List list, Context context) { this.context = context; this.list = list; } @Override
public int getCount() { if (list == null) return 0; return list.size(); } @Override public Object getItem(int position) { if (list == null) return null; return list.get(position); } @Override public long getItemId(int position) { if (list == null) return 0;
return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.item, parent, false); viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } HashMap hashMap = (HashMap) list.get(position); viewHolder.name.setText((String) hashMap.get("name")); viewHolder.age.setText(String.valueOf((int) hashMap.get("age")));
return convertView; } class ViewHolder { TextView name, age; public ViewHolder(View view) { this.name = (TextView) view.findViewById(R.id.name); this.age = (TextView) view.findViewById(R.id.age); } } }}
从essets中获取json字符串并放到listview
本文介绍了一个具体的Android应用程序示例,展示了如何使用ListView组件结合自定义适配器显示从JSON文件中读取的数据。文章详细解释了如何创建一个能够解析JSON数据并将其展示在ListView上的适配器。

被折叠的 条评论
为什么被折叠?



