I am newbie in android also JSON.I am trying to displaying JSON format data from web server using recyclerviw.On my MainActivity Code i used HashMap inside ArrayList and I have parsed data from web server and put it into HashMap under ArrayList.I put id, name, email, mobile data in HashMap under ArrayList. But I want to display only email and mobile data using recyclerview. But I don't know how to display only email, and mobile data using recyclerview.
Here is my JSON Web Server Link: http://api.androidhive.info/contacts/
My full code is given below:
public class MainActivity extends AppCompatActivity {
JSONArray contacts;
Context context;
ArrayList<HashMap<String, String>> contactList;
public static final String TAG =MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
ArrayAdapter adapter = new ArrayAdapter(context,contactList,contacts);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
new getContacts().execute();
}
private class getContacts extends AsyncTask<Void, Void, Void>{
@Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(getApplicationContext(),"JSON Data is" +
" downloading",Toast.LENGTH_LONG).show();
}
@Override
protected Void doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
String url = "http://api.androidhive.info/contacts/";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG,"Response from url: " + jsonStr);
if(jsonStr != null){
try{
JSONObject jsonObject = new JSONObject(jsonStr);
contacts = jsonObject.getJSONArray("contacts");
for (int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);
contactList.add(contact);
}
}catch (final JSONException e){
Log.e(TAG, "Json parsing error: " +e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),"Json parsing error: "
+ e.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
}else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),"Couldn't get json from server. Check LogCat for possible errors",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
}
public class ArrayAdapter extends RecyclerView.Adapter<ArrayAdapter.MyViewHolder>{
Context context;
ArrayList<HashMap<String, String>> contactList;
JSONArray contacts;
public ArrayAdapter(Context context, ArrayList<HashMap<String, String>> contactList, JSONArray contacts) {
this.context = context;
this.contactList = contactList;
this.contacts = contacts;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.row_item,parent,false);
return new MyViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.email.setText((CharSequence) contactList.get(position));
holder.mobile.setText((CharSequence) contactList.get(position));
}
@Override
public int getItemCount() {
return contacts.length();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView email;
TextView mobile;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
if(contacts.length() >= 2){
email = itemView.findViewById(R.id.email);
mobile = itemView.findViewById(R.id.mobile);
}
}
}
}
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl){
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn =(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
}catch (MalformedURLException e){
Log.e(TAG,"MalformException: " + e.getMessage());
}catch (ProtocolException e){
Log.e(TAG,"ProtocolException: " + e.getMessage());
}catch (IOException e){
Log.e(TAG, "IOException: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is){
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
boolean line;
try {
while (line = reader.readLine() != null){
sb.append(line).append('\n');
}
}catch (IOException e){
e.printStackTrace();
}finally {
try {
is.close();
}catch (IOException e){
e.printStackTrace();
}
}
return sb.toString();
}
}
In your onBindViewHolder method of arrayAdapter.class
Change this:
holder.email.setText((CharSequence) contactList.get(position));
With:
holder.email.setText((CharSequence) contactList.get(position).get("email"));
Do the same things for other item too
holder.email.setText((CharSequence) contactList.get(position).get("email"); holder.mobile.setText((CharSequence) contactList.get(position).get("mobile"); Get email and mobile from arraylist by key name
Try this
MainActivity
public class MainActivity extends AppCompatActivity {
private ArrayAdapter adapter;
public static final String TAG =MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
adapter = new ArrayAdapter(getApplicationContext());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
new getContacts().execute();
}
private class getContacts extends AsyncTask<Void, Void, List<HashMap<String, String>>> {
@Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(getApplicationContext(),"JSON Data is" +
" downloading",Toast.LENGTH_LONG).show();
}
@Override
protected List<HashMap<String, String>> doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
String url = "http://api.androidhive.info/contacts/";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG,"Response from url: " + jsonStr);
if(jsonStr != null){
try{
JSONObject jsonObject = new JSONObject(jsonStr);
List<HashMap<String, String>> contactList = new ArrayList<>();
JSONArray contacts = jsonObject.getJSONArray("contacts");
for (int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);
contactList.add(contact);
}
return contactList;
}catch (final JSONException e){
Log.e(TAG, "Json parsing error: " +e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),"Json parsing error: "
+ e.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
}else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),"Couldn't get json from server. Check LogCat for possible errors",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
@Override
protected void onPostExecute(List<HashMap<String, String>> result) {
super.onPostExecute(result);
if(result != null){
adapter.add(result);
adapter.notifyDataSetChanged();
}
}
}
}
ArrayAdapter
public class ArrayAdapter extends RecyclerView.Adapter<ArrayAdapter.MyViewHolder>{
Context context;
LayoutInflater inflater;
List<HashMap<String, String>> contactList;
public ArrayAdapter(Context context) {
this.context = context;
inflater = LayoutInflater.from(context);
this.contactList = new ArrayList<>();
}
public void add(List<HashMap<String, String>> arg){
contactList.addAll(arg);
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = inflater.inflate(R.layout.row_item,parent,false);
return new MyViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
HashMap<String, String> data = contactList.get(position);
holder.bindData(data);
}
@Override
public int getItemCount() {
return contactList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView email;
private TextView mobile;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
email = itemView.findViewById(R.id.email);
mobile = itemView.findViewById(R.id.mobile);
}
public void bindData(HashMap<String, String> data){
email.setText(data.get("email"));
mobile.setText(data.get("mobile"));
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.