2017-09-03 1 views
-2

J'ai récemment commencé à écrire une application qui m'a permis d'obtenir des informations sur un forum. J'ai utilisé la bibliothèque JSoup pour extraire les données. Ma première partie va bien. Lorsque l'application s'ouvre, elle reçoit simplement des données du site (noms de sous-forum) et les transmet pour que ListView puisse les afficher. Quand j'appuie sur un élément de la liste, il obtient simplement la liste des sujets dans le sous-forum. Toutes les choses fonctionnent correctement sauf la listview n'est pas mise à jour correctement.utiliser viewpager avec différents fragments?

Comme vous pouvez le voir quand je presse un élément de la liste (juste le premier élément de la liste) puis mis loadedSub à vrai il obtient la liste de fil à l'aide d'un async-tâche puis dans le postexecute il appelle notifyDataSetChanged() sur PagerAdapter. Le problème est qu'il met juste à jour l'interface utilisateur parfaitement, même en laissant 1 onglet seulement comme je le voulais, mais le problème est que threadList n'apparaît pas dans le listview. Il me montre seulement le listview avec les données précédentes, pas la liste des discussions.

Devrais-je utiliser une autre activité ou y a-t-il quelque chose qui me manque?

enter image description here enter image description here

MainActivity.java

package com.ovnis.sscattered.elakiriunofficial; 

import android.app.ProgressDialog; 
import android.content.Context; 
import android.os.AsyncTask; 
import android.support.design.widget.TabLayout; 
import android.support.design.widget.FloatingActionButton; 
import android.support.design.widget.Snackbar; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar; 

import android.support.v4.app.Fragment; 
import android.support.v4.app.FragmentManager; 
import android.support.v4.app.FragmentPagerAdapter; 
import android.support.v4.view.ViewPager; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.ViewGroup; 

import android.widget.AdapterView; 
import android.widget.ListView; 
import android.widget.Toast; 

import org.jsoup.Connection; 
import org.jsoup.Jsoup; 
import org.jsoup.nodes.Document; 
import org.jsoup.nodes.Element; 
import org.jsoup.select.Elements; 

import java.io.IOException; 

public class MainActivity extends AppCompatActivity { 

    /** 
    * The {@link android.support.v4.view.PagerAdapter} that will provide 
    * fragments for each of the sections. We use a 
    * {@link FragmentPagerAdapter} derivative, which will keep every 
    * loaded fragment in memory. If this becomes too memory intensive, it 
    * may be best to switch to a 
    * {@link android.support.v4.app.FragmentStatePagerAdapter}. 
    */ 
    public static SectionsPagerAdapter mSectionsPagerAdapter; 

    /** 
    * The {@link ViewPager} that will host the section contents. 
    */ 
    public static ViewPager mViewPager; 

    public static String[][] forumListSubForumsList = new String[13][]; 
    public static String[][] forumListSubForumListLinks = new String[13][]; 

    public static String[][] threadListLinks = new String[2][]; 

    static Context context; 

    public String[] forumNumbers = {"1", "86", "89", "6", 
            "66", "79", "70", "12", 
            "16", "33", "42", "25", 
            "22"}; 

    public static String subforumLink; 

    static boolean loaded = false; 
    static boolean loadedSub = false; 

    static boolean subForumMode = false; 

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

     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 
     // Create the adapter that will return a fragment for each of the three 
     // primary sections of the activity. 
     mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); 

     // Set up the ViewPager with the sections adapter. 
     mViewPager = (ViewPager) findViewById(R.id.container); 
     mViewPager.setAdapter(mSectionsPagerAdapter); 



     TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); 
     tabLayout.setupWithViewPager(mViewPager); 

     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
     fab.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
         .setAction("Action", null).show(); 
      } 
     }); 

     new GetSubForumList().execute(); 

     context = getBaseContext(); 
    } 


    @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) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 

    /** 
    * A placeholder fragment containing a simple view. 
    */ 
    public static class SubForumsFrag extends Fragment { 
     /** 
     * The fragment argument representing the section number for this 
     * fragment. 
     */ 

     static ListView listview; 
     static ForumListAdapter adapter; 

     int pos = 0; 

     public SubForumsFrag() { 

     } 

     /** 
     * Returns a new instance of this fragment for the given section 
     * number. 
     */ 
     public static SubForumsFrag newInstance(int pos) { 
      SubForumsFrag fragment = new SubForumsFrag(); 
      Bundle args = new Bundle(); 
      args.putInt("poskey", pos); 
      fragment.setArguments(args); 
      return fragment; 
     } 

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

      View rootView = inflater.inflate(R.layout.list_base, container, false); 
      listview = (ListView) rootView.findViewById(R.id.listview); 

      pos = getArguments().getInt("poskey"); 

      if(loaded){ 
       adapter = new ForumListAdapter(getActivity(), forumListSubForumsList[pos]); 
      } 
      listview.setAdapter(adapter); 

      listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
       @Override 
       public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
        Toast.makeText(getContext(), forumListSubForumListLinks[pos][position], Toast.LENGTH_SHORT).show(); 
        subForumMode = true; 
        subforumLink = forumListSubForumListLinks[pos][position]; 
        new GetThreadList().execute(); 
       } 
      }); 

      return rootView; 
     } 
    } 

    public static class ThreadListFrag extends Fragment { 
     /** 
     * The fragment argument representing the section number for this 
     * fragment. 
     */ 

     static ListView listview; 
     static ForumListAdapter adapter; 

     int pos = 0; 

     public ThreadListFrag() { 

     } 

     /** 
     * Returns a new instance of this fragment for the given section 
     * number. 
     */ 
     public static ThreadListFrag newInstance() { 
      ThreadListFrag fragment = new ThreadListFrag(); 
      return fragment; 
     } 

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

      View rootView = inflater.inflate(R.layout.list_base, container, false); 
      listview = (ListView) rootView.findViewById(R.id.listview); 

      if(loadedSub){ 
       adapter = new ForumListAdapter(getActivity(), threadListLinks[0]); 
      } 
      listview.setAdapter(adapter); 

      listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
       @Override 
       public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
        //Toast.makeText(getContext(), forumListSubForumListLinks[pos][position], Toast.LENGTH_SHORT).show(); 
       } 
      }); 

      return rootView; 
     } 
    } 

    /** 
    * A {@link FragmentPagerAdapter} that returns a fragment corresponding to 
    * one of the sections/tabs/pages. 
    */ 
    public class SectionsPagerAdapter extends FragmentPagerAdapter { 

     public SectionsPagerAdapter(FragmentManager fm) { 
      super(fm); 
     } 

     @Override 
     public Fragment getItem(int position) { 
      // getItem is called to instantiate the fragment for the given page. 
      // Return a SubForumsFrag (defined as a static inner class below). 

      if(!subForumMode){ 
       return SubForumsFrag.newInstance(position); 
      }else{ 
       return ThreadListFrag.newInstance(); 
      } 
     } 

     @Override 
     public int getCount() { 
      // Show 13 total pages. 

      if(!subForumMode){ 
       return 13; 
      }else{ 
       return 1; 
      } 
     } 

     @Override 
     public CharSequence getPageTitle(int position) { 
      if(!subForumMode){ 
       switch (position) { 
        case 0: 
         return "Elakiri"; 
        case 1: 
         return "Cooking"; 
        case 2: 
         return "B & M"; 
        case 3: 
         return "General"; 
        case 4: 
         return "E. Traveler"; 
        case 5: 
         return "Automobile"; 
        case 6: 
         return "Motorcycles"; 
        case 7: 
         return "Entertainment"; 
        case 8: 
         return "C & I"; 
        case 9: 
         return "S. Piyasa"; 
        case 10: 
         return "Elakiri Magic"; 
        case 11: 
         return "Games"; 
        case 12: 
         return "Mobile"; 
       } 
      }else{ 
       return "Bitch Me"; 
      } 
      return null; 
     } 

     @Override 
     public int getItemPosition(Object obj){ 
      return POSITION_NONE; 
     } 
    } 

    class GetSubForumList extends AsyncTask<Void, Integer, String> 
    { 
     String TAG = getClass().getSimpleName(); 

     ProgressDialog dialog; 

     protected void onPreExecute(){ 
      Log.d(TAG + " PreExceute","On pre Exceute......"); 

      dialog = new ProgressDialog(MainActivity.this); 
      dialog.setTitle("Loading..."); 
      dialog.setIndeterminate(true); 
      dialog.setCancelable(false); 
      dialog.show(); 
     } 

     protected String doInBackground(Void...arg0){ 
      Log.d(TAG + " DoINBackGround","On doInBackground..."); 

      try { 
       Connection.Response response = Jsoup.connect("http://www.elakiri.com/forum/") 
         .execute(); 

       Document parsedDoc = response.parse(); 

       Element doc; 
       Elements doce; 

       for(int i = 0; i < forumNumbers.length; i++){ 
        doc = parsedDoc.select("tbody#collapseobj_forumbit_" + forumNumbers[i]).first(); 
        doce = doc.select("a[href] strong"); 
        forumListSubForumsList[i] = new String[(doce.size()+1)/2]; 
        forumListSubForumListLinks[i] = new String[(doce.size()+1)/2]; 
        for(int q = 0; q < (doce.size()+1)/2; q++){ 
         forumListSubForumsList[i][q] = doce.get(q*2).text(); 
         forumListSubForumListLinks[i][q] = doce.get(q*2).parent().absUrl("href"); 
        } 
       } 

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

      return "Shot"; 
     } 

     protected void onProgressUpdate(Integer...a){ 
      Log.d(TAG + " onProgressUpdate", "You are in progress update ... " + a[0]); 

     } 

     protected void onPostExecute(String result) { 
      Log.d(TAG + " onPostExecute", "" + result); 

      loaded = true; 
      mViewPager.invalidate(); 
      mSectionsPagerAdapter.notifyDataSetChanged(); 

      dialog.dismiss(); 
     } 
    } 

    static class GetThreadList extends AsyncTask<Void, Integer, String> 
    { 
     String TAG = getClass().getSimpleName(); 

     ProgressDialog dialog; 

     protected void onPreExecute(){ 
      Log.d(TAG + " PreExceute","On pre Exceute......"); 

      dialog = new ProgressDialog(context); 
      dialog.setTitle("Loading..."); 
      dialog.setIndeterminate(true); 
      dialog.setCancelable(false); 
//   dialog.show(); 
     } 

     protected String doInBackground(Void...arg0){ 
      Log.d(TAG + " DoINBackGround","On doInBackground..."); 

      try { 
       Connection.Response response = Jsoup.connect(subforumLink) 
         .execute(); 

       Element doc = response.parse().select("tbody#threadbits_forum_2").first(); 

       Elements doce = doc.select("a[id^=thread_title_]"); 

       threadListLinks[0] = new String[doce.size()]; 
       threadListLinks[1] = new String[doce.size()]; 

       for(int i = 0; i < doce.size(); i++){ 
        threadListLinks[0][i] = doce.get(i).text(); 
        threadListLinks[1][i] = doce.get(i).absUrl("href"); 
       } 

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

      return "Shot"; 
     } 

     protected void onProgressUpdate(Integer...a){ 
      Log.d(TAG + " onProgressUpdate", "You are in progress update ... " + a[0]); 

     } 

     protected void onPostExecute(String result) { 
      Log.d(TAG + " onPostExecute", "" + result); 

      loadedSub = true; 
      mViewPager.invalidate(); 
      mSectionsPagerAdapter.notifyDataSetChanged(); 
     } 
    } 
} 

ForumListAdapter.java

public class ForumListAdapter extends ArrayAdapter<String> { 
    private final Context context; 
    private final String[] values; 

    public ForumListAdapter(Context context, String[] values) { 
     super(context, R.layout.main_adapter ,values); 
     this.context = context; 
     this.values = values; 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     LayoutInflater inflater = (LayoutInflater) context 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View rowView = inflater.inflate(R.layout.main_adapter, parent, false); 
     TextView textView = (TextView) rowView.findViewById(R.id.firstLine); 
     textView.setText(values[position]); 

     return rowView; 
    } 
} 

Répondre

0

D'accord, je l'ai résolu en utilisant FragmentStatePageAda pter au lieu d'utiliser FragmentPageAdapter