0

I want to display a JSONObject in listview.

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);
                        }
                    });

What I want is if a user clicks on eg - mahesh in previous activity then I want to get the details for that name from json file - id,name,email,... and display that in listview.

StudentManagerInterface

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

StudentDetails

Getter and Setter methods.

StudentManager

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;

I'm using retrofit and I'm a newbie in this. Thanks @TaQuangTu for answering but I'm confused because I'm not using JSONArray. What changes I have to make in my code?

2 Answers2

0

Your code is almost correct except the below part.

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);

You're getting values (id and name) from a empty (or newly created) HashMap instead adding data to it. A simple changes like below may solve your problem (as I haven't tested code myself).

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);

If above specified solution doesn't fix the problem, I would suggest you to debug the code and ensure that the studentDetails (ArrayList) is not empty. Which means your API is returning the proper data.

Edit

To display only name just do the below changes.

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

Remove id values from Adapter (pass only names). And also remove id_textview TextView from XML layout. That's it!

Good luck!

Shashanth
  • 4,995
  • 7
  • 41
  • 51
0

Assume you have had Json string. Example

 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" },
 .... ]"

Then, create an array list to store StudentDetails objects from the Json string:

 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;
 }

After that, create a simple layout for each listview item as something likes that: File 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>

Then, create custom adapter for the list view with the above layout.

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;
    }
}

Then, in mainActivity,assuming you have a listview, let's set adapter for it.

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);

Now, you have had all student information in the ArrayList studentList, everthing become easy with you.

TaQuangTu
  • 2,155
  • 2
  • 16
  • 30