【问题标题】:Get JSONObject from JSONArray and display in listview - Retrofit从 JSONArray 中获取 JSONObject 并显示在 listview 中 - Retrofit
【发布时间】:2018-10-12 21:15:26
【问题描述】:

我想在列表视图中显示一个 JSONObject。

private void showStudentInfo(final List<StudentDetails> studentDetails) {

    String userNameValue = getIntent().getStringExtra("name");

    if(studentDetails != null) {
        final ArrayList<Map<String, Object>> itemDataList = new ArrayList<>();

        int size = studentDetails.size();

        for(int i=0; i<size; i++)
        {
            StudentDetails student = studentDetails.get(i);

            Map<String, Object> listItemMap = new HashMap<>();
            listItemMap.put("id", student.getId());
            listItemMap.put("name", student.getId());
            listItemMap.put("email", student.getId());
            listItemMap.put("phone", student.getId());
            listItemMap.put("addresS", student.getId());

            itemDataList.add(listItemMap);
        }

        SimpleAdapter simpleAdapter = new SimpleAdapter(this, itemDataList, R.layout.list_row,
                new String[]{"id", "name","email","phone","addresS"}, 
                new int[]{R.id.id_textview, 
                        R.id.name_textview,
                        R.id.email_textview,
                        R.id.phone_textview,
                        R.id.address_textview
                });
    }
}

JSON

[{
    "id": "1",
    "name": "Ramesh",
    "email": "Ramesh@gmail.com",
    "phone": "123456789",
    "addresS": "blah blah blah"
},

{
    "id": "2",
    "name": "Mahesh",
    "email": "Mahesh@gmail.com",
    "phone": "123456789",
    "addresS": "blah blah blah"
},

....
]

OnClickListener

studentListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(final AdapterView<?> parent, View view, int position, long id) {

                    selectedItem = studentDetails.get(position).getName();

                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);

                    alertDialogBuilder.setPositiveButton("View", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(MainActivity.this, selectedItem, Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(MainActivity.this, DetailsActivity.class);
                            intent.putExtra("name", selectedItem);
                            startActivity(intent);
                        }
                    });

我想要的是,如果用户在之前的活动中单击例如 - mahesh,那么我想从 json 文件中获取该名称的详细信息 - id、name、email ......并将其显示在列表视图中。

StudentManager界面

 @GET("rnr0k")
public Call<List<StudentDetails>> getUserByName(
        @Query("name") String studentNameValue
);

学生详情

Getter and Setter methods.

学生经理

private static String BASEURL = "https://api.myjson.com/bins/";

public static StudentManagerInterface getStudentManagerService(Converter.Factory converterFactory) {

    Retrofit.Builder retrofitBuilder = new Retrofit.Builder();

    retrofitBuilder.baseUrl(BASEURL);

    if(converterFactory!=null) {
        retrofitBuilder.addConverterFactory(converterFactory);
    }

    Retrofit retrofit = retrofitBuilder.build();

    StudentManagerInterface studentManagerInterface = retrofit.create(StudentManagerInterface.class);
    return studentManagerInterface;

我正在使用改造,我是这方面的新手。感谢@TaQuangTu 的回答,但我很困惑,因为我没有使用 JSONArray。 我必须对我的代码进行哪些更改?

【问题讨论】:

  • 您想加载所有学生,然后在列表视图中只显示他们的姓名,并在每次点击项目时显示学生的完整信息,对吧?
  • 是的,我正在显示所有学生列表,如果用户单击任何学生姓名,那么在下一个活动中,我只想显示该学生的所有详细信息。
  • 好的,等我,我正在输入问题的答案
  • 好的,谢谢!我在等。

标签: json listview arraylist gson retrofit2


【解决方案1】:

您的代码几乎是正确的,除了以下部分。

Map<String,Object> listItemMap = new HashMap<>();
listItemMap.get(student.getId());    // here is the problem
listItemMap.get(student.getName());  // here is the problem
itemDataList.add(listItemMap);

您从空的(或新创建的)HashMap 获取值(id 和名称),而不是向其中添加数据。像下面这样的简单更改可能会解决您的问题(因为我自己没有测试过代码)。

Map<String, Object> listItemMap = new HashMap<>();
listItemMap.put("id", student.getId());     // use put() with key "id"
listItemMap.put("name", student.getName()); // use put() with key "name"
itemDataList.add(listItemMap);

如果上述解决方案不能解决问题,我建议您调试代码并确保studentDetails (ArrayList) 不为空。这意味着您的 API 正在返回正确的数据。

编辑

要仅显示名称,只需进行以下更改。

SimpleAdapter simpleAdapter = new SimpleAdapter(this, itemDataList,R.layout.list_row,
            new String[]{"name"}, new int[]{R.id.name_textview});

从适配器中删除 id 值(仅传递名称)。并从 XML 布局中删除 id_textview TextView。就是这样!

祝你好运!

【讨论】:

  • 您好,感谢您的回复。我做了一些更改并且正在工作,但现在我想要的只是 userNameValue 的数据应该显示在 listview 上。
  • 嘿,请再次检查我的问题,我已编辑。谢谢!
  • 检查这个 StackOverflow answer。按照代码并使用startActviity() 方法将名称传递给下一个活动。
  • 我已经这样做了,但我想从 json 数组中获取该名称的详细信息。
【解决方案2】:

假设你有 Json 字符串。示例

 String mJson = "[{
    "id": "1",
    "name": "Ramesh",
    "email": "Ramesh@gmail.com",
    "phone": "123456789",
    "addresS": "blah blah blah" },
 {
    "id": "2",
    "name": "Mahesh",
    "email": "Mahesh@gmail.com",
    "phone": "123456789",
    "addresS": "blah blah blah" },
 .... ]"

然后,创建一个数组列表来存储来自 Json 字符串的StudentDetails 对象:

 ArrayList<User> getArrayList(String mJson)
  {
       ArrayList<User> studentArrayList= new ArrayList<>();
       try
       {
           JSONArray jsonArray = new JSONArray(mJson);
           for(int i=0;i<jsonArray.length();i++)
           {
               JSONObject student= (JSONObject) jsonArray.getJSONObject(i);
               StudentDetails studentId= student.getInt("id");
               String studentName= student.getString("name");
               //get more fields if you want
               studentArrayList.add(new StudentDetails(userId,name,/*parameter*/));//assuming class StudentDetails have the constructor
           }
       } catch (JSONException e) {
           e.printStackTrace();
       }
       return studentArrayList;
 }

之后,为每个列表视图项创建一个简单的布局,如下所示: 文件 layout_studen_item.xml

 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        android:orientation="vertical"
        xmlns:android="http://schemas.android.com/apk/res/android" 
        android:layout_width="match_parent"
        android:layout_height="match_parent">
         <TextView
             android:id="@+id/tv_name"
             android:text="Name"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:textSize="25sp"
             android:textColor="#161616"/>
        <TextView
            android:id="@+id/tv_id"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="20sp"
            android:textColor="#000000" />
    </LinearLayout>

然后,使用上述布局为列表视图创建自定义适配器。

public class StudentAdapter extends BaseAdapter {
    private Context mContext;
    private int mIdResourceLayout;
    private List<StudentDetails> StudentList;

    public StudentAdapter(Context mContext, int mIdResourceLayout, List<StudentDetails> StudentList)
    {
        this.mContext = mContext;
        this.mIdResourceLayout = mIdResourceLayout;
        this.studentList= studentList;
    }
    @Override
    public int getCount() {
        return studentList.size();
    }

    @Override
    public Object getItem(int i) {
        return studentList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return studentList.get(i).getmId(); //getmID is a method of StudentDetails class
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup)
    {
        ViewHolder viewHolder = null;
        if(view==null)
        {
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(mIdResourceLayout,null);
            viewHolder = new ViewHolder();
            viewHolder.mTextViewName = view.findViewById(R.id.tv_name);
            viewHolder.mTextViewId   = view.findViewById(R.id.tv_id);
            view.setTag(viewHolder);
        }
        else
        {
                viewHolder = (ViewHolder) view.getTag();
        }
        viewHolder.mTextViewId.setText("Id: "+studentList.get(i).getmId());
        viewHolder.mTextViewName.setText("Name: "+studentList.get(i).getmName());//getmName is a method of class StudentDetails
        return view;
    }
    private class ViewHolder
    {
        TextView mTextViewName,mTextViewId;
    }
}

那么,在mainActivity中,假设你有一个listview,让我们为它设置adapter。

ArrayList<StudentDetails> studentList = getArrayList(mJson); //mJson is the json file that i have mentioned above
StudentAdapter adapter= new StudentAdapter(MainActivity.this,R.layout.layout_student_item,studentList);
mListViewUser.setAdapter(adapter);

现在,您已经在 ArrayList studentList 中获得了所有学生信息,一切都变得容易了。

【讨论】:

  • 嘿!感谢您付出宝贵的时间。你能检查我的问题吗?我已经编辑过了。
猜你喜欢
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多