在 customadapter 中设置 setAdapter() 时的空指针

Null pointer at setting setAdapter() in customadapter

我有两个布局用于单个 activity 我将动态更改布局。这里空指针出现在该行。

  1. 我尝试将视图从布局 1 更改为布局 2
  2. listview.setadapter(列表视图适配器)

    lv2.setAdapter(lva);

我收到的错误是

java.lang.NullPointerException at in.prasilabs.eagleeye.Log$DBSync.onPostExecute(Log.java:170)

public class Log extends Activity {

    ListView lv1;
    ListView lv2;

    @Override
    protected void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.logmenu);

        lv1 = (ListView) findViewById(R.id.listView1);

        final Activity act = getParent();

        String[] menu = new String[] 
        {
            "Last 10 log",
            "All logs (100)",

        };

        ArrayAdapter<String> menuadapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,android.R.id.text1, menu);

        lv1.setAdapter(menuadapter);

        lv1.setOnItemClickListener(new OnItemClickListener() {
            DBSync dbs;
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                case 0:
                    dbs = new DBSync(position, Log.this, act);
                    dbs.execute();
                    break;

                default:    
                    break;
                }
            }
        });
    }

    class DBSync extends AsyncTask<String, Void, Void> {
        int q;
        String[] time = new String[]{"No logs"};
        String[] status = new String[]{"closed"};
        Context cnt;
        Activity act;
        public DBSync(int qu, Log lg, Activity ac) {
            q = qu;
            cnt = lg;
            act = ac;
        }

        @Override
        protected Void doInBackground(String... params) {   
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            //setContentView(R.layout.log);

        time = new String[]{"hii","yes"};
        status = new String[]{"no", "yes"};
        boolean isFirstXml=true;//evaluatingConditionFunction();
        LayoutInflater inflator=getLayoutInflater();
        View view=inflator.inflate(isFirstXml?R.layout.logmenu:R.layout.log, null, false);
        view.startAnimation(AnimationUtils.loadAnimation(cnt, android.R.anim.slide_out_right));
        **setContentView(view);**
        lv2 = (ListView) findViewById(R.id.listView2);

        ListViewAdapter lva = new ListViewAdapter(act, time, status);
        **lv2.setAdapter(lva);**
        lv2.refreshDrawableState();


        }           
    }
}

您正在呼叫 setContentView 两次。

setContentView(R.layout.log);
setContentView(R.layout.logmenu);

通过调用它两次,只会设置第二个(R.layout.logmenu)。我猜 R.id.listView2R.layout.log 中。因此,(ListView) findViewById(R.id.listView2) returns 为空,lv2 为空。当您尝试调用 lv2.setAdapter 时,您尝试在一个空对象上设置适配器 - 您的应用程序崩溃了。