有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java更新。在ListView中编辑后的txt文件?

我正在尝试更新一个。通过列表视图显示的txt文件。 我有一个从ListView中删除行的按钮,但我希望它也能更新我的列表中的行。txt文件,同时保持其结构,以便在编辑后正确显示在ListView中

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

非常感谢

我必须更清楚地编辑它。在列表视图中显示的txt文件。 当我在ListView中删除该行时,我希望它在列表中被删除。txt文件

下面是我在ViewMeds中看到的列表视图的代码。爪哇:

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

import 安卓.app.ActionBar;
import 安卓.graphics.Color;
import 安卓.util.Log;
import 安卓.util.SparseBooleanArray;
import 安卓.view.View.OnClickListener;
import 安卓.app.Activity;
import 安卓.app.AlertDialog;
import 安卓.app.Fragment;
import 安卓.app.FragmentManager;
import 安卓.content.DialogInterface;
import 安卓.content.Intent;
import 安卓.os.Bundle;
import 安卓.os.Environment;
import 安卓.support.v4.widget.DrawerLayout;
import 安卓.text.method.ScrollingMovementMethod;
import 安卓.view.LayoutInflater;
import 安卓.view.Menu;
import 安卓.view.MenuInflater;
import 安卓.view.MenuItem;
import 安卓.view.View;
import 安卓.view.ViewGroup;
import 安卓.widget.AdapterView;
import 安卓.widget.ArrayAdapter;
import 安卓.widget.Button;
import 安卓.widget.EditText;
import 安卓.widget.ListView;
import 安卓.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,
                安卓.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("安卓.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));
    }*/
}

以及写入文件本身,如我的主要活动所示。爪哇:

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) 个答案

  1. # 1 楼答案

    在单击“删除”按钮的侦听器中使用这行代码解决:

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