如何在android中运行时更新列表视图数据

时间:2013-12-18 10:18:16

标签: android listview android-listview

我有list-view with check-box,它从数据库加载数据。我也有一个按钮,当我按下按钮时,微调器会弹出2条消息“编辑”和“删除”。删除工作完全正常。如果我选择编辑选项并按确定,则编辑文本将进入警报窗口,并带有两个按钮确定和取消。

现在我希望无论我在编辑文本中输入什么并按下确定按钮,所选的列表视图数据(已选中)应该使用新文本更新,无论我在编辑文本中输入了什么。那么如何实现这一目标。请帮我。任何帮助,将不胜感激。提前谢谢。

我创建数据库的代码:

public class DataManipulatorClass {

public static final String KEY_ROWID = "id";
private static final String DATABASE_NAME = "mydatabaseclass.db";
private static final int DATABASE_VERSION = 1;
static final String TABLE_NAME = "newtableclass";
private static Context context;
static SQLiteDatabase db;
OpenHelper openHelper = null;

private SQLiteStatement insertStmt;

private static final String INSERT = "insert into " + TABLE_NAME
        + "(classname) values (?)";

public DataManipulatorClass(Context context) {
    DataManipulatorClass.context = context;
    OpenHelper openHelper = new OpenHelper(DataManipulatorClass.context);
    DataManipulatorClass.db = openHelper.getWritableDatabase();
    this.insertStmt = DataManipulatorClass.db.compileStatement(INSERT);
    //this.db = openHelper.getWritableDatabase();
}

public long insert(String classname) {
    this.insertStmt.bindString(1, classname);
    return this.insertStmt.executeInsert();
}

public void close() {
    if (openHelper != null) {
        openHelper.close();
    }
}

public void deleteAll() {
    db.delete(TABLE_NAME, null, null);
}

public List<String[]> selectAll() {
    List<String[]> list = new ArrayList<String[]>();
    Cursor cursor = db.query(TABLE_NAME,
            new String[] { "id", "classname" }, null, null, null, null,
            "classname asc");
    int x = 0;
    if (cursor.moveToFirst()) {
        do {
            String[] b1 = new String[] { cursor.getString(0),
                    cursor.getString(1) };
            list.add(b1);
            x = x + 1;
        } while (cursor.moveToNext());
    }
    if (cursor != null && !cursor.isClosed()) {
        cursor.close();
    }
    cursor.close();
    return list;
}

public boolean delete(long rowId) {
    /** this method deletes by id, the first column in your database */
    return db.delete(TABLE_NAME, KEY_ROWID + "=" + rowId, null) > 0;
}

private static class OpenHelper extends SQLiteOpenHelper {
    OpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + TABLE_NAME
                + " (id INTEGER PRIMARY KEY, classname TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }
}
}

我的活动课程:

public class Classes extends Activity implements OnClickListener {

ImageView imageViewNewClass, imageViewDelete;
ListView mListView;
String[] stg1;
List<String[]> names2 = null;
DataManipulatorClass dataManipulator;
ArrayAdapter<CharSequence> adapterSpinner;
ArrayAdapter<String> adapter;

/** Sliding Menu */
boolean alreadyShowing = false;
private int windowWidth;
private Animation animationClasses;
private RelativeLayout classesSlider;
LayoutInflater layoutInflaterClasses;

@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.classes);

    imageViewNewClass = (ImageView) findViewById(R.id.newclass);
    imageViewDelete = (ImageView) findViewById(R.id.deletemenu);
    mListView = (ListView) findViewById(R.id.displaydata);

    Display display = getWindowManager().getDefaultDisplay();
    windowWidth = display.getWidth();
    display.getHeight();
    layoutInflaterClasses = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    imageViewDelete.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            deleteMenuSpinner();
        }

        private void deleteMenuSpinner() {
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(
                    Classes.this);

            final Spinner spinnerDelete = new Spinner(Classes.this);
            alertDialog.setView(spinnerDelete);

            adapterSpinner = ArrayAdapter.createFromResource(Classes.this,
                    R.array.delete_menu,
                    android.R.layout.simple_spinner_item);
            adapterSpinner
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinnerDelete.setAdapter(adapterSpinner);

            alertDialog.setPositiveButton("Ok",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int which) {

                                    Delete operation code.....
                                }

                            } else {
                                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                                        Classes.this);
                                final EditText updateClass = new EditText(
                                        Classes.this);
                                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                                        LinearLayout.LayoutParams.MATCH_PARENT,
                                        LinearLayout.LayoutParams.MATCH_PARENT);
                                updateClass.setLayoutParams(lp);
                                alertDialogBuilder.setView(updateClass);
                                alertDialogBuilder
                                        .setTitle("Edit Operation");
                                alertDialogBuilder
                                        .setMessage("Enter New Class Name")
                                        .setCancelable(false)
                                        .setPositiveButton(
                                                "Yes",
                                                new DialogInterface.OnClickListener() {
                                                    public void onClick(
                                                            DialogInterface dialog,
                                                            int id) {
                                                    }
                                                })
                                        .setNegativeButton(
                                                "No",
                                                new DialogInterface.OnClickListener() {
                                                    public void onClick(
                                                            DialogInterface dialog,
                                                            int id) {
                                                        dialog.cancel();
                                                    }
                                                });
                                AlertDialog alertDialog = alertDialogBuilder
                                        .create();
                                alertDialog.show();
                            }
                        }
                    });

            alertDialog.setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int which) {
                            dialog.cancel();
                        }
                    });
            alertDialog.show();
        }
    });

    findViewById(R.id.skirrmenu).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!alreadyShowing) {
                alreadyShowing = true;
                openSlidingMenu();
            }
        }
    });

    imageViewNewClass.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent(Classes.this, Class_Create.class);
            startActivity(intent);
        }
    });

    mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View item,
                int position, long id) {
            // Toast.makeText(getApplicationContext(),
            // "Listview item clicked", Toast.LENGTH_LONG).show();

            SparseBooleanArray sp = mListView.getCheckedItemPositions();
            StringBuffer str = new StringBuffer();
            for (int i = 0; i < sp.size(); i++) {
                if (sp.valueAt(i) == true) {
                    String s = ((TextView) mListView.getChildAt(i))
                            .getText().toString();
                    str = str.append(" " + s);
                }
            }
            Toast.makeText(Classes.this,
                    "Selected items are " + str.toString(),
                    Toast.LENGTH_LONG).show();

            // Intent intent = new Intent(Classes.this, PlayAudio.class);
            // startActivity(intent);
        }
    });

    dataManipulator = new DataManipulatorClass(this);
}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();

    names2 = dataManipulator.selectAll();

    stg1 = new String[names2.size()];
    int x = 0;
    String stg;

    for (String[] name : names2) {
        stg = "Class Name : " + name[1];
        stg1[x] = stg;
        x++;
    }

    adapter = new ArrayAdapter<String>(this,
            R.layout.custom_list_item_multiple_choice, stg1);
    mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    mListView.setBackgroundResource(R.drawable.assignmentheader);
    mListView.setCacheColorHint(Color.TRANSPARENT);
    mListView.setAdapter(adapter);
    adapter.notifyDataSetChanged();
}

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    if (dataManipulator != null)
        dataManipulator.close();
}
}

1 个答案:

答案 0 :(得分:0)

按下OK按钮时,可以尝试使用adapter.notifyDataSetChanged()。但它会更新整个列表。如果这是您所需要的,那么这就是解决方案。 要更新一个列表项,您可以尝试:

private void updateView(int index, String updateText){
    View v = yourListView.getChildAt(index - 
       yourListView.getFirstVisiblePosition());
    TextView someText = (TextView) v.findViewById(R.id.sometextview);
    someText.setText(updateText);
}