你如何用 asynctask json 做 pojo

Posted

技术标签:

【中文标题】你如何用 asynctask json 做 pojo【英文标题】:How do you do pojo with asynctask json 【发布时间】:2017-07-25 17:42:29 【问题描述】:

我将 https://jsonplaceholder.typicode.com/users 与 asynctask 一起使用,但我使用 pojo 对象。

我应该在 之间添加什么代码?应该写哪一行,怎么写?

DataRetriever.java

public DataRetriever(Activity activity) 
    activityWeakReference = new WeakReference<>(activity);
    current_activity = activityWeakReference.get();


@Override
protected void onPreExecute() 

    imageView = (ImageView) current_activity.findViewById(R.id.imageView);
    if (current_activity != null) 
        recyclerView = (RecyclerView) current_activity.findViewById(R.id.recyclerView);
        swipeRefreshLayout = (SwipeRefreshLayout) current_activity.findViewById(R.id.swipe_container);

        swipeRefreshLayout.setColorSchemeResources(
                android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);

        recyclerView.setHasFixedSize(true);

     else 
        Log.d(TAG, "unable to get current activity");
        Toast.makeText(current_activity, "unable to get current activity", Toast.LENGTH_SHORT).show();
    
    super.onPreExecute();
    progressDialog = new ProgressDialog(current_activity);
    progressDialog.setMessage("Loading...");
    progressDialog.show();


@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) 
    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("id");
                    name = array_items.optString("name");
                    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());
    


@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 
           //            Log.d(TAG, "unable to get data");
        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;

  

你对我的重要建议

谢谢!

【问题讨论】:

【参考方案1】:

您可以使用 GSON 和 POJO 轻松做到这一点

首先..你需要创建几个模型

Post.java

public class Post

    private String id;

    private String phone;
    private String username;
    private String website;
    private Address address;
    private String email;
    private Company company;
    private String name;

    //setter and getter

公司.java

public class Company

    private String catchPhrase;
    private String name;
    private String bs;

    //setter and getter

地址.java

public class Address

    private Geo geo;
    private String zipcode;
    private String street;
    private String suite;
    private String city;

    //setter and getter

地理.java

public class Geo

    private String lng;
    private String lat;

    //setter and getter

之后,您从 API 获得的 json 字符串。使用 Gson 解析它..

List<Post> post = new Gson().fromJson(YOUR_JSON_STRING,new TypeToken<List<Post>>() .getType());

【讨论】:

以上是关于你如何用 asynctask json 做 pojo的主要内容,如果未能解决你的问题,请参考以下文章

你如何用 JGit 做相当于“git show tagname”的操作?

教你如何用 sketch 做插画,看完惊呆了

你如何用 jQuery 检测你何时接近屏幕底部? [复制]

python爬虫技术如何挣钱?手把手教你如何用Python做副业月入30000+!

python爬虫技术如何挣钱?手把手教你如何用Python做副业月入30000+!

大神教你如何用Python爬取手机壁纸,就是这么为所欲为!