当我打开应用程序时必须读取外部并将所有号码从联系人复制到该文件但是当我尝试总是强行关闭时。
public class anti_spam extends TabActivity {
/** Called when the activity is first created. */
BufferedReader reader;
public String[] Number;
int x=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//------------------------
getListNumber();
File logFile = new File("root/log.txt");
//Hitung Jumlah isi File
try {
reader = new BufferedReader(new FileReader("root/log.txt"));
try {
while (reader.readLine()!= null)
{
x++;
}
reader.close();
} catch (IOException e) {}
} catch (FileNotFoundException e1) {}
//Hapus File Jika Jumlah Kontak Beda
if (x-1 != Number.length){
logFile.delete();
}
if (!logFile.exists())
{
try
{
logFile.createNewFile();
Toast.makeText(getBaseContext(), "Data Berhasil Dibuat", Toast.LENGTH_LONG).show();
//Isi File
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
String[] numTemp;
String numBaru;
for(int i=0;i<Number.length;i++)
{
numTemp = Number[i].split("-");
numBaru = (numTemp[0]+numTemp[1]+numTemp[2]);
if (numBaru.substring(0, 1).equals("0"))
{
numBaru = numBaru.replaceFirst("0","+62");
}
buf.append(numBaru + "\n");
}
buf.newLine();
buf.close();
}
catch (IOException e)
{
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}}
清单上的
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"> </uses-permission> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"> </uses-permission>
答案 0 :(得分:0)
请在清单文件中添加。
<uses-permission android:name="android.permission.READ_CONTACTS" />
答案 1 :(得分:0)
@Dhiren关于向清单文件添加权限是正确的:
<uses-permission android:name="android.permission.READ_CONTACTS" />
但问题还有更多,请继续阅读......
我认为您可能需要更多关注您可以写入的文件夹。
在Environment.getExternalStorageDirectory()上查看此链接,了解如何操作。
这些答案中还有一些有用的代码: