我也是android的新手,也是JSON。我正在尝试使用recyclerviw从Web服务器显示JSON格式数据。在我的MainActivity代码上,我在ArrayList内使用了HashMap,并从Web服务器上解析了数据并将其放入ArrayList下的HashMap中。我将ID,名称,电子邮件,移动数据放在ArrayList下的HashMap中。但是我只想使用recyclerview显示电子邮件和移动数据。但是我不知道如何使用recyclerview仅显示电子邮件和移动数据。
这是我的JSON Web服务器链接:http://api.androidhive.info/contacts/
我的完整代码如下:
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();
}
}
答案 0 :(得分:0)
在arrayAdapter.class的onBindViewHolder方法中
更改此内容:
holder.email.setText((CharSequence) contactList.get(position));
使用:
holder.email.setText((CharSequence) contactList.get(position).get("email"));
对其他物品也做同样的事情
答案 1 :(得分:0)
holder.email.setText((CharSequence)contactList.get(position).get(“ email”); holder.mobile.setText((CharSequence)contactList.get(position).get(“ mobile”); 通过键名从arraylist获取电子邮件和手机
答案 2 :(得分:0)
尝试一下
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"));
}
}
}