在我的应用程序中,我正在尝试创建一个片段活动,其左侧是列表视图,右侧是详细视图。
当运行te intent时,我得到一个例外:
10-29 17:25:56.025: E/AndroidRuntime(19344): FATAL EXCEPTION: main
10-29 17:25:56.025: E/AndroidRuntime(19344): java.lang.RuntimeException: Unable to start activity ComponentInfo{be.pxl.minecraftguide/be.pxl.minecraftguide.Commands}: android.view.InflateException: Binary XML file line #11: Error inflating class fragment
10-29 17:25:56.025: E/AndroidRuntime(19344): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
10-29 17:25:56.025: E/AndroidRuntime(19344): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
10-29 17:25:56.025: E/AndroidRuntime(19344): at android.app.ActivityThread.access$600(ActivityThread.java:140)
10-29 17:25:56.025: E/AndroidRuntime(19344): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
10-29 17:25:56.025: E/AndroidRuntime(19344): at android.os.Handler.dispatchMessage(Handler.java:99)
10-29 17:25:56.025: E/AndroidRuntime(19344): at android.os.Looper.loop(Looper.java:137)
10-29 17:25:56.025: E/AndroidRuntime(19344): at android.app.ActivityThread.main(ActivityThread.java:4898)
10-29 17:25:56.025: E/AndroidRuntime(19344): at java.lang.reflect.Method.invokeNative(Native Method)
10-29 17:25:56.025: E/AndroidRuntime(19344): at java.lang.reflect.Method.invoke(Method.java:511)
10-29 17:25:56.025: E/AndroidRuntime(19344): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1008)
10-29 17:25:56.025: E/AndroidRuntime(19344): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:775)
10-29 17:25:56.025: E/AndroidRuntime(19344): at dalvik.system.NativeStart.main(Native Method)
10-29 17:25:56.025: E/AndroidRuntime(19344): Caused by: android.view.InflateException: Binary XML file line #11: Error inflating class fragment
10-29 17:25:56.025: E/AndroidRuntime(19344): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
10-29 17:25:56.025: E/AndroidRuntime(19344): at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
10-29 17:25:56.025: E/AndroidRuntime(19344): at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
10-29 17:25:56.025: E/AndroidRuntime(19344): at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
10-29 17:25:56.025: E/AndroidRuntime(19344): at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
10-29 17:25:56.025: E/AndroidRuntime(19344): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:308)
10-29 17:25:56.025: E/AndroidRuntime(19344): at android.app.Activity.setContentView(Activity.java:1924)
10-29 17:25:56.025: E/AndroidRuntime(19344): at be.pxl.minecraftguide.Commands.onCreate(Commands.java:12)
10-29 17:25:56.025: E/AndroidRuntime(19344): at android.app.Activity.performCreate(Activity.java:5206)
10-29 17:25:56.025: E/AndroidRuntime(19344): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
10-29 17:25:56.025: E/AndroidRuntime(19344): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
10-29 17:25:56.025: E/AndroidRuntime(19344): ... 11 more
10-29 17:25:56.025: E/AndroidRuntime(19344): Caused by: java.lang.NullPointerException
10-29 17:25:56.025: E/AndroidRuntime(19344): at java.util.Arrays$ArrayList.<init>(Arrays.java:38)
10-29 17:25:56.025: E/AndroidRuntime(19344): at java.util.Arrays.asList(Arrays.java:154)
10-29 17:25:56.025: E/AndroidRuntime(19344): at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:128)
10-29 17:25:56.025: E/AndroidRuntime(19344): at be.pxl.minecraftguide.CommandsList.onCreateView(CommandsList.java:26)
10-29 17:25:56.025: E/AndroidRuntime(19344): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1478)
10-29 17:25:56.025: E/AndroidRuntime(19344): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:900)
10-29 17:25:56.025: E/AndroidRuntime(19344): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1082)
10-29 17:25:56.025: E/AndroidRuntime(19344): at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1184)
10-29 17:25:56.025: E/AndroidRuntime(19344): at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:285)
10-29 17:25:56.025: E/AndroidRuntime(19344): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:676)
10-29 17:25:56.025: E/AndroidRuntime(19344): ... 21 more
这是我的xml文件,其中抛出异常:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
android:id="@+id/commandsLayout"
tools:context=".Commands" >
<fragment //Exception here
android:name="be.pxl.minecraftguide.CommandsList"
android:id="@+id/commandslist"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"
tools:layout="@layout/commandslist" />
<fragment android:name="be.pxl.minecraftguide.CommandDetails"
android:id="@+id/commanddetails"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent"
tools:layout="@layout/commanddetails" />
</LinearLayout>
这是我的Commands类:
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class Commands extends FragmentActivity {
@Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
setContentView(R.layout.commands);
}
}
这是第一个片段xml:
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/minecraft_portrait"
android:transcriptMode="alwaysScroll" >
</ListView>
这是第二个片段xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/txtFragCommandID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/txtFragCommandDesc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/txtFragCommandID"
android:layout_below="@+id/txtFragCommandID"
android:layout_marginTop="20dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
这是第一个片段类:
import java.util.List;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import be.pxl.minecraftguide.model.Command;
//FragmentActivity van support libraries
public class CommandsList extends ListFragment {
private List<Command> commands;
private String[] listValues;
private String[][] detailValues;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Bron: http://wptrafficanalyzer.in/blog/a-listfragment-application-in-android/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(inflater.getContext(), R.layout.commandslist, listValues);
setListAdapter(adapter);
setListShown(true);
getListView().setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View fragmentView, int rowIndex, long arg3) {
View detailView = fragmentView.findViewById(R.layout.commanddetails);
TextView title = (TextView)detailView.findViewById(R.id.txtFragCommandID);
TextView description = (TextView)detailView.findViewById(R.id.txtFragCommandDesc);
title.setText(detailValues[rowIndex][0]);
description.setText(detailValues[rowIndex][0]);
}
});
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onStart() {
super.onStart();
}
public void createCommands() {
commands.add(new Command(1, "Chat commands", "melp, ? [page, commandname]",
"Shows a list of available commands per page or further information to the commandname." +
"\r\nNote: the multiplayer-only commands are not listed in single-player games, even when open to LAN players."));
commands.add(new Command(2, "Chat commands", "me <actiontext>",
"Similar to the /emote or /action, and the same as the /me commands in IRC clients, the /me command sends a narrative message to the other players in the form of * Yourname actiontext (e.g., * Notch sneezes. or * Notch exploded. )."));
commands.add(new Command(3, "Chat commands", "msg, tell, w <playername>",
"Used to send a private message to a player on the server. Very useful on servers if you need to ask/tell something from/to another player without other players seeing."));
commands.add(new Command(4, "Player commands", "achievement give <achievement> [playername]",
"Gives a player an achievement, and all prerequisite achievements."));
commands.add(new Command(5, "Player commands", "effect <playername> <effect> [seconds] [amplifier]",
"Gives the targeted player the specified effect for the specified time (default is 30 seconds)." +
"\r\nEffects have a limit of 1,000,000 seconds, and the amplifier field has a limit of 255."));
commands.add(new Command(6, "Player commands", "effect <playername> clear",
"Clears all effects on playername."));
commands.add(new Command(7, "Player commands", "enchant <playername> <enchantment ID> [enchantment level]",
"Enchants the item that the player is currently holding, according to enchantment ID."));
commands.add(new Command(8, "Player commands", "give <playername> <item> [amount] [metadata] [dataTag]",
"Spawns amount (defaults to 1) of the item defined by item with the specified metadata (defaults to 0) at playername's location."));
commands.add(new Command(9, "Player commands", "kill <playername>",
"Inflicts 1000 (Heart.svg × 500) damage to the playername, killing them. (Even an extreme Resistance /effect doesn't protect)."));
commands.add(new Command(10, "Server commands", "debug true|false",
"Starts a new debug profiling session or stops the session currently running." +
"\r\nIt notifies about potential performance bottlenecks in the console when active and creates a profiler results file in the folder debug when stopped."));
commands.add(new Command(11, "Server commands", "defaultgamemode survival | creative | adventure",
"Sets the default game mode that is shown on the world selection menu. New players that join the world will be put into the default game mode."));
commands.add(new Command(12, "Server commands", "difficulty peaceful | easy | normal | hard",
"Changes the difficulty. The difficulties can be abbreviated to p/e/n/h or 0/1/2/3 respectively."));
commands.add(new Command(13, "Server commands", "gamerule <rulename> [true | false]",
"Activates or deactivates the rulename. If true/false is not given, displays the current status of rulename. Available rules are:" +
"\r\n- commandBlockOutput - Whether command blocks should notify admins when they perform commands." +
"\r\ndoFireTick - Whether fire should spread." +
"\r\ndoMobLoot - Whether mobs should drop items." +
"\r\ndoMobSpawning - Whether mobs should naturally spawn." +
"\r\ndoTileDrops - Whether blocks should have drops." +
"\r\nkeepInventory - Whether the player should keep items in their inventory if they die." +
"\r\nmobGriefing - Whether creepers, endermen, ghasts, and withers should be able to change blocks, or zombies, skeletons, and zombie pigmen can pick up items." +
"\r\nnaturalRegeneration - Whether the player can regenerate health naturally if their hunger is at a regenerable state." +
"\r\ndoDaylightCycle - Whether the day/night cycle is in effect or not."));
commands.add(new Command(14, "Environment commands", "time set <number | day | night>",
"Sets the world time. Number is an integer between 0 and 24000, inclusive, where 0 is dawn, 6000 midday, 12000 dusk and 18000 midnight."));
commands.add(new Command(15, "Environment commands", "time add <number>",
"Increments the world time. Number is an integer between 0 and 24000."));
commands.add(new Command(16, "Environment Commands", "toggledownfall",
"Toggles rain and snow."));
commands.add(new Command(17, "Environment commands", "weather (clear | rain | thunder) [seconds]",
"Changes the weather for the specified duration."));
listValues = new String[commands.size()];
detailValues = new String[commands.size()][2];
for (int counter = 0; counter < commands.size(); counter++) {
Command command = commands.get(counter);
listValues[counter] = command.getCommandCategory();
detailValues[counter][0] = command.getCommandTitle();
detailValues[counter][1] = command.getCommandDescription();
}
}
}
这是第二个片段类:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class CommandDetails extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.commanddetails, container, false);
}
}
我已经看到更多这样的问题,我确认我正在扩展正确的类(FragmentActivity) 这是我的项目浏览器:
答案 0 :(得分:1)
在CommandsList类的onCreateView中使用它时,不会初始化变量listValues,因此也就是NullPointer。问题出在这一行:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(inflater.getContext(), R.layout.commandslist, listValues);
此时String []尚不存在......您需要首先调用createCommands()并在向该方法添加值之前初始化该方法中的String []变量,如下所示:
listValues = new String[commands.size()];