简体   繁体   English

Android更新数据片段

[英]Android update data fragment

It will be like 3 hours I try to update data from a activity to a fragment. 就像3个小时,我尝试将数据从活动更新为片段。 I check all pages but it didn't work... 我检查了所有页面,但是没有用...

I have to made a BookManager. 我必须做一个BookManager。 I have create some class to do it. 我创建了一些课程来做。

I have a main activity with two fragment, a first empty for the moment and a second with the summary of my list of book (most price of book, average...). 我有一个主要活动,其中有两个片段,第一个片段暂时是空的,第二个片段是我的书籍清单的摘要(书籍的最高价格,平均价格...)。 When I want to add a book, I use a new activity and take data back after add the book (its work). 当我想添加一本书时,我使用了一个新的活动,并在添加这本书之后(工作)取回数据。 and I want to refresh the fragment after add the book. 我想在添加书籍后刷新片段。

Code of my main activity : 我主要活动的代码:

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}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

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

private SimpleBookManager bookManager;

public final static int ADD_BOOK_REQUEST = 1;

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

    bookManager = new SimpleBookManager();

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

}


@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.button_add_menu) {
        Intent intent = new Intent(MainActivity.this, AddBookActivity.class);
        startActivityForResult(intent, ADD_BOOK_REQUEST);
        return true;
    }

    return super.onOptionsItemSelected(item);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {


    if (requestCode == ADD_BOOK_REQUEST) {
        // On vérifie aussi que l'opération s'est bien déroulée
        if (resultCode == RESULT_OK) {
            // On affiche le bouton qui a été choisi
            String[] valueBook = data.getStringArrayExtra("VALUE");

            Book book = this.bookManager.createBook();

            book.setTitle(valueBook[0]);
            book.setAuthor(valueBook[1]);
            book.setCourse(valueBook[2]);
            book.setIsbm(valueBook[3]);
            book.setPrice((int) Integer.parseInt(valueBook[4]));

        }
    }
}


/**
 * 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 PlaceholderFragment (defined as a static inner class below).

        switch (position) {
            case 0:
                return PlaceholderFragment.newInstance(position + 1);
            case 1:
                Fragment frag = SummaryFragment.newInstance(bookManager);

                return frag;

        }
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 2 total pages.
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "COLLECTION";
            case 1:
                return "SUMMARY";
        }
        return null;
    }
}

In the method onActivityResult, I add the book and I want here to refresh or eventuelly when I'm back to the summary fragment. 在onActivityResult方法中,我添加了这本书,当我回到摘要片段时,我想在这里刷新或最终更新。 I tried with a FragmentTransaction , but the commit didn't work, because I don't have a tag to get my fragment (I don't know how it works to get one)... And the we don't have instance of the fragment because we use a static method to create it. 我尝试了FragmentTransaction ,但是提交没有用,因为我没有标签来获取我的片段(我不知道如何获取一个片段)...而且我们没有实例片段的原因,因为我们使用静态方法来创建它。

Code of my fragment : 我的片段代码:

public class SummaryFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String BOOKMANAGER = "book";


    // TODO: Rename and change types of parameters
    private String[] info;


    private OnFragmentInteractionListener mListener;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *

     * @return A new instance of fragment SummaryFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SummaryFragment newInstance(SimpleBookManager bookManager) {

        String[] info = new String[5];

        info[0] = String.valueOf(bookManager.count());
        info[1] = String.valueOf(bookManager.getTotalCost());
        info[2] = String.valueOf(bookManager.getMaxPrice());
        info[3] = String.valueOf(bookManager.getMinPrice());
        info[4] = String.valueOf(bookManager.getMeanPrice());

        SummaryFragment fragment = new SummaryFragment();
        Bundle args = new Bundle();
        args.putStringArray(BOOKMANAGER, info);

        fragment.setArguments(args);

        return fragment;
    }

    public SummaryFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            this.info = getArguments().getStringArray(BOOKMANAGER);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View rootView;
        TextView textView;

        rootView = inflater.inflate(R.layout.fragment_summary, container, false);


        textView = (TextView) rootView.findViewById(R.id.nbbook_value);
        textView.setText(this.info[0]);

        textView = (TextView) rootView.findViewById(R.id.totalcost_value);
        textView.setText(this.info[1] + " SEK");

        textView = (TextView) rootView.findViewById(R.id.mostprice_value);
        textView.setText(this.info[2] + " SEK");

        textView = (TextView) rootView.findViewById(R.id.leastprice_value);
        textView.setText(this.info[3] + " SEK");

        textView = (TextView) rootView.findViewById(R.id.averageprice_value);
        textView.setText(this.info[4] + " SEK");

        return rootView;
    }


    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {


        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        Activity a;

        if (context instanceof Activity){
            a=(Activity) context;
        }

    }



    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

}

You can get the Fragment instance by calling FragmentPagerAdapter's getItem method. 您可以通过调用FragmentPagerAdapter的getItem方法获取Fragment实例。

SummaryFragment frag = (SummaryFragment) mSectionsPagerAdapter.getItem(1);

And then call a method in the Fragment instance to refresh display, make sure to check null before calling method on the Fragment. 然后在Fragment实例中调用方法以刷新显示,请确保在调用Fragment上的方法之前检查null。

if (frag != null) {
        frag.refreshBook(book);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM