用的ListView BaseAdapter [英] ListView With BaseAdapter

查看:143
本文介绍了用的ListView BaseAdapter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学习BaseAdapter。我有自定义列表视图。我想从数据库填充列表视图的数据。我得到空指针错误。这里是我的code。

DbTools.java

 公共类的DBTools扩展SQLiteOpenHelper {    公共DBTool中(上下文的背景下){
         超级(上下文中,local.db,空,1);}@覆盖
公共无效的onCreate(SQLiteDatabase DB){
    db.execSQL(CREATE TABLE阿树(名称VARCHAR,地址为varchar));
}@覆盖
公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){
    db.execSQL(删除表是否存在阿树);
    的onCreate(DB);
}公共无效InsertDb(字符串名称,地址字符串){    SQLiteDatabase分贝= getWritableDatabase();
    ContentValues​​ CV =新ContentValues​​();
    cv.put(姓名,姓名);
    cv.put(地址,地址);
    db.insert(阿苏,空,CV);
    db.close();
}公众的ArrayList< NameAddress> getAllData(){
    ArrayList的< NameAddress> dataFromDb =新的ArrayList< NameAddress>();
    SQL字符串=选择名称,从阿树地址;
    SQLiteDatabase分贝= this.getWritableDatabase();
    光标光标= db.rawQuery(SQL,NULL);
    如果(cursor.moveToFirst()){
        做{
            NameAddress NA =新NameAddress();
            na.NamesDb = cursor.getString(0)的ToString();
            na.AddressDb = cursor.getString(1)的ToString();
            dataFromDb.add(NA);
        }而(cursor.moveToNext());
    }
    返回dataFromDb;   }
}

这是我的Adapter类中,我扩展BaseAdapter

Adapter.java

 公共类适配器扩展了BaseAdapter { 公众的ArrayList< NameAddress>结果;
LV的ListView;
私人上下文的背景下;
DBTool中的DBTools =新的DBTools(背景);
私人LayoutInflater吹气= NULL;
公共适配器(上下文的背景下,ArrayList的< NameAddress> RSLT){
    RSLT =结果;
    this.context =背景;
    吹气=(LayoutInflater)(this.context).getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@覆盖
公众诠释的getCount(){
    返回result.size();
}@覆盖
公共对象的getItem(INT位置){
    返回的位置;
}@覆盖
众长getItemId(INT位置){
    返回的位置;
}@覆盖
公共查看getView(INT位置,查看convertView,父母的ViewGroup){    最后NameAddress tmpdata伪= result.get(位置);
    保持架H =新持有人();
    DBTool中的DBTools =新的DBTools(背景);    查看rootView;
    rootView = inflater.inflate(R.layout.row,NULL);
    h.textView1 =(TextView中)rootView.findViewById(R.id.mainText);
    h.textView2 =(TextView中)rootView.findViewById(R.id.subText);
    h.textView1.setText(tmpData.NamesDb);
    h.textView2.setText(tmpData.AddressDb);    返回rootView;
}类持有人{
    公众的TextView textView1,textView2;
}
}

MainActivity.java

 公共类MainActivity延伸活动{ListView的mainList;
按钮来保存;
EditText上的姓名,地址;
DBTool中的DBTools =新的DBTools(本);
ArrayList的< NameAddress> addList;
专用适配器adpter;@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);    mainList =(ListView控件)findViewById(R.id.mainList);
    节省=(按钮)findViewById(R.id.button1);
    名称=(EditText上)findViewById(R.id.nameEditText);
    地址=(EditText上)findViewById(R.id.addressEditText);    save.setOnClickListener(新OnClickListener(){        @覆盖
        公共无效的onClick(视图v){            字符串tempName = name.getText()的toString()。
            字符串tempAdd = address.getText()的toString()。
            dbTools.InsertDb(tempName,tempAdd);            Toast.makeText(getApplicationContext(),增加了成功,Toast.LENGTH_SHORT).show();
            name.setText();
            address.setText();        }
    });    addList =新的ArrayList< NameAddress>();
    addList = dbTools.getAllData();
    adpter =新的适配器(这一点,addList);
    adpter.notifyDataSetChanged();
    mainList.setAdapter(adpter);}
}

和我的模型类

NameAddress.java

 公共类NameAddress {
  串NamesDb;
  串AddressDb;
}

在我的row.xml只有两个textviews

activity_main.xml中

 < LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
的xmlns:工具=htt​​p://schemas.android.com/tool​​s
机器人:ID =@ + ID / LinearLayout1
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:方向=垂直
工具:上下文=com.ashu.customlist.MainActivity><的EditText
    机器人:ID =@ + ID / nameEditText
    机器人:layout_width =match_parent
    机器人:layout_height =WRAP_CONTENT
    机器人:提示=@字符串/名
    机器人:EMS =10的android:inputType下=TEXT>    < requestFocus的/>
< /&的EditText GT;<的EditText
    机器人:ID =@ + ID / addressEditText
    机器人:layout_width =match_parent
    机器人:layout_height =WRAP_CONTENT
    机器人:提示=@字符串/地址
    机器人:EMS =10/><按钮
    机器人:ID =@ + ID /按钮1
    机器人:layout_width =match_parent
    机器人:layout_height =WRAP_CONTENT
    机器人:文字=@字符串/保存/>< ListView控件
    机器人:ID =@ + ID / mainList
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent>
< /&的ListView GT;
< / LinearLayout中>

LOG

  08-26 17:12:30.874:W / dalvikvm(19002):主题ID = 1:螺纹未捕获的异常退出(组= 0x41ee3d88)
08-26 17:12:30.874:E / AndroidRuntime(19002):异常
08-26 17:12:30.874:E / AndroidRuntime(19002):致命异常:主要
08-26 17:12:30.874:E / AndroidRuntime(19002):工艺:com.ashu.customlist,PID:19002
08-26 17:12:30.874:E / AndroidRuntime(19002):了java.lang.RuntimeException:无法启动活动ComponentInfo {com.ashu.customlist / com.ashu.customlist.MainActivity}:显示java.lang.NullPointerException
08-26 17:12:30.874:E / AndroidRuntime(19002):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2237)
08-26 17:12:30.874:E / AndroidRuntime(19002):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
08-26 17:12:30.874:E / AndroidRuntime(19002):在android.app.ActivityThread.access $ 800(ActivityThread.java:145)
08-26 17:12:30.874:E / AndroidRuntime(19002):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1243)
08-26 17:12:30.874:E / AndroidRuntime(19002):在android.os.Handler.dispatchMessage(Handler.java:102)
08-26 17:12:30.874:E / AndroidRuntime(19002):在android.os.Looper.loop(Looper.java:136)
08-26 17:12:30.874:E / AndroidRuntime(19002):在android.app.ActivityThread.main(ActivityThread.java:5127)
08-26 17:12:30.874:E / AndroidRuntime(19002):在java.lang.reflect.Method.invokeNative(本机方法)
08-26 17:12:30.874:E / AndroidRuntime(19002):在java.lang.reflect.Method.invoke(Method.java:515)
08-26 17:12:30.874:E / AndroidRuntime(19002):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:825)
08-26 17:12:30.874:E / AndroidRuntime(19002):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
08-26 17:12:30.874:E / AndroidRuntime(19002):在dalvik.system.NativeStart.main(本机方法)
08-26 17:12:30.874:E / AndroidRuntime(19002):致:显示java.lang.NullPointerException
08-26 17:12:30.874:E / AndroidRuntime(19002):在com.ashu.customlist.Adapter.getCount(Adapter.java:31)
08-26 17:12:30.874:E / AndroidRuntime(19002):在android.widget.ListView.setAdapter(ListView.java:480)
08-26 17:12:30.874:E / AndroidRuntime(19002):在com.ashu.customlist.MainActivity.onCreate(MainActivity.java:55)
08-26 17:12:30.874:E / AndroidRuntime(19002):在android.app.Activity.performCreate(Activity.java:5231)
08-26 17:12:30.874:E / AndroidRuntime(19002):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-26 17:12:30.874:E / AndroidRuntime(19002):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2201)
08-26 17:12:30.874:E / AndroidRuntime(19002):... 11个


解决方案

问题

您正在初始化 DBTool中的DBTools =新的DBTools(本); 在活动的变量声明部分 MainActivity

SOLUTION

移动此行的onCreate

DBTool中的DBTools =新的DBTools(本);

这行已经在里面pferably在的onCreate 法的活动生命周期方法,$ P $之一。除非上下文

  @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);        DBTool中的DBTools =新的DBTools(本);
    }

问题

  adpter.notifyDataSetChanged();
mainList.setAdapter(adpter);

这两个行的不要求在一个时间打电话

SOLUTION


  1. 使用此 mainList.setAdapter(adpter); 第一次您正在设置您的适配器


  2. 和调用 adpter.notifyDataSetChanged(); 当你的数据被更改


问题

您是在变量声明部分还初始化下面一行放在适配器类。

  DBTool中的DBTools =新的DBTools(背景);

由于上下文变量为null你不能初始化这个。

在构造函数中的另一个问题是,你是空结果保存到参数 RSLT 。其实这应该是其他方式。

SOLUTION

更新适配器的构造是这样的。

  DBTool中DBTool中;
公共适配器(上下文的背景下,ArrayList的< NameAddress> RSLT){
    结果= RSLT; //此行被交换
    this.context =背景;
    DBTool中=新的DBTools(背景);
    吹气=(LayoutInflater)(this.context).getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

也无需初始化 DBTool中 getView

I am learning BaseAdapter. I have custom listview. I want to fill data in listview from database. I am getting error of Null Pointer. Here is my code.

DbTools.java

public class DbTools extends SQLiteOpenHelper {

    public DbTools(Context context) {
         super(context, "local.db", null, 1);

}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table ashu(Name varchar, address varchar)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("Drop Table if Exists ashu");
    onCreate(db);
}

public void InsertDb(String Name,String address) {

    SQLiteDatabase db = getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put("Name", Name);
    cv.put("address", address);
    db.insert("ashu", null, cv);
    db.close();
}

public ArrayList<NameAddress> getAllData(){
    ArrayList<NameAddress> dataFromDb = new ArrayList<NameAddress>();
    String SQL = "Select Name, address from ashu";
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(SQL, null);
    if (cursor.moveToFirst()){
        do{
            NameAddress na = new NameAddress();
            na.NamesDb = cursor.getString(0).toString();
            na.AddressDb = cursor.getString(1).toString();
            dataFromDb.add(na);             
        } while(cursor.moveToNext());
    }
    return dataFromDb;

   }
}

This is my Adapter class in which I extended BaseAdapter

Adapter.java

public class Adapter extends BaseAdapter{

 public ArrayList<NameAddress> result;
ListView lv;
private Context context;
DbTools dbTools = new DbTools(context);
private LayoutInflater inflater = null;


public Adapter(Context context,ArrayList<NameAddress> rslt){
    rslt=result;
    this.context=context;
    inflater =  (LayoutInflater)(this.context).getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}


@Override
public int getCount() {     
    return result.size();
}

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

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

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

    final NameAddress tmpData = result.get(position);
    Holder h = new Holder();
    DbTools dbTools = new DbTools(context);

    View rootView;
    rootView = inflater.inflate(R.layout.row, null);
    h.textView1 = (TextView) rootView.findViewById(R.id.mainText);
    h.textView2 = (TextView) rootView.findViewById(R.id.subText);
    h.textView1.setText(tmpData.NamesDb);
    h.textView2.setText(tmpData.AddressDb);

    return rootView;
}

class Holder{   
    public TextView textView1, textView2;
}
}

MainActivity.java

public class MainActivity extends Activity {

ListView mainList;
Button save;
EditText name,address;
DbTools dbTools = new DbTools(this);
ArrayList<NameAddress> addList;
private Adapter adpter;

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

    mainList = (ListView)findViewById(R.id.mainList);
    save = (Button)findViewById(R.id.button1);
    name = (EditText)findViewById(R.id.nameEditText);
    address = (EditText)findViewById(R.id.addressEditText);

    save.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            String tempName = name.getText().toString();
            String tempAdd = address.getText().toString();
            dbTools.InsertDb(tempName, tempAdd);

            Toast.makeText(getApplicationContext(), "Added Successfully", Toast.LENGTH_SHORT).show();
            name.setText("");
            address.setText("");

        }
    });

    addList = new ArrayList<NameAddress>();
    addList = dbTools.getAllData();
    adpter = new Adapter(this, addList);
    adpter.notifyDataSetChanged();
    mainList.setAdapter(adpter);

}
}

And I have model class

NameAddress.java

public class NameAddress {
  String NamesDb;
  String AddressDb;
}

And In my row.xml there are only two textviews

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.ashu.customlist.MainActivity" >

<EditText
    android:id="@+id/nameEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/name"
    android:ems="10" android:inputType="text">

    <requestFocus />
</EditText>

<EditText
    android:id="@+id/addressEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/address"
    android:ems="10" />

<Button
    android:id="@+id/button1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/save" />

<ListView
    android:id="@+id/mainList"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
</ListView>
</LinearLayout>

LOG

08-26 17:12:30.874: W/dalvikvm(19002): threadid=1: thread exiting with uncaught exception (group=0x41ee3d88)
08-26 17:12:30.874: E/AndroidRuntime(19002): Exception
08-26 17:12:30.874: E/AndroidRuntime(19002): FATAL EXCEPTION: main
08-26 17:12:30.874: E/AndroidRuntime(19002): Process: com.ashu.customlist, PID: 19002
08-26 17:12:30.874: E/AndroidRuntime(19002): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ashu.customlist/com.ashu.customlist.MainActivity}: java.lang.NullPointerException
08-26 17:12:30.874: E/AndroidRuntime(19002):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2237)
08-26 17:12:30.874: E/AndroidRuntime(19002):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
08-26 17:12:30.874: E/AndroidRuntime(19002):    at android.app.ActivityThread.access$800(ActivityThread.java:145)
08-26 17:12:30.874: E/AndroidRuntime(19002):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1243)
08-26 17:12:30.874: E/AndroidRuntime(19002):    at android.os.Handler.dispatchMessage(Handler.java:102)
08-26 17:12:30.874: E/AndroidRuntime(19002):    at android.os.Looper.loop(Looper.java:136)
08-26 17:12:30.874: E/AndroidRuntime(19002):    at android.app.ActivityThread.main(ActivityThread.java:5127)
08-26 17:12:30.874: E/AndroidRuntime(19002):    at java.lang.reflect.Method.invokeNative(Native Method)
08-26 17:12:30.874: E/AndroidRuntime(19002):    at java.lang.reflect.Method.invoke(Method.java:515)
08-26 17:12:30.874: E/AndroidRuntime(19002):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
08-26 17:12:30.874: E/AndroidRuntime(19002):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
08-26 17:12:30.874: E/AndroidRuntime(19002):    at dalvik.system.NativeStart.main(Native Method)
08-26 17:12:30.874: E/AndroidRuntime(19002): Caused by: java.lang.NullPointerException
08-26 17:12:30.874: E/AndroidRuntime(19002):    at com.ashu.customlist.Adapter.getCount(Adapter.java:31)
08-26 17:12:30.874: E/AndroidRuntime(19002):    at android.widget.ListView.setAdapter(ListView.java:480)
08-26 17:12:30.874: E/AndroidRuntime(19002):    at com.ashu.customlist.MainActivity.onCreate(MainActivity.java:55)
08-26 17:12:30.874: E/AndroidRuntime(19002):    at android.app.Activity.performCreate(Activity.java:5231)
08-26 17:12:30.874: E/AndroidRuntime(19002):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-26 17:12:30.874: E/AndroidRuntime(19002):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2201)
08-26 17:12:30.874: E/AndroidRuntime(19002):    ... 11 more

解决方案

ISSUE

You are initializing DbTools dbTools = new DbTools(this); in variable declaration portion of your activity MainActivity.

SOLUTION

Move this line to onCreate

DbTools dbTools = new DbTools(this);

This line has to be inside one of the activity lifecycle methods, preferably in onCreate method. Unless the Context will be null

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

        DbTools dbTools = new DbTools(this);
    }

ISSUE

adpter.notifyDataSetChanged();
mainList.setAdapter(adpter);

Both of these lines are not required to call at a time.

SOLUTION

  1. Use this mainList.setAdapter(adpter); the first time you are setting your adapter.

  2. And call adpter.notifyDataSetChanged(); when your dataset is changed.

ISSUE

You are initializing the below line also in your Adapter class at the variable declaration portion.

DbTools dbTools = new DbTools(context);

As the context variable is null you cant initialize this.

Another problem in the constructor is that you are saving the null result to the parameter rslt. Actually it should be in the other way.

SOLUTION

Update the adapter constructor like this.

DbTools dbTools;
public Adapter(Context context,ArrayList<NameAddress> rslt){
    result = rslt; //this line is swapped
    this.context=context;
    dbTools = new DbTools(context);
    inflater =  (LayoutInflater)(this.context).getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

Also no need to initialize DbTools in getView method

这篇关于用的ListView BaseAdapter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆