gpt4 book ai didi

java - AssetManager空指针异常

转载 作者:行者123 更新时间:2023-12-01 18:36:02 25 4
gpt4 key购买 nike

我在代码中标有/Here/的行上遇到空指针异常。我花了大约 2 个小时查找 AssetManager 以及如何使用它等,但仍然无法弄清楚为什么它为空。我已经从上下文和资源中单独调用了 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;
}

}

最佳答案

您缺少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 的资源。因此,您应该在初始化 View 之前将布局的内容设置为 Activity

你也可以使用

res = getResources();

关于java - AssetManager空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21971261/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com