[英]How to display JSON format data from web server using recyclerview in android
I am newbie in android also JSON.I am trying to displaying JSON format data from web server using recyclerviw.我是 android 的新手,也是 JSON。我正在尝试使用来自 Z2567A5EC93305EB7AC2DZE8 服务器的 JSON 格式数据显示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.
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.
但我只想使用 recyclerview 显示 email 和移动数据。 But I don't know how to display only email, and mobile data using recyclerview.
但我不知道如何只显示 email 和使用 recyclerview 的移动数据。
Here is my JSON Web Server Link: http://api.androidhive.info/contacts/这是我的 JSON Web 服务器链接: 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在你的 arrayAdapter.class 的 onBindViewHolder 方法中
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 holder.email.setText((CharSequence) contactList.get(position).get("email"); holder.mobile.setText((CharSequence) contactList.get(position).get("mobile"); 获取email和手机来自 arraylist 的键名
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"));
}
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.