你怎么能用asynctask json添加pojo

时间:2017-03-16 13:21:06

标签: java android json android-asynctask pojo

我想从Pojo.class中添加,因为我想使用Pojo Object。但DataRetriever有我的错误。 DataRetriever例如case1 id,name来自Pojo.class getName,getId。还有这个网站https://jsonplaceholder.typicode.com/users

DataRetriever.java

 private void jsonParser(String jsonString) {
    ArrayList<Post> posts = new Gson().fromJson(jsonString,
            new TypeToken<ArrayList<Post>>() {
            }.getType());
    int names_count, id;
    String name;
    try {
        JSONArray jsonArray = new JSONArray(jsonString);
        names_count = jsonArray.length();
        if (!listValues.isEmpty())
            listValues.clear();
        if (!pictureValues.isEmpty())
            pictureValues.clear();
        for (int i = 0; i < names_count; i++) {
            JSONObject array_items = jsonArray.getJSONObject(i);
            ListValues jsonValues, pictureValue;
            switch (type) {
                case 1:
                    id = array_items.optInt(posts.getClass().getName());
                    name = array_items.optString(posts.getClass().getUserId());
                    jsonValues = new ListValues(id, name);
                    listValues.add(jsonValues);
                    break;
                case 2:
                    id = array_items.optInt("userId");
                    name = array_items.optString("title");
                    if (id == recieved_id) {
                        jsonValues = new ListValues(id, name);
                        listValues.add(jsonValues);
                    }
                    break;
                case 3:
                    id = array_items.optInt("albumId");
                    name = array_items.optString("title");
                    String pictureURL = array_items.getString("url");
                    if (id == recieved_id) {
                        jsonValues = new ListValues(id, name);
                        pictureValue = new ListValues(id, pictureURL);
                        listValues.add(jsonValues);
                        pictureValues.add(pictureValue);
                    }
                    break;
            }
        }
    } catch (JSONException e) {
        Log.d(TAG, e.getLocalizedMessage());
    }
    }

Post.java

public class Post implements Serializable {
@SerializedName("userId")
private int userId;
@SerializedName("name")
@Expose
public String name;

@SerializedName("id")
private int id;

@SerializedName("title")
private String title;

@SerializedName("body")
private String body;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getUserId() {
    return userId;
}

public void setUserId(int userId) {
    this.userId = userId;
}


public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getBody() {
    return body;
}

public void setBody(String body) {
    this.body = body;
}
   }

MyError: enter image description here

2 个答案:

答案 0 :(得分:1)

您输入错误是因为您在name中分配的id不是整数类型。

您在userId上呼叫(getUserId()) getClass()的第二件事是错误的

//Wrong
id = array_items.optInt(posts.getName());// for name
name = array_items.optString(posts.getUserId());// for user id

//Correct
    id = array_items.optInt(posts.getUserId());
    name = array_items.optInt(posts.getName());

修改你的for循环

 for (int i = 0; i < names_count; i++) {
            Post post = posts.get(i);// add this line also
            JSONObject array_items = jsonArray.getJSONObject(i);
            ListValues jsonValues, pictureValue;
            switch (type) {
                case 1:
                    id = array_items.optInt(post.getUserId());
                    name = array_items.optInt(post.getName());//write these 2 lines

                    jsonValues = new ListValues(id, name);
                    listValues.add(jsonValues);
                    break;
                case 2:
                    id = array_items.optInt("userId");
                    name = array_items.optString("title");
                    if (id == recieved_id) {
                        jsonValues = new ListValues(id, name);
                        listValues.add(jsonValues);
                    }
                    break;
                case 3:
                    id = array_items.optInt("albumId");
                    name = array_items.optString("title");
                    String pictureURL = array_items.getString("url");
                    if (id == recieved_id) {
                        jsonValues = new ListValues(id, name);
                        pictureValue = new ListValues(id, pictureURL);
                        listValues.add(jsonValues);
                        pictureValues.add(pictureValue);
                    }
                    break;
            }
        }

//更新了答案

-----------------------------------com.example.Address.java-----------------------------------

package com.example;// your package name

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang3.builder.ToStringBuilder;

public class Address {

@SerializedName("street")
@Expose
private String street;
@SerializedName("suite")
@Expose
private String suite;
@SerializedName("city")
@Expose
private String city;
@SerializedName("zipcode")
@Expose
private String zipcode;
@SerializedName("geo")
@Expose
private Geo geo;

public String getStreet() {
return street;
}

public void setStreet(String street) {
this.street = street;
}

public String getSuite() {
return suite;
}

public void setSuite(String suite) {
this.suite = suite;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getZipcode() {
return zipcode;
}

public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}

public Geo getGeo() {
return geo;
}

public void setGeo(Geo geo) {
this.geo = geo;
}

@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}

}
-----------------------------------com.example.Company.java-----------------------------------

package com.example;// your package name

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang3.builder.ToStringBuilder;

public class Company {

@SerializedName("name")
@Expose
private String name;
@SerializedName("catchPhrase")
@Expose
private String catchPhrase;
@SerializedName("bs")
@Expose
private String bs;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getCatchPhrase() {
return catchPhrase;
}

public void setCatchPhrase(String catchPhrase) {
this.catchPhrase = catchPhrase;
}

public String getBs() {
return bs;
}

public void setBs(String bs) {
this.bs = bs;
}

@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}

}
-----------------------------------com.example.Geo.java-----------------------------------

package com.example;// your package name

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang3.builder.ToStringBuilder;

public class Geo {

@SerializedName("lat")
@Expose
private String lat;
@SerializedName("lng")
@Expose
private String lng;

public String getLat() {
return lat;
}

public void setLat(String lat) {
this.lat = lat;
}

public String getLng() {
return lng;
}

public void setLng(String lng) {
this.lng = lng;
}

@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}

}
-----------------------------------com.example.UserModel.java-----------------------------------

package com.example;// your package name

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang3.builder.ToStringBuilder;

public class UserModel {

@SerializedName("id")
@Expose
private Integer id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("username")
@Expose
private String username;
@SerializedName("email")
@Expose
private String email;
@SerializedName("address")
@Expose
private Address address;
@SerializedName("phone")
@Expose
private String phone;
@SerializedName("website")
@Expose
private String website;
@SerializedName("company")
@Expose
private Company company;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

public String getWebsite() {
return website;
}

public void setWebsite(String website) {
this.website = website;
}

public Company getCompany() {
return company;
}

public void setCompany(Company company) {
this.company = company;
}

@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}

}

答案 1 :(得分:0)

DataRetriever.java

@SafeVarargs
@Override
protected final Integer doInBackground(List<String>... integers) {
    HttpURLConnection httpURLConnection = null;
    URL url;
    List<String> local_list = integers[0];
    type = Integer.parseInt(local_list.get(0));
    String jsonString, jsonData;
    return_status = 0;
    switch (type) {
        case 1:
            url_string = "https://jsonplaceholder.typicode.com/users";
            break;
        case 2:
            url_string = "https://jsonplaceholder.typicode.com/albums";
            recieved_id = Integer.parseInt(local_list.get(1));
            title = local_list.get(2);
            break;
        case 3:
            url_string = "https://jsonplaceholder.typicode.com/photos";
            recieved_id = Integer.parseInt(local_list.get(1));
            title = local_list.get(2);
            break;
    }
    try {
        url = new URL(url_string);
        httpURLConnection = (HttpURLConnection) url.openConnection();
        int statusCode = httpURLConnection.getResponseCode();
        if (statusCode == 200) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            StringBuilder stringBuilder = new StringBuilder();
            while ((jsonData = bufferedReader.readLine()) != null) {
                stringBuilder.append(jsonData);
            }
            jsonString = stringBuilder.toString();
            jsonParser(jsonString);
            return_status = 1;
        } else {
            Log.d(TAG, "Some error occurred could'nt fetch data");
            Toast.makeText(current_activity, "Some error occurred could'nt fetch data", Toast.LENGTH_SHORT).show();
            return_status = 0;
        }
        publishProgress(local_list);
    } catch (Exception e) {
        Log.d(TAG, e.getLocalizedMessage());
    } finally {
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }
    }

    return return_status;
}


private void jsonParser(String jsonString) {
    ArrayList<Post> posts = new Gson().fromJson(jsonString,
            new TypeToken<ArrayList<Post>>() {
            }.getType());
    int names_count, id;
    String name;
    try {
        JSONArray jsonArray = new JSONArray(jsonString);
        names_count = jsonArray.length();
        if (!listValues.isEmpty())
            listValues.clear();
        if (!pictureValues.isEmpty())
            pictureValues.clear();
        for (int i = 0; i < names_count; i++) {
            Post post = posts.get(i);
            JSONObject array_items = jsonArray.getJSONObject(i);
            ListValues jsonValues, pictureValue;
            switch (type) {
                case 1:
                    id = array_items.optInt(String.valueOf(post.getId()));
                    name = array_items.optString(post.getName());
                    jsonValues = new ListValues(id, name);
                    listValues.add(jsonValues);
                    break;
                case 2:
                    id = array_items.optInt(String.valueOf(post.getUserId()));
                    name = array_items.optString(post.getTitle());
                    if (id == recieved_id) {
                        jsonValues = new ListValues(id, name);
                        listValues.add(jsonValues);
                    }
                    break;
                case 3:
                    id = array_items.optInt(post.getName());
                    name = array_items.optString(post.getTitle());
                    String pictureURL = array_items.getString("url");
                    if (id == recieved_id) {
                        jsonValues = new ListValues(id, name);
                        pictureValue = new ListValues(id, pictureURL);
                        listValues.add(jsonValues);
                        pictureValues.add(pictureValue);
                    }
                    break;
            }
        }
    } catch (JSONException e) {
        Log.d(TAG, e.getLocalizedMessage());
    }
}

@Override
protected void onProgressUpdate(final List<String>... values) {
    List<String> progressList = values[0];
    Log.d(TAG, progressList.get(0));
    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            switch (type) {
                case 1:
                    new DataRetriever(current_activity).execute(values[0]);
                case 2:
                    new DataRetriever(current_activity).execute(values[0]);
                case 3:
                    new DataRetriever(current_activity).execute(values[0]);
            }
        }
    });
    super.onProgressUpdate(values);
}



@Override
protected void onPostExecute(final Integer integer) {
    if (integer != 0) {

        recyclerAdapter = new RecyclerAdapter(listValues);
        recyclerView.addItemDecoration(new ListItemDecorator(current_activity.getApplicationContext()));
        recyclerView.setAdapter(recyclerAdapter);

        // use a linear layout manager
        mLayoutManager = new LinearLayoutManager(current_activity);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());


        if (swipeRefreshLayout.isRefreshing())
            swipeRefreshLayout.setRefreshing(false);




        recyclerView.addOnItemTouchListener(new RecyclerTouchListener(current_activity.getApplicationContext(), recyclerView, new ClickListener() {
            @Override
            public void onClick(View view, int position) {
                String pictureURL = null;
                ListValues feed = listValues.get(position);
                if (!pictureValues.isEmpty()) {
                    ListValues feed2 = pictureValues.get(position);
                    pictureURL = feed2.getValue();
                }
                String value = feed.getValue();
                switch (type) {
                    case 1:
                        intent = new Intent(current_activity, AlbumActivity.class);
                        intent.putExtra("id", (position + 1));
                        intent.putExtra("value", value);
                        current_activity.startActivity(intent);
                        break;
                    case 2:
                        intent = new Intent(current_activity, PhotosActivity.class);
                        intent.putExtra("id", (position + 1));
                        intent.putExtra("value", value);
                        current_activity.startActivity(intent);
                        break;
                    case 3:
                        intent = new Intent(current_activity, ImageDisplay.class);
                        intent.putExtra("imageUrl", pictureURL);
                        current_activity.startActivity(intent);
                        break;
                }

            }

            @Override
            public void onLongClick(View view, int position) {
            }
        }));
    } else {

        if (swipeRefreshLayout.isRefreshing()) {
            Toast.makeText(current_activity, "Unable to refresh data! Try opening application again", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(current_activity, "Failed to fetch data! try again", Toast.LENGTH_SHORT).show();
        }
    }
    super.onPostExecute(integer);
    progressDialog.dismiss();
}



public interface ClickListener {
    void onClick(View view, int position);

    void onLongClick(View view, int position);
}

public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

    private GestureDetector gestureDetector;
    private ClickListener clickListener;

    public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
        this.clickListener = clickListener;
        gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                if (child != null && clickListener != null) {
                    clickListener.onLongClick(child, recyclerView.getChildPosition(child));
                }
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {

        View child = rv.findChildViewUnder(e.getX(), e.getY());
        if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
            clickListener.onClick(child, rv.getChildPosition(child));
        }
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {
    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }
}
      }

Post.java

  public class Post implements Serializable {
@SerializedName("userId")
private int userId;
@SerializedName("name")
@Expose
public String name;

@SerializedName("id")
private int id;

@SerializedName("title")
private String title;

@SerializedName("body")
private String body;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getUserId() {
    return userId;
}

public void setUserId(int userId) {
    this.userId = userId;
}


public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getBody() {
    return body;
}

public void setBody(String body) {
    this.body = body;
}

}