1

我有一个类构造函数。在里面我想使用 getResources 来使用字符串资源。当我想运行该应用程序时,它会产生一个错误,告诉“不幸的是 myProject 已停止”。

    public EhsanAdapter(Context c) {
            context = c;
            size = 5;
            list = new ArrayList<SingleRow>();

            Resources res = c.getResources();
    }

这有什么问题?当我用 getresource 命令注释该行时,我没有错误。

这是全班:

package com.example.listviewba;

import java.util.ArrayList;

import android.content.Context;
import android.content.res.Resources;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

class SingleRow{
    String title;
    String description;
    int image;

    public SingleRow(String title,String description,int image) {
        this.title = title;
        this.description=description;
        this.image=image;
    }
}

public class EhsanAdapter extends BaseAdapter{

    Context context;
    int size;
    ArrayList<SingleRow> list;


    public EhsanAdapter(Context c) {
        context = c;
        size = 5;
        list = new ArrayList<SingleRow>();
        Resources res = c.getResources();
    }
    @Override
    public int getCount() {
        return size;
    }

    @Override
    public Object getItem(int arg0) {
        return null;
    }

    @Override
    public long getItemId(int arg0) {
        return 0;
    }

    public void addView(){
        size++;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        RowView view = null;

        if (convertView == null){
            view = new RowView(this.context);
        }
        else{
            view = (RowView) convertView;
        }
        view.setLeftText("Shit");
        view.setRightText("Fuck");
        return view;
    }

}

这就是我打电话给班级的方式:

package com.example.listviewba;

public class MainActivity extends Activity {

    EhsanAdapter adapter = new EhsanAdapter(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final ListView lv = (ListView) findViewById(R.id.listview1);

        lv.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.main, menu);
        return true;
    }

}
4

1 回答 1

0

EhsanAdapter adapter = new EhsanAdapter(this);像这样向下移动:

final ListView lv = (ListView) findViewById(R.id.listview1);
EhsanAdapter adapter = new EhsanAdapter(this);
lv.setAdapter(adapter);

你不能在之前宣布它,onCreate因为你的Context意志null在这个时候。

或者,如果您希望您EhsanAdapter成为实例变量,则可以在类中声明它,例如private EhsanAdapter adapter;

onCreate你开始喜欢adapter = new EhsanAdapter(this);

于 2013-10-14T14:37:53.090 回答