如何从Android中的MainActivity中保存ArrayList?

时间:2016-07-21 02:37:40

标签: java android arraylist save

我有一个数组(在这里称为arrayMain),我需要在添加项目时保存,并在应用程序启动时加载。我已经彻底研究了这个问题,看到使用像gson和SharedPreferences这样的解决方案,但是我的程序中都没有。我相信这些不起作用,因为解决方案假设您没有将它放在MainActivity中,而是将其放在另一个类中。

我是编程新手,我还在学习。因此,请包括我必须做的一切(包括进口东西等),因为我不太了解所有这些。因为我不知道我的代码是如何交互的,所以我几乎包含了所有代码,因此我不会遗漏任何内容。谢谢你的帮助。

代码:

public class MainActivity extends AppCompatActivity {

public static ArrayAdapter<String> mItemViewerAdapter;

public static ArrayList<String> arrayMain = new ArrayList<String>();


@Override
protected void onCreate(Bundle savedInstanceState) {


// Get ArrayList


    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState == null) {

        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceHolderFragment()).commit();
    }


    // *** POPUP field (that I left out) that returns StringMain ***
        ArrayMain.add(StringMain);

// Set ArrayList

public static class PlaceHolderFragment extends Fragment {

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

        mItemViewerAdapter =
                new ArrayAdapter<String>(
                        getActivity(),
                        R.layout.list_item_itemList,
                        R.id.list_item_itemList_textview,
                        arrayMain
                );

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

        ListView listView = (ListView) rootView.findViewById(R.id.listview_ItemList);
        listView.setAdapter(mItemViewerAdapter);
        return rootView;

    }

}

}

1 个答案:

答案 0 :(得分:0)

首先,你必须了解Json的概念。如何将字符串转换为json,反之亦然。如何使用json数组和json对象。 然后你会发现它很容易存储json&#34; string&#34;共享首选项中的数据。从共享首选项中获取字符串数据,并根据需要将其转换为json Arrray或对象。 在要在数组列表中加载数据的类中使用此数据。 这不是直接执行,你必须考虑, 您想要存储数据的内容以及如何在班级中使用存储的数据。

相关问题