【问题标题】:How to show saved data inside multiple fragments?如何在多个片段中显示保存的数据?
【发布时间】:2019-01-27 15:34:48
【问题描述】:

简介

大家好,目前我正在开发一个问题表单应用程序。在 MainActivity 中,用户可以添加一个项目,之后会打开一个 QuestionListActivity。单击该列表中的第一项将打开 Main2Activity。此活动包含 3 个片段,均包含一个问题(Edittext)。用户在片段中实现的数据是可保存的。回答并保存问题后,每个表单都以列表的形式出现在 MainActivity 中。单击这些项目会将它们带回 QuestionListActivity,然后单击第一个项目应再次打开片段,并显示其保存的数据。

问题

保存片段后,到MainActivity的字符串是成功的,例如。通过保存第一个片段(询问表单名称)设置的标题。因此,保存到我的实用程序类是成功的。问题是,单击 MainActivity 中的已保存项目,然后单击 QuestionList 中的第一个项目以打开 Main2Activity(带问题的片段),打开片段但带有空的 EditText 字段,应显示保存的数据以查看它们或进行更改。

问题

如何在多个片段中而不是在一个活动中显示保存的数据,我做错了什么?并且在使用 8 个问题(每个问题一个片段)时是否建议使用相同的格式?

(我在 StackOverFlow 上找不到合适的问题,因为几乎所有关于这个主题的问题都是关于实例状态 ed。但这在我的项目中不是问题)

代码

这是我的 Main2Activity 和一个片段(Frag1)。我设置的另一个片段与 Frag1 的设置方式相同。我可能在片段 java 类中做错了什么,但我不确定是什么。希望有人可以帮助我。

public class Main2Activity extends AppCompatActivity {

private SectionsPagerAdapter mSectionsPagerAdapter;

private ViewPager mViewPager;

private String mNoteFileName;

private Note mLoadedNote;
private EditText title, question2, question3;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    title = findViewById(R.id.note_et_title1);

    question2 = findViewById(R.id.note_et_question2);

    question3 = findViewById(R.id.note_et_question3);

    String title;
    String question2 ;
    String question3;
    mNoteFileName = getIntent().getStringExtra("NOTE_FILE");
    if(mNoteFileName !=null && !mNoteFileName.isEmpty()) {
        mLoadedNote = Utilities.getNoteByName(this, mNoteFileName);
        if(mLoadedNote !=null) {
            title = mLoadedNote.getTitle();
            question2 = mLoadedNote.getQuestion2();
            question3 = mLoadedNote.getQuestion3();
        }
    }

    List<Fragment> fragments = new ArrayList<>();
    fragments.add(Frag1.newInstance(title));
    fragments.add(Frag2.newInstance(question2));
    fragments.add(Frag3.newInstance(question3));

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),fragments);

    mViewPager = (ViewPager) findViewById(R.id.container);

    mViewPager.setAdapter(mSectionsPagerAdapter);

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

    mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.menu_note_new, menu);
    return true;
}

private void saveNote() {
    Note note;

    if(title.getText().toString().trim().isEmpty()){
        Toast.makeText(this, "Please enter a title", Toast.LENGTH_SHORT).show();

    }

    if(mLoadedNote ==null) {
        note = new Note(System.currentTimeMillis(), title.getText().toString(), question2.getText().toString(), question3.getText().toString());

    }else {
        note = new Note(mLoadedNote.getDateTime(), title.getText().toString(), question2.getText().toString(), question3.getText().toString());

    }

    if (Utilities.saveNote(this, note)){
        Toast.makeText(this, "saved", Toast.LENGTH_SHORT).show();

    }else{
        Toast.makeText(this, "not enough space", Toast.LENGTH_SHORT).show();

    }

    finish();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

        case R.id.action_note_save:
            saveNote();

            break;
    }

    return true;
}


public static class PlaceholderFragment extends Fragment {


    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }


    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main2, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}


public class SectionsPagerAdapter extends FragmentPagerAdapter {

    private List<Fragment> mFragments;

    public SectionsPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
        super(fm);
        mFragments = fragments;
    }

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

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

}

public class Frag1 extends Fragment {
private static final String EXTRA_TEXT = "text";
private EditText mEtTitle;

public static Frag1 newInstance(String message) {
    Bundle args = new Bundle();
    args.putString(EXTRA_TEXT, message);
    Frag1 fragment = new Frag1();
    fragment.setArguments(args);
    return fragment;
}
public Frag1 () {

}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.frag1_layout, container, false);
    mEtTitle = (EditText) view.findViewById(R.id.note_et_title1);
    Bundle bundle = getArguments();
    if (bundle != null) {
        mEtTitle.setText(bundle.getString(EXTRA_TEXT));
    }
    return view;
}

}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_green_light">

<TextView
    android:id="@+id/textView3"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"
    android:text="Vraag 1, bv naam" />

<EditText
    android:id="@+id/note_et_title1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"
    android:ems="10"
    android:gravity="top"
    android:inputType="textMultiLine" />

【问题讨论】:

    标签: android android-fragments android-activity android-edittext save


    【解决方案1】:

    您应该使用共享首选项或数据库来保存您的数据并显示它。

    【讨论】:

      【解决方案2】:

      我会建议你稍微改变你目前的方法。

      首先在每个片段中创建辅助方法newInstance,它将返回该片段的实例。例如 Frag1

      public class Frag1 extends Fragment {
          private static final String EXTRA_TEXT = "text";
          private EditText mEtTitle;
      
          public static Frag1 newInstance(String message) {
              Bundle args = new Bundle();
              args.putString(EXTRA_TEXT, message);
              Frag1 fragment = new Frag1();
              fragment.setArguments(args);
              return fragment;
          }
          public Frag1 () {
      
          }
          @Nullable
          @Override
          public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
              View view = inflater.inflate(R.layout.frag1_layout, container, false);
              mEtTitle = (EditText) view.findViewById(R.id.note_et_title1);
              Bundle bundle = getArguments();
              if (bundle != null) {
                  mEtTitle.setText(bundle.getString(EXTRA_TEXT));
              }
              return view;
          }
      }
      

      SectionsPagerAdapter 中传递片段列表。 供参考特此修改SectionsPagerAdapter

      public class SectionsPagerAdapter extends FragmentPagerAdapter {
      
          private List<Fragment> mFragments;
      
          public SectionsPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
              super(fm);
              mFragments = fragments;
          }
      
          @Override
          public Fragment getItem(final int position) {
              return mFragments.get(position);
          }
      
          @Override
          public int getCount() {
              return mFragments.size();
          }
      }
      

      那就换个叫法

      mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),<List of Fragments>);
      

      特此分享修改后的Activity#onCreate

      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main2);
          Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
          setSupportActionBar(toolbar);
      
          String title = "";
          String question2 = "";
          String question3 = "";
          mNoteFileName = getIntent().getStringExtra("NOTE_FILE");
          if(mNoteFileName !=null && !mNoteFileName.isEmpty()) { 
              mLoadedNote = Utilities.getNoteByName(this, mNoteFileName);
              if(mLoadedNote !=null) {
                  title = mLoadedNote.getTitle();
                  question2 = mLoadedNote.getQuestion2();
                  question3 = mLoadedNote.getQuestion3();  
              }
          }
      
          List<Fragment> fragments = new ArrayList<>();
          fragments.add(Frag1.newInstance(title));
          fragments.add(Frag2.newInstance(question2));
          fragments.add(Frag3.newInstance(question3));
      
          mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),fragments);
      
          mViewPager = (ViewPager) findViewById(R.id.container);
      
          mViewPager.setAdapter(mSectionsPagerAdapter);
      
          TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
      
          mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
          tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
      }
      

      【讨论】:

      • 非常感谢您的回答先生,但我仍然有一个问题。就在这里,它仍然说变量可能尚未初始化。你能看到我做错了什么吗?在那之后,我认为这可能会奏效! (我改变了我的代码) List fragment = new ArrayList();片段.add(Frag1.newInstance(title));片段.add(Frag2.newInstance(question2));片段.add(Frag3.newInstance(question3));
      • 你有什么错误?确保您已经为其他两个片段以及类似于 Frag1 的 Frag2 和 Frag3 创建了 newInstance 方法
      • 我做了,我得到的错误:错误:变量标题可能尚未初始化,错误:变量问题2可能尚未初始化,错误:变量问题3可能尚未初始化。
      • 用 null 或空初始化它们,也更新了相同的答案
      • 当我应用更改时,当我想在模拟器中保存笔记时,我的 saveNote 部分出现空对象引用错误。但它适用于打开和查看我已经拥有的已保存项目!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多