我创建了写入和读取文件的应用程序。当我单击按钮时,我的文件正在写入,并且在同一按钮单击上也会读取文件。我希望当我的文件被写入时,该文件将其保存到SQLite中。我在网上冲浪,但找不到合适的来源或想法如何做到这一点。
该文件与输入字符串进行比较,例如"代码"。如果此input_String与存储在SQLite数据库中的文件匹配,则匹配用户无法继续进一步的过程。我正在就此寻求建议。这是我的代码。
活动类:
public class Write extends Activity {
/** Called when the activity is first created. */
EditText myText;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.abc);
myText = (EditText) findViewById(R.id.myText);
Button createButton = (Button) findViewById(R.id.btnCreate);
Button readButton = (Button) findViewById(R.id.btnRead);
createButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
createFile(myText.getText().toString());
myText.setText("");
readFile();
}
});
}
private void createFile(String Text)
{
FileOutputStream fos = null;
try
{
fos = openFileOutput("mynote.txt", MODE_PRIVATE);
fos.write(Text.getBytes());
Toast.makeText(getApplicationContext(), "File created succesfully",
Toast.LENGTH_SHORT).show();
}
catch (FileNotFoundException e)
{
Log.e("CreateFile", e.getLocalizedMessage());
}
catch (IOException e)
{
Log.e("CreateFile", e.getLocalizedMessage());
}
finally
{
if (fos != null)
{
try
{
// drain the stream
fos.flush();
fos.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
和DataBase_Adapter代码:
//Table Name
public static final String TABLE_NAME_CODE="code_table";
//Colum,n Names
public static final String KEY_CODE_ID="ID";
public static final String KEY_CODE_NAME="USERNAME";
//Table Create Statement
public static final String DATABASE_CREATE_CODE = "CREATE TABLE "+TABLE_NAME_CODE+" ("+KEY_CODE_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+KEY_CODE_NAME+"TEXT)";
//Insert Code in Database code_table
public void saveCode(String strKey_Code)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put(KEY_CODE_NAME , strKey_Code);
// Insert the row into your table
db.insert(TABLE_NAME_CODE, null, newValues);
}
您采取的方法可以改进一点,考虑仅在数据库中存储文件名,您已经保存了文件,对吗? 为什么要再次将其内容存储在数据库中?