更新和删除ListView中的SQLite行

时间:2014-01-30 00:54:29

标签: android sqlite listview

你好我对Android开发甚至Java都很陌生,我做了一个应该连接到SQLite数据库并能够插入更新,显示和删除数据的应用程序。到目前为止,我能够插入数据并将其显示在列表视图中。从这里我的计划是在列表视图的每个项目中有两个按钮,一个要删除,一个要更新,但我正在努力让按钮工作任何帮助将不胜感激,谢谢。

此活动接受输入并在表格中插入一行

package com.example.votesmart2;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.example.votesmart2.FeedReaderContract.FeedEntry;

import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class Zip extends Activity {


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


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

    public void onSubmit(View view){

        System.out.println("button just pressed");

        FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(getApplicationContext());

        System.out.println("database class instantized/database created");

        EditText first = (EditText)findViewById(R.id.fname_input);
        String finalFirst = first.getText().toString();

        EditText last = (EditText)findViewById(R.id.lname_input);
        String finalLast = last.getText().toString();

        EditText zip = (EditText)findViewById(R.id.zipcode_input);
        int finalZip = Integer.parseInt(zip.getText().toString());

        EditText age = (EditText)findViewById(R.id.age_input);
        int finalAge =Integer.parseInt(age.getText().toString());

        EditText sex = (EditText)findViewById(R.id.sex_input);
        String finalSex = sex.getText().toString();
        System.out.println("gets all data from edit text");


        SQLiteDatabase db = mDbHelper.getWritableDatabase();
        System.out.println("got writable database");

        ContentValues values = new ContentValues();
        values.putNull(FeedEntry._ID);
        values.put(FeedEntry.col_first, finalFirst);
        values.put(FeedEntry.col_last, finalLast);
        values.put(FeedEntry.col_zip, finalZip);
        values.put(FeedEntry.col_age, finalAge);
        values.put(FeedEntry.col_sex, finalSex);



        long newRowId = db.insert(FeedEntry.table_name, null, values);



        Intent intent = new Intent(Zip.this, EditProfile.class);
        startActivity(intent);
    }
}

这是显示我的数据的活动

package com.example.votesmart2;


import java.util.ArrayList;
import java.util.List;

import com.example.votesmart2.FeedReaderContract.FeedEntry;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class EditProfile extends ListActivity {

    protected void onCreate(Bundle savedInstanceState) {
        System.out.println("onCreate begins");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.editprofile);
        Intent intent = getIntent();
        System.out.println("intent received");


        FeedReaderDbHelper feedReaderDbHelper = new FeedReaderDbHelper(this);
        System.out.println("istantiate db class");

        ListView listView = (ListView)findViewById(R.id.list);
        System.out.println("list view declared");
        ListAdapter listAdapter = new ListAdapter(this, feedReaderDbHelper.getRecords());
        System.out.println("running of select query complete");
        listView.setAdapter(listAdapter);
        System.out.println("values sent to adapter for listview formatting");   

            }


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

    /*public void onDelete(View view){
        DeleteRecord deleteRecord = new DeleteRecord();
        deleteRecord.deleteRecord(null);
        Intent i = new Intent(EditProfile.this, EditProfile.class);  //your class
        startActivity(i);
        finish();
        }*/

    public void onUpdate(View view){

    }
}   

这是我的适配器

package com.example.votesmart2;


import com.example.votesmart2.FeedReaderContract.FeedEntry;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ImageButton;
import android.widget.TextView;

public class ListAdapter extends CursorAdapter{

    public ListAdapter(Context context, Cursor cursor){
        super(context, cursor);

    }
    @Override
    public void bindView(View view, final Context context, Cursor cursor) {
        // TODO Auto-generated method stub
        TextView nameTextView = (TextView) view.findViewById(R.id.first_view).getTag();
        nameTextView.setText(cursor.getString(cursor.getColumnIndex(FeedEntry.col_first)));
        TextView lastTextView = (TextView) view.findViewById(R.id.last_view);
        lastTextView.setText(cursor.getString(cursor.getColumnIndex(FeedEntry.col_last)));
        TextView zipTextView = (TextView) view.findViewById(R.id.zip_view);
        zipTextView.setText(cursor.getString(cursor.getColumnIndex(FeedEntry.col_zip))); 
        TextView ageTextView = (TextView) view.findViewById(R.id.age_view);
        ageTextView.setText(cursor.getString(cursor.getColumnIndex(FeedEntry.col_age)));
        TextView sexTextView = (TextView) view.findViewById(R.id.sex_view);
        sexTextView.setText(cursor.getString(cursor.getColumnIndex(FeedEntry.col_sex)));

        Button delete = (Button) view.findViewById(R.id.delete);
        delete.setTag(nameTextView);


    }
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        // TODO Auto-generated method stub
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View view = inflater.inflate(R.layout.profile_list_item,  parent, false);


        return view;
    }

     public void onDelete()
       {
         //FeedReaderDbHelper dbHelper = new FeedReaderDbHelper(context);
         //dbHelper.delete(nameTextView);
         FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(null);//getApplicationContext()
         SQLiteDatabase db = mDbHelper.getWritableDatabase();
         String selection = FeedEntry.col_first + " LIKE = ";
         String[] selectionArgs = { String.setTag()};
         db.delete(FeedEntry.table_name, selection, selectionArgs);
     }

}

和我的数据库助手

package com.example.votesmart2;

import com.example.votesmart2.FeedReaderContract.FeedEntry;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.TextView;

public class FeedReaderDbHelper extends SQLiteOpenHelper{

    private static final String text_type = " TEXT";
    private static final String int_type = " INTEGER";
    private static final String comma_sep = ", ";
    private static final String open_paren = " (";
    private static final String close_paren = ")";
    private static final String sql_create_entries = "CREATE TABLE " + FeedEntry.table_name + open_paren + 
            FeedEntry.col_id +  " INTEGER PRIMARY KEY, " + 
            FeedEntry.col_first + text_type + comma_sep +
            FeedEntry.col_last + text_type + comma_sep +
            FeedEntry.col_zip + int_type + comma_sep +
            FeedEntry.col_age + int_type + comma_sep +
            FeedEntry.col_sex + text_type + close_paren;

    private static final String sql_delete_entries = "DROP TABLE IF EXISTS " + FeedEntry.table_name;

        //INCREMENT VERSION NUMBER IF CHANGE DATABASE SCHEMA
        public static final int database_version = 7;
        public static final String database_name = "VoteSmarter.db";

        public FeedReaderDbHelper(Context context) {
            super(context, database_name, null, database_version);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            db.execSQL(sql_create_entries);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            db.execSQL(sql_delete_entries);
            onCreate(db);
        }

        SQLiteDatabase db = getWritableDatabase();
        public Cursor getRecords(){
            String[] projection = { FeedEntry.col_id,
                    FeedEntry.col_first,
                    FeedEntry.col_last,
                    FeedEntry.col_zip,
                    FeedEntry.col_age, 
                    FeedEntry.col_sex};

            String sortOrder = FeedEntry.col_first + " DESC";

            Cursor c = db.query(FeedEntry.table_name, projection, null, null, null, null, sortOrder);
            return c; 
        }


        public void delete(TextView nameTextView) {
            // TODO Auto-generated method stub
            String selection = FeedEntry.col_first + " LIKE ?";
            String[] selectionArgs = { String.valueOf(nameTextView)};
            db.delete(FeedEntry.table_name, selection, selectionArgs);
        }
}

任何帮助都会受到赞赏我一直在努力解决这个问题。谢谢

1 个答案:

答案 0 :(得分:0)

您是否需要保持视图静态?或者如果你只是将一个监听器放在适配器中并在主活动上实现该功能,那么当触摸删除按钮时,适配器将通知监听器,然后主活动可以处理重新加载适配器的过程。

在我的情况下,我需要使用不同的方法,第一种是将侦听器放在片段中并在主活动中实现活动。

片段:

public class ListFragment extends Fragment{

public static final String TAG = ListFragment.class.getSimpleName();
private ListAdapter mAdapter;
private ListStoreAdapter sAdapter;
private ListView listView;
private Context mContext;
private View mView;
private OnItemSelectedListener listener;

public interface OnItemSelectedListener{
    public void onImageSelected(int p, View v, String r, String g, String f);
}

@Override
public void onCreate(Bundle args){
    super.onCreate(args);
    args = getArguments();

    ... create code goes here ...
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    super.onCreateView(inflater, container, savedInstanceState);
    View view = inflater.inflate(R.layout.fragment_list_view, container, false);
    mContext = getActivity();
    mView = view;
    setImage();
    return view;

}

public void setImage(){
    listView = (ListView)mView.findViewById(R.id.list_view);
    listView.setAdapter(sAdapter);

    listView.setOnItemClickListener(new OnItemClickListener() { 
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) { 
            final View thumb = v.findViewById(R.id.itemViewList);
            String code;
            String flag;
            if(goodsCd != null){
                code = goodsCd[position];
            }else{
                code = "";
            }

            if(flags != null){
                flag = flags[position];
            }else{
                flag = "1";
            }
            listener.onImageSelected(position, thumb, codes[position], code, flag);
        } 
    });

}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    if (activity instanceof OnItemSelectedListener) {
        listener = (OnItemSelectedListener) activity;
    }else{
        throw new ClassCastException(activity.toString()+" must implemenet HomeFragmentActivity.OnItemSelectedListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    // Guarantees that we never accidentally leak the Activity instance.
    listener = null;
}

}

现在,适配器就是这个,并且还实现了一个delete函数,它调用main活动上的静态void,当信息发生变化时,它将刷新整个片段。

public class ListAdapter extends BaseAdapter{
private Context mContext;
private boolean isCloud;

public ListAdapter(Context c, String[] d, File[] f, ArrayList<String> l, boolean i, String[] fn, String[] t, String[] cd){
    ... Initialise the variables here ...
}

@Override
public int getCount() {
    return files.length;
}

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

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v;
    final ImageView imageView;
    TextView title;
    TextView date;
    ImageView checkMark, download;
    TableRow downloadBtn, deleteBtn, openBtn;

    if(convertView == null){
        v           = vi.inflate(R.layout.individual_list_cell, null);
        downloadBtn = (TableRow)v.findViewById(R.id.downloadBtn);
        deleteBtn   = (TableRow)v.findViewById(R.id.delBtn);
        openBtn     = (TableRow)v.findViewById(R.id.openBtn);
    }else{
        v            = (View)convertView;
        downloadBtn = (TableRow)v.findViewById(R.id.downloadBtn);
        deleteBtn   = (TableRow)v.findViewById(R.id.delBtn);
        openBtn     = (TableRow)v.findViewById(R.id.openBtn);
    }

    ... Some code goes here ...
            ... the delete button is as follow ...
    if(!isCloud){

        final String volString = files[position];
        deleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {HomeFragmentActivity.onDeletePressed(volString);}
        });

        downloadBtn.setVisibility(View.INVISIBLE);
        deleteBtn.setVisibility(View.VISIBLE);
        openBtn.setVisibility(View.INVISIBLE);
    }

    return v;
}

}

最后,主要活动将实现OnItemSelectedListener并将具有静态void onDeletePressed

public class HomeFragmentActivity extends SlidingFragmentActivity implements GridFragment.OnItemSelectedListener, ListFragment.OnItemSelectedListener,
                                                                OnCheckedChangeListener{

静态空白

public static void onDeletePressed(final String v){
    String msg = mContext.getResources().getString(R.string.delete_warning);

            ... Prepare the code to delete the file in here ...

    AlertDialog alert = mBuilder.create();
    alert.setTitle(mContext.getResources().getString(R.string.delete_title));
    alert.setMessage(String.format(msg, v));
    alert.setButton(AlertDialog.BUTTON_POSITIVE, mContext.getResources().getString(R.string.ok_button),
            new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            try{

                file.delete();
                                    //This will update the database
                localHelper.updateDownloadedMagazine(delVal, v);
                                    //Then update the array for the new fragment
                ArrayList<ArrayList<String>> localArray = localHelper.retrieveLocalMagazines();
                if(localArray != null){
                    volsArrayLocal = localArray.get(0);
                    datesArrayLocal = localArray.get(1);
                    codeArrayLocal  = localArray.get(2);
                    fileArrayLocal  = localArray.get(3);
                    titleArrayLocal = localArray.get(4);
                    coversLocal = new String[volsArrayLocal.size()];
                    for(int x=0; x< fileArrayLocal.size(); x++){
                        coversLocal[x] = volsArrayLocal.get(x)+Common.COVER_EXT;
                    }
                }
                                    //Replace the information of the fragment
                HomeFragmentActivity hf = new HomeFragmentActivity();
                //And call the function to replace the fragment
                                    hf.localOnClick();

            }catch(Exception e){
                e.printStackTrace();
            }
        }
    });
    alert.setButton(AlertDialog.BUTTON_NEGATIVE, mContext.getResources().getString(R.string.cancel_button),
            new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    alert.show();

}

到目前为止,这种方法对我来说很好,我希望它可以帮助你解决问题。

大卫