George Guo George Guo - 4 years ago 157
JSON Question

Getting an array from a JSON object in Java

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download