如何使用Vollley库解决服务类问题?

时间:2019-02-10 20:34:27

标签: java android service android-volley

我想从我的wordpress网站上提取数据。我在wordpress中使用rest-api2。我正在使用排球库提取数据。我的数据是json,即时通讯使用gson库解析数据。我正在推送对象列表我的数据。 我的代码在片段或活动中工作,我想在服务类中使用此代码,但它不工作。

MainActivity:

startService(new Intent(context,VeriServis.class));//in onCreate()

这是我的服务等级:

public class VeriServis extends Service {
    Context context = this;
    Gson gson;
    List<Object> list;
    Map<String,Object> mapPost;
    Map<String,Object> mapTitle;
    Map<String,Object> mapContent;
    List<Object> alList = new ArrayList<>();
    List<Data> dataList;
    String postTitle[];
    String postImg[];
    String postContent;
    String postDate;
    int postID;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        pullAndPushData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    public void pullAndPushData(){
        String url = "https://haberyaziyorum.com/wp/json/wp/v2/posts?categories=17&page=1";
        System.out.println(url);
        StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                gson = new Gson();
                list = (List)gson.fromJson(s, List.class);
                alList.addAll(list);
                postTitle = new String[alList.size()];
                postImg = new String[alList.size()];
                dataList = new ArrayList<>();
                for(int i=0;i<alList.size();i++){
                    mapPost = (Map<String, Object>)alList.get(i);
                    mapTitle  = (Map<String, Object>)mapPost.get("title");
                    mapContent  = (Map<String, Object>)mapPost.get("content");
                    postTitle[i] = (String)mapTitle.get("rendered");
                    postImg[i] = (String)mapPost.get("jetpack_featured_media_url");
                    postID = ((Double)mapPost.get("id")).intValue();
                    postDate = mapPost.get("date").toString();
                    postContent = mapContent.get("rendered").toString();
                    Data d = new Data(17,postID,postTitle[i],postContent,postDate,postImg[i]);
                    System.out.println(postID+"||"+postTitle[i]+"||"+postContent+"||"+postDate+"||"+postImg[i]);
                    dataList.add(d);

                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        RequestQueue rQueue = Volley.newRequestQueue(context);
        rQueue.add(request);
    }
}

我该如何解决?

0 个答案:

没有答案