如何让用户能够在android中的列表视图中编辑项目

时间:2016-03-13 16:52:16

标签: java android sqlite

我有一个listView,每个项目都是一个textView,一个dataBase包含3列(" ID" - " NAME" - " TAG"),什么在列表视图中可显示的是名称,用户在editBox中输入它以及与之关联的标记并存储在dataBase中我现在想要当用户长按每个项目时打开一个新活动包含2个编辑框一个用于标签的名称和标签,然后输入它们,以便更新已经点击过的标签。 这是我的代码

数据库函数类:

package com.chaos.twittertask;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DataBase {

    private SQLiteDatabase mDatabase;
    private DB_Helper helper;

    public DataBase(Context context) {
        helper = new DB_Helper(context);
    }

    protected void open() {
        mDatabase = helper.getWritableDatabase();
    }

    public void close() {
        if (mDatabase != null) {
            mDatabase.close();
        }
    }
    public Cursor getAllNames()
    {
        String[] col = { "NAME" };
        Cursor cursor = mDatabase.query(
                "task", // table name
                col, // column names
                null, // where clause
                null, // where params
                null, // groupby
                null, // having
                null // orderby
        );

        return cursor;
    }

    public Cursor getTagByID(int id) {
        String[] columns = { "TAG"};

        return mDatabase.query(
                "task", // table name
                columns, // column names
                "ID" + " = " + id, // where clause // id param. could be here or appended as it is ^
                null, // where params
                null, // groupby
                null, // having
                null // orderby
        );
    }

    public void insertTagAndName(String name,String tag) {

            ContentValues newTask = new ContentValues();
            newTask.put("NAME", name);
            newTask.put("TAG",tag);
            mDatabase.insert("task", null, newTask);

    }


    public void updateNameAndTag(int id,String name,String tag) {
        ContentValues editTask = new ContentValues();
        editTask.put("NAME", name);
        editTask.put("TAG", tag);
        mDatabase.update(
                "task", // table name
                editTask, // values
                "ID" + " = " + id, // where clause
                null // where params
        );
    }
    public void getNameId(String name) {
        mDatabase.execSQL("SELECT ID from task WHERE NAME="+name);
    }
    public void deleteTagById(int id) {
        mDatabase.delete(
                "task", // table name
                "ID" + "=" + id, // where clause
                null // where params
        );
    }

}

MatinActivity:

package com.chaos.twittertask;

import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private Button save;
    private EditText name;
    private EditText tag;
    private TextView headline;
    private ListView list;
    private DataBase dataBase;
    private String[] names;
    private Cursor  cursor;
    private ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        save= (Button) findViewById(R.id.save);
        name=(EditText) findViewById(R.id.name);
        tag=(EditText) findViewById(R.id.tag);
        headline=(TextView) findViewById(R.id.tagged_searches);
        list=(ListView) findViewById(R.id.listView);
        dataBase=new DataBase(MainActivity.this);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dataBase.insertTagAndName(name.getText().toString(), tag.getText().toString());
                name.setText("");
                tag.setText("");
                Toast.makeText(MainActivity.this, "Tag has been added successfully ",
                        Toast.LENGTH_LONG).show();
                loadData();
            }
    });
        list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

                return false;
            }
        });
    }

    protected void onResume() {
        super.onResume();
        loadData();
    }


    private void loadData()
    {
        int i=0;
        dataBase.open();
        cursor = dataBase.getAllNames();
        names = new String[cursor.getCount()];
        try {
            cursor.moveToFirst();
            int index_name = cursor.getColumnIndex("NAME");
            do {
                names[i] = cursor.getString(index_name);
                i++;
            }while (cursor.moveToNext());
                    adapter = new ArrayAdapter<String>(
                    this,
                    R.layout.list_item, R.id.name_item,
                    names);
            list.setAdapter(adapter);
        }catch (Exception e) {
            Toast.makeText(getApplicationContext(), e.getMessage(),
                    Toast.LENGTH_LONG).show();
        }
    }

}

1 个答案:

答案 0 :(得分:1)

这不难做到 您的ListView项目将包含一个TextView,它将是名称。
最好的方法是创建2个东西,一个自定义适配器和一个Dialog Fragment。让我们开始吧
创建一个将保存数据的新类,在您的情况下,它的名称和标志。

    public class ListItem{

    String name;
    String flag;

        public ListItem(String name, String flag) {
            this.name= name;
            this.flag= flag;
        }
    }

好。现在,您的自定义适配器将需要此类的实例而不是String。它将使用常规适配器但使用ListItem执行相同的操作     创建一个这样的新类:

    public class ListItemAdapter extends ArrayAdapter<ListItem>{


    public ListItemAdapter(Context context, List<ListItem> items) {
        super(context, 0, items);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Context context = getContext();
        ListItem item = getItem(position);
        View rootView = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);


        TextView name = (TextView) rootView.findViewById(R.id.your_text_view_item);
        name.setText(item.name);

        return rootView;
    }
}

现在创建了自定义适配器。它需要一个具有2个值的ListItem,但只使用1.另一个将在以后使用
使用自定义适配器就像普通适配器一样。但是在“&lt;&gt;”中使用了String使用ListItem

现在你需要一个会显示2个EditTexts的Dialog Fragment。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">

<EditText
    android:id="@+id/dialog_name_edit_text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="4dp"
    android:layout_marginLeft="4dp"
    android:layout_marginRight="4dp"
    android:layout_marginTop="4dp"/>

<EditText
    android:id="@+id/dialog_flag_edit_text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="4dp"
    android:layout_marginLeft="4dp"
    android:layout_marginRight="4dp"
    android:layout_marginTop="4dp"
    android:inputType="textPassword"" />

您将把Fragment中的数据传递给您的Activity,这是一个Interface的抽象方法。就像这样:

public interface MyCallback{
    void callback(String name, String flag);
}

public class ListViewDialogFragment extends DialogFragment {



    MyCallback myCallback;
    EditText nameEditText;
    EditText flagEditText;

    public ListViewDialogFragment() {

    }

    public static ListViewDialogFragment newInstance(String title, MyCallback callback){
        ListViewDialogFragment fragment = new ListViewDialogFragment ();
        Bundle args = new Bundle();
        args.putString("title", title);
        fragment.setArguments(args);
        myCallback = callback;
        return fragment;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

    View rootView = getActivity().getLayoutInflater().inflate(R.layout.xml_we_just_created, null);
    nameEditText= (EditText) rootView.findViewById(R.id.dialog_name_edit_text);
    flagEditText= (EditText) rootView.findViewById(R.id.dialog_flag_edit_text);

    final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setView(rootView);

        String title = getArguments().getString("title");

        builder.setTitle(title);
        builder.setPositiveButton("Confirmar", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            String name = nameEditText.getText.toString();
            String flag = flagEditText.getText.toString();
            if(!name.equals("") && !flag.equals(""))
                myCallback.callback(name, flag);
        }
    });
    }
}


大!现在,只要您想编辑listItem,就需要调用它 打电话的方式是:

    ListViewDialogFragment fragment = ListViewDialogFragment.newInstance("Your_Title", new ListViewDialogFragment.MyCallback(){
        @Override
        public void callback(String name, String flag){
            //Do whatever you want with the name and flag.
            //You can create a ListItem with these 2 and update your adapter.
        }
    });
    fragment.show(getFragmentManager(), "");

要将数据发送到数据库,请执行以下操作:

adapter.getItem(i).name;

adapter.getItem(i).flag;

其中“i”是ListView的索引。 ;)