这里是我的json文件:settings.json(在资产文件夹中:]
{
"settings": [
{
"level": "upper"
}
]
}
我在Android Studio中工作。我从json文件在TextView中打印高位单词,但是这不起作用,我的应用程序崩溃了。想法?我在Java文件中的代码:
public class MainActivity extends AppCompatActivity {
ArrayList<String> level = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray userArray = obj.getJSONArray("settings");
for (int i = 0; i < userArray.length(); i++) {
JSONObject userDetail = userArray.getJSONObject(i);
level.add(userDetail.getString("level"));
}
} catch(JSONException e){
e.printStackTrace();
}
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(level.get(0));
setContentView(R.layout.activity_main);
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("settings.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
谢谢。Android,json,源代码...
我希望这对您有用,
像这样编写onCreate()
方法,
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray userArray = obj.getJSONArray("settings");
for (int i = 0; i < userArray.length(); i++) {
JSONObject userDetail = userArray.getJSONObject(i);
level.add(userDetail.getString("level"));
}
} catch(JSONException e){
e.printStackTrace();
}
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(level.get(0));
}
首先设置setContentView()
方法,然后初始化您的文本视图。在您的代码中,在初始化布局之前,您将访问文本视图。
以及为什么else在if函数中起作用?该级别的记录更高。如果不正确,为什么呢?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
// get JSONObject from JSON file
JSONObject obj = new JSONObject(loadJSONFromAsset());
// fetch JSONArray named users
JSONArray userArray = obj.getJSONArray("settings");
// implement for loop for getting users list data
for (int i = 0; i < userArray.length(); i++) {
// create a JSONObject for fetching single user data
JSONObject userDetail = userArray.getJSONObject(i);
// fetch email and name and store it in arraylist
level.add(userDetail.getString("level"));
}
} catch(JSONException e){
e.printStackTrace();
}
TextView textView = (TextView) findViewById(R.id.textView);
if (level.get(0) == "upper") {
textView.setText(level.get(0));
} else {
}