这几天我遇到了这个非常烦人的问题,我似乎无法完全解决它。我正在尝试打开一个.csv
文件,所以我将它导入到res/raw/
我的项目文件夹中。然后我试图通过该getResources()
方法打开并阅读它,而这正是我得到NullPointerException
. 这是读取文件并用可用行填充数组的方法。
这是我从类Activity
创建对象的地方,然后我想从类调用方法。newwords
Words
PlayWithRawFiles()
Words
public class Swear_Activity extends Activity implements OnInitListener, OnClickListener {
private Words newwords;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swear);
}
public void onClick(View view){
try {
newwords.PlayWithRawFiles();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("greshka");
e.printStackTrace();
}
}
}
现在这是我得到错误的类
public class Words{
public Word[] wordsArray;
private String locale = "de";
public Words(String locale) {
if (locale != null ) {
this.locale = locale;
}
}
Context c;
public void PlayWithRawFiles() throws IOException {
String str="";
StringBuffer buf = new StringBuffer();
int i = 0;
InputStream is = c.getResources().openRawResource(R.raw.est);
BufferedReader reader = null;
try{
if (is != null) reader = new BufferedReader(new InputStreamReader(is));
}
catch(Exception e) {
System.out.println ("ss");
e.printStackTrace();
}
if (is!=null) {
while ((str = reader.readLine()) != null) {
Word wd = new Word(1,"str");
this.wordsArray[i] = wd;
i++;
}
}
is.close();
}
}
这是类Word
public class Word {
private int type;
private String data;
public Word(int type, String data){
this.type = type;
this.data=data;
}
public int getType(){
return this.type;
}
public String getData(){
return this.data;
}
}
这是堆栈跟踪
07-10 13:28:58.558:E/AndroidRuntime(647):致命异常:主要
07-10 13:28:58.558: E/AndroidRuntime(647): java.lang.NullPointerException
07-10 13:28:58.558: E/AndroidRuntime(647): 在 de.android.swearapp.Swear_Activity.onClick(Swear_Activity.java:32)
07-10 13:28:58.558: E/AndroidRuntime(647): 在 >android.view.View.performClick(View.java:2408)
07-10 13:28:58.558: E/AndroidRuntime(647): 在 android.view.View$PerformClick.run(View.java:8816)
07-10 13:28:58.558: E/AndroidRuntime(647): 在 android.os.Handler.handleCallback(Handler.java:587)
07-10 13:28:58.558: E/AndroidRuntime(647): 在 android.os.Handler.dispatchMessage(Handler.java:92)
07-10 13:28:58.558: E/AndroidRuntime(647): 在 android.os.Looper.loop(Looper.java:123)
07-10 13:28:58.558: E/AndroidRuntime(647): 在 android.app.ActivityThread.main(ActivityThread.java:4627)
07-10 13:28:58.558: E/AndroidRuntime(647): 在 java.lang.reflect.Method.invokeNative(Native Method)
07-10 13:28:58.558: E/AndroidRuntime(647): 在 java.lang.reflect.Method.invoke(Method.java:521)
07-10 13:28:58.558: E/AndroidRuntime(647): 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-10 13:28:58.558: E/AndroidRuntime(647): 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-10 13:28:58.558: E/AndroidRuntime(647): at dalvik.system.NativeStart.main(Native Method)
我做错了什么?我真的被困在了这一点上。先感谢您!