我的代码中标有/ Here /的行上出现空指针异常。我花了大约2个小时查找AssetManager以及如何使用它等,但仍然无法弄清楚为什么它是null。我已经从上下文和资源中调用了getAssets(),但我仍然是null。有人可以帮我从这里出去吗? 感谢。
package com.hamc17.CatFacts;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class FactsActivity extends Activity{
Context context;
Resources res;
@Override
public void onCreate(Bundle savedInstanceBundle){
super.onCreate(savedInstanceBundle);
context = getApplicationContext();
res = context.getResources();
Button getFactButton = (Button) findViewById(R.id.getFactButton);
getFactButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast toastMessageOnClick = new Toast(FactsActivity.this);
toastMessageOnClick.setText(getFact());
if((toastMessageOnClick.toString()).length()>50)
{
toastMessageOnClick.setDuration(10);
}
else
{
toastMessageOnClick.setDuration(Toast.LENGTH_LONG);
}
toastMessageOnClick.show();
}
});
}
String[] factArray = getFactsFromTextFile().split(";");
private String getFactsFromTextFile(){
/*Here*/ AssetManager assMan = context.getAssets();
try{
BufferedReader buff = new BufferedReader(new InputStreamReader(assMan.open("facts.txt")));
String line;
StringBuilder build = new StringBuilder();
while((line = buff.readLine()) != null)
{
build.append(line).append(System.getProperty("line.seperator"));
}
return build.toString();
}
catch (IOException e)
{
Toast toastMessage = new Toast(getApplicationContext());
toastMessage.setText(e.toString() + "\n Whoops, there was an error! ");
toastMessage.show();
return "";
}
finally
{
try{
assMan.close();
}
catch (Exception e)
{
//Whatever Trevor
}
}
}
private String getFact(){
String randomFactString = "";
int factCount = factArray.length;
Random rng = new Random();
int randomNum = rng.nextInt()*factCount;
randomFactString = factArray[randomNum];
return randomFactString;
}
}
答案 0 :(得分:4)
您缺少setContentView(R.layout.mylayout);
@Override
public void onCreate(Bundle savedInstanceBundle){
super.onCreate(savedInstanceBundle);
setContentView(R.layout.mylayout);
Button getFactButton = (Button) findViewById(R.id.getFactButton);
findViewById
查找当前膨胀布局中具有id的资源。因此,您应该在初始化视图之前将布局的内容设置为活动
您也可以使用
res = getResources();
答案 1 :(得分:0)
而不是创建一个局部变量来获取Activity的Context只需使用getBaseContext();每次要获取Context的引用。
所以这样的话:
AssetManager assMan = getBaseContext().getAssets();