我有这个应用程序在我的主菜单中,我想在文本视图中显示获得的星星,这是用文本文件写的。而且如果我赚了更多星星,我想读取数据并添加获得的星星并附加到txtfile。由于某些原因,我的应用程序崩溃,我被困在这里几个小时。有人可以帮我这个吗?
这是我的代码:
import android.widget.TextView;
public class MainActivity extends Activity {
private static TextView txt_stars;
private static final String FILENAME = "Stars.txt";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onButtonClickListener();
txt_stars = (TextView) findViewById(R.id.txtStars);
//This is where I should view the number of stars remaining
}
public void onButtonClickListener {
button_next = (Button) findViewById(R.id.btnNext);
button_next.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setMessage("You have earned 50 stars");
alert.setCancelable(false);
alert.setPositiveButton("next", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Can anyone please help me here?
//this should compute the data inserted in textfile and the stars earned, and the result should append to the file.
}
});
AlertDialog alertDialog = alert.create();
alertDialog.show();
}
}
);
}
}

感谢您的帮助。
答案 0 :(得分:2)
您可以编写两个辅助方法来进行读写。
private String readStars(String file) {
BufferedReader reader = null;
String stars = null;
StringBuffer buffer = new StringBuffer();
try {
reader = new BufferedReader(new FileReader(file));
if(reader != null){
while((stars = reader.readLine())!= null){buffer.append(stars);};// if you have more lines in your text if not you can simply say reader.readLine()
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return buffers.toString(); // or you can send the length to get the number of stars but you should take care to remove emptylines and empty strings.
}
private String appendStars(String file, String starData) {
BufferedWriter writer = null;
String stars = null;
try {
writer = new BufferedWriter(new FileWriter(file));
if(writer != null){
writer.append(starData);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
return stars;
}
并在对话框和按钮侦听器中调用它们并获取数据并将数据附加到文件中。
SharedPreferences preferences = null;
在OncreateView中:
//This is where I should view the number of stars remaining
String starsData = readStars("stars.file"); // or you can read it from preference as other said
/* if you are trying to get it from preferences . here is the sampel*/
preferences = getSharedPreferences("your preferences key", MODE_PRIVATE); // mode completely depends on you. you can change it as per requirements.
starsData = preferences.getString("your stars edittext key", ""); // default values can be anything either 1 or empty if string. your choice
txt_stars.setText(starsData);
在Dialoglistener中:
//Can anyone please help me here?
//this should compute the data inserted in textfile and the stars earned, and the result should append to the file.
String newStars = txt_stars.getText().toString();
//do the stars calculation and depending . If it is a sample app you can simply append the star in the new line to the file and see if it works for you and later you can modify based on the requirements.
appendStars("stars.txt", newStars);
// if you want to use the sharedpreferences
SharedPreferences.Editor editor = preferences.edit();
editor.putString("your stars edittext key", newStars);
editor.commit();
答案 1 :(得分:2)
你想要自己处理低级管理是一件好事但是值得,当你不得不花更多的时间用它来制作更酷的东西时。
Android
提供Shared Preference
框架,主要处理少量数据Primitives
(例如int
,boolean
,String
,{{ 1}}等)。它可以做更多的事情,但你会尽可能多地使用它。
这可以轻松减少您的代码,因为它会为您处理低级编码。
我已经编写了可以使用的测试。如果您想查看
,它也会上传到GitHub linkfloat
xml文件
public class SharedPreferencesActivity extends Activity {
private EditText count_editText;
private TextView count_textView;
private Button save_read_button;
private static final String FILE_NAME = "text"; //this is the name of file where you will save your count
private static final String COUNT_KEY = "COUNT_KEY"; // this framework saves data in xml, so we will need key value pair, so this would be a key
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shared_prefrences);
sharedPreferences = getApplicationContext().getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
initializeUI();
String count_Integer = sharedPreferences.getString(COUNT_KEY, "");
count_textView.setText("" + count_Integer);
count_editText.setText("" + count_Integer);
}
private void initializeUI() {
count_editText = (EditText) findViewById(R.id.SharedPreferencesActivity_editText);
count_textView = (TextView) findViewById(R.id.SharedPreferencesActivity_textView);
save_read_button = (Button) findViewById(R.id.SharedPreferencesActivity_button);
save_read_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String count_text = count_editText.getText().toString();
if (count_text != null && count_text.length() > 0) {
count_textView.setText("" + count_text);
editor.putString(COUNT_KEY, count_text).apply();
} else {
Toast.makeText(getApplicationContext(), "Kindly provide a valid number", Toast.LENGTH_SHORT).show();
}
}
});
}
}
输出
在DDMS中,您可以提取文件以查看数据的外观
当您打开此文件时,您可能会看到输入的数据保存在您提供的键值对中。这将是这样的......
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="4dp"
android:gravity="center"
android:orientation="vertical"
android:padding="4dp">
<EditText
android:id="@+id/SharedPreferencesActivity_editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_margin="4dp"
android:ems="10"
android:inputType="number"
android:padding="4dp" />
<TextView
android:id="@+id/SharedPreferencesActivity_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_margin="4dp"
android:padding="4dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="@+id/SharedPreferencesActivity_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_margin="4dp"
android:padding="4dp"
android:text="Read_Save"
android:textAllCaps="false" />
</LinearLayout>