javaandroidjsonandroid-webservice

Multiple Service calling by using Volley


I have a MainActivity where the Swipeable Tabs are created and from there two fragments are called. I have 2 webservice for Fragment A and Fragment B where I have to parse data coming from server. I am using volley. When I am in the first fragment; both the webservice are being called and the data are not loaded for the first time.

But in the Second time it is showing correctly but it should be like this that when I am in Fragment A the service of the Fragment A should be called and when I am in Fragment B the service of the Fragment B should be called. I am attaching the code snippets.

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

Solution

  • What probably happens is that the two fragments are both loaded even though you are only looking at one fragment at a time. Instead of creating a new RequestQueue on every request you should only have one. For example create an Application class like so:

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

    Don't forget to add your application class to your manifest inside the <activity> tag:

    <application
        android:name=".MyApp"
    

    Now you can put requests on that queue from your fragments:

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