Android 在单击按钮时从适配器类重新加载ListView数据

Android 在单击按钮时从适配器类重新加载ListView数据,android,listview,android-listview,android-arrayadapter,Android,Listview,Android Listview,Android Arrayadapter,我正在尝试构建一个具有自定义适配器的应用程序,并且所有列表视图行都有三个按钮。我对自定义适配器中的所有按钮进行了onClick操作。单击按钮时,我可以更改数据源,但是我无法从自定义适配器重新加载数据 public class CallListViewCustomAdapter extends ArrayAdapter<Person> { Context context; SQLiteDatabase sb; private static final String SAMPLE_

我正在尝试构建一个具有自定义适配器的应用程序,并且所有
列表视图
行都有三个
按钮
。我对自定义适配器中的所有
按钮进行了
onClick
操作。单击
按钮时,我可以更改数据源,但是我无法从自定义适配器重新加载数据

public class CallListViewCustomAdapter extends ArrayAdapter<Person> {
 Context context;
 SQLiteDatabase sb;
 private static final String SAMPLE_DB_NAME = "androidData.sqlite";
 private static final String SAMPLE_TABLE_NAME = "calldetails";
    int layoutResourceId;   
    ArrayList<Person> data = new ArrayList<Person>();

    public CallListViewCustomAdapter(Context context, int layoutResourceId, ArrayList<Person> data) {
        super(context, layoutResourceId,data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;
    }
    public void refresh(ArrayList<Person>list)
    {           
        data = list;
        notifyDataSetChanged();
    } 
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        convertView = null;
        View row = convertView;
       final int fPosition = position;
        if(row == null)
        {
            LayoutInflater inflater = ((Activity)context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);               
            final WeatherHolder holder = new WeatherHolder();
            holder.phoneNumber = (TextView)row.findViewById(R.id.number);
            holder.fname =  (TextView)row.findViewById(R.id.fName);
            holder.call = (Button)row.findViewById(R.id.callButton);
            holder.skip = (Button)row.findViewById(R.id.skip);
            holder.called = (Button)row.findViewById(R.id.called);
            holder.called.setTag(position);
            Person weather = data.get(position);
            holder.phoneNumber.setText(weather.number);
            holder.fname.setText(weather.fName);
            holder.call.setOnClickListener(new View.OnClickListener() {                 
                @Override
                public void onClick(View arg0) {
                    holder.called.setVisibility(View.VISIBLE);///error comes 
                    holder.skip.setVisibility(View.VISIBLE);///error comes 
                    Intent callIntent = new Intent(Intent.ACTION_CALL);
                    callIntent.setData(Uri.parse("tel:" + data.get(fPosition).number));
                    callIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(callIntent);                  

                }
            });
            holder.called.setOnClickListener(new View.OnClickListener() {                   
                @Override
                public void onClick(View arg0) {
                    //business logic for data source change 
                    refresh(data);///I want listview change here
                    sb.close();
                    Log.v("ONMESSAGE", "HARD");
                    }
            });
          //  holder.desc= (TextView)row.findViewById(R.id.txtViewDescription);
           // holder.switchState = (Switch)row.findViewById(R.id.switch1);             
            row.setTag(holder);
        }




        return row;
    }

    static class WeatherHolder
    {
        TextView phoneNumber;
        TextView fname;
        Switch switchState;
        Button call,skip,called;
    }
公共类CallListViewCustomAdapter扩展了ArrayAdapter{
语境;
sqlitesb数据库;
私有静态最终字符串SAMPLE\u DB\u NAME=“androidData.sqlite”;
私有静态最终字符串示例\u表\u NAME=“calldetails”;
国际布局资源;
ArrayList数据=新的ArrayList();
公共CallListViewCustomAdapter(上下文上下文、int-layoutResourceId、ArrayList数据){
超级(上下文、布局资源ID、数据);
this.layoutResourceId=layoutResourceId;
this.context=上下文;
这个数据=数据;
}
公共无效刷新(ArrayList)
{           
数据=列表;
notifyDataSetChanged();
} 
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
convertView=null;
视图行=转换视图;
最终int F位置=位置;
if(行==null)
{
LayoutInflater充气器=((活动)上下文)。getLayoutInflater();
行=充气机。充气(layoutResourceId,父级,false);
最终挡雨板=新挡雨板();
holder.phoneNumber=(TextView)row.findViewById(R.id.number);
holder.fname=(TextView)row.findViewById(R.id.fname);
holder.call=(Button)row.findViewById(R.id.callButton);
holder.skip=(按钮)row.findViewById(R.id.skip);
holder.called=(按钮)row.findViewById(R.id.called);
支架.调用.设置标签(位置);
人员天气=数据。获取(位置);
holder.phoneNumber.setText(天气号码);
holder.fname.setText(weather.fname);
holder.call.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图arg0){
holder.called.setVisibility(View.VISIBLE);///出现错误
holder.skip.setVisibility(View.VISIBLE);///出现错误
Intent callIntent=新意图(Intent.ACTION\u调用);
setData(Uri.parse(“tel:”+data.get(fPosition.number));
callIntent.addFlags(意图、标志、活动、新任务);
背景。起始触觉(callIntent);
}
});
holder.called.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图arg0){
//用于数据源更改的业务逻辑
刷新(数据);///我想在这里更改listview
(某人接近);
Log.v(“ONMESSAGE”、“HARD”);
}
});
//holder.desc=(TextView)row.findViewById(R.id.txtViewDescription);
//holder.switchState=(Switch)row.findViewById(R.id.switch1);
row.setTag(支架);
}
返回行;
}
静态类风挡
{
文本视图电话号码;
文本视图fname;
开关状态;
按钮调用、跳过、调用;
}
}

使用列表的片段

public class NewFragment extends Fragment{
View rootView;
ProgressDialog pDialog;
private ListView listView1;
CallListViewCustomAdapter adapter;
private static final String SAMPLE_DB_NAME = "androidData.sqlite";
private SQLiteDatabase sampleDB;

ArrayList<Person>list;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    rootView = inflater.inflate(R.layout.newfragment, container, false);
    initDB();       
    list = new ArrayList<Person>();
    new CallLogDetails().execute();
    return rootView;
}
public int checkTable() {
    int return_var = 0;
    sampleDB = getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, Context.MODE_PRIVATE, null);
    Cursor cc = sampleDB.rawQuery("SELECT * FROM " + "calldetails", null);
    if (cc != null){
        if (cc.moveToFirst()) {
            do {
                return_var = cc.getInt(1);
            } while (cc.moveToNext());
        }
    }


    return return_var;
}
public void parseandStoreOpearation()
{
    try{
        CSVReader reader = new CSVReader(new InputStreamReader(getActivity().getAssets().open("batch2.csv")));
        String [] nextLine;
        sampleDB = getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, Context.MODE_PRIVATE, null);

        while ((nextLine = reader.readNext()) != null) {
            //Log.v("ONMESSAGE", "YES");
            Log.v("ONMESSAGE", "Name: [" + nextLine[0] + "]\nAddress: [" + nextLine[1] + "]\nEmail: [" + nextLine[2] + "]");
            if(!nextLine[0].equals("First Name"))
            {
                //Person newPerson = new Person(nextLine[0],nextLine[1], nextLine[2], 1);
                ContentValues cv = new ContentValues();
                cv.put("callNumber", nextLine[2]);
                cv.put("fName", nextLine[0]);
                cv.put("lName", nextLine[1]);
                cv.put("callflag", 1);
                sampleDB.insert("calldetails", null, cv);
                //list.add(newPerson);

            }
        }       
        }
        catch(Exception e)
        {
            Log.v("ONMESSAGE", "EXCEPTION " + e.toString());
        }
}
 public ArrayList<Person> getList()
 {
     ArrayList<Person> arr = new ArrayList<Person>();
     sampleDB= getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, Context.MODE_PRIVATE, null);
     Cursor cc = sampleDB.rawQuery("SELECT * FROM " +"calldetails", null);      
     if(cc != null)
    if(cc.moveToFirst()){
     do
     {   Log.v("Datas",cc.getString(2)+ " " +cc.getString(3) + " " + cc.getString(1) + " " + cc.getInt(4));
         Person ph = new Person(cc.getString(2), cc.getString(3), cc.getString(1),cc.getInt(4),cc.getInt(0));           
         arr.add(ph);

     }while(cc.moveToNext());
    }
     sampleDB.close();
     Log.v("ONMESSAGE", new Integer(arr.size()).toString());
     return arr;
 }
 private void initDB() {
        sampleDB =  getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, Context.MODE_PRIVATE, null);
        sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " +
                "calldetails" +" (callid INTEGER PRIMARY KEY AUTOINCREMENT,"+ "callNumber TEXT," +
                " fName TEXT," + "lName TEXT," + "callflag INTEGER);");


    }

private class CallLogDetails extends AsyncTask<Void,Void,Void>{

    @Override
     protected void onPreExecute(){
        pDialog = new ProgressDialog(getActivity());
        pDialog.setTitle("Processing");
        pDialog.setMessage("Loading Number List");
        pDialog.setIndeterminate(true);
        pDialog.setCancelable(false);
        pDialog.show();
     }

    protected void onPostExecute(Void params){
        super.onPostExecute(params);
        pDialog.dismiss();
        if(list.size() == 0)
     {
         list.add(new Person("No Data", "NO Data", "No Data", 0,0));
     }

     Collections.reverse(list);
     if(adapter != null)
     adapter.clear();
     adapter = new CallListViewCustomAdapter(getActivity(),
                R.layout.listview_row, list);
     listView1 = (ListView)getActivity().findViewById(R.id.lvAlbumList);

    listView1.setOnItemLongClickListener(new OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                final int arg2, long arg3) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("Delete Record");
            builder.setMessage("Do you want to delete the record?");
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    // TODO Auto-generated method stub
                    if(list.size() > 0){

                    sampleDB=getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, SQLiteDatabase.OPEN_READWRITE, null);
                     //sampleDB.execSQL("DELETE FROM "+ SAMPLE_DB_NAME + " " + "WHERE callDesc= " + desc);
                    //sampleDB.execSQL("DELETE FROM calldetails WHERE callDesc='"+desc+"';"); 
                    Toast.makeText(getActivity(), "Row Deleted", Toast.LENGTH_LONG).show();
                     sampleDB.close();
                     new CallLogDetails().execute();
                    }
                    else
                        Toast.makeText(getActivity(), "This is a default object. You can not delete this.", Toast.LENGTH_LONG).show();

                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    // TODO Auto-generated method stub
                    arg0.cancel();

                }
            });
            builder.show();
                 return false;

}
});

     listView1.setAdapter(adapter);


    }
    @Override
    protected Void doInBackground(Void... arg0) {
        list.clear();
        if(checkTable() == 0)
        {
            parseandStoreOpearation();
        }
        list = getList();
        Log.v("ONMESSAGE", "Doing");
        return null;
    }

 }
public类NewFragment扩展了Fragment{
视图根视图;
ProgressDialog;
私有列表视图列表视图1;
CallListViewCustomAdapter适配器;
私有静态最终字符串SAMPLE\u DB\u NAME=“androidData.sqlite”;
私有sqlitedatabasesampledb;
阵列主义者;
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
//TODO自动生成的方法存根
rootView=充气机。充气(R.layout.newfragment,container,false);
initDB();
列表=新的ArrayList();
新建CallLogDetails().execute();
返回rootView;
}
公共整数检查表(){
int return_var=0;
sampleDB=getActivity().openOrCreateDatabase(SAMPLE\u DB\u NAME,Context.MODE\u PRIVATE,null);
游标cc=sampleDB.rawQuery(“从“+”calldetails”中选择*,null);
如果(cc!=null){
if(cc.moveToFirst()){
做{
return_var=cc.getInt(1);
}而(cc.moveToNext());
}
}
返回值;
}
public void parseandStoreOpearation()
{
试一试{
CSVReader reader=新的CSVReader(新的InputStreamReader(getActivity().getAssets().open(“batch2.csv”));
字符串[]下一行;
sampleDB=getActivity().openOrCreateDatabase(SAMPLE\u DB\u NAME,Context.MODE\u PRIVATE,null);
而((nextLine=reader.readNext())!=null){
//Log.v(“ONMESSAGE”、“YES”);
Log.v(“ONMESSAGE”,“Name:[“+nextLine[0]+”]\n地址:[“+nextLine[1]+”]\nEmail:[“+nextLine[2]+”]);
如果(!nextLine[0].equals(“名字”))
{
//Person newPerson=新的Person(nextLine[0],nextLine[1],nextLine[2],1);
ContentValues cv=新的ContentValues();
cv.put(“电话号码”,第二行[2]);
cv.put(“fName”,下一行[0]);
cv.put(“lName”,下一行[1]);
cv.put(“callflag”,1);
sampleDB.insert(“calldetails”,null,cv);
//列表。添加(newPerson);
}
}       
}
捕获(例外e)
{
Log.v(“ONMESSAGE”、“EXCEPTION”+e.toString());
}
}
公共ArrayList getList()
{
ArrayList arr=新的ArrayList();
sampleDB=getActivity().openOrCreateDatabase(SAMPLE\u DB\u NAME,Context.MODE\u PRIVATE,null);
游标cc=sampleDB.rawQuery(“从“+”calldetails”中选择*
CallListViewCustomAdapter thadapter=new CallListViewCustomAdapter(MainActivity.this, R.layout.list,numAl);
NumberList.setAdapter(thadapter);

@Override
public void onClick(View v) {

thadapter.notifyDataSetChanged();

}
});
public void refresh(ArrayList<Person>list)
 {           

    data.clear();
    data.addAll(list);

    this.notifyDataSetChanged();
 }