在ListView中编辑后更新.txt文件?

时间:2014-10-21 06:19:55

标签: java android listview android-listview

我正在尝试更新通过ListView显示的.txt文件。 我有一个从ListView中删除行的按钮,但是我希望它还可以更新我的.txt文件中的行,同时保留它们的结构,以便它们在编辑后正确显示在ListView中。

重要提示:output.txt文件的更新输出必须保持相同的格式,以确保在列表视图中正确显示。

非常感谢。

编辑:更清楚地说,我在ListView中显示了一个.txt文件。 当我删除ListView中的行时,我希望它也可以在.txt文件中删除。

这是我在ViewMeds.Java中看到的列表视图的代码:

package ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmeds;

import android.app.ActionBar;
import android.graphics.Color;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View.OnClickListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.widget.DrawerLayout;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;


public class viewMeds extends Activity {



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTitle("View Medications");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_meds);


        String SDRoot = Environment.getExternalStorageDirectory().getPath();
        final File output = new File(SDRoot,"output.txt");
        //Get the text file

        //Read text from file


        StringBuilder text = new StringBuilder();
        final ListView lv = (ListView)findViewById(R.id.viewMedsTxt);
        lv.setItemsCanFocus(true);


        final List<String> lines = new ArrayList<>();
        Scanner reader = null;
        try {
            reader = new Scanner(new FileInputStream(output), "UTF-8");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


        while(reader.hasNextLine())
            lines.add(reader.nextLine());

        if(!reader.hasNextLine()){
            lines.add("You have no medications, add some from the start screen!");
        }
            reader.close();

        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                this,
                android.R.layout.simple_list_item_1,
                lines );


        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                for (int j = 0; j < parent.getChildCount(); j++)
                    parent.getChildAt(j).setBackgroundColor(Color.TRANSPARENT);

                // change the background color of the selected element
                view.setBackgroundColor(Color.LTGRAY);
            }
        });

        lv.setAdapter(arrayAdapter);



        Button delete = (Button)findViewById(R.id.deleteMed);
        delete.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {


                /** Getting the checked items from the listview */
                SparseBooleanArray checkedItemPositions = lv.getCheckedItemPositions();
                int itemCount = lv.getCount();

                for(int i=itemCount-1; i >= 0; i--){
                    if(checkedItemPositions.get(i)){
                        arrayAdapter.remove(lines.get(i));
                    }
                }
                checkedItemPositions.clear();
                arrayAdapter.notifyDataSetChanged();


            }
        });

    }


    public void removeLine(final File file, final int lineIndex) throws IOException{
        final List<String> lines = new LinkedList<>();
        final Scanner reader = new Scanner(new FileInputStream(file), "UTF-8");
        while(reader.hasNextLine())
            lines.add(reader.nextLine());
        reader.close();
        if(lineIndex >= 0 && lineIndex <= lines.size() - 1)
        lines.remove(lineIndex);
        final BufferedWriter writer = new BufferedWriter(new FileWriter(file, false));
        for(final String line : lines)
            writer.write(line);
        writer.flush();
        writer.close();
    }



    public void restoreActionBar() {
        ActionBar actionBar = getActionBar();
        actionBar.setTitle("View Medications");
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.action_settings:
                Intent prefIntent = new Intent("android.intent.action.PREFS");
                startActivity(prefIntent);
                break;
            case R.id.exit:
                finish();
                break;

        }

        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        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;
        }

        public PlaceholderFragment() {
        }
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.activity_main, container, false);
        return rootView;
    }

   /* @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity) activity).onSectionAttached(
                getArguments.getInt(ARG_SECTION_NUMBER));
    }*/
}

以及在我的MainActivity.Java中看到的文件本身:

Button addbutton = (Button)findViewById(R.id.addMeds);
        addbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String outputLine = medOut.getText() + " "+ doseOut.getText() +" "+ dayout.getText() +":" + " "+ ":" + timeOut.getText() + "\n";

                try {
                    FileOutputStream fOut = new FileOutputStream(output, true);
                    OutputStreamWriter myOutputStreamWriter = new OutputStreamWriter(fOut);
                    myOutputStreamWriter.append(outputLine);
                    myOutputStreamWriter.flush();
                    myOutputStreamWriter.close();
                    Toast.makeText(getBaseContext(), "Medication Added",
                            Toast.LENGTH_SHORT).show();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    Toast.makeText(getBaseContext(), e.getMessage(),
                            Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(getBaseContext(), e.getMessage(),
                            Toast.LENGTH_SHORT).show();
                }






            }
        });

1 个答案:

答案 0 :(得分:0)

使用点击侦听器中的这行代码解决了删除按钮:

for(int i=itemCount-1; i >= 0; i--){
                    if(checkedItemPositions.get(i)){
                        arrayAdapter.remove(lines.get(i));
                        try {
                            removeLine(output,i);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                }

并将我的removeLines方法更改为

 public void removeLine(final File file, final int lineIndex) throws IOException{
        final List<String> lines = new LinkedList<>();
        final Scanner reader = new Scanner(new FileInputStream(file), "UTF-8");
        while(reader.hasNextLine())
            lines.add(reader.nextLine());
        reader.close();
        if(lineIndex >= 0 && lineIndex <= lines.size() - 1)
            lines.remove(lineIndex);
        final BufferedWriter writer = new BufferedWriter(new FileWriter(file, false));
        for(final String line : lines)
            writer.write(line + "\n");
        writer.flush();
        writer.close();
    }