Domanda

I have an app with ViewPager and ViewPagerIndicator. I have two tabs made ​​with TabPageIndicator. Each tab loads a listivew with data of Internet. When I run the app loads the data from tab 1 and 2, this causes very slow to show the view. I want that when I started my app only load data tab 1 and when I move or click on tab 2 load the data for that tab.

Can you help me?

Thank you.

My code:

MainActivity

public class MainActivity extends FragmentActivity {
private static final String[] CONTENT = new String[] { "Releases", "Artists" };
private ListView listRls;
private List<Fragment> listaFragments;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);        


    listaFragments = new ArrayList<Fragment>();
    listaFragments.add(new FragmRls());
    listaFragments.add(new FragmArt());


    MyFragmentAdapter adapter = new MyFragmentAdapter(getSupportFragmentManager(),
            listaFragments);

    ViewPager pager = (ViewPager)findViewById(R.id.pager);
    pager.setAdapter(adapter);

    TabPageIndicator indicator = (TabPageIndicator)findViewById(R.id.indicator);
    indicator.setViewPager(pager);



}

class MyFragmentAdapter extends FragmentStatePagerAdapter {
     //Implementacion del fragmentStateADapter

    private List<Fragment> fragments;

    public MyFragmentAdapter(FragmentManager fm, List<Fragment> fragments) {
        super(fm);
        // TODO Auto-generated constructor stub
        this.fragments = fragments;
    }

    @Override
    public Fragment getItem(int position) {
        // TODO Auto-generated method stub
        return fragments.get(position);
    }

     @Override
     public CharSequence getPageTitle(int position) {
         return CONTENT[position % CONTENT.length].toUpperCase();
     }


    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return fragments.size();
    }



}//fin adapter
}//fin class

Code in one of the classes that extend from ListFragement, the other is identical.

public class FragmRls extends ListFragment{

JSONParser jParser = new JSONParser();
private static String url_all_post = "http://adeptlabel.com/listReleaseforTab.php";
private static String url_all_art = "http://adeptlabel.com/listArtists.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_posts = "wp_posts";
private static final String TAG_TITULO = "titulo";
private static final String TAG_IMAGEN = "imagen";      
JSONArray posts = null;

private ArrayList <ElementosList> elementos = new ArrayList <ElementosList>();


public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){

    return inflater.inflate(R.layout.fragmrls, null);

}//Fin On CreateView    

  @Override
   public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        elementos.clear();
        loadDataJsonRls();
        for(int i=0;i<ListViewConfig.getResim_list_txt().size();i++)
        {
            elementos.add(new ElementosList(ListViewConfig.getResim_list_txt().get(i),
                    ListViewConfig.getResim_list_img().get(i)));
        }
        ArrayAdapter<ElementosList>adaptador = new AdaptadorList(getActivity(),elementos);
        setListAdapter(adaptador);

  }

public void loadDataJsonRls()
{
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    // getting JSON string from URL
    JSONObject json = jParser.makeHttpRequest(url_all_post, "GET", params);     
    // Check your log cat for JSON reponse
    Log.d("All releases: ", json.toString());

    try {
        // Checking for SUCCESS TAG
        int success = json.getInt(TAG_SUCCESS);
        if (success == 1) {             
            posts = json.getJSONArray(TAG_posts);               
            //Borramos los arrayList 
            ListViewConfig.deleteResim_list_img();
            ListViewConfig.deleteResim_list_txt();              
            // looping through All post
            for (int i = 0; i < posts.length(); i++) {
                boolean repite = false;
                JSONObject c = posts.getJSONObject(i);
                // Storing each json item in variable
                String titulo = c.getString(TAG_TITULO);
                String imagen = c.getString(TAG_IMAGEN);    
                for(int j=0;j<ListViewConfig.getResim_list_txt().size();j++)
                {
                    if(titulo.equals(ListViewConfig.getResim_list_txt().get(j)))
                    {
                        repite = true;
                    }
                }
                if(repite==false)
                {
                    ListViewConfig.addImageUrls(imagen);
                    ListViewConfig.addTextUrls(titulo);
                }               
            }
        } else {
            //Log.d("MainActivity.class", "No success Json");

    }
    } catch (JSONException e) {
        e.printStackTrace();
    }

}//fin cargarDatosJsonRls()


}//fin class
È stato utile?

Soluzione

If you want to load data associated with second tab when user switch to that tab, try to move code that loads data from onCreate to a public method. Then set OnPageChangeListener and load data when onPageSelected is called.

Furthermore, make sure that you load data asynchronously, for example using AsyncTask.

Altri suggerimenti

You are making your network calls on the UI thread, this is why your UI is slow. You may want to use an AsyncTask, effectively moving your network activity to another thread. Its doInBackground method will handle the network things, and the onPostExecute method allows you to update your UI when the execution of the Task is finished. More details in the official documentation here.

Additionally, depending on your needs and time, you could either pre-load the data so the loading time when the user is presented with the screen is reduced, or show a ProgressBar while you are loading the data, then update the UI when loading is done.

The solution to my problem I found here:

(ViewPager, ListView, and AsyncTask, first page blank, all data in the second page

However, thanks for your attention Nartus and 2Dee.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top