Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 更新和删除ListView中的SQLite行_Android_Sqlite_Listview - Fatal编程技术网

Android 更新和删除ListView中的SQLite行

Android 更新和删除ListView中的SQLite行,android,sqlite,listview,Android,Sqlite,Listview,您好,我对Android开发非常陌生,甚至对Java也不熟悉。我正在制作一个应用程序,可以连接到SQLite数据库,并能够插入更新、显示和删除数据。到目前为止,我能够插入数据并在listview中显示它。从这里开始,我的计划是在listview的每个项目中有两个按钮,一个要删除,一个要更新,但我正在努力使这些按钮正常工作。如有任何帮助,将不胜感激。谢谢 此活动接收输入并将行插入我的表 package com.example.votesmart2; import java.util.regex.

您好,我对Android开发非常陌生,甚至对Java也不熟悉。我正在制作一个应用程序,可以连接到SQLite数据库,并能够插入更新、显示和删除数据。到目前为止,我能够插入数据并在listview中显示它。从这里开始,我的计划是在listview的每个项目中有两个按钮,一个要删除,一个要更新,但我正在努力使这些按钮正常工作。如有任何帮助,将不胜感激。谢谢

此活动接收输入并将行插入我的表

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);
        }
}

任何帮助都将不胜感激,我已经为此奋斗了一段时间。谢谢

您需要保持视图静止吗?或者,如果您只是在适配器中放置一个侦听器并在主活动上实现该功能,那么当按下delete按钮时,适配器将通知侦听器,然后主活动可以处理重新加载适配器的过程

在我的例子中,我必须使用不同的方法,第一种方法是将侦听器放在片段中,并在主活动中实现活动

片段:

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;
}

}
和静态空洞

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();

}
publicstaticvoidondeletepressed(最终字符串v){
String msg=mContext.getResources().getString(R.String.delete_警告);
…在此准备删除文件的代码。。。
AlertDialog alert=mBuilder.create();
setTitle(mContext.getResources().getString(R.string.delete_title));
alert.setMessage(String.format(msg,v));
alert.setButton(AlertDialog.BUTTON_正值,mContext.getResources().getString(R.string.ok_按钮),
新建DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int which){
试一试{
delete();
//这将更新数据库
updateDownloadedMagazine(delVal,v);
//然后更新新片段的数组
ArrayList 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=新字符串[volsArrayLocal.size()];
对于(int x=0;x
到目前为止,这种方法对我很有效,我希望它能帮助你解决你的问题

大卫

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();

}