0

How would I go about parsing this JSON object and getting the "groups" array in Java on Android.

{ "groups": [ "Total_Social_Beta_Testers", "Test_Group" ] }

Here's my code:

LoginActivity.java

    Response.Listener<String> responseListener = new Response.Listener<String>() {


        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonResponse = new JSONObject(response);
                boolean success = jsonResponse.getBoolean("success");

                if (success) {
                    String username = jsonResponse.getString("username");
                    String email = jsonResponse.getString("email");
                    String gender = jsonResponse.getString("gender");
                    String country = jsonResponse.getString("country");
                    String verified = jsonResponse.getString("verified");
                    String avatar = jsonResponse.getString("avatar");
                    //String group = jsonResponse.getString("groups");

                    int numlength = 0;
                    int CI = 0;

                    JSONArray jsonArrayGR = jsonResponse.getJSONArray("groups");
                    //String array of 500 spots
                    String rows = "";

                    for (int i = 0; i < jsonArrayGR.length(); i++){
                        CI++;
                        rows = jsonArrayGR.getString(i);
                    }
                    //int rows = jsonResponse.getInt("rows");

                    //Starting Activity
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    intent. addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                    intent.putExtra("username", username);
                    intent.putExtra("email", email);
                    intent.putExtra("gender", gender);
                    intent.putExtra("country", country);
                    intent.putExtra("verified", verified);
                    intent.putExtra("avatar", avatar);
                    intent.putExtra("groups", rows);

                    //intent.putExtra("rows", rows);

                    session.createUserSession(
                            username,
                            email,
                            gender,
                            country,
                            verified,
                            avatar,
                            rows
                    );

                    Toast.makeText(getBaseContext(), "Login succeed, welcome!" , Toast.LENGTH_LONG).show();

                    //Adding a new flag to start the activity
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    LoginActivity.this.startActivity(intent);
                    _loginButton.setEnabled(true);
                    finish();

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

    };
    LoginRequest loginRequest = new LoginRequest(e, password, responseListener);
    RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
    queue.add(loginRequest);

UserSession.java

 public void createUserSession(
        String name,
        String email,
        String gender,
        String country,
        String verified,
        String avatar,
        String groups){

    //Storage_Start session
    editor.putBoolean(IS_USER_LOGIN, true);

    // Storing name in pref
    editor.putString(KEY_NAME, name);

    //Storage of the email in pref
    editor.putString(KEY_EMAIL, email);

    //Storing the gender
    editor.putString(KEY_GENDER, gender);

    //Storing the country
    editor.putString(KEY_COUNTRY, country);

    //Storing the verified
    editor.putString(KEY_VERIFIED, verified);

    //Storing avatar
    editor.putString(KEY_AVATAR, avatar);

    //Storing groups
    editor.putString(KEY_GROUPS, groups);

    //Storing the gRows
    //editor.putInt(INT_GROUPS, numlength);

    //commit changes
    editor.commit();
}




/**
 * Get stored session data
 * */
public HashMap<String, String> getUserDetails(){

    //Use hashmap to store user credentials
    HashMap<String, String> user = new HashMap<String, String>();

    // user name
    user.put(KEY_NAME, pref.getString(KEY_NAME, null));

    // user email id
    user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));

    //gender
    user.put(KEY_GENDER, pref.getString(KEY_GENDER, null));

    //country
    user.put(KEY_COUNTRY, pref.getString(KEY_COUNTRY, null));

    //verifed?
    user.put(KEY_VERIFIED, pref.getString(KEY_VERIFIED, null));

    //Avatar
    user.put(KEY_AVATAR, pref.getString(KEY_AVATAR, null));

    //Groups
    user.put(KEY_GROUPS, pref.getString(KEY_GROUPS, null));

    // return user
    return user;
}

UPDATE This is where I am storing the values into the recyclerview:

public class ChatsAdapter extends RecyclerView.Adapter<ChatsAdapter.MyViewHolder> {
private List<Groups> chatlist;

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView group;

    public MyViewHolder(View view) {
        super(view);
        group = (TextView) view.findViewById(R.id.groups);
    }
}

public ChatsAdapter(List<Groups> chatlist){
    this.chatlist = chatlist;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)    {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.chat_row_list, parent, false);

    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    Groups groups = chatlist.get(position);
    holder.group.setText(groups.getTitle());
}

@Override
    public int getItemCount() {
        return chatlist.size();
   }
}

And this is how I am defining the strings:

 public class Groups {
    private String groups = "";

    public Groups() {
    }

     public Groups(String groups) {
         this.groups = groups;
     }

     public String getTitle() {
         return groups;
     }
   }

This is how I am displaying the values set by the adapter (above) in my main activity:

    //groups
    String g = user.get(UserSessionManager.KEY_GROUPS);

    String numrows = user.get(UserSessionManager.INT_GROUPS);

    //String grows = user.get(UserSessionManager.INT_GROUPS);


    int rows = Integer.parseInt(numrows);

    Groups groups = new Groups(g);
    groupslist.add(groups);


    chatsAdapter.notifyDataSetChanged();
George Guo
  • 13
  • 7

4 Answers4

0

You should make a ArrayList<String> from this JSONArray and use this List to fill your RecyclerView,

 ArrayList<String> listdata = new ArrayList<String>();
 if (jArray != null) { 
     for (int i=0;i<jArray.length();i++)
           listdata.add(jsonArrayGR.getString(i));
 } 

Now you can send this List to your MainActivity and fill your RecyclerView, which is required by you.

In current Activity ->

Bundle extra = new Bundle();
extra.putSerializable("list", listdata);

Intent intent = new Intent(getBaseContext(), MainActivity.class);
intent.putExtra("extra", extra);

In Mainactivity ->

Bundle extra = getIntent().getBundleExtra("extra");
ArrayList<Object> objects = (ArrayList<Object>) extra.getSerializable("objects")
jack jay
  • 2,493
  • 1
  • 14
  • 27
0

in your app.gradle, add this line under dependencies

compile 'com.google.code.gson:gson:2.3'

and the sync your project.

Now create a .java file with name GroupsModal.java
add this in your GroupsModal.java file

private Groups groups;

//getters and setters

Now create a .java file with name Groups.java
and add these lines :

private String Total_Social_Beta_Testers;
//getters and setters

now in your loginActivity.java

@Override
        public void onResponse(String response) {
 GroupsModal groupsModal = gson.fromJson(response, GroupsModal.class);

if(groupsModal.getSuccessResponse == 200){
  // successfully logged in
 /*
 * you can create classes and variables according to your JSON here
 * for gson.fromJson,
 * define at the top of loginActivity,
 * private Gson gson = new Gson();
 */
}
}

Hope it helps..

sohaib karim
  • 281
  • 2
  • 12
  • Okay. I still don't get it. Somewhat, but no all of it. Btw. I already have a file called Groups.java – George Guo Feb 05 '17 at 00:15
  • GSON is a library which helps us in parsing the JSON easy. When u will receive the response from the API and you pass that response in your GroupsModal.java file, it will search for the **keyword** groups in that file, and once it finds it, it will start the parsing if it finds the matching key from the API and your file. That's all bro.. Try the code, Hopefull you will get some output. – sohaib karim Feb 05 '17 at 00:21
  • if(groupsModal.getSuccessResponse == 200){ – George Guo Feb 05 '17 at 00:23
  • No no.. i did copy that from your question, i thought u must be having some fields under group array with name "successResponse", so the getter and setter would be for **getSuccessResponse()** and **setSuccessResponse()** u need to define your variables their.. and you can search for video tutorials on Gson , there you can learn better i hope. check this link for reference [link](https://www.youtube.com/watch?v=GFh-X3WqQgw) – sohaib karim Feb 05 '17 at 00:28
  • From my question, whenever I am looping through the array, it always gets the last variable. – George Guo Feb 05 '17 at 00:55
0

String[] getStringArray(String name, JSONObject object) throws JSONException {
  JSONArray jsonArray = object.getJSONArray(name);
  String[] array = new String[jsonArray.length()];
  for (int i = 0; i < jsonArray.length(); i++){
    array[i] = jsonArray.getString(i);
  }
  return array;
}
Jake Holzinger
  • 5,783
  • 2
  • 19
  • 33
  • Errors: object.getJSONArray(name); and jsonArray.getString(i) Error:(100, 58) error: unreported exception JSONException; must be caught or declared to be thrown – George Guo Feb 05 '17 at 00:40
  • Thank you! I have found a better solution. Thanks for taking the time to answer though. Really do appreciate it. – George Guo Feb 05 '17 at 02:52
0

i believe here you must be facing problem

 for (int i = 0; i < jsonArrayGR.length(); i++){
                        CI++;
                        rows = jsonArrayGR.getString(i);
                    }

this is because you are not appending rows value in each loop, instead you are over writing the previous values.
easy solution

rows = jsonArrayGR.getString(i)+rows;

best solution

StringBuilder rows = new StringBuilder();

                    for (int i = 0; i < jsonArrayGR.length(); i++){
                        CI++;
                        rows.append(jsonArrayGR.getString(i));
                    }

and finally use it in your code

intent.putExtra("groups", rows);

P.S. if you want to use rows as String later, just use
String rows = rows.toString();

i hope this will surely help you :D

sohaib karim
  • 281
  • 2
  • 12
  • Okay. This solves the problem of displaying the whole row. The only thing I want to know is to separate the different rows into different textviews in a recyclerview – George Guo Feb 05 '17 at 01:31
  • I did not understand, you are doing the right thing in your onBindViewHolder of your ADAPTER class. Can you bit more specific that how you want your data to get displayed ? and also what you are getting currently ? – sohaib karim Feb 05 '17 at 10:23
  • Currently I am seeing the data as: Total_Social_Beta_TestersTest_Group. I want to display it like this:. Total_Social_Beta_Testers and Test_Group to be displayed separately. Not together. – George Guo Feb 05 '17 at 11:40
  • I have 2 rows, and I want to display one row per text view – George Guo Feb 05 '17 at 11:42
  • you mean the value of **groups.getTitle()** is **"Total_Social_Beta_TestersTest_Group"** ? And you want to display it in your **TextField group** . And the output shuould be row1 = Total_Social_Beta_Testers and row2 = Test_Group ? Am i correct ? – sohaib karim Feb 05 '17 at 11:59
  • Correct. That's want I want. – George Guo Feb 05 '17 at 12:16
  • `Groups groups = chatlist.get(position);` `String myGroupArray = groups.getTitle().split("");` `holder.group.setText(myGroupdArray[0]);` `holder.group.setText(myGroupArray[1]);` Try this code in your **onBindViewHolder()** in your adapter. Sorry for bad formatting, i don't know to use
    in comments here :D. Anyway, check and let me know
    – sohaib karim Feb 05 '17 at 12:23
  • I am receiving an error `String myGroupArray = groups.getTitle().split("");` . It says incompatible types. It expects a string, not a string[] – George Guo Feb 05 '17 at 12:33
  • sorry, my bad, Still sleepy :D . instead of String myGroupArray = groups.getTitle().split(""); use, String myGroupArray[ ] = groups.getTitle().split(""); – sohaib karim Feb 05 '17 at 12:35
  • It worked. But, I am only seeing the first letter of the the row. Not the whole row. – George Guo Feb 05 '17 at 12:39
  • `Groups groups = chatlist.get(position);` `String myString = groups.getTitle().substring(0,25); String mySecondString = groups.getTitle().substring(25);` `holder.group.setText(myString);` `holder.group.setText(mySecondString);` Instead of my previous comment, use this, But, this will only work in case of the string **Total_Social_Beta_TestersTest_Group** , if you want anything else, you need to use **regex java split** . You can google that later, first try this – sohaib karim Feb 05 '17 at 13:05
  • Do I need to do `String mystring = groups.toString().substring(0,25)`? – George Guo Feb 05 '17 at 13:10
  • Is this the problem? I have this on my main activity: `for (int i = 0; i < rows; i++){Groups groups = new Groups(g);groupslist.add(groups);}` – George Guo Feb 05 '17 at 13:19
  • for (int i = 0; i < rows; i++){Groups groups = new Groups(g);groupslist.add(groups);} . This is making no sense brother, why are you trying to add **n** groups in your groups list ? And what is **g** ? – sohaib karim Feb 05 '17 at 13:53
  • `g` is the variable I created in the session `String g = user.get(UserSessionManager.KEY_GROUPS);` – George Guo Feb 05 '17 at 13:59
  • And I want to display **n** groups because I want to list different groups per row. – George Guo Feb 05 '17 at 14:00
  • I have tried your methods and the second string always appears. I want to display the 2 values inside the JASON array in one recycler veiw. – George Guo Feb 05 '17 at 16:13