2

我使用列表视图,当我尝试更新列表视图但不更改时

我把方法放进 updateTggl()SaveData(),所以当我保存数据时,列表会改变但不起作用

这是我的方法

private void updateTggl() 
{
    DatabaseHelper dbConnector = new DatabaseHelper(this);

   if (getIntent().getExtras() != null)
   {
       dbConnector.updateTanggal(rowID,tglEt.getText().toString());
   }
}

这是代码 updateTanggal 方法

public void updateTanggal(long id, String tglb) 
  {
     ContentValues editTgl = new ContentValues();
     editTgl.put("tglb", tglb);
     SQLiteDatabase db = this.getWritableDatabase();
     db.update("petak_tetap", editTgl, "_id=" + id, null);
     db.close();
  }

调用列表视图的代码

db = new DatabaseHelper(this);
        constantsCursor = db.getReadableDatabase().rawQuery(
                "SELECT _ID, alamat, tglb " + "FROM petak_tetap ORDER BY _ID",
                null);

        ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.row,
                constantsCursor, new String[] { DatabaseHelper.ID,
                        DatabaseHelper.ALAMAT, DatabaseHelper.TANGGAL_AKHIR },
                new int[] { R.id.id, R.id.alamat, R.id.tglakhir });

        setListAdapter(adapter);
        registerForContextMenu(getListView());

这是完整的代码活动

package hariff.ltis.petaktetap;

import hariff.ltis.mainmenu.R;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class MainPetakTetap extends ListActivity {
    private int year;
    private int month;
    private int day;
    static final int DATE_DIALOG_ID = 999;
    private LocationManager lm;
    private LocationListener locListener;
    private TextView latTxt, lonTxt;
    public static final int DIALOG_DATE_AWAL = 5;
    public static final int DIALOG_DATE_AKHIR = 6;
    Intent intent = null;
    private static final int ADD_ID = Menu.FIRST + 1;
    private static final int DELETE_ID = Menu.FIRST + 3;
    private static final int UPDATE_ID = Menu.FIRST + 4;
    private static final int DETAIL_ID = Menu.FIRST + 5;
    private static final int CANCEL = Menu.FIRST + 6;
    public static final int SHOW_SUB_ACTIVITY_VIEW = 3;
    private DatabaseHelper db = null;
    private DatabaseHelper ds = null;
    private Cursor constantsCursor = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.banner);

        //ds = new DatabaseHelper(getApplicationContext());
        //ds.loadAll();

        db = new DatabaseHelper(this);
        constantsCursor = db.getReadableDatabase().rawQuery(
                "SELECT _ID, alamat, tglb " + "FROM petak_tetap ORDER BY _ID",
                null);

        ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.row,
                constantsCursor, new String[] { DatabaseHelper.ID,
                        DatabaseHelper.ALAMAT, DatabaseHelper.TANGGAL_AKHIR },
                new int[] { R.id.id, R.id.alamat, R.id.tglakhir });

        setListAdapter(adapter);
        registerForContextMenu(getListView());


        Button button = (Button) findViewById(R.id.btnKembali);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                LogOut();
                setResult(RESULT_OK, null);
                finish();
            }
        });

        button = (Button) findViewById(R.id.btnDataBaru);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                add();
            }
        });

    }// onCreate

    private void LogOut(){

    }//LogOut

    @Override
    public void onDestroy() {
        super.onDestroy();

        constantsCursor.close();
        db.close();
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenu.ContextMenuInfo menuInfo) {
        menu.add(Menu.NONE, DETAIL_ID, Menu.NONE, "Detail");
        menu.add(Menu.NONE, UPDATE_ID, Menu.NONE, "Update");
        menu.add(Menu.NONE, DELETE_ID, Menu.NONE, "Delete");
        menu.add(Menu.NONE, CANCEL, Menu.NONE, "Back")

        .setAlphabeticShortcut('d');
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {

        case DETAIL_ID:
            AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
                    .getMenuInfo();

            detail(info.id);
            return (true);

        case DELETE_ID:
            AdapterView.AdapterContextMenuInfo infoDetail = (AdapterView.AdapterContextMenuInfo) item
                    .getMenuInfo();

            delete(infoDetail.id);
            return (true);

        case UPDATE_ID:
            AdapterView.AdapterContextMenuInfo infoCode = (AdapterView.AdapterContextMenuInfo) item
            .getMenuInfo();

            addCode(infoCode.id);
            return (true);

        case CANCEL:

        }

        return (super.onOptionsItemSelected(item));
    }

    private LocationManager lman;
    private LocationListener locaListener;
    private TextView latTxtt, lonTxtt;
    private EditText tvDisplayDateAwal, tvDisplayDateAkhir;
    private DatePicker dpResult;

    private void add() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View addView = inflater.inflate(R.layout.add_edit, null);
        latTxtt = (TextView) addView.findViewById(R.id.latitudeTxtt);
        lonTxtt = (TextView) addView.findViewById(R.id.longitudeTxtt);

        lman = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locaListener = new MyLocationListenerDialog();
        lman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 10,
                locaListener);
        final DialogWrapper wrapper = new DialogWrapper(addView);

        tvDisplayDateAwal = (EditText) addView.findViewById(R.id.tglawal);
        tvDisplayDateAkhir = (EditText) addView.findViewById(R.id.tglakhir);
        dpResult = (DatePicker) addView.findViewById(R.id.dpResult);
        dpResult.setVisibility(View.GONE);

        final Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day = c.get(Calendar.DAY_OF_MONTH);

        // set current date into textview
        tvDisplayDateAkhir.setText(new StringBuilder()
                // Month is 0 based, just add 1
                .append(day).append("-").append(month + 1).append("-")
                .append(year).append(" "));

        // set current date into datepicker
        dpResult.init(year, month, day, null);
        Date date1 = (Date) new Date(dpResult.getYear() - 1900,
                dpResult.getMonth(), dpResult.getDayOfMonth());
        SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy");
        String dateString = dates.format(date1);
        tvDisplayDateAkhir.setText(dateString);

        View showDlgAwal = addView.findViewById(R.id.tglawal);
        showDlgAwal.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                showDialog(DIALOG_DATE_AWAL);
            }
        });

        View showDlgAkhir = addView.findViewById(R.id.tglakhir);
        showDlgAkhir.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                showDialog(DIALOG_DATE_AKHIR);
            }
        });


        Dialog dialog = null;

        new AlertDialog.Builder(this)

                .setTitle(R.string.add_title)
                .setView(addView)
                .setPositiveButton(R.string.ok,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int whichButton) {
                                processAdd(wrapper);
                                // stop gps
                                lman.removeUpdates(locaListener);
                            }
                        })

                .setNegativeButton(R.string.cancel,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int whichButton) {
                                // stop the gps when cancel
                                lman.removeUpdates(locaListener);
                            }
                        }).show();


    }// akhir fungsi add



    public Dialog onCreateDialog(int id) {
        switch (id) {
        case (DIALOG_DATE_AWAL):
            return new DatePickerDialog(this, datePickerListenerAwal, year,
                    month, day);

        case (DIALOG_DATE_AKHIR):
            return new DatePickerDialog(this, datePickerListenerAkhir, year,
                    month, day);
        }
        return null;
    }// onCreateDialog

    // isi dialog awal
    private DatePickerDialog.OnDateSetListener datePickerListenerAwal = new DatePickerDialog.OnDateSetListener() {

        // when dialog box is closed, below method will be called.
        public void onDateSet(DatePicker view, int selectedYear,
                int selectedMonth, int selectedDay) {
            year = selectedYear;
            month = selectedMonth;
            day = selectedDay;

            // set selected date into textview
            tvDisplayDateAwal.setText(new StringBuilder().append(day)
                    .append("-").append(month + 1).append("-").append(year)
                    .append(" "));

            // set selected date into datepicker also
            dpResult.init(year, month, day, null);

            Date date1 = (Date) new Date(dpResult.getYear() - 1900,
                    dpResult.getMonth(), dpResult.getDayOfMonth());
            SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy");
            String dateString = dates.format(date1);
            tvDisplayDateAwal.setText(dateString);
        }
    };

    // isi dialog akhir
    private DatePickerDialog.OnDateSetListener datePickerListenerAkhir = new DatePickerDialog.OnDateSetListener() {

        // when dialog box is closed, below method will be called.
        public void onDateSet(DatePicker view, int selectedYear,
                int selectedMonth, int selectedDay) {
            year = selectedYear;
            month = selectedMonth;
            day = selectedDay;

            // set selected date into textview
            tvDisplayDateAkhir.setText(new StringBuilder().append(day)
                    .append("-").append(month + 1).append("-").append(year)
                    .append(" "));

            // set selected date into datepicker also
            dpResult.init(year, month, day, null);

            Date date1 = (Date) new Date(dpResult.getYear() - 1900,
                    dpResult.getMonth(), dpResult.getDayOfMonth());
            SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy");
            String dateString = dates.format(date1);
            tvDisplayDateAkhir.setText(dateString);
        }
    };

    private class MyLocationListenerDialog implements LocationListener {
        @Override
        public void onLocationChanged(Location loc) {
            // TODO Auto-generated method stub
            if (loc != null) {
                latTxtt.setText(String.valueOf(loc.getLatitude()));
                lonTxtt.setText(String.valueOf(loc.getLongitude()));
            }
        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }//onProviderDisabled

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }//onProviderEnabled

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }//onStatusChanged

        protected void onPause() {
            lman.removeUpdates(locaListener);
            onPause();
        }

        private void stopListening() {
            if (lman != null) {
                lman.removeUpdates(this);
            }
        }

    }



    private void detail(final long rowId) {
        if (rowId > 0) {
            LayoutInflater inflater = LayoutInflater.from(this);
            View addView = inflater.inflate(R.layout.detail_tetap, null);

            final DialogWrapper wrapper = new DialogWrapper(addView);
            TextView idDt = (TextView) addView.findViewById(R.id.idDetail);
            TextView codeTxtDt = (TextView) addView
                    .findViewById(R.id.codeDetail);
            TextView alamatTxtDt = (TextView) addView
                    .findViewById(R.id.alamatDetail);
            TextView batasTxtDt = (TextView) addView
                    .findViewById(R.id.batasDetail);
            TextView latTxtDt = (TextView) addView.findViewById(R.id.latDetail);
            TextView lonTxtDt = (TextView) addView.findViewById(R.id.lonDetail);
            TextView luasTxtDt = (TextView) addView
                    .findViewById(R.id.luasDetail);
            TextView tglAwaltxtDt = (TextView) addView
                    .findViewById(R.id.tglAwalDetail);
            TextView tglAkhirtxtDt = (TextView) addView
                    .findViewById(R.id.tglAkhirDetail);
            // View editTextHidden = (EditText) findViewById(R.id.txtHidden);
            // database handler
            DatabaseHelper db = new DatabaseHelper(getApplicationContext());
            // Spinner Drop down elements
            SQLiteDatabase dbs = db.getReadableDatabase();

            Cursor cursor = dbs.rawQuery("SELECT * FROM petak_tetap where _ID="
                    + rowId + "", null);
            if (cursor.moveToFirst()) {
                do {
                    String noId = cursor.getString(0); // Here you can get data
                                                        // from table and stored
                                                        // in string if it has
                                                        // only one string.
                    String code = cursor.getString(1);
                    String alamat = cursor.getString(2);
                    String batas = cursor.getString(3);
                    String lat = cursor.getString(4);
                    String lon = cursor.getString(5);
                    String luas = cursor.getString(6);
                    String tglAwal = cursor.getString(7);
                    String tglAkhir = cursor.getString(8);

                    idDt.setText(noId);
                    codeTxtDt.setText(code);
                    alamatTxtDt.setText(alamat);
                    batasTxtDt.setText(batas);
                    latTxtDt.setText(lat);
                    lonTxtDt.setText(lon);
                    luasTxtDt.setText(luas);
                    tglAwaltxtDt.setText(tglAwal);
                    tglAkhirtxtDt.setText(tglAkhir);

                } while (cursor.moveToNext());
            }
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
            new AlertDialog.Builder(this)
                    .setTitle(R.string.detail_title)

                    .setView(addView)
                    .setPositiveButton(R.string.ok,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int whichButton) {
                                    // ignore, just dismiss
                                }
                            }).show();
        }
    }


    private void addCode(final long rowId) {
        if (rowId > 0) {

            // View editTextHidden = (EditText) findViewById(R.id.txtHidden);
            // database handler
            DatabaseHelper db = new DatabaseHelper(getApplicationContext());
            // Spinner Drop down elements
            SQLiteDatabase dbs = db.getReadableDatabase();

            Cursor cursor = dbs.rawQuery("SELECT * FROM petak_tetap where _ID="
                    + rowId + "", null);
            if (cursor.moveToFirst()) {
                do {
                    String noId = cursor.getString(0); // Here you can get data
                                                        // from table and stored
                                                        // in string if it has
                                                        // only one string.
                    String code = cursor.getString(1);
                    String alamat = cursor.getString(2);
                    String batas = cursor.getString(3);
                    String lat = cursor.getString(4);
                    String lon = cursor.getString(5);
                    String luas = cursor.getString(6);
                    String tglAwal = cursor.getString(7);
                    String tglAkhir = cursor.getString(8);
                    Intent intent = new Intent(MainPetakTetap.this, MainUpdate.class);
                    intent.putExtra("new_variable_name",code);
                    intent.putExtra("row_id",noId);
                    intent.putExtra("tanggal_akhir",tglAkhir);
                    startActivity(intent);

                } while (cursor.moveToNext());
            }
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }


            //Bundle extras = new Bundle();

            //intent.putExtras(extras);


        }
    }


    private void delete(final long rowId) {
        if (rowId > 0) {
            new AlertDialog.Builder(this)
                    .setTitle(R.string.delete_title)
                    .setPositiveButton(R.string.ok,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int whichButton) {
                                    processDelete(rowId);
                                }
                            })
                    .setNegativeButton(R.string.cancel,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int whichButton) {
                                    // ignore, just dismiss
                                }
                            }).show();
        }
    }

    private void processAdd(DialogWrapper wrapper) {
        ContentValues values = new ContentValues(2);

        values.put(DatabaseHelper.CODE, wrapper.getCode());
        values.put(DatabaseHelper.ALAMAT, wrapper.getAlamat());
        values.put(DatabaseHelper.BATAS, wrapper.getBatas());
        values.put(DatabaseHelper.LAT, wrapper.getLat());
        values.put(DatabaseHelper.LON, wrapper.getLon());
        values.put(DatabaseHelper.LUAS, wrapper.getLuas());
        values.put(DatabaseHelper.TANGGAL_AWAL, wrapper.getTglA());
        values.put(DatabaseHelper.TANGGAL_AKHIR, wrapper.getTglB());

        db.getWritableDatabase().insert("petak_tetap", DatabaseHelper.ALAMAT,
                values);
        constantsCursor.requery();
    }

    private void processDelete(long rowId) {
        String[] args = { String.valueOf(rowId) };

        db.getWritableDatabase().delete("petak_tetap", "_ID=?", args);
        constantsCursor.requery();
    }

    class DialogWrapper {
        EditText codeField = null;
        EditText alamatField = null;
        EditText batasField = null;
        EditText luasField = null;
        EditText tglAField = null;
        EditText tglBField = null;
        TextView latField = null;
        TextView lonField = null;
        View base = null;

        DialogWrapper(View base) {
            this.base = base;
            tglBField = (EditText) base.findViewById(R.id.tglakhir);
        }

        String getCode() {
            return (getCodeField().getText().toString());
        }

        String getAlamat() {
            return (getAlamatField().getText().toString());
        }

        String getBatas() {
            return (getBatasField().getText().toString());
        }

        String getLuas() {
            return (getLuasField().getText().toString());
        }

        String getTglA() {
            return (getTglAField().getText().toString());
        }

        String getTglB() {
            return (getTglBField().getText().toString());
        }

        String getLat() {
            return (getLatField().getText().toString());
        }

        String getLon() {
            return (getLonField().getText().toString());
        }

        private EditText getCodeField() {
            if (codeField == null) {
                codeField = (EditText) base.findViewById(R.id.code);
            }
            return (codeField);
        }

        private EditText getAlamatField() {
            if (alamatField == null) {
                alamatField = (EditText) base.findViewById(R.id.alamat);
            }

            return (alamatField);
        }

        private EditText getBatasField() {
            if (batasField == null) {
                batasField = (EditText) base.findViewById(R.id.batas);
            }

            return (batasField);
        }

        private TextView getLatField() {
            if (latField == null) {
                latField = (TextView) base.findViewById(R.id.latitudeTxtt);
            }

            return (latField);
        }

        private TextView getLonField() {
            if (lonField == null) {
                lonField = (TextView) base.findViewById(R.id.longitudeTxtt);
            }

            return (lonField);
        }

        private EditText getLuasField() {
            if (luasField == null) {
                luasField = (EditText) base.findViewById(R.id.luas);
            }

            return (luasField);
        }

        private EditText getTglAField() {
            if (tglAField == null) {
                tglAField = (EditText) base.findViewById(R.id.tglawal);
            }

            return (tglAField);
        }

        private EditText getTglBField() {
            if (tglBField == null) {
                tglBField = (EditText) base.findViewById(R.id.tglakhir);
            }

            return (tglBField);
        }
    }
}

如何解决?

4

1 回答 1

0

更新sqlite在listview android中不起作用

您没有指定您使用的是哪种适配器。但可能有一些CursorAdapter

所以你应该调用cursor.requery()或者你可以再次执行查询来获取新的Cursor,然后将这个新的Cursor交换到CursorAdapter中。

如果第一种方法不起作用,您也可以尝试使用changeCursor()或在您的适配器上。swapCursor()

yourAdapter.changeCursor(newCursor);

如果你不使用 CursorAdapter 有方法notifyDataSetChanged()

于 2013-03-13T08:23:46.470 回答