天啊,我试图通过这样做来启动fragmentActivity:
Intent intent = new Intent(this, CircleListActivity.class);
intent.putExtra("cats", cats);
startActivity(intent);
finish();
来自另一个片段活动,当我这样做时,我在LogCat中得到它:
09-02 22:54:03.093: E/AndroidRuntime(2943): java.lang.NullPointerException
09-02 22:54:03.093: E/AndroidRuntime(2943): at com.example.masterdetailsexample.adapter.SampleAdapter.<init>(SampleAdapter.java:30)
09-02 22:54:03.093: E/AndroidRuntime(2943): at com.example.masterdetailsexample.CircleListFragment$2.onPostExecute(CircleListFragment.java:84)
09-02 22:54:03.093: E/AndroidRuntime(2943): at com.example.masterdetailsexample.CircleListFragment$2.onPostExecute(CircleListFragment.java:1)
09-02 22:54:03.093: E/AndroidRuntime(2943): at android.os.AsyncTask.finish(AsyncTask.java:631)
09-02 22:54:03.093: E/AndroidRuntime(2943): at android.os.AsyncTask.access$600(AsyncTask.java:177)
09-02 22:54:03.093: E/AndroidRuntime(2943): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
09-02 22:54:03.093: E/AndroidRuntime(2943): at android.os.Handler.dispatchMessage(Handler.java:99)
09-02 22:54:03.093: E/AndroidRuntime(2943): at android.os.Looper.loop(Looper.java:176)
09-02 22:54:03.093: E/AndroidRuntime(2943): at android.app.ActivityThread.main(ActivityThread.java:5365)
09-02 22:54:03.093: E/AndroidRuntime(2943): at java.lang.reflect.Method.invokeNative(Native Method)
09-02 22:54:03.093: E/AndroidRuntime(2943): at java.lang.reflect.Method.invoke(Method.java:511)
09-02 22:54:03.093: E/AndroidRuntime(2943): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
09-02 22:54:03.093: E/AndroidRuntime(2943): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
09-02 22:54:03.093: E/AndroidRuntime(2943): at dalvik.system.NativeStart.main(Native Method)
当我测试时,我发现错误是由CircleListFragment.java:84
或adapter = new SampleAdapter(getActivity(), devices);
引起的 - 我已经过测试,我看到getActivity()
返回null。有人能告诉我为什么会这样吗?
这是我的代码:
public class CircleListFragment extends ListFragment {
private static final String STATE_ACTIVATED_POSITION = "activated_position";
private Callbacks mCallbacks = sDummyCallbacks;
private int mActivatedPosition = ListView.INVALID_POSITION;
private ArrayList<Device> devices;
private SharedPreferences prefs;
boolean paused = false;
int index, top;
private SampleAdapter adapter;
public interface Callbacks {
public void onItemSelected(int id, ArrayList<Device> devices);
}
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
public void onItemSelected(int id, ArrayList<Device> devices) {
}
};
public CircleListFragment() {
}
@Override
public void onPause() {
paused = true;
index = getListView().getFirstVisiblePosition();
View v = getListView().getChildAt(0);
top = (v == null) ? 0 : v.getTop();
super.onPause();
}
@Override
public void onResume() {
if (adapter != null && devices != null) {
for (int i = 0; i < devices.size(); i++) {
devices.get(i).setChecked(false);
}
adapter.notifyDataSetChanged();
}
super.onResume();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
devices = new ArrayList<Device>();
prefs = getActivity().getSharedPreferences(
getActivity().getPackageName(), Context.MODE_PRIVATE);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
getJSONFromUrl(Constants.DEVICES_URL);
return null;
}
protected void onPostExecute(Void result) {
Log.v("--", getActivity()+" | "+devices);
adapter = new SampleAdapter(getActivity(), devices);
setListAdapter(adapter);
getListView().setDivider(
getActivity().getResources().getDrawable(
R.drawable.transperent_color));
getListView().setDividerHeight(20);
if (Constants.isTablet(getActivity()))
getListView().setPadding(20, 20, 20, 20);
else
getListView().setPadding(10, 10, 10, 10);
};
}.execute();
}
public void getJSONFromUrl(String url) {
try {
JSONParser jParser = new JSONParser();
// get JSON data from URL
JSONArray jArray = jParser.getJSONArrayFromUrl(url);
// Log.v("--", jArray.toString());
for (int i = 0; i < jArray.length(); i++) {
JSONObject j = jArray.getJSONObject(i);
JSONArray arr = j.getJSONArray("devices");
ArrayList<SubDevice> subDevices = new ArrayList<SubDevice>();
for (int k = 0; k < arr.length(); k++) {
JSONObject o = arr.getJSONObject(k);
subDevices.add(new SubDevice(o.getInt("id"), o
.getString("text"), o.getString("title"), false));
}
devices.add(new Device(j.getString("title"), j.getInt("id"),
subDevices, false));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (savedInstanceState != null
&& savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
setActivatedPosition(savedInstanceState
.getInt(STATE_ACTIVATED_POSITION));
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setDivider(
getResources().getDrawable(R.drawable.transperent_color));
getListView().setDividerHeight(20);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof Callbacks)) {
throw new IllegalStateException(
"Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = sDummyCallbacks;
}
@Override
public void onListItemClick(ListView listView, View view, int position,
long id) {
super.onListItemClick(listView, view, position, id);
mCallbacks.onItemSelected(position, devices);
Log.v("--",
"IS CHECKED" + prefs.getString(devices.get(position) + "", ""));
for (int i = 0; i < devices.size(); i++) {
devices.get(i).setChecked(false);
if (prefs.getString(devices.get(i) + "", "").length() > 0) {
listView.setItemChecked(i, true);
Log.v("--", "checking " + i);
}
}
devices.get(position).setChecked(true);
listView.setItemChecked(position, true);
adapter.notifyDataSetChanged();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mActivatedPosition != ListView.INVALID_POSITION) {
outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
}
}
public void setActivateOnItemClick(boolean activateOnItemClick) {
getListView().setChoiceMode(
activateOnItemClick ? ListView.CHOICE_MODE_MULTIPLE
: ListView.CHOICE_MODE_NONE);
}
private void setActivatedPosition(int position) {
if (position == ListView.INVALID_POSITION) {
getListView().setItemChecked(mActivatedPosition, false);
} else {
getListView().setItemChecked(position, true);
}
mActivatedPosition = position;
}
}
CircleListActivity
课程:
public class CircleListActivity extends FragmentActivity implements
CircleListFragment.Callbacks {
private Button proceed;
private boolean mTwoPane;
// private ArrayList<Device> devices;
private ArrayList<Categories> categories;
SharedPreferences prefs;
private ArrayList<Device> devices;
@SuppressWarnings("unchecked")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_circle_list);
if (Constants.isTablet(this)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
prefs = getSharedPreferences(getPackageName(), MODE_PRIVATE);
initActionBar();
if (!prefs.getBoolean(Constants.DEVICES_INTRO, false)
&& Constants.isTablet(this)) {
Intent in = new Intent(this, DevicesIntro.class);
startActivity(in);
prefs.edit().putBoolean(Constants.DEVICES_INTRO, true).commit();
}
devices = new ArrayList<Device>();
devices = (ArrayList<Device>) getIntent().getSerializableExtra(
Constants.DEVICES_EXTRA);
categories = (ArrayList<Categories>) getIntent().getSerializableExtra(
"cats");
proceed = (Button) findViewById(R.id.list_proceed);
proceed.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(CircleListActivity.this,
TestSearch.class);
intent.putExtra("fromDevs", true);
prefs.edit().putBoolean("fromDevs", true).commit();
intent.putExtra("cats", categories);
// intent.putExtra(Constants.DEVICES_DETAIL_EXTRA, devices);
if (prefs.getBoolean("set", false)) {
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
prefs.edit().putBoolean("set", true).commit();
}
prefs.edit().putBoolean("set", true).commit();
startActivity(intent);
finish();
}
});
if (findViewById(R.id.circle_detail_container) != null) {
mTwoPane = true;
((CircleListFragment) getSupportFragmentManager().findFragmentById(
R.id.circle_list)).setActivateOnItemClick(true);
Log.v("--", "circle activity tw");
}
// TODO: If exposing deep links into your app, handle intents here.
}
@Override
public void onItemSelected(int position, ArrayList<Device> devices) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putSerializable(Constants.DEVICES_DETAIL_EXTRA, this.devices
.get(position).getDevices());
arguments.putInt(Constants.PARENT, this.devices.get(position).getId());
CircleDetailFragment fragment = new CircleDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.circle_detail_container, fragment).commit();
} else {
Intent detailIntent = new Intent(this, CircleDetailActivity.class);
detailIntent.putExtra(Constants.DEVICES_DETAIL_EXTRA,
this.devices.get(position).getDevices());
detailIntent.putExtra(Constants.PARENT, this.devices.get(position)
.getId());
Log.v("--", devices.get(position).getId() + " }}");
startActivity(detailIntent);
}
}
private void initActionBar() {
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#e91a34")));
getActionBar().setCustomView(R.layout.actionbar_custom_view_home);
// actionBar.setcu
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setDisplayShowCustomEnabled(true);
getActionBar().setDisplayUseLogoEnabled(false);
getActionBar().setDisplayShowHomeEnabled(false);
// getActionBar().setHomeButtonEnabled(true);
// getActionBar().setIcon(R.drawable.menu);
}
}
答案 0 :(得分:0)
如果getActivity()
方法中onPostExecute()
返回null,则表示片段未附加。您需要执行空检查以防止崩溃,然后查看碎片分离的原因。
答案 1 :(得分:0)
getActivity实际上不是null
,因为您可以在getActivity().getSharedPreferences
方法中直接使用onCreate
,这意味着它不为空。