Java 活动启动且未选中复选框时的NullPointerException

Java 活动启动且未选中复选框时的NullPointerException,java,android,checkbox,nullpointerexception,Java,Android,Checkbox,Nullpointerexception,我正在尝试实现以下代码: public CheckBox checkboxer() { final CheckBox box = (CheckBox) findViewById(R.id.cbBox); Log.d(LOG_TAG, "make ListView clickable"); lvMain.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void o

我正在尝试实现以下代码:

 public CheckBox checkboxer() {
    final CheckBox box = (CheckBox) findViewById(R.id.cbBox);
    Log.d(LOG_TAG, "make ListView clickable");
    lvMain.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view,
               int position, long id) {              
            box.setChecked(true);
        }
    });       
    return box;
}

   private void savebox(final boolean isChecked) {
    SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean("check", isChecked);
    editor.commit();
    Log.d(LOG_TAG, "checkbox is saved");
}

private boolean load() { 
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
return sharedPreferences.getBoolean("check", false);}
日志表明它已保存。 当我放面包的时候

onResume(){
     checkboxer().setChecked(load());
} 
出现
NullPointerException

我认为这是因为在活动开始运行时没有检查和保存任何内容。我说得对吗?我怎样才能四处走动

多谢各位。 我们开始

Logcat:

08:18:37.830    1773    example.CustomAdapter   ERROR   AndroidRuntime  FATAL EXCEPTION: main
08:18:37.830    1773    example.CustomAdapter   ERROR   AndroidRuntime  java.lang.RuntimeException: Unable to resume activity {example.CustomAdapter/example.CustomAdapter.ChildActivity}: java.lang.NullPointerException
08:18:37.830    1773    example.CustomAdapter   ERROR   AndroidRuntime      at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2120)
08:18:37.830    1773    example.CustomAdapter   ERROR   AndroidRuntime      at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2135)
08:18:37.830    1773    example.CustomAdapter   ERROR   AndroidRuntime      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1668)
08:18:37.830    1773    example.CustomAdapter   ERROR   AndroidRuntime      at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08:18:37.830    1773    example.CustomAdapter   ERROR   AndroidRuntime      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
08:18:37.830    1773    example.CustomAdapter   ERROR   AndroidRuntime      at android.os.Handler.dispatchMessage(Handler.java:99)
08:18:37.830    1773    example.CustomAdapter   ERROR   AndroidRuntime      at android.os.Looper.loop(Looper.java:123)
08:18:37.830    1773    example.CustomAdapter   ERROR   AndroidRuntime      at android.app.ActivityThread.main(ActivityThread.java:3683)
08:18:37.830    1773    example.CustomAdapter   ERROR   AndroidRuntime      at java.lang.reflect.Method.invokeNative(Native Method)
08:18:37.830    1773    example.CustomAdapter   ERROR   AndroidRuntime      at java.lang.reflect.Method.invoke(Method.java:507)
08:18:37.830    1773    example.CustomAdapter   ERROR   AndroidRuntime      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08:18:37.830    1773    example.CustomAdapter   ERROR   AndroidRuntime      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08:18:37.830    1773    example.CustomAdapter   ERROR   AndroidRuntime      at dalvik.system.NativeStart.main(Native Method)
08:18:37.830    1773    example.CustomAdapter   ERROR   AndroidRuntime  Caused by: java.lang.NullPointerException
08:18:37.830    1773    example.CustomAdapter   ERROR   AndroidRuntime      at example.CustomAdapter.ChildActivity.onResume(ChildActivity.java:256)
08:18:37.830    1773    example.CustomAdapter   ERROR   AndroidRuntime      at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1150)
08:18:37.830    1773    example.CustomAdapter   ERROR   AndroidRuntime      at android.app.Activity.performResume(Activity.java:3832)
08:18:37.830    1773    example.CustomAdapter   ERROR   AndroidRuntime      at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2110)
08:18:37.830    1773    example.CustomAdapter   ERROR   AndroidRuntime      ... 12 more
对不起,我忘了。这可能是因为在我的适配器类中,我使用了View方法吗

 CheckBox cbBuy = (CheckBox) view.findViewById(R.id.cbBox);

    cbBuy.setOnCheckedChangeListener(myCheckChangList);

    cbBuy.setTag(position);

    cbBuy.setChecked(p.box);
    return view;`
而且

  OnCheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

      getProduct((Integer) buttonView.getTag()).box = isChecked;
    }
  };
很抱歉,我是一个新手,可能不明白适配器中的复选框声明和活动中的复选框声明之间可能存在什么样的条件差。如果是因为这种矛盾造成的,请解释

以下是
onResume
onPause

@Override
protected void onResume() {
    super.onResume();
    Log.d(LOG_TAG, "ChildActivity: onResume()");
    DataSourceChild.openToWriteChild();
    checkboxer();

}

@Override
protected void onPause() {
    super.onPause();
    Log.d(LOG_TAG, "ChildActivity: onPause()");

    DataSourceChild.closeChild();

    savebox(checkboxer().isChecked());

}
整个代码太大了。让我为您提供onCreate first`public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.child)

加载程序包含checkboxer,如下所示` public void loader(int val){

现在在custom BoxAdapter中,我有以下内容

`  @Override
  public View getView(int position, View convertView, ViewGroup parent) {

    View view = convertView;
    if (view == null) {
      view = lInflater.inflate(R.layout.childitem, parent, false);
    }

    Product p = getProduct(position);
    ((TextView) view.findViewById(R.id.tvDescr)).setText(p.name);
    ((TextView) view.findViewById(R.id.tvPrice)).setText(p.price + "");
    ((ImageView) view.findViewById(R.id.ivImage)).setImageResource(p.image);

    CheckBox cbBuy = (CheckBox) view.findViewById(R.id.cbBox);

    cbBuy.setOnCheckedChangeListener(myCheckChangList);

    cbBuy.setTag(position);

    cbBuy.setChecked(p.box);
    return view;
  }`
很抱歉给您带来不便。但我想知道发生了什么事

您的示例只需单击即可工作。非常感谢。我已尝试用以下方式更新我的适配器视图方法

`  public View getView(final int position, View convertView, ViewGroup parent) {

    View view = convertView;
    if (view == null) {
      view = lInflater.inflate(R.layout.childitem, parent, false);
    }

    Product p = getProduct(position);

    ((TextView) view.findViewById(R.id.tvDescr)).setText(p.name);
    ((TextView) view.findViewById(R.id.tvPrice)).setText(p.price + "");
    ((ImageView) view.findViewById(R.id.ivImage)).setImageResource(p.image);

    CheckBox cbBuy = (CheckBox) view.findViewById(R.id.cbBox);

    cbBuy.setTag(position);

    cbBuy.setChecked(mIsChecked[position]);

    cbBuy.setOnCheckedChangeListener (new OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

      mIsChecked[position] = isChecked;
      getProduct((Integer) buttonView.getTag()).box = isChecked;
    }
  });

    return view;
  }
  `
并在onCreate中进行了更改

 `    public void loader(int val) {

        item_values = child_datasource.readItem(val);

        lvMain = (ListView) findViewById(R.id.lvMain);

        boolean[] isChecked = new boolean[item_values.size()];
        for (int i = 0; i < item_values.size(); i++) {
            isChecked[i] = false;
        }

        boxAdapter = new BoxAdapter(this, item_values, isChecked);

        lvMain.setAdapter(boxAdapter);

        registerForContextMenu(lvMain);

        boxAdapter.notifyDataSetChanged();
    }`
`public void loader(int val){
item_values=child_datasource.readItem(val);
lvMain=(ListView)findViewById(R.id.lvMain);
boolean[]isChecked=new boolean[item_values.size()];
对于(int i=0;i

当我离开ChildActivity时,它仍然无法保存支票。我很遗憾,我无法应用您的示例,而且我对Android的了解还不足以像您这样轻松地使用View进行操作。如果您能进一步解释我应该如何更改View以获得结果,我将不胜感激,如果没有,那么很抱歉占用您的时间。

活动开始时onResume()将被调用。因此,在onResume()中,只需在调用setChecked函数之前进行检查,这样它就应该仅在checkboxer()不为null时执行,以确保它仅在活动恢复时执行

onResume(){
     if(checkboxer() != null)
          checkboxer().setChecked(load());
}
带有复选框和列表视图的示例活动

package com.example.checkdoubltap;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

public class CheckLayoutParams extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.lin);
    ListView list = (ListView) findViewById(R.id.listview);
    boolean[] isChecked = new boolean[countryStrings.length];
    for(int i=0;i<countryStrings.length; i++){
        isChecked[i] = false;
    }
    CheckBoxAdapter adapter = new CheckBoxAdapter(CheckLayoutParams.this, countryStrings, isChecked);

    list.setAdapter(adapter);

}

private String[] countryStrings = { "Afghanistan", "Albania",
        "Algeria", "Andorra", "Angola", "Anguilla", "Antigua and Barbuda",
        "Argentina", "Armenia", "Aruba", "Ascension Island", "Australia",
        "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh",
        "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda",
        "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana",
        };
}
具有listview的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<ListView 
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:id="@+id/listview"
>
</ListView>
</LinearLayout>

当活动启动时,onResume()将被调用。因此在onResume()中,只需在调用setChecked函数之前进行检查,这样它就应该仅在checkboxer()不为null时执行,以确保它仅在活动恢复时执行

onResume(){
     if(checkboxer() != null)
          checkboxer().setChecked(load());
}
带有复选框和列表视图的示例活动

package com.example.checkdoubltap;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

public class CheckLayoutParams extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.lin);
    ListView list = (ListView) findViewById(R.id.listview);
    boolean[] isChecked = new boolean[countryStrings.length];
    for(int i=0;i<countryStrings.length; i++){
        isChecked[i] = false;
    }
    CheckBoxAdapter adapter = new CheckBoxAdapter(CheckLayoutParams.this, countryStrings, isChecked);

    list.setAdapter(adapter);

}

private String[] countryStrings = { "Afghanistan", "Albania",
        "Algeria", "Andorra", "Angola", "Anguilla", "Antigua and Barbuda",
        "Argentina", "Armenia", "Aruba", "Ascension Island", "Australia",
        "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh",
        "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda",
        "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana",
        };
}
具有listview的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<ListView 
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:id="@+id/listview"
>
</ListView>
</LinearLayout>



调试器对空指针说了些什么?只是猜测一下……您可以将复选框声明为类成员,然后在onCreate()中将其初始化为box=(Checkbox)findViewById(R.id.cbBox);我将复选框移到了方法中,目的是避免NullPointer向我们显示此行的代码:at example.CustomAdapter.ChildActivity.onResume(ChildActivity.java:256)别忘了调用super.onResume();+可能是您没有设置contentview?调试器对空指针说了什么?只是猜测一下……您可以将复选框声明为类成员,然后在onCreate()中将其初始化为box=(Checkbox)findViewById(R.id.cbBox);我将复选框移到了方法,目的是避免NullPointer为我们提供此行的代码:at example.CustomAdapter.ChildActivity.onResume(ChildActivity.java:256)别忘了调用super.onResume()+可能是您没有设置contentview吗?我也是这么想的。它会运行,但在检查复选框时不会保存。您在onPause中有保存框功能,对吗?功能正常吗?在onResume中,它应该正确设置Check。由于Log.d(Log_标记,“复选框已保存”);在safebox方法的末尾,当我运行不带onResume的代码时{checkboxer().setChecked(load())}它显示了我的日志。你能看一下我编辑的问题吗?可能是我的适配器引起的问题。我也是这么想的。它运行,但在检查复选框时不保存。你在onPause中有存储框功能,对吗?功能正常吗?在onResume中,它应该正确设置复选框。我只能猜测它是否正常工作由于Log.d(Log_标记,“checkbox已保存”);在safebox方法的末尾,当我在没有onResume的情况下运行代码{checkboxer().setChecked(load())}时,它会显示日志。请查看我编辑的问题。问题可能是由我的适配器引起的。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<ListView 
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:id="@+id/listview"
>
</ListView>
</LinearLayout>