如何使用数据库查询在其他活动中显示listview的数据?

时间:2017-03-31 12:46:42

标签: android sqlite listview

我有一个listview,其值为两个edittext。第一个sqlite数据库保存这些edittextand的值,然后在listviews中转换它。我想要的是当用户点击列表项时,它将使用数据库查询显示下一个活动中该项的值。谁能告诉我怎么能这样做呢。请详细回答我,因为我是android的新手

2 个答案:

答案 0 :(得分:0)

在项目上单击获取项目的行ID。 使用行id获取特定行

来调用查询
String selection = KEYID + " = ? ";
String[] selectionArgs = new String[]{rowId};
        Cursor cursor = database.query(TABLENAME, null, selection, selectionArgs, null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                //PARSE AND RETURN DATA
            }
        }

答案 1 :(得分:0)

            **Check this full code   MainActivity**
            package com.example.developer.database;
            import android.content.DialogInterface;
            import android.content.Intent;
            import android.database.Cursor;
            import android.database.sqlite.SQLiteDatabase;
            import android.os.Bundle;
            import android.os.Environment;
            import android.support.v7.app.AlertDialog;
            import android.support.v7.app.AppCompatActivity;
            import android.text.InputType;
            import android.util.Patterns;
            import android.view.View;
            import android.widget.Button;
            import android.widget.ListView;
            import android.widget.TextView;


            import com.example.developer.database.helper.DBhelper;
            import com.example.developer.database.model.Contact;
            import com.example.developer.database.model.MyListAdapter;

            import java.io.BufferedWriter;
            import java.io.File;
            import java.io.FileWriter;
            import java.util.ArrayList;

            public class MainActivity extends AppCompatActivity implements View.OnClickListener {
                DBhelper dBhelper;
                private Button SUBMIT;
                SQLiteDatabase sqldb;
                TextView infotext;
                private Button edit;
                private String[] arrText =
                        new String[]{"First Name","useremail", "password"
                                ,"city","phone no"};
                private String[]arrcity=new String[]{"INDIA","PAKISTAN","CHINA"};
                //    private String[] arrTemp;
                ArrayList<Contact> arrlst = new ArrayList<>();
                private MyListAdapter myListAdapter;

                private String adap1="adap1";


                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
                    edit=(Button)findViewById(R.id.next);
                    infotext=(TextView) findViewById(R.id.infotext);

                    edit.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent i=new Intent(MainActivity.this,Show.class);
                            startActivity(i);
                        }
                    });


                    dBhelper=new DBhelper(this);
                    //arrTemp = new String[arrText.length];


                    for (int i = 0; i < arrText.length; i++) {
                        Contact reg =new Contact();
                        reg.setFieldName(arrText[i]);
                        // reg.setValue("");

                        switch (i){
                            case 5:
                                reg.setInput_type(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                                break;
                            case 6:
                                reg.setInput_type(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                                break;
                        }

                        arrlst.add(reg);
                    }

                    myListAdapter = new MyListAdapter(MainActivity.this,arrlst,adap1);

                    ListView listView = (ListView) findViewById(R.id.listViewMain);
                    listView.setAdapter(myListAdapter);

                    setupViews();

                }
                public void setupViews() {
                    SUBMIT = (Button) findViewById(R.id.submit);

                    SUBMIT.setOnClickListener(MainActivity.this);

                }


                @Override
                public void onClick(View v) {

                    if (v.getId() == R.id.submit) {
                        String NAME=arrlst.get(0).getValue();
                        String Email=arrlst.get(1).getValue();
                        String Password=arrlst.get(2).getValue();
                        String City=AppData.city;
                        String PhoneNo=arrlst.get(4).getValue();

                        arrlst.get(0).setError("");
                        arrlst.get(1).setError("");
                        arrlst.get(2).setError("");
                        arrlst.get(3).setError("");
                        arrlst.get(4).setError("");

                        if(NAME.length()<1) {

            //                alert();
                            arrlst.get(0).setError("Not a valid Name");
                            myListAdapter.notifyDataSetChanged();

                        }
                        else if(NAME.length()<1)
                        {
                            alert();
                        }
                        else if(Password.length()<1){
                            alert();
                        }
                        else if (City.isEmpty()){
                            alert();
                        }
                        else if(!isValidEmail(Email) ){
                            // Toast.makeText(getBaseContext(), "please give proper email", Toast.LENGTH_SHORT).show();
                            arrlst.get(1).setError("Not a valid email");
                            myListAdapter.notifyDataSetChanged();
                        }
                        else {
                            dBhelper.inserRecord(NAME,Email,Password,City,PhoneNo,AppData.city_pos);
                            Toast.makeText(MainActivity.this, "inserted.", Toast.LENGTH_LONG).show();
                            Intent i=new Intent(MainActivity.this,Show.class);
                            startActivity(i);
                        }

                    }
                }
                public void alert(){
                    AlertDialog.Builder adb=new AlertDialog.Builder(MainActivity.this);
                    adb.setTitle("UnSucessful");
                    adb.setMessage("You're not Successfully Registered!");
                    adb.setPositiveButton("OK",new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();

                        }
                    });
                    AlertDialog AD=adb.create();
                    AD.show();
                }
                private boolean isValidEmail(String EMAIL) {

                    return Patterns.EMAIL_ADDRESS.matcher(EMAIL).matches();
                }


            }

            **Adapter for MainActivity**
        package com.example.developer.database.adapter;

        import android.app.Activity;
        import android.content.Context;
        import android.text.Editable;
        import android.text.TextWatcher;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.AdapterView;
        import android.widget.ArrayAdapter;
        import android.widget.BaseAdapter;
        import android.widget.EditText;
        import android.widget.Spinner;
        import android.widget.TextView;

        import com.example.developer.database.AppData;
        import com.example.developer.database.MainActivity;
        import com.example.developer.database.R;
        import com.example.developer.database.helper.DBhelper;
        import com.example.developer.database.model.Contact;

        import java.util.ArrayList;

        /**
         * Created by sanjeev on 31/3/17.
         */
        public class MyListAdapter extends BaseAdapter {

            Context context;

            ArrayList<Contact> arrlst;
            LayoutInflater inflater;
            ArrayList<String> citylist=new ArrayList<>();

            String dec = "";
            String adap1 = "";
            String ada2 = "";
            private Contact contact ;

            public MyListAdapter(Activity activity, ArrayList<Contact> arrlst,Contact contact,String ada2) {
                this.context = activity;
                this.arrlst = arrlst;
                inflater = activity.getLayoutInflater();
                this.contact = contact;
                this.ada2 = ada2;
                dec = ada2;
                citylist.add("Kolkata");
                citylist.add("burdwan");
                citylist.add("bankura");citylist.add("mednipur");citylist.add("birbhum");
                citylist.add("malda");
                citylist.add("Coachbihar");
            }

            public MyListAdapter(MainActivity mainActivity, ArrayList<Contact> arrlst, String adap1) {
                this.context = mainActivity;
                this.arrlst = arrlst;
                inflater = mainActivity.getLayoutInflater();
                this.adap1 = adap1;
                dec = adap1;

                citylist.add("Kolkata");
                citylist.add("burdwan");
                citylist.add("bankura");citylist.add("mednipur");citylist.add("birbhum");
                citylist.add("malda");
                citylist.add("Coachbihar");
            }

            @Override
            public int getCount() {

                Log.d("ppp",""+arrlst.size());
                return arrlst.size();
            }

            @Override
            public Object getItem(int position) {
                return arrlst.get(position);
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            private class ViewHolder {
                TextView textView1;
                EditText editText1;
                public Spinner spinner;

                public ViewHolder(View item) {
                    editText1 = (EditText) item.findViewById(R.id.editText1);
                }

            }

            @Override
            public View getView(final int position, View convertView, ViewGroup parent) {
                final int pos = position;

                final ViewHolder holder;
                if (pos == 3) {
                    convertView = inflater.inflate(R.layout.spinner, null, false);

                } else {
                    convertView = inflater.inflate(R.layout.layout, null, false);
                }


                    holder = new ViewHolder(convertView);
                    convertView.setTag(holder);

                if(pos==3){
                    holder.spinner = (Spinner) convertView.findViewById(R.id.sp);
                    holder.textView1 = (TextView) convertView.findViewById(R.id.textView1);

                }
                else{
                    holder.textView1 = (TextView) convertView.findViewById(R.id.textView1);
                    holder.editText1 = (EditText) convertView.findViewById(R.id.editText1);

                    holder.textView1.setText(arrlst.get(pos).getFieldName());
                }

                if (pos == 3) {

                    holder.textView1.setText(arrlst.get(3).getFieldName());
                    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
                            (context, android.R.layout.simple_spinner_item,citylist);

                    dataAdapter.setDropDownViewResource
                            (android.R.layout.simple_spinner_dropdown_item);

                    holder.spinner.setAdapter(dataAdapter);

                    if(contact!=null) {

                        holder.spinner.setSelection(contact.getCITYPOSITION());
                    }

                    holder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            AppData.city = holder.spinner.getSelectedItem().toString();
                            AppData.city_pos= holder.spinner.getSelectedItemPosition();
                        }
                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {

                        }
                    });

                }else{
                    holder.editText1.setTag(pos);
                    holder.editText1.setHint(arrlst.get(pos).getFieldName());
                    holder.editText1.setText(arrlst.get(pos).getValue());
                    holder.editText1.setInputType(arrlst.get(pos).getInput_type());
                }



                if (pos == 3) {

                }else {

                if(!arrlst.get(pos).getError().equalsIgnoreCase("")){
                    holder.editText1.setError(arrlst.get(pos).getError());
                    holder.editText1.requestFocus();
                }

                holder.editText1.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void afterTextChanged(Editable editable) {
                        Log.d("POS", "" + pos + " VAL" + editable.toString());
                        int pos = (int) holder.editText1.getTag();

                        arrlst.get(pos).setValue(editable.toString());

                    }
                });
                }
                return convertView;
            }

        }
        **Database code**

            package com.example.developer.database.helper;

        import android.content.ContentValues;
        import android.content.Context;
        import android.database.Cursor;
        import android.database.sqlite.SQLiteDatabase;
        import android.database.sqlite.SQLiteOpenHelper;
        import android.util.Log;

        import com.example.developer.database.model.Contact;

        import java.util.ArrayList;

        public class DBhelper extends SQLiteOpenHelper {

            private static String CREATE_TABLE1;

            //    Database name
            static String DATABASE_NAME = "EmployeeRecords";

            //    Talble name
            public static final String TABLE1_NAME = "employee";

            //      Fields for table
            public static final String ID = "id";
            public static final String NAME = "name";
            public static final String EMAIL = "email";
            public static final String PASSWORD = "password";
            public static final String CITY = "city";
            public static final String PHONE = "phone";
            public  static final String CITYPOS= "city_pos";


            //      Required resorces to manage database
            private ContentValues cValues;
            private SQLiteDatabase dataBase = null;
            private Cursor cursor;

            public DBhelper(Context context) {
                super(context, context.getExternalFilesDir(null).getAbsolutePath()
                        + "/" + DATABASE_NAME, null, 1);
            }
            @Override
            public void onCreate(SQLiteDatabase db) {
                CREATE_TABLE1 = "CREATE TABLE " + TABLE1_NAME +"("
                        + ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "
                        + NAME + " TEXT NOT NULL, "
                        + EMAIL + " TEXT NOT NULL, "
                        + PASSWORD + " TEXT NOT NULL, "+ CITY + " TEXT NOT NULL, "+ PHONE + " TEXT NOT NULL, "+ CITYPOS + " INTEGER) ";


                db.execSQL(CREATE_TABLE1);

            }

            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

                db.execSQL("DROP TABLE IF EXISTS " + TABLE1_NAME);

                onCreate(db);
            }

            public void inserRecord(String name, String email , String password , String city, String phone, int city_pos) {

                dataBase = getWritableDatabase();
                cValues = new ContentValues();

                cValues.put(NAME, name);
                cValues.put(EMAIL, email);
                cValues.put(PASSWORD, password);
                cValues.put(CITY, city);
                cValues.put(PHONE, phone);
                cValues.put(CITYPOS, city_pos);

                // insert data into database
                dataBase.insert(TABLE1_NAME, null, cValues);

                dataBase.close();
            }
            public void updateRecord(String name, String email ,String password , String city , String phone,int city_pos) {

                dataBase = getWritableDatabase();

                cValues = new ContentValues();

                if(name!=null) {

                    cValues.put(NAME, name);
                }
                if(email!=null) {
                    cValues.put(EMAIL, email);
                } if(password!=null) {
                    cValues.put(PASSWORD, password);
                } if(city!=null) {
                    cValues.put(CITY, city);
                } if(phone!=null) {
                    cValues.put(PHONE, phone);
                }
                    cValues.put(CITYPOS, city_pos);



        //    Update data from database table
                dataBase.update(DBhelper.TABLE1_NAME, cValues,
                        null, null);

                dataBase.close();
            }



            public ArrayList<Contact> getValues() {
                ArrayList<Contact> values = new ArrayList<Contact>();
                String selectQuery = "SELECT  * FROM " + TABLE1_NAME;
                SQLiteDatabase db = this.getReadableDatabase();
                Cursor cursor = db.rawQuery(selectQuery, null);
                if(cursor.moveToFirst()) {
                    do {
                        Contact contact = new Contact();
                        contact.setID(cursor.getString(0));
                        contact.setNAME(cursor.getString(1));
                        contact.setEMAIL(cursor.getString(2));
                        contact.setPASSWORD(cursor.getString(3));
                        contact.setCITY(cursor.getString(4));
                        contact.setPHONE(cursor.getString(5));
                        contact.setCITYPOSITION(cursor.getInt(6));
                        Log.d("jjj","ghh"+cursor);
        // Adding contact to list
                        values.add(contact);
                     //
        //  values.add(cursor.getString(cursor.getColumnInde"value")));
                    }while(cursor.moveToNext());
                }
                cursor.close();
                db.close();
                return values;
            }


            public void deleteUser(String id)
            {
                SQLiteDatabase db = this.getWritableDatabase();
                try
                {
                    db.delete(TABLE1_NAME, "ID = ?", new String[] { id });
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
                finally
                {
                    db.close();
                }
            }

            public Contact getContact(String id) {
                SQLiteDatabase db = this.getReadableDatabase();
                Cursor cursor = db.query(TABLE1_NAME, new String[] { ID,
                                NAME, EMAIL, PASSWORD, CITY, PHONE, CITYPOS}, ID + "=?",
                        new String[] { String.valueOf(id) }, null, null, null, null);
                if (cursor != null)
                    cursor.moveToFirst();

                Contact contact = new Contact(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getInt(6));
                Log.d("aaa","ggg"+contact);
        // return contact
                return contact;
            }


        }
        **ShowListActivityAdapter code here**

           package com.example.developer.database.adapter;


    import com.example.developer.database.model.Contact;

    import java.util.ArrayList;

    public class UserAdapter extends BaseAdapter {
        ArrayList<Contact> arrayList;
        Activity activity;
        LayoutInflater infl;
        public UserAdapter(Activity activity, ArrayList<Contact> arrayList) {
            //getting values from MainActivity
            infl = activity.getLayoutInflater();
            this.arrayList = arrayList;
            this.activity = activity;

        }
        @Override
        public int getCount() {
            Log.d("aaa", "" + arrayList.size());
            return arrayList.size();
        }

        @Override
        public Object getItem(int position) {
            return arrayList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }
        static class ViewHolder {
            TextView name;
            TextView email;
            TextView password;
            TextView city;
            TextView phone;

            public ViewHolder(View item) {
                //we have to find the id of listview to avoid viewlost
                name= (TextView)item.findViewById(R.id.name);
                email=(TextView)item.findViewById(R.id.email);
                password=(TextView)item.findViewById(R.id.password);
                city=(TextView)item.findViewById(R.id.city);
                phone=(TextView)item.findViewById(R.id.phone);


            }
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            final int pos = position;
            View view = convertView;
            final  ViewHolder holder ;
    //      view will be null for the first time only
            if (view == null) {
                view = infl.inflate(R.layout.layout1, parent, false);
                holder = new ViewHolder(view);
                view.setTag(holder);

            } else {
                holder = (ViewHolder) view.getTag();
            }
            holder.name.setText(arrayList.get(pos).getNAME());
            holder.email.setText(arrayList.get(pos).getEMAIL());
            holder.password.setText(arrayList.get(pos).getPASSWORD());
            holder.city.setText(arrayList.get(pos).getCITY());
            holder.phone.setText(arrayList.get(pos).getPHONE());



            return view;
        }
    }


    package com.example.developer.database.model;

/**
 * Created by sanjeev on 31/3/17.
 */
public class Contact {
    String fieldName, value;
    int input_type = -1;
    String city;
    String error = "";
    String NAME,EMAIL,PASSWORD,CITY,PHONE,ID;
    int CITYPOSITION;

    public Contact(String string, String string1, String string2, String string3, String string4, int pos) {
        this.NAME = string;
        this.EMAIL = string1;
        this.PASSWORD = string2;
        this.CITY = string3;
        this.PHONE = string4;
        this.CITYPOSITION = pos;
    }

    public Contact() {

    }

    public String getFieldName() {
        return fieldName;
    }

    public void setFieldName(String fieldName) {
        this.fieldName = fieldName;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public int getInput_type() {
        return input_type;
    }

    public void setInput_type(int input_type) {
        this.input_type = input_type;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getID() {
        return ID;
    }

    public void setID(String ID) {
        this.ID = ID;
    }

    public String getNAME() {
        return NAME;
    }

    public void setNAME(String NAME) {
        this.NAME = NAME;
    }

    public String getEMAIL() {
        return EMAIL;
    }

    public void setEMAIL(String EMAIL) {
        this.EMAIL = EMAIL;
    }

    public String getPASSWORD() {
        return PASSWORD;
    }

    public void setPASSWORD(String PASSWORD) {
        this.PASSWORD = PASSWORD;
    }

    public String getCITY() {
        return CITY;
    }

    public void setCITY(String CITY) {
        this.CITY = CITY;
    }

    public String getPHONE() {
        return PHONE;
    }

    public void setPHONE(String PHONE) {
        this.PHONE = PHONE;
    }

    public int getCITYPOSITION() {
        return CITYPOSITION;
    }

    public void setCITYPOSITION(int CITYPOSITION) {
        this.CITYPOSITION = CITYPOSITION;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }
}