Android:在viewpager选项卡中阻止和更新listview内容

时间:2015-10-24 23:40:56

标签: android android-fragments android-asynctask android-tablayout

抱歉,我找不到解决问题的好方法。我正在尝试使用少量选项卡进行应用程序(viewpager)每个选项卡都是不同的片段。我想要做的是单击其中一个选项卡/片段中的按钮,然后更新另一个中的列表视图内容。 Listview本身包含来自网站的搜索结果。要进行搜索,我需要将2个搜索参数作为字符串传递。 listview在Asynctask中,我使用jsoup来解析网站内容。应用程序启动后,每次尝试都会出错。

我的代码(已跳过导入)

MainActivity

public class MainActivity extends AppCompatActivity{

    private DrawerLayout mDrawerLayout;
    private Menu menu;
    private NavigationView navView;

    public static String nazwaStanowiska;

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


        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        final ActionBar ab = getSupportActionBar();
        ab.setHomeAsUpIndicator(R.drawable.ic_menu);
        ab.setDisplayHomeAsUpEnabled(true);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        if (navigationView != null) {
            setupDrawerContent(navigationView);
        }

        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        if (viewPager != null) {
            setupViewPager(viewPager);
        }

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


        navView = (NavigationView)findViewById(R.id.nav_view);
        Menu m = navView.getMenu();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.sample_actions, menu);

        MenuItem item = menu.add("Cokolwiek");
        item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                return false;
            }
        });
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void setupViewPager(ViewPager viewPager) {
        Adapter adapter = new Adapter(getSupportFragmentManager());
        adapter.addFragment(new SearchFragment(), "Search");
        adapter.addFragment(new ProbaListFragment(), "Results");
        viewPager.setAdapter(adapter);
    }

    private void setupDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        menuItem.setChecked(true);
                        mDrawerLayout.closeDrawers();
                        return true;
                    }
                });
    }

    static class Adapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragments = new ArrayList<>();
        private final List<String> mFragmentTitles = new ArrayList<>();

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

        public void addFragment(Fragment fragment, String title) {
            mFragments.add(fragment);
            mFragmentTitles.add(title);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitles.get(position);
        }
    }
}

SearchFragment - 在buttonClick之后,这个片段应该向ProbaListFragment发送2个字符串。我知道在frag-activ通信中,建议使用接口,但首先我想完成所有工作。只要我将字符串传递给另一个片段,例如textview,它就可以工作。

public class SearchFragment extends Fragment {

    private View view;
    static Button mButton;
    private EditText mMiejsce, mStanowisko, mProba;
    public static boolean isButtonClicked = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.search_fragment, container, false);


        mStanowisko = (EditText)view.findViewById(R.id.stanowisko);
        mMiejsce = (EditText)view.findViewById(R.id.miejscePracy);

        mProba = (EditText)view.findViewById(R.id.proba);

        mButton = (Button)view.findViewById(R.id.buttonSearch);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ReceiveFragment.setmyText(mStanowisko.getText().toString());
                //ProbaListFragment.cleanMyJobList();
                ProbaListFragment.setmyText(mStanowisko.getText().toString(), mMiejsce.getText().toString());
                //isButtonClicked = true;
            }
        });
        return view;
    }
}

和ProbaListFragment本身:

public class ProbaListFragment extends Fragment{

    public Elements jobName, jobName2, jobNameComp, jobName2Comp;

    static List<String> mListaTest1 = new ArrayList<>();
    static List<String> mListaTest2 = new ArrayList<>();
    static List<String> mListaLinki = new ArrayList<>();

    private View view;
    private Button mButton;
    private JazzyListView mListView;
    static ArrayList<String> jobList = new ArrayList<String>();
    private JobListAdapter mAdapter;

    static String tekstPrzekazany;
    static String doURLwork;
    static String doURLplace;


    ViewPager viewPager;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.activity_listview, container, false);


        viewPager = (ViewPager) getActivity().findViewById(R.id.viewpager);

        mListView = (JazzyListView) view.findViewById(R.id.list);
        mListView.setTransitionEffect(new FanEffect());
        mListView.setItemsCanFocus(true);
        //Progress bar
        //mListView.setEmptyView(view.findViewById(R.id.progressBarLoading));

        new NewThread().execute();

       // Toast.makeText(getApplicationContext(), "Wyszukiwanie ofert...", Toast.LENGTH_LONG).show();


        mAdapter = new JobListAdapter(getContext(), jobList);
        mListView.setAdapter(mAdapter);

        mAdapter.notifyDataSetChanged();

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(getContext(), "Siema", Toast.LENGTH_LONG).show();



                viewPager.setCurrentItem(0);
            }
        });

        return view;
    }

    public static void setmyText(final String stringWork, String stringPlace) {

        doURLwork = stringWork;
        doURLplace = stringPlace;
    }

    @Override
    public void onResume() {
        mAdapter.notifyDataSetChanged();
        super.onResume();
    }

    public class NewThread extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... strtext) {

            //String doURLwork = mainActiv.nazwaStanowiska;
            //doURLwork = "kierowca";
            //String doURLplace = mainActiv.nazwaMiejscowosci;
            //doURLplace = "Wroclaw";

            Document doc, doc2, docProba;
            Elements classs, lins, elProba;
            String uerele;
            try {
                doc = (Document) Jsoup.connect("http://www.infopraca.pl/praca?q=" + doURLwork + "&lc=" + doURLplace)
                        .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0").get();
                doc2 = (Document) Jsoup.connect("http://www.pracuj.pl/praca/" + doURLwork + ";kw/" + doURLplace + ";wp")
                        .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0").get();

                docProba = (Document) Jsoup.connect("http://www.infopraca.pl/praca/junior-java-developer/wroclaw/11774542?vj4=1")
                        .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0").get();

                elProba = docProba.select("div#txt-descryption");


                //Elements info = docProba.select("div#txt-description")

                //Oferty
                jobName = doc.select("h2.p-job-title a[href]"); //Infopraca
                jobName2 = doc2.select("h2.offer__list_item_link a[href]");  //pracuj.pl

                //Firmy
                jobNameComp = doc.select("h3.p-name.company a[href]"); //Infopraca
                jobName2Comp = doc2.select("h3.offer__list_item_link a[href]");  //pracuj.pl

                //Oferty pracy
                //Infopraca
                mListaTest1.clear();
                for (Element jobNames : jobName) {
                    mListaTest1.add(jobNames.text() + "\n");
                }

                //Pracuj.pl
                for (Element jobNames2 : jobName2) {
                    mListaTest1.add(jobNames2.text() + "\n");
                }
                if(mListaTest1.size()==0){
                    Toast.makeText(getContext(), "Zmie? parametry wyszukiwania!", Toast.LENGTH_LONG).show();
                }

                //--------------------------------------------------

                //Firmy
                //Infopraca
                mListaTest2.clear();
                for (Element jobNames : jobNameComp) {
                    mListaTest2.add(jobNames.text() + "\n");
                }

                //Pracuj.pl
                for (Element jobNames2 : jobName2Comp) {
                    mListaTest2.add(jobNames2.text() + "\n");
                }

                //Linki do ofert
                //Infopraca
                for (Element link : jobName) {
                    mListaLinki.add(link.attr("abs:href"));
                }

                //Pracuj.pl
                for (Element link : jobName2) {
                    mListaLinki.add(link.attr("abs:href"));
                }

                jobList.clear();
                for(int i=0; i<mListaTest1.size(); i++){
                    jobList.add(mListaTest1.get(i)+"\n"+mListaTest2.get(i));
                }

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

如何修复它以便它能以良好的方式工作? 另一个问题是 - 我可以动态添加新标签吗? 我的意思是 - 例如 - 当用户点击按钮时,会出现带有结果(listview)的标签/片段?或者按钮点击后出现标签,因为现在它从应用程序的开头可见,无论按钮是否已被按下都无关紧要。

我的logcat:

java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:299)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
            at java.util.concurrent.FutureTask.run(FutureTask.java:239)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
            at java.lang.Thread.run(Thread.java:841)
     Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
            at android.os.Handler.<init>(Handler.java:197)
            at android.os.Handler.<init>(Handler.java:111)
            at android.widget.Toast$TN.<init>(Toast.java:324)
            at android.widget.Toast.<init>(Toast.java:91)
            at android.widget.Toast.makeText(Toast.java:238)
            at com.support.android.designlibdemo.ProbaListFragment$NewThread.doInBackground(ProbaListFragment.java:174)
            at com.support.android.designlibdemo.ProbaListFragment$NewThread.doInBackground(ProbaListFragment.java:128)
            at android.os.AsyncTask$2.call(AsyncTask.java:287)
            at java.util.concurrent.FutureTask.run(FutureTask.java:234)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
            at java.lang.Thread.run(Thread.java:841)

Plz借给我一些帮助!

编辑:另外请告诉我为什么只有当我点击SearchFragment中的EditText以便出现键盘时才显示我的列表视图,然后我会转到ProbaListFragment并按回按钮(键盘隐藏起来)?

1 个答案:

答案 0 :(得分:0)

“无法在未调用Looper.prepare()的线程内创建处理程序。”您试图触摸视图以在线程中显示其不属性的文本。

   Toast.makeText(getContext(), "Zmie? parametrywyszukiwania!", Toast.LENGTH_LONG).show();

如果你想要显示吐司把它放在runOnUithread或使用处理程序