当我运行Android应用时,主屏幕上没有任何内容。这是可疑的所以我尝试了几个print语句来查看字符串值是否实际设置。没有任何东西打印到我的控制台,所以我查看了logcat并找到了以下内容:
03-05 00:37:14.958: E/(9918): <s3dReadConfigFile:75>: Can't open file for reading
有人能看出这段代码有什么问题吗?这对我来说似乎很简单,我不明白为什么它不会正常工作。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<contact> contacts = new ArrayList<contact>();
File file = new File("contacts.json");
String s = "Hello";
//System.out.println(s);
try {
Scanner in = new Scanner(file);
StringBuilder sb = new StringBuilder();
while(in.hasNext()){
sb.append(in.next());
}
System.out.println(s.substring(0,10));
in.close();
JSONArray ja = new JSONArray(s);
for (int i = 0; i < ja.length(); i++) {
JSONObject obj = ja.getJSONObject(i);
contact c = new contact(); // Creates an empty contact object
// Retrieves contact information from JSONObject
String name = obj.getString("name");
int employeeId = obj.getInt("employeeId");
String company = obj.getString("company");
String detailsURL = obj.getString("detailsURL");
String imageURL = obj.getString("imageURL");
long birthdate = obj.getLong("birthdate");
//Sets contact values to retrieved JSON data and adds to the ArrayList
c.setName(name);
c.setEmployeeId(employeeId);
c.setCompany(company);
c.setDetailsURL(detailsURL);
c.setImageURL(imageURL);
c.setBirthdate(birthdate);
contacts.add(c);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Error");
}
答案 0 :(得分:0)
在文件构造函数中传递带文件名的完整路径,而不是仅传递文件名。如果文件在SDCARD内,则执行:
String Root_Dir = Environment.getExternalStorageDirectory().getAbsolutePath();
File file = new File(Root_Dir+"/contacts.json");