使用Volley进行多服务呼叫

时间:2016-03-04 14:47:13

标签: java android json android-webservice

我有一个MainActivity,其中创建了Swipeable选项卡,并从那里调用了两个片段。我有2个片段A和片段B的web服务,我必须解析来自服务器的数据。我正在使用凌空抽射。当我在第一个片段;正在调用Web服务,并且第一次没有加载数据。

但是在第二次它正确显示但是它应该是这样的,当我在片段A中时应该调用片段A的服务,当我在片段B中时,应该调用片段B的服务。我正在附上代码片段。

MainActivity.java

public class MainActivity extends AppCompatActivity {
    DrawerLayout mDrawerLayout;
    NavigationView mNavigationView;
    FragmentManager mFragmentManager;
    FragmentTransaction mFragmentTransaction;

    int status = 0 ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /**
         *Setup the DrawerLayout and NavigationView
         */

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mNavigationView = (NavigationView) findViewById(R.id.shitstuff);
        android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
        // Show menu icon

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        /**
         * Lets inflate the very first fragment
         * Here , we are inflating the NewsFragment as the first Fragment
         */

        mFragmentManager = getSupportFragmentManager();
        mFragmentTransaction = mFragmentManager.beginTransaction();
        mFragmentTransaction.replace(R.id.containerView, new NewsFragment()).commit();

//        mNavigationView.setBackgroundColor(Color.parseColor("#CFCFCF"));
        /**
         * Setup click events on the Navigation View Items.
         */

        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                mDrawerLayout.closeDrawers();


                if (menuItem.getItemId() == R.id.nav_item_sent) {
                    FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
                    fragmentTransaction.replace(R.id.containerView, new SportsFragment()).commit();

                    status = 1;

                    if (status == 1){

                    }

                }

                if (menuItem.getItemId() == R.id.nav_item_inbox) {
                    FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
                    xfragmentTransaction.replace(R.id.containerView, new NewsFragment()).commit();
                }

                if (menuItem.getItemId() == R.id.nav_item_sent){
                    FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
                    xfragmentTransaction.replace(R.id.containerView, new VideosFragment()).commit();
                }

                if (menuItem.getItemId() == R.id.nav_item_draft) {
                    FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
                    xfragmentTransaction.replace(R.id.containerView, new OpinionFragment()).commit();
                }

                if (menuItem.getItemId() == R.id.nav_item_sports) {
                    FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
                    xfragmentTransaction.replace(R.id.containerView, new SportsFragment()).commit();
                }

                if (menuItem.getItemId() == R.id.nav_item_weather) {
                    FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
                    xfragmentTransaction.replace(R.id.containerView, new NewsFragment()).commit();
                }

                return false;
            }

        });

        /**
         * Setup Drawer Toggle of the Toolbar
         */



    ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name,
            R.string.app_name);

    mDrawerLayout.setDrawerListener(mDrawerToggle);

    mDrawerToggle.syncState();

}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_about_us:
                Intent intent = new Intent(MainActivity.this, AboutUs.class);
                startActivity(intent);
                return true;

            case R.id.action_terms_of_use:
                Intent intent_two = new Intent(MainActivity.this, TermsUse.class);
                startActivity(intent_two);
                return true;

            case R.id.action_privacy_policy:
                Intent intent_three = new Intent(MainActivity.this, PrivacyPolicy.class);
                startActivity(intent_three);
                return true;

            case R.id.action_contact_us:
                Intent intent_four = new Intent(MainActivity.this, ContactUs.class);
                startActivity(intent_four);

            case R.id.search:
//                hidetext();
                Toast.makeText(MainActivity.this, "In the development Phase... Thank You...", Toast.LENGTH_SHORT).show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

//    private void hidetext() {
//
//        Intent i = new Intent(MainActivity.this, SearchResultActivity.class);
//        startActivity(i);
//    }
}

TopNewsFragment

public class TopNewsFragment extends Fragment {

    // Log tag
    private static final String TAG = MainActivity.class.getSimpleName();

    private static final String url = "http://sikkimexpress.itstunner.com/api/homenewslist/topnews";
    private ProgressDialog pDialog;
    private List<Movie> movieList = new ArrayList<Movie>();
    Movie movie;
    private ListView listView;
    private CustomListAdapter adapter;
    String imageURL = "", title = "", description = "";
    public static final String KEY_ID = "news_id";
    public static final String KEY_HEADURL = "news_url";
    public static final String KEY_DETAILS = "news_details";
    public static final String KEY_TITLE = "news_title";

    RequestQueue requestQueue;

    public TopNewsFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.fragment_news, container, false);

        listView = (ListView) rootView.findViewById(R.id.list);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int Position,
                                    long offset) {
                // TODO Auto-generated method stub
                Movie item = (Movie) adapter.getItem(Position);
                Intent intent = new Intent(rootView.getContext(), DetailsPage.class);
                intent.putExtra(KEY_ID, item.getNewsId());
                intent.putExtra(KEY_HEADURL, item.getThumbnailUrl());
                intent.putExtra(KEY_TITLE, item.getTitle());
                intent.putExtra(KEY_DETAILS, item.getDescription());

                startActivity(intent);


            }
        });

//        requestQueue = Volley.newRequestQueue(getActivity());
        adapter = new CustomListAdapter(getActivity(), movieList);
        listView.setAdapter(adapter);

        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Loading...Please Wait...");
        pDialog.setCancelable(false);
        pDialog.show();

        Volley.newRequestQueue(getActivity()).add(new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
             @Override
             public void onResponse(JSONObject response) {
                 hidePDialog();
                 try {
                     JSONArray jsonArray = response.getJSONArray("HomeNews");

//                    if (jsonArray.length() == 0) {
//                        new AlertDialog.Builder(getActivity())
//                                .setTitle("Alert")
//                                .setMessage("No Items found...")
//                                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        // continue with delete
//                                    }
//                                })
//                                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        // do nothing
//                                    }
//                                })
//                                .setIcon(android.R.drawable.ic_dialog_alert)
//                                .show();
//                    }

                     for (int i = 0; i < jsonArray.length(); i++) {
                         JSONObject homenews = jsonArray.getJSONObject(i);
                         Movie movie = new Movie();
                         movie.setNewsId(homenews.getString("NewsId"));
                         movie.setDateTime(homenews.getString("DateTime"));
                         movie.setNewsType(homenews.getString("NewsType"));
                         movie.setTitle(homenews.getString("Title"));
                         title = movie.setTitle(homenews.getString("Title"));
                         description = movie.setDescription(homenews.getString("Description"));
                         movie.setDescription(homenews.getString("Description"));
                         imageURL = movie.setThumbnailUrl(homenews.getString("MainImageThumbnail"));
                         movie.setThumbnailUrl(homenews.getString("MainImageThumbnail"));

                         movieList.add(movie);

                         System.out.println("Setting up in ListView");
//                        System.out.println("Result:- " + newsId + " " + dateTime + " " + newsType + " " + title + " " + description + " " + mainImageURL);
                     }
                 } catch (JSONException e) {
                     e.printStackTrace();
                 }
                 adapter.notifyDataSetChanged();
             }
         }, new Response.ErrorListener() {
             @Override
             public void onErrorResponse(VolleyError error) {
//                new AlertDialog.Builder(getActivity())
//                        .setTitle("No Connectivity ")
//                        .setMessage("Please check your internet connectivity!")
//                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
//                            public void onClick(DialogInterface dialog, int which) {
//                                // continue with delete
//                            }
//                        })
//                                //.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
//                                //public void onClick(DialogInterface dialog, int which) {
//                                // do nothing
//                                //}
//                                //})
//                        .setIcon(android.R.drawable.ic_dialog_alert)
//                        .show();
                 hidePDialog();
             }
         }));

//        AppController.getInstance().addToRequestQueue(jsonObjectRequest);
//        requestQueue.add(jsonObjectRequest);
        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }
}

LatestNewsFragment.java

public class LatestNewsFragment extends Fragment {

    // Log tag
    private static final String TAG = MainActivity.class.getSimpleName();

    private static final String url = "http://sikkimexpress.itstunner.com/api/homenewslist/latest";
    private ProgressDialog pDialog;
    private List<Movie> movieList = new ArrayList<Movie>();
    private ListView listView;
    private CustomListAdapter adapter;
    // contacts JSONArray
    private JSONArray users = null;
    RequestQueue requestQueue;
    public static final String KEY_HEADURL="news_url";
    public static final String KEY_DETAILS="news_details";
    public static final String KEY_TITLE = "news_title";

    public LatestNewsFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.fragment_news, container, false);

        listView = (ListView) rootView.findViewById(R.id.list);

//        requestQueue = Volley.newRequestQueue(getActivity());
        adapter = new CustomListAdapter(getActivity(), movieList);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int Position,
                                    long offset) {
                // TODO Auto-generated method stub
                Movie item = (Movie) adapter.getItem(Position);
                Intent intent = new Intent(rootView.getContext(), DetailsPage.class);
//                intent.putExtra("URL", movie.getThumbnailUrl());
//                intent.putExtra("title", movie.getTitle());
//                intent.putExtra("description", movie.getDescription());

                intent.putExtra(KEY_HEADURL, item.getThumbnailUrl());
                intent.putExtra(KEY_TITLE, item.getTitle());
                intent.putExtra(KEY_DETAILS, item.getDescription());

                startActivity(intent);


            }
        });

        pDialog = new ProgressDialog(getActivity());
        // Showing progress dialog before making http request
        pDialog.setMessage("Loading...Please Wait...");
        pDialog.setCancelable(false);
        pDialog.show();

        Volley.newRequestQueue(getActivity()).add(new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
//            JsonObjectRequest jsonObjectRequest =

            @Override
            public void onResponse(JSONObject response) {
                try {
                    hidePDialog();

                    JSONArray jsonArray = response.getJSONArray("HomeNews");

//                    if (jsonArray.length() == 0){
//                        new AlertDialog.Builder(getActivity())
//                                .setTitle("Alert")
//                                .setMessage("No Items found...")
//                                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        // continue with delete
//                                    }
//                                })
//                                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        // do nothing
//                                    }
//                                })
//                                .setIcon(android.R.drawable.ic_dialog_alert)
//                                .show();
//                    }

                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject homenews = jsonArray.getJSONObject(i);
                        Movie movie = new Movie();
                        movie.setNewsId(homenews.getString("NewsId"));
                        movie.setDateTime(homenews.getString("DateTime"));
                        movie.setNewsType(homenews.getString("NewsType"));
                        movie.setTitle(homenews.getString("Title"));
                        movie.setDescription(homenews.getString("Description"));
                        movie.setThumbnailUrl(homenews.getString("MainImageThumbnail"));

                        movieList.add(movie);
                        System.out.println("Setting up in ListView");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                adapter.notifyDataSetChanged();
            }
        },

                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
//                        new AlertDialog.Builder(getActivity())
//                                .setTitle("No Connectivity ")
//                                .setMessage("Please check your internet connectivity!")
//                                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        // continue with delete
//                                    }
//                                })
//                                        //.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
//                                        //public void onClick(DialogInterface dialog, int which) {
//                                        // do nothing
//                                        //}
//                                        //})
//                                .setIcon(android.R.drawable.ic_dialog_alert)
//                                .show();
                        hidePDialog();
                    }
                }));

//        AppController.getInstance().addToRequestQueue(jsonObjectRequest);
//        requestQueue.add(jsonObjectRequest);
        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

可能发生的是,即使您一次只查看一个片段,这两个片段都会被加载。而不是在每个请求上创建一个新的RequestQueue,你应该只有一个。例如,像这样创建一个Application类:

public class MyApp extends Application {

    private RequestQueue mRequestQueue;

    private static MyApp mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized MyApp getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }
}

不要忘记将您的应用程序类添加到<activity>标记内的清单中:

<application
    android:name=".MyApp"

现在,您可以从片段中对该队列发出请求:

JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,
            URL, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            //Do something with response
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            //Do something with error
        }
    });

    //Put the actual request on the queue
    MyApp.getInstance().addToRequestQueue(req);