如果项目已经在listView中,如何在对话框中显示?

时间:2014-08-16 11:59:04

标签: android sqlite listview

我有一个应用程序,用户可以在edittexts中输入一些值,并在列表视图中查看此值。使用SQLite存储值。到目前为止一切正常。我想要的是在用户尝试添加数据库中已存在的值时出现一个对话框。谁能帮助我用这种方式编写示例?非常感谢!

Absente:

package ro.radioamatori;

import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


@SuppressLint("ShowToast")
public class Absente extends Activity {

    private DbHelper_absente mHelpera;
    private SQLiteDatabase dataBase;
    TextView n;




    private ArrayList<String> userId = new ArrayList<String>();
    private ArrayList<String> user_fName = new ArrayList<String>();
    private ArrayList<String> user_lName = new ArrayList<String>();
    private ArrayList<String> d = new ArrayList<String>();
    private ArrayList<String> stime = new ArrayList<String>();
    private ArrayList<String> etime = new ArrayList<String>();
    private ArrayList<String> freq = new ArrayList<String>();
    private ArrayList<String> mode = new ArrayList<String>();
    private ArrayList<String> station = new ArrayList<String>();
    private ArrayList<String> loc = new ArrayList<String>();
    private ArrayList<String> tqsl = new ArrayList<String>();
    private ArrayList<String> mqsl = new ArrayList<String>();
    private ArrayList<String> comm = new ArrayList<String>();

    private ListView userLista;
    private AlertDialog.Builder build;

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

        userLista = (ListView) findViewById(R.id.Lista);




        TextView getTotalCount = (TextView) findViewById(R.id.textView1);
        getTotalCount.setText("Total conne"+userLista.getCount());

        mHelpera = new DbHelper_absente(this);

        //add new record
        findViewById(R.id.btnAdda).setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                Intent i = new Intent(getApplicationContext(),
                        Adauga_absente.class);
                i.putExtra("update", false);
                startActivity(i);

            }
        });

        //click to update data
        userLista.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {

                Intent i = new Intent(getApplicationContext(),
                        Adauga_absente.class);
                i.putExtra("Fname", user_fName.get(arg2));
                i.putExtra("Lname", user_lName.get(arg2));
                i.putExtra("ID", userId.get(arg2));
                i.putExtra("date", d.get(arg2));
                i.putExtra("date", stime.get(arg2));
                i.putExtra("date", etime.get(arg2));
                i.putExtra("date", freq.get(arg2));
                i.putExtra("date", mode.get(arg2));
                i.putExtra("date", station.get(arg2));
                i.putExtra("date", loc.get(arg2));
                i.putExtra("date", tqsl.get(arg2));
                i.putExtra("date", mqsl.get(arg2));
                i.putExtra("date", comm.get(arg2));
                i.putExtra("update", true);
                startActivity(i);

            }
        });

        //long click to delete data
        userLista.setOnItemLongClickListener(new OnItemLongClickListener() {

            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                    final int arg2, long arg3) {

                build = new AlertDialog.Builder(Absente.this);
                build.setTitle("Esti sigur ca vrei sa stergi? ");
                build.setMessage("Esti sigur ca vrei sa stergi aceasta inregistrare ?");
                build.setPositiveButton("Da",
                        new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog,
                                    int which) {

                                Toast.makeText(
                                        getApplicationContext(), "Inregistrarea a fost stearsa", 3000).show();

                                dataBase.delete(
                                        DbHelper.TABLE_NAME,
                                        DbHelper.KEY_ID + "="
                                                + userId.get(arg2), null);
                                displayData();
                                dialog.cancel();
                            }
                        });

                build.setNegativeButton("Nu",
                        new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog,
                                    int which) {
                                dialog.cancel();
                            }
                        });
                AlertDialog alert = build.create();
                alert.show();

                return true;
            }
        });
    }

    @Override
    protected void onResume() {
        displayData();
        super.onResume();
    }

    /**
     * displays data from SQLite
     */
    private void displayData() {
        dataBase = mHelpera.getWritableDatabase();
        Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
                + DbHelper.TABLE_NAME, null);

        userId.clear();
        user_fName.clear();
        user_lName.clear();
        d.clear();
        stime.clear();
        etime.clear();
        freq.clear();
        mode.clear();
        station.clear();
        loc.clear();
        tqsl.clear();
        mqsl.clear();
        comm.clear();
        if (mCursor.moveToFirst()) {
            do {
                userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
                user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
                user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
                d.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_D)));
                stime.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_STIME)));
                etime.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ETIME)));
                freq.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FREQ)));
                mode.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_MODE)));
                station.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_STATION)));
                loc.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LOC)));
                tqsl.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_TQSL)));
                mqsl.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_MQSL)));
                comm.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_COMM)));


            } while (mCursor.moveToNext());
        }
        NoteAdapter disadpt = new NoteAdapter(Absente.this,userId, user_fName, user_lName, d, stime, etime, freq, mode, station, loc, tqsl, mqsl, comm);
        userLista.setAdapter(disadpt);
        mCursor.close();
    }



}

DBHelper:

package ro.radioamatori;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DbHelper extends SQLiteOpenHelper {
    static String DATABASE_NAME="userdata";
    public static final String TABLE_NAME="user";
    public static final String KEY_FNAME="fname";
    public static final String KEY_ID="id";
    public static final String KEY_LNAME="lname";
    public static final String KEY_D="date";
    public static final String KEY_STIME="stime";
    public static final String KEY_ETIME="etime";
    public static final String KEY_FREQ="freq";
    public static final String KEY_MODE="mode";
    public static final String KEY_STATION="station";
    public static final String KEY_LOC="loc";
    public static final String KEY_TQSL="tqsl";
    public static final String KEY_MQSL="mqsl";
    public static final String KEY_COMM="comm";
    public DbHelper(Context context) {
        super(context, DATABASE_NAME, null, 2);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_D+" TEXT, "+KEY_STIME+" TEXT, "+KEY_ETIME+" TEXT, "+KEY_FREQ+" TEXT, "+KEY_MODE+" TEXT, "+KEY_STATION+" TEXT, "+KEY_LOC+" TEXT, "+KEY_TQSL+" TEXT, "+KEY_MQSL+" TEXT, "+KEY_COMM+" TEXT)";
        db.execSQL(CREATE_TABLE);

    }

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

    }

}

适配器:

  package ro.radioamatori;

    import java.util.ArrayList;

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.TextView;

    public class NoteAdapter extends BaseAdapter {
        private Context mContext;
        private ArrayList<String> id;
        private ArrayList<String> firstName;
        private ArrayList<String> lastName;
        private ArrayList<String> date = new ArrayList<String>();
        private ArrayList<String> stime = new ArrayList<String>();
        private ArrayList<String> etime = new ArrayList<String>();
        private ArrayList<String> freq = new ArrayList<String>();
        private ArrayList<String> mode = new ArrayList<String>();
        private ArrayList<String> station = new ArrayList<String>();
        privat

e ArrayList<String> loc = new ArrayList<String>();
    private ArrayList<String> tqsl = new ArrayList<String>();
    private ArrayList<String> mqsl = new ArrayList<String>();
    private ArrayList<String> comm = new ArrayList<String>();

    public NoteAdapter(Context c, ArrayList<String> id,
            ArrayList<String> fname, ArrayList<String> lname,
            ArrayList<String> date, ArrayList<String> stime,
            ArrayList<String> etime, ArrayList<String> freq,
            ArrayList<String> mode, ArrayList<String> station,
            ArrayList<String> loc, ArrayList<String> tqsl,
            ArrayList<String> mqsl, ArrayList<String> comm) {
        this.mContext = c;

        this.id = id;
        this.firstName = fname;
        this.lastName = lname;
        this.date = date;
        this.stime = stime;
        this.etime = etime;
        this.freq = freq;
        this.mode = mode;
        this.station = station;
        this.loc = loc;
        this.tqsl = tqsl;
        this.mqsl = mqsl;
        this.comm = comm;
    }

    public int getCount() {
        // TODO Auto-generated method stub
        return id.size();
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    public View getView(int pos, View child, ViewGroup parent) {
        Holder mHolder;
        LayoutInflater layoutInflater;
        if (child == null) {
            layoutInflater = (LayoutInflater) mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            child = layoutInflater.inflate(R.layout.note_items, null);
            mHolder = new Holder();
            mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
            mHolder.d = (TextView) child.findViewById(R.id.d);
            mHolder.st = (TextView) child.findViewById(R.id.st);
            mHolder.et = (TextView) child.findViewById(R.id.et);
            mHolder.f = (TextView) child.findViewById(R.id.f);
            mHolder.m = (TextView) child.findViewById(R.id.m);
            mHolder.s = (TextView) child.findViewById(R.id.s);
            mHolder.l = (TextView) child.findViewById(R.id.l);
            mHolder.tq = (TextView) child.findViewById(R.id.tq);
            mHolder.mq = (TextView) child.findViewById(R.id.mq);
            mHolder.c = (TextView) child.findViewById(R.id.c);

            child.setTag(mHolder);
        } else {
            mHolder = (Holder) child.getTag();
        }
        mHolder.txt_id.setText("Connection: " + id.get(pos));
        mHolder.d.setText("Data: " + date.get(pos));
        mHolder.st.setText("Start time: " + stime.get(pos));
        mHolder.et.setText("End time: " + etime.get(pos));
        mHolder.f.setText("Frequency: " + freq.get(pos));
        mHolder.m.setText("Mode: " + mode.get(pos));
        mHolder.s.setText("Station: " + station.get(pos));
        mHolder.l.setText("Location: " + loc.get(pos));
        mHolder.tq.setText("Their QSL: " + tqsl.get(pos));
        mHolder.mq.setText("My QSL: " + mqsl.get(pos));
        mHolder.c.setText("Comment: " + comm.get(pos));


        return child;
    }

    public class Holder {
        TextView d;
        TextView st;
        TextView et;
        TextView f;
        TextView m;
        TextView s;
        TextView l;
        TextView tq;
        TextView mq;
        TextView c;
        TextView txt_id;
        TextView txt_fName;
        TextView txt_lName;
    }

}

Adauga_absente:

package ro.radioamatori;

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

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class Adauga_absente extends Activity implements OnClickListener {
private Button btn_save;
private EditText edit_first,edit_last,d,st,et,f,m,s,l,tq,mq,c;
private DbHelper_absente mHelper;
private SQLiteDatabase dataBase;
private String id,fname,lname,date,stime,etime,freq,mode,station,loc,tqsl,mqsl,comm;
private boolean isUpdate;

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

        btn_save=(Button)findViewById(R.id.save_btna); 
        d=(EditText)findViewById(R.id.d);
        st=(EditText)findViewById(R.id.st);
        et=(EditText)findViewById(R.id.et);
        f=(EditText)findViewById(R.id.f);
        m=(EditText)findViewById(R.id.m);
        s=(EditText)findViewById(R.id.s);
        l=(EditText)findViewById(R.id.l);
        tq=(EditText)findViewById(R.id.tq);
        mq=(EditText)findViewById(R.id.mq);
        c=(EditText)findViewById(R.id.c);

        SimpleDateFormat dateF = new SimpleDateFormat("EEE, d MMM yyyy", Locale.getDefault());
        SimpleDateFormat timeF = new SimpleDateFormat("HH:mm", Locale.getDefault());
        String date = dateF.format(Calendar.getInstance().getTime());
        String time = timeF.format(Calendar.getInstance().getTime());

        d.setText(date);
        st.setText(time);


       isUpdate=getIntent().getExtras().getBoolean("update");
        if(isUpdate)
        {
            id=getIntent().getExtras().getString("ID");
            fname=getIntent().getExtras().getString("Fname");
            lname=getIntent().getExtras().getString("Lname");
            date=getIntent().getExtras().getString("Date");
            stime=getIntent().getExtras().getString("Stime");
            etime=getIntent().getExtras().getString("Etime");
            freq=getIntent().getExtras().getString("Freq");
            mode=getIntent().getExtras().getString("Mode");
            station=getIntent().getExtras().getString("Station");
            loc=getIntent().getExtras().getString("Loc");
            tqsl=getIntent().getExtras().getString("Tqsl");
            mqsl=getIntent().getExtras().getString("Mqsl");
            comm=getIntent().getExtras().getString("Comm");
            edit_first.setText(fname);
            edit_last.setText(lname);
            d.setText(date);
            st.setText(stime);
            et.setText(etime);
            f.setText(freq);
            m.setText(mode);
            s.setText(station);
            l.setText(loc);
            tq.setText(tqsl);
            mq.setText(mqsl);
            c.setText(comm);


        }

         btn_save.setOnClickListener(this);

         mHelper=new DbHelper_absente(this);

    }

    // saveButton click event 
    public void onClick(View v) {
        fname=edit_first.getText().toString().trim();
        lname=edit_last.getText().toString().trim();
        date=d.getText().toString().trim();
        stime=st.getText().toString().trim();
        etime=et.getText().toString().trim();
        freq=f.getText().toString().trim();
        mode=m.getText().toString().trim();
        station=s.getText().toString().trim();
        loc=l.getText().toString().trim();
        tqsl=tq.getText().toString().trim();
        mqsl=mq.getText().toString().trim();
        comm=c.getText().toString().trim();
        if(fname.length()>0 && lname.length()>0 && date.length()>0 && stime.length()>0 && etime.length()>0 && freq.length()>0 && mode.length()>0 && station.length()>0 && loc.length()>0 && tqsl.length()>0 && mqsl.length()>0 && comm.length()>0)
        {
            saveData();
        }
        else
        {


        }



    }

    /**
     * save data into SQLite
     */
    private void saveData(){
        dataBase=mHelper.getWritableDatabase();
        ContentValues values=new ContentValues();

        values.put(DbHelper.KEY_FNAME,fname);
        values.put(DbHelper.KEY_LNAME,lname );
        values.put(DbHelper.KEY_D,date );
        values.put(DbHelper.KEY_STIME,stime );
        values.put(DbHelper.KEY_ETIME,etime );
        values.put(DbHelper.KEY_FREQ,freq );
        values.put(DbHelper.KEY_MODE,mode );
        values.put(DbHelper.KEY_STATION,station );
        values.put(DbHelper.KEY_LOC,loc );
        values.put(DbHelper.KEY_TQSL,tqsl );
        values.put(DbHelper.KEY_MQSL,mqsl );
        values.put(DbHelper.KEY_COMM,comm );


        System.out.println("");
        if(isUpdate)
        {    
            //update database with new data 
            dataBase.update(DbHelper.TABLE_NAME, values, DbHelper.KEY_ID+"="+id, null);
        }
        else
        {
            //insert data into database
            dataBase.insert(DbHelper.TABLE_NAME, null, values);
        }
        //close database
        dataBase.close();
        finish();


    }

}

1 个答案:

答案 0 :(得分:1)

在您的情况下在类DbHelper中编写以下方法,以从List中的sqlite获取所有数据

// Getting All Contacts
        public List<DataOfUser> getAllContacts() {
            List<DataOfUser> dist = new ArrayList<DataOfUser>();
            // Select All Query
            String selectQuery = "SELECT  * FROM " + ITEM.TABLE_DATA;
            SQLiteDatabase db = this.getWritableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);

            // looping through all rows and adding to list
            if (cursor.moveToFirst()) {
                do {
                    DataOfUser contact = new DataOfUser();
                    contact.setID(Integer.parseInt(cursor.getString(0)));
                    contact.setD(cursor.getString(1));
                    contact.setDate(cursor.getString(2));


                    dist.add(contact);
                } while (cursor.moveToNext());
                  //
            }

            // return contact list
            return dist;
        }


//Ii is class with public getters and setters to access data    from sqlite.change according to your need   


public class DataOfUser {

    int _id;
    String _data;
    String _date;

    // Empty constructor
    public DataOfUser(){

    }


    // constructor

    // getting ID
    public int getID(){
        return this._id;
    }

    // setting id
    public void setID(int id){
        this._id = id;
    }

    // getting name
    public String getD(){
        return this._data;
    }

    // setting name
    public void setD(String s){
        this._data = s;
    }
    //
    public void setDate(String string) {
        // TODO Auto-generated method stub
         this._date = string;
    }

   public String getDate(){
            return this._date ;
        }

}




//the code below  is just example to get idea to check same value don't  copy paste it
//code to check already exist value as follows
//List<DataOfUser> dataofuse=new ArrayList<DataOfUser>(); create List<DataOfUser> of  in your code for getting data from sqlite
dataofuse = dbHelper.getAllContacts(); 




                if(dataofuse!=null)

                {            
                     //imp


                            for (DataOfUser dataOfUser2 : dataofuse) {
                            //  (dataOfUser2.getD(),dataOfUser2.getDate(),dataOfUser2.getID())  to get the data                
                                 if(//compare data from edittext and fetch data according to above line is same then)
                                 break;
                            }

                            //write code to show dialog or toast here
                }