如何通过Android中的HasMap以csv格式的文件写入数据?

时间:2019-03-01 09:18:17

标签: android firebase firebase-realtime-database

下面是代码,如果我的类是在HashMap中从firebase提取数据的,则我已将该数据存储到arraylist中,并将数组列表的数据转换为逗号分隔的字符串,但无法正常工作。我的Firebase数据的屏幕截图。 .. enter image description here

SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_report);
        sharedPreferences = getSharedPreferences("Pref", Context.MODE_PRIVATE);
        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                ArrayList<Map<String, CompanyData>> myArrList = new ArrayList<>();
                Map<String, CompanyData> userData = (Map<String, CompanyData>) dataSnapshot.getValue();
                myArrList.add(userData);
                Log.d("data", userData.toString());
                csv(myArrList);
                Log.d("99", sharedPreferences.getString("generalStrings", ""));

                String path =
                        Environment.getExternalStorageDirectory() + File.separator + "Mccia";
                // Create the folder.
                File folder = new File(path);
                folder.mkdirs();

                // Create the file.
                File file = new File(folder, "config.csv");
                try {
                    file.createNewFile();
                    FileOutputStream fOut = new FileOutputStream(file);
                    OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
                    myOutWriter.append(sharedPreferences.getString("generalStrings", ""));
                    myOutWriter.close();

                    fOut.flush();
                    fOut.close();
                } catch (IOException e) {
                    Log.e("Exception", "File write failed: " + e.toString());
                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });


    }

下面是我将列表数据转换为字符串的方法

private ArrayList<Map<String, CompanyData>> csv(ArrayList<Map<String, CompanyData>> mapArrayList) {
        ArrayList<Map<String, CompanyData>> g = mapArrayList;
        SharedPreferences.Editor editor = sharedPreferences.edit();
        StringBuilder st = new StringBuilder();
        for (Map<String, CompanyData> item : g) {
            st.append(item);
        }
        if (!g.isEmpty()) {
            editor.putString("generalStrings", st.toString().substring(0, st.toString().length() - 1));
            editor.apply();
        } else {
            editor.putString("generalStrings", " ");
            editor.apply();
        }
        return g;
    }

请帮助我或给我一些想法。我有openCsv和superCSV库,但没有帮助。

0 个答案:

没有答案