setAdapter()上的NullPointerException

时间:2015-07-06 10:44:40

标签: android android-listview

我有一个包含2个LinearLayouts的登录页面。 1st包含登录小部件(2个EditTexts和一个Button)。 2nd包含一个显示公共项目的ListView。但是实现ListView我得到以下错误:

Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference

这是我的activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:gravity="center">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dip"
    android:orientation="vertical"
    android:layout_weight="1">

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/email"
    android:layout_marginTop="35dip"
    android:text="testapi@canvasflip.com"
    android:textColor="#000000"/>

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/email"
    android:id="@+id/password"
    android:hint="password"
    android:text="canvas123"
    android:textColor="#000000"
    android:layout_marginTop="35dip"
    android:inputType="textPassword"/>
<Button
    android:layout_width="match_parent"
    android:layout_below="@+id/password"
    android:layout_height="wrap_content"
    android:layout_marginTop="35dip"
    android:id="@+id/submit"
    android:text="submit"/>

</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_weight="1">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/list1">

    </ListView>
</LinearLayout>

和MainActivity.java:

public class MainActivity extends DrawerActivity {

EditText e;
EditText p;
Button s;
String getEmail, getPassword;

ListView mDrawerList, mPublicProjectsList;
protected DrawerLayout mDrawerLayout;

ArrayAdapter<String> mPublicProjectsAdapter;

public static HttpClient httpClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
    mDrawerList = (ListView)findViewById(android.R.id.list);
    mPublicProjectsList =(ListView)findViewById(R.id.list1);
    String[] projectItems = {"Project1", "Project2", "Project3", "Project4"};
    mPublicProjectsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, projectItems);
    mPublicProjectsList.setAdapter(mPublicProjectsAdapter);


    //setContentView(R.layout.activity_main);
    LayoutInflater layoutInflater = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View contentView = layoutInflater.inflate(R.layout.activity_main, null,false);
    mDrawerLayout.addView(contentView, 0);

    e = (EditText)findViewById(R.id.email);
    p = (EditText)findViewById(R.id.password);
    s = (Button)findViewById(R.id.submit);
    s.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getEmail = e.getText().toString();
            getPassword = p.getText().toString();
            new HttpHandler().execute();
        }
    });
}



    /*mPublicProjectsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        Intent intent;
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if(position == 0){
                intent = new Intent(getApplicationContext(), PlayBack.class);
                intent.putExtra("playUrl", "http://canvasflip.com/protected/app/playback.php?project=694");
                startActivity(intent);
            }
            else if(position == 1){
                intent = new Intent(getApplicationContext(), PlayBack.class);
                intent.putExtra("playUrl", "http://canvasflip.com/protected/app/playback.php?project=696");
                startActivity(intent);
            }
            else if(position == 2){
                intent = new Intent(getApplicationContext(), PlayBack.class);
                intent.putExtra("playUrl", "http://canvasflip.com/protected/app/playback.php?project=698");
                startActivity(intent);
            }
            else{
                intent = new Intent(getApplicationContext(), PlayBack.class);
                intent.putExtra("playUrl", "http://canvasflip.com/protected/app/playback.php?project=777");
                startActivity(intent);
            }
        }
    });*/


/*private void addDrawerItems() {
    String[] navItems = {"Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7"};
    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, navItems);
    mDrawerList.setAdapter(adapter);
}*/

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

private class HttpHandler extends AsyncTask<String, Void, Void> {
    String url  ="some url";
    String responseStr="";
    @Override
    protected Void doInBackground(String... params) {
        httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        try {
            List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
            nameValuePair.add(new BasicNameValuePair("loginId", getEmail));
            nameValuePair.add(new BasicNameValuePair("password", getPassword));
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            responseStr = EntityUtils.toString(httpEntity);
            JSONObject jsonObject = new JSONObject(responseStr);
            final String jsonResult = jsonObject.getString("result");
            MainActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if(jsonResult.equals("success")) {
                        Intent i = new Intent(getBaseContext(), ProjectList.class);
                        startActivity(i);
                    }
                    else {
                        Toast.makeText(getBaseContext(), "failed", Toast.LENGTH_LONG).show();
                    }
                }
            });

        }catch(Exception e) {
            System.out.println(e.getMessage());
        }
        return null;
    }
  }
}

DrawerActivity.java:

public class DrawerActivity extends ActionBarActivity{
ListView mDrawerList;
protected DrawerLayout mDrawerLayout;
ArrayAdapter<String> adapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.drawer_layout);
    mDrawerList = (ListView)findViewById(android.R.id.list);
    mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
    mActivityTitle = getTitle().toString();
    /*getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);*/
    addDrawerItems();
    setUpDrawer();

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
}

public void setUpDrawer() {
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close){
      public void onDrawerOpened(View drawerView) {
          super.onDrawerOpened(drawerView);
          getSupportActionBar().setTitle("NAVIGATION");
          invalidateOptionsMenu();
      }

        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            getSupportActionBar().setTitle(mActivityTitle);
            invalidateOptionsMenu();
        }
    };


    mDrawerToggle.setDrawerIndicatorEnabled(true);
    mDrawerLayout.setDrawerListener(mDrawerToggle);
}

private void addDrawerItems() {
    String[] navItems = {"Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7"};
    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, navItems);
    mDrawerList.setAdapter(adapter);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    mDrawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    mDrawerToggle.onConfigurationChanged(newConfig);
 }
}

4 个答案:

答案 0 :(得分:1)

1st:取消对setContentView()方法的反应,以便显示它 第二:你为什么使用android.R:

mDrawerList = (ListView)findViewById(android.R.id.list);

你应该总是使用你的R而不是机器人。我猜这里是null对象的来源......不幸的是,大多数开发人员都没有抓住这些东西或者检查它们是否为null?

答案 1 :(得分:0)

编辑#1:

我做了一个转换(就像我在评论中说的那样)请试一试,看看它是否有效。由于您尝试实例化属于Main的视图,因此在引用它之前需要先对其进行充气。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
    mDrawerList = (ListView)findViewById(android.R.id.list);+


    //setContentView(R.layout.activity_main);
    LayoutInflater layoutInflater = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View contentView = layoutInflater.inflate(R.layout.activity_main, null,false);
    mDrawerLayout.addView(contentView, 0);
        mPublicProjectsList =(ListView)contentView.findViewById(R.id.list1);
    String[] projectItems = {"Project1", "Project2", "Project3", "Project4"};
    mPublicProjectsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, projectItems);
    mPublicProjectsList.setAdapter(mPublicProjectsAdapter);

    e = (EditText)findViewById(R.id.email);
    p = (EditText)findViewById(R.id.password);
    s = (Button)findViewById(R.id.submit);
    s.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getEmail = e.getText().toString();
            getPassword = p.getText().toString();
            new HttpHandler().execute();
        }
    });
}

您尚未为活动设置内容视图。

在super.onCreate之后你应该打电话:

setContentView(R.layout.main_activity);

只有你的代码的其余部分:

    mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
    mDrawerList = (ListView)findViewById(android.R.id.list);
    mPublicProjectsList =(ListView)findViewById(R.id.list1);
    String[] projectItems = {"Project1", "Project2", "Project3", "Project4"};
    mPublicProjectsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, projectItems);
    mPublicProjectsList.setAdapter(mPublicProjectsAdapter);

或者至少在“膨胀”布局后打电话。因为否则使用“findViewById”将不会“找到”任何视图。

答案 2 :(得分:0)

你忘了void Scene::mousePressEvent(QGraphicsSceneMouseEvent * event) { if(eDrawLines == sceneMode) { dragBeginPoint = event->scenePos(); dragEndPoint = dragBeginPoint; QList<QGraphicsItem*> all = items(); for (int i = 0; i < all.size(); i++) { QGraphicsItem *gi = all[i]; // Clicked point lies inside existing rect if( QGraphicsRectItem::Type == gi->type() && gi->contains(dragBeginPoint)) { std::cout << "Pressed inside existing rect" << std::endl; return; } } std::cout << "Point not found, add new rectangle" << std::endl; } QGraphicsScene::mousePressEvent(event); } 检查以下代码:

setContentView ();

答案 3 :(得分:0)

首先需要执行setContentView(),这将创建视图,然后你应该使用findViewById()找到它们并对它们进行处理。请检查以下代码。

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

    setContentView(R.layout.activity_main);

    mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
    mDrawerList = (ListView)findViewById(android.R.id.list);
    mPublicProjectsList =(ListView)findViewById(R.id.list1);
    String[] projectItems = {"Project1", "Project2", "Project3", "Project4"};
    mPublicProjectsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, projectItems);
    mPublicProjectsList.setAdapter(mPublicProjectsAdapter);


    e = (EditText)findViewById(R.id.email);
    p = (EditText)findViewById(R.id.password);
    s = (Button)findViewById(R.id.submit);
    s.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getEmail = e.getText().toString();
            getPassword = p.getText().toString();
            new HttpHandler().execute();
        }
    });
}