COntext在其他活动中使用,而不是main,在数据库操作中给出空指针异常

时间:2013-01-21 04:55:04

标签: android android-context

@Override
public void onCreate(Bundle savedInstanceState) {

    /*Intent z=new Intent(this, HomePage.class);
    startActivityForResult(z, REQUEST_CODE);*/

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ctx = this;
    datasource = new CommentsDataSource(this);
    datasource.open();
    refresh();
}
private void refresh(){
    List<Comment> values = datasource.getAllComments();
    List<Comment> value_dif= new ArrayList<Comment>();
    for(int i=0;i<values.size();i++){
        Comment comment=new Comment();
        comment=values.get(i);
        if(comment.getToGive()>comment.getToTake())
            comment.setComment(comment.getComment()+" "+(comment.getToGive()-comment.getToTake()));
        else
            comment.setComment(comment.getComment()+" "+(comment.getToTake()-comment.getToGive()));
            value_dif.add(i,comment);
    }
    ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
            android.R.layout.simple_list_item_1, value_dif);
    setListAdapter(adapter);



    ListView listView = (ListView)findViewById(android.R.id.list);
    listView.setAdapter(new ArrayAdapter<Comment>(this, android.R.layout.simple_list_item_1, value_dif) {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView textView = (TextView) super.getView(position, convertView, parent);
            List<Comment> values = datasource.getAllComments();
            Comment comment=datasource.getHisaab(values.get(position).getComment());
            if(comment.getToGive()>comment.getToTake()){
                textView.setTextColor(Color.RED);
            }
            else{
                textView.setTextColor(Color.GREEN);
            }
            /*String currentLocation = RouteFinderBookmarksActivity.this.getResources().getString(R.string.Current_Location);
            int textColor = textView.getText().toString().equals(currentLocation) ? R.color.holo_blue : R.color.text_color_btn_holo_dark;
            textView.setTextColor(RouteFinderBookmarksActivity.this.getResources().getColor(textColor));*/
            return textView;
        }
    });

}

如果我在其他活动中使用数据库操作再次创建数据源对象并给出上下文,那么它会显示错误......如果我在此活动中执行数据库操作,则一切运行良好.....

2 个答案:

答案 0 :(得分:0)

ListView listView = (ListView)findViewById(android.R.id.list);方法的onCreatesetListAdapter(adapter);行之前初始化refresh()

答案 1 :(得分:0)

尝试使用应用程序的上下文而不是活动的上下文:将this替换为this.getApplicationContext()