gpt4 book ai didi

java - 尝试通过列表从 .txt 中删除一行时应用强制关闭

转载 作者:行者123 更新时间:2023-11-30 02:36:13 25 4
gpt4 key购买 nike

我正在尝试从 .txt 文件中删除一行,当用户单击按钮并收到提示时,但我正在强制关闭。

删除代码如下:

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

import android.app.ActionBar;
import android.util.Log;
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.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
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();

try {
BufferedReader br = new BufferedReader(new FileReader(output));
String line;

while ((line = br.readLine()) != null) {
text.append("Medication: " + line);
text.append("\n\n");

}
}
catch (IOException e) {
//You'll need to add proper error handling here
}

//Find the view by its id
TextView tv = (TextView)findViewById(R.id.viewMedsTxt);
tv.setMovementMethod(new ScrollingMovementMethod());

//Set the text
tv.setText(text);

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


final AlertDialog.Builder alert = new AlertDialog.Builder(viewMeds.this);

alert.setTitle("Delete a Medication");
alert.setMessage("Enter Which Line The Desired Medication Is On:");

// Set an EditText view to get user input
final EditText input = new EditText(viewMeds.this);
alert.setView(input);

alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
int value = -1;

try {
value = Integer.parseInt(input.toString());
value = value -1;
Log.i("", value + " is a number");
} catch (NumberFormatException e) {
alert.setMessage("That wasn't a number.\nEnter Which Line The Desired Medication Is On:");
}
// Do something with value!

try {
removeLine(output,value);
} catch (IOException e) {
e.printStackTrace();
}
}
});

alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});

alert.show();


}
});

}


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

这是当我输入 1 时 logcat 输出的内容:

10-20 21:15:29.554  10258-10258/ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmeds E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmeds, PID: 10258
java.lang.IndexOutOfBoundsException
at java.util.LinkedList.remove(LinkedList.java:660)
at ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmeds.viewMeds.removeLine(viewMeds.java:136)
at ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmeds.viewMeds$1$1.onClick(viewMeds.java:107)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5034)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1270)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1086)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)

非常感谢。

编辑:写入文件的代码:

String SDRoot = Environment.getExternalStorageDirectory().getPath();
final File output = new File (SDRoot,"output.txt");

if(!output.exists()){
try {
output.createNewFile();
Context context = getApplicationContext();
CharSequence text = "Output File Created!";
int duration = Toast.LENGTH_LONG;

Toast fileCreated = Toast.makeText(context, text, duration);
fileCreated.show();
} catch (IOException e) {
Context context = getApplicationContext();
CharSequence text = "Output File Not Created!";
int duration = Toast.LENGTH_LONG;

Toast fileNotCreated = Toast.makeText(context, text, duration);
fileNotCreated.show();
e.printStackTrace();
}
}


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

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






}
});

最佳答案

尝试替换这段代码:

assert lineIndex >= 0 && lineIndex <= lines.size() - 1;
lines.remove(lineIndex);

使用此代码:

if(lineIndex >= 0 && lineIndex <= lines.size() - 1)
lines.remove(lineIndex);

关于java - 尝试通过列表从 .txt 中删除一行时应用强制关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26478807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com