使用 Volley 调用多个服务

Multiple Service calling by using Volley

我有一个 MainActivity,其中创建了可滑动选项卡,并从那里调用了两个片段。我有 2 个用于片段 A 和片段 B 的网络服务,我必须在其中解析来自服务器的数据。我正在使用排球。当我在第一个片段时;正在调用 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;
        }
    }
}

可能发生的情况是,即使您一次只查看一个片段,也会同时加载两个片段。不要在每个请求上都创建一个新的 RequestQueue,而应该只创建一个。例如,像这样创建一个应用程序 class:

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);
    }
}

不要忘记将您的应用程序 class 添加到 <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);