在Android中创建脱机SQLite数据库

时间:2014-06-17 05:18:42

标签: android sqlite

我尝试在Android应用程序中为我的发送作业模块创建离线SQLite数据库。但数据库没有在DDMS中创建。告诉我在下面的给定代码中我错了。

    Fregmentsendjob.java

    public class FragmentSendJob extends Fragment implements OnClickListener {
        // this Fragment will be called from MainActivity

        private Button submit,cancel;
        private EditText ename,mobno,picktime,unit,street,suburb,destination,fare,city;
        private Spinner state,group;
        private ViewGroup vgroup ;

            String name,pass;
            String status_key;
            private Typeface ftype;
            private static MyDialog dialog1;


            Bitmap bitmap1, bitmap2,bitmap3;
            Bitmap[] bitmap;
            String[] driver_details;
            private byte imageInByte1[],imageInByte2[],imageInByte3[] ;
            private Context mContext;


            public String advertisement_count;

         private String mename,mmobno,mpicktime,munit,mstreet,msuburb,mstate, msendjob,mcity,mdestination,mfare,mgroup,login_token;
       // private String sename,smobno,spicktime,sunit,sstreet,ssuburb,sstate, ssendjob,scity,sdestination,sfare,sgroup,login_token;
        private static FragmentDialog dialog;
        //private  SendJobDataBase db; 
        private  PasswordDB db; 
        static final int DIALOG_ID = 0;

         private SharedPreferences pref1,pref;
        String latitude,longitude;
        public String job_id;



        public FragmentSendJob(){}

         @Override
         public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
           {
            View rootView = inflater.inflate(R.layout.sendjob_fragment, container, false);
            pref1=this.getActivity().getSharedPreferences("LocDetails", getActivity().MODE_WORLD_READABLE);
            pref=this.getActivity().getSharedPreferences("Driver", getActivity().MODE_WORLD_READABLE);
            login_token=pref.getString("login_token","login_token"); 
            latitude = pref1.getString("latitude","latitude"); 
            longitude = pref1.getString("longitude","longitude"); 

            ename = (EditText) rootView.findViewById(R.id.ename);
            mobno  = (EditText) rootView.findViewById(R.id.mobno);
            picktime  = (EditText) rootView.findViewById(R.id.picktime);
            unit  = (EditText) rootView.findViewById(R.id.unit);
            street  = (EditText) rootView.findViewById(R.id.street);
            suburb  = (EditText) rootView.findViewById(R.id.suburb);
            destination  = (EditText) rootView.findViewById(R.id.destination);
            state = (Spinner) rootView.findViewById(R.id.state);
            fare=(EditText)  rootView.findViewById(R.id.fare);
            group = (Spinner) rootView.findViewById(R.id.group);
            city  = (EditText) rootView.findViewById(R.id.city);
            vgroup = (ViewGroup) rootView.findViewById(R.id.rel); 
            submit = (Button) rootView.findViewById(R.id.submit);


            submit.setOnClickListener(new OnClickListener() {

                    public void onClick(View v) {
                        // TODO Auto-generated method stub


                        new SendJob().execute();
                  /*  Intent intent =new Intent(getActivity(),GetCurrentLocation.class);
                    startActivity(intent); 

                    System.out.println(">>>>>>>>>>>>>>>>>"+latitude+"***********");
                    System.out.println(">>>>>>>>>>>>"+longitude+"***********");*/


                    }

                });



            cancel = (Button) rootView.findViewById(R.id.cancel);
            cancel.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                for (int i = 0, count = vgroup.getChildCount(); i < count; ++i) {
                        View view = vgroup.getChildAt(i);
                        if (view instanceof EditText) {
                            ((EditText)view).setText("");
                        }
                    }

                    }       
            });

            String[] mystate= new String[]{"New South Wales","Victoria","Queensland","Northern Territory","Western Australia","South Australia"};       
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), R.layout.listrow, mystate);

            state.setAdapter(adapter);  

                    state.setOnItemSelectedListener(new OnItemSelectedListener() {

                                public void onItemSelected(AdapterView<?> arg0, View arg1,int pos, long arg3) {
                                    // TODO Auto-generated method stub

                                    mcity =  state.getSelectedItem().toString();

                       String s1=arg0.getItemAtPosition(pos).toString();
                            if(s1.equals("New South Wales"))
                                city.setText("Sydney");
                            else if(s1.equals("Victoria"))
                                city.setText("Melbourne");
                            else if(s1.equals("Queensland"))
                                city.setText("Brisbane");
                            else if(s1.equals("Northern Territory"))
                                city.setText("Darwin");
                            else if(s1.equals("Western Australia"))
                                city.setText("Perth");
                            else if(s1.equals("South Australia"))
                                city.setText("Adelaide");

                                 }
                                public void onNothingSelected(AdapterView<?> arg0) {
                                    // TODO Auto-generated method stub

                                }
                            });


                    String[] mygroups= new String[]{"My Group","My Secondary group","Everyone"};
                    ArrayAdapter<String> adapters = new ArrayAdapter<String>(this.getActivity(),
                            R.layout.listrow, mygroups);
                    group.setAdapter(adapters);

                    group.setOnItemSelectedListener(new OnItemSelectedListener() {

                                public void onItemSelected(AdapterView<?> arg0, View arg1,
                                        int pos, long arg3) {
                                    // TODO Auto-generated method stub

                                    msendjob = group.getItemAtPosition(pos).toString();
                                    //gender.setText(setgender);
                                }

                                public void onNothingSelected(AdapterView<?> arg0) {
                                    // TODO Auto-generated method stub

                                }
                            });
            return rootView;
           }



        private class SendJob extends AsyncTask<String, String, String[]> {
            ProgressDialog pDialog = new ProgressDialog(getActivity());

            @Override
            protected String[] doInBackground(final String... params) 
            {
                ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
                if (conMgr.getActiveNetworkInfo() != null
                        && conMgr.getActiveNetworkInfo().isAvailable()
                        && conMgr.getActiveNetworkInfo().isConnected()) 
                {
                    HttpClient httpclient = new DefaultHttpClient();
                    try 
                    {

                    System.out.print("***** login token *****"+login_token);
                    JSONObject job= new JSONObject();
                    mename = ename.getText().toString();
                    mmobno = mobno.getText().toString();
                    mpicktime = picktime.getText().toString();
                    munit = unit.getText().toString();
                    mstreet = street.getText().toString();
                    msuburb = suburb.getText().toString();
                    mstate = state.getSelectedItem().toString();
                    mcity = city.getText().toString();
                    mdestination = destination.getText().toString();
                    mgroup = group.getSelectedItem().toString();
                    mfare = fare.getText().toString();

                    mename.replace("" ,"%20");
                    mmobno.replace("" ,"%20");
                    mpicktime.replace("" ,"%20");
                    munit.replace("" ,"%20");
                    mstreet.replace("" ,"%20");
                    mstate.replace("" ,"%20"); 
                    msuburb.replace("" ,"%20");
                    mcity.replace("" ,"%20");
                    mdestination.replace("" ,"%20");
                    mgroup.replace("" ,"%20");
                    mfare.replace("" ,"%20");

                         job.put("name",mename);
                         job.put("mobile_no",mmobno);
                         job.put("pickup_time",mpicktime);
                         job.put("unit_no",munit);
                         job.put("street_name",mstreet);
                         job.put("state",mstate);
                         job.put("suburb",msuburb);
                         job.put("city",mcity);
                         job.put("destination",mdestination);
                         job.put("group",mgroup);
                         job.put("fare",mfare);
                         job.put("latitude",latitude);
                         job.put("longitude",longitude);
                         job.put("status_key","2");
                         job.put("method","send_job");
                         job.put("login_token",login_token);

                        StringEntity se = new StringEntity(job.toString());
                        HttpPost httppost = new HttpPost("http://suntechwebsolutions.com/clients/mobileapp_now/webservice.php");
                        httppost.setEntity(se);
                        HttpResponse response = httpclient.execute(httppost);
                        String data = EntityUtils.toString(response.getEntity());
                        Log.i("response", data);

                        System.out.println("response "+data);
                        String call;
                        call = data;

                                    System.out.println("print me............."+call);

                                    JSONObject jo = new JSONObject(data);
                                    Log.d("response", jo.toString(4));

                                    /*JSONObject jobId= jo.getJSONObject("id");  
                                    job_id=jobId.getString("id");*/


                                    if(jo.getString("err-code").equals("0"))
                                    {
                                        final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
                                        alert.setTitle("Alert!!!");
                                        alert.setMessage(jo.getString("message"));
                                        alert.setPositiveButton("Ok",
                                                new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog,
                                                    int whichButton) 
                                            {
                                                pDialog.dismiss();
                                                dialog.dismiss();

                                /*   Intent intent =new Intent(getActivity(),HandleData.class);
                                        intent.putExtra("pickupsuburb", ssuburb);
                                        intent.putExtra("destination", sdestination);
                                        startActivity(intent);*/


                                             }
                                        });
                                        getActivity().runOnUiThread(new Runnable() {
                                            public void run() {
                                                alert.show();
                                            }
                                        });
                                    }
                                    else
                                    {
                                final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
                                        alert.setTitle("Alert !");
                                        alert.setMessage(jo.getString("message"));
                                        alert.setPositiveButton("Ok",
                                                new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog,
                                                    int whichButton) {
                                                dialog.dismiss();


                                            }
                                        });
                                        getActivity().runOnUiThread(new Runnable() 
                                        {
                                            public void run() 
                                            {
                                                pDialog.dismiss();
                                                alert.show();
                                            }
                                        });
                                    }

                                }
                                catch (Exception e) 
                                {
                                    e.printStackTrace();
                                }
                            }
                            return params;
                        }
                        @Override
                        protected void onPostExecute(String[] result) 
                        {

                            super.onPostExecute(result);
                        }       
           }
    public void onClick(View arg0) {
            // TODO Auto-generated method stub

        }

    public void onLocationChanged(Location arg0) {
        // TODO Auto-generated method stub

    }

    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub

    }

    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub

    }

    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // TODO Auto-generated method stub

    }
    }






    **SendJobDatabase.java**

     public class SendJobDataBase 
     {
        private static final  String DATABASE_NAME = "SENDJOB.db";
        private static final int DATABASE_VERSION = 2;
        static final String TABLE_NAME = "jobsend";
        private static final String KEY_ID = "id";
        private static Context context;
        static SQLiteDatabase db;
        private final ArrayList<member> user = new ArrayList<member>();

        OpenHelper helper;
        private SQLiteStatement insertStmt;

//创建字符串值并将该字符串值插入表名

        private static final String INSERT = "insert into " + TABLE_NAME + " (mename,mmobno,mpicktime,munit,mstreet,msuburb,mstate,mcity,mdestination,mfare,mgroup) values (?,?,?,?,?,?,?,?,?,?,?)";

       // private static final String INSERT = "insert into " + TABLE_NAME + " (sename,smobno,spicktime,sunit,sstreet,ssuburb,sstate,scity,sdestination,sfare,sgroup) values (?,?,?,?,?,?,?,?,?,?,?)";
        protected static final String enternpw = null;
        public SendJobDataBase(Context context) {
        SendJobDataBase.context = context;
        OpenHelper openHelper = new OpenHelper(SendJobDataBase.context);
        SendJobDataBase.db = openHelper.getWritableDatabase();
        this.insertStmt = SendJobDataBase.db.compileStatement(INSERT);
        }
        //public long insert(String sename,String smobno,String spicktime,String sunit,String sstreet,String ssuburb,String sstate,String scity,String sdestination,String sfare,String sgroup) {
        public long insert(String mename,String mmobno,String mpicktime,String munit,String mstreet,String msuburb,String mstate,String mcity,String mdestination,String mfare,String mgroup) {

        this.insertStmt.bindString(1, mename);
        this.insertStmt.bindString(2, mmobno);
        this.insertStmt.bindString(3, mpicktime);
        this.insertStmt.bindString(4, munit);
        this.insertStmt.bindString(5, mstreet);
        this.insertStmt.bindString(6, msuburb);
        this.insertStmt.bindString(7, mstate);
        this.insertStmt.bindString(8, mcity);
        this.insertStmt.bindString(9, mdestination);
        this.insertStmt.bindString(10, mfare);
        this.insertStmt.bindString(11, mgroup);

        return this.insertStmt.executeInsert();
        }

        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","sename","smobno","spicktime","sunit","sstreet","ssuburb","sstate","scity","sdestination","sfare","sgroup" }, null, null, null, null, "sename asc");

        Cursor cursor = db.query(TABLE_NAME, new String[] { "id","mename","mmobno","mpicktime","munit","mstreet","msuburb","mstate","mcity","mdestination","mfare","mgroup" }, null, null, null, null, "sename asc");
        int x=0;
        if (cursor.moveToFirst()) {
           do {
            String[] b1=new String[]{cursor.getString(0),cursor.getString(1),cursor.getString(2),
                    cursor.getString(3),cursor.getString(4),cursor.getString(5),
                    cursor.getString(6),cursor.getString(7),cursor.getString(8),cursor.getString(9),cursor.getString(10),cursor.getString(11)};
            list.add(b1);
            x=x+1;
           } while (cursor.moveToNext());
        }
        if (cursor != null && !cursor.isClosed()) {
           cursor.close();
        }
        cursor.close();
        return list;
       }

         public ArrayList<member> getMembersList() {
            ArrayList<member> user = new ArrayList<member>();

            String selectQuery = "SELECT * FROM jobsend WHERE ssendjob LIKE '%One%'" ;

            Cursor cursor = db.rawQuery(selectQuery,null);

             if(cursor != null && cursor.getCount() > 0) {
                 if (cursor.moveToFirst()) {
                do {
                member contact = new member();
                contact.setID(Integer.parseInt(cursor.getString(0)));
              contact.setName(cursor.getString(1));

              user.add(contact);
            } while (cursor.moveToNext());
        }
             }
                  cursor.close();
        return user;  

        }  


        public ArrayList<member> getMembersList2() {
            ArrayList<member> user = new ArrayList<member>();

            String selectQuery = "SELECT * FROM jobsend WHERE ssendjob LIKE '%Two%'" ;

            Cursor cursor = db.rawQuery(selectQuery,null);

             if(cursor != null && cursor.getCount() > 0) {
                 if (cursor.moveToFirst()) {
                do {
                member contact = new member();
                contact.setID(Integer.parseInt(cursor.getString(0)));
              contact.setName(cursor.getString(1));

              user.add(contact);
            } while (cursor.moveToNext());
        }
             }
                  cursor.close();
        return user;  

        }  

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

       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, sename TEXT, smobno TEXT,spicktime TEXT,spickaddr TEXT, sfair TEXT,ssendjob TEXT)");
             db.execSQL("CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY, mename TEXT, mmobno TEXT,mpicktime TEXT,mpickaddr TEXT, mfair TEXT,msendjob TEXT)");


        }

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

     public Cursor rawQuery(String selectQuery ,Object object) {
        // TODO Auto-generated method stub

        return null;
    }    
    public static SendJobDataBase getDBAdapterInstance(FragmentGroups viewPassword) {
        // TODO Auto-generated method stub
        return null;
    }
    public Object getenternpw() {
        // TODO Auto-generated method stub
        return null;
    }
    public static Cursor getSinlgeEntry() {
        // TODO Auto-generated method stub

        Cursor cur =db.rawQuery("SELECT * FROM "+  TABLE_NAME, null);
        // colName1+"='"+name+"'" ->  wherclause
        System.out.println("Record count are "+cur.getCount());
        return cur; 

    }



    static public void close() {
        // TODO Auto-generated method stub

    }
    /* public SendJobDataBase open() throws SQLException {
        // TODO Auto-generated method stub
        db = helper.getWritableDatabase();
        return this;
    }   */
     public SendJobDataBase getWritableDatabase() {
        // TODO Auto-generated method stub
        return null;
    }   


     public void Delete_Contact(int id) {
         SQLiteDatabase db = helper.getWritableDatabase();
        db.delete(TABLE_NAME, KEY_ID + " = ?",
            new String[] { String.valueOf(id) });
        db.close();
        }


     public ArrayList<member> Get_Contacts() {

        try {
            user.clear();

            // Select All Query
            String selectQuery = "SELECT * FROM jobsend";

            SQLiteDatabase db = helper.getWritableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);

            // looping through all rows and adding to list
            if (cursor.moveToFirst()) {
            do {
                member contact = new member();
                contact.setID(Integer.parseInt(cursor.getString(0)));
                contact.setName(cursor.getString(1));
              //  contact.setPhoneNumber(cursor.getString(2));
             //   contact.setEmail(cursor.getString(3));
                // Adding contact to list
                user.add(contact);
            } while (cursor.moveToNext());
            }

            // return contact list
            cursor.close();
            db.close();
            return user;
        } catch (Exception e) {
            // TODO: handle exception
            Log.e("all_contact", "" + e);
        }

        return user;
       }

    }

1 个答案:

答案 0 :(得分:0)

在android中创建sqlite-database-

这是DatabaseHelper.java:

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

            public class DatabaseHelper extends SQLiteOpenHelper {

                private static final String TAG = "DatabaseHelper";

                // Database Version
                private static final int DATABASE_VERSION = 1;

                // Database Name
                private static final String DATABASE_NAME = "DBPRODUCT";

                // Table Names
                private static final String TABLE_REGISTRATION = "tbl_registration";

                //tbl_registration Table- Column Names

                private static final String KEY_ID = "id";
                private static final String KEY_FIRSTNAME = "firstname";
                private static final String KEY_LASTNAME = "lastname";
                private static final String KEY_EMAIL = "email";
                private static final String KEY_MOBILE = "mobile";
                private static final String KEY_PASSWORD = "password";
                private static final String KEY_STATUS = "status";


                // Table Create Statements
                // tbl_registration table create statement
                private static final String CREATE_TABLE_REGISTRATION = "CREATE TABLE "
                        + TABLE_REGISTRATION + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_FIRSTNAME + " TEXT," + KEY_LASTNAME + " TEXT," + KEY_EMAIL + " TEXT," + KEY_MOBILE + " TEXT," + KEY_PASSWORD + " TEXT," + KEY_STATUS + " INTEGER" + ")";


                public DatabaseHelper(Context context) {
                    super(context, DATABASE_NAME, null, DATABASE_VERSION);
                    SQLiteDatabase db = this.getWritableDatabase();

                }

                @Override
                public void onCreate(SQLiteDatabase db) {
                    // creating required tables
                    db.execSQL(CREATE_TABLE_REGISTRATION);

                }

                @Override
                public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                    // on upgrade drop older tables
                    db.execSQL("DROP TABLE IF EXISTS " + TABLE_REGISTRATION);

                    // create new tables
                    onCreate(db);
                }

                //insert in to tbl_registratin
                    public boolean insertRegistration(String firstname, String lastname, String email, String mobile, String password, int status) {
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(KEY_FIRSTNAME, firstname);
                    contentValues.put(KEY_LASTNAME, lastname);
                    contentValues.put(KEY_EMAIL, email);
                    contentValues.put(KEY_MOBILE, mobile);
                    contentValues.put(KEY_PASSWORD, password);
                    contentValues.put(KEY_STATUS, status);
                    SQLiteDatabase db = this.getWritableDatabase();

                    long result = db.insert(TABLE_REGISTRATION, null, contentValues);
                    if (result == -1) {
                        return false;
                    } else {
                        return true;
                    }


                }

                //Get DATA UPDATE
                public boolean updateRegistration(String firstname, String lastname, String mobile, String password,String email, int status)
                {
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(KEY_FIRSTNAME, firstname);
                    contentValues.put(KEY_LASTNAME, lastname);
                    contentValues.put(KEY_MOBILE, mobile);
                    contentValues.put(KEY_PASSWORD, password);
                    contentValues.put(KEY_EMAIL,email);
                    contentValues.put(KEY_STATUS, status);
                    SQLiteDatabase db = this.getWritableDatabase();

            //        long result = db.update(TABLE_REGISTRATION,contentValues, null,null);
                    long result=db.update(TABLE_REGISTRATION,contentValues, KEY_EMAIL +"='" + email +"'", null);
                    if (result == -1) {
                        return false;
                    } else {
                        return true;
                    }

                }

                // Get Data from tbl_registration
                public Cursor getData() {
                    SQLiteDatabase db = this.getWritableDatabase();
                    String qry = "select * from " + TABLE_REGISTRATION;
                    Cursor res = db.rawQuery(qry, null);
                    return res;
                }

                public Cursor getDataForRegistration(String email) {
                    SQLiteDatabase db = this.getWritableDatabase();
                    String qry = "select * from " + TABLE_REGISTRATION + " where " + KEY_EMAIL + "='" + email +"'";
                    Cursor res = db.rawQuery(qry, null);
                    return res;
                }
                //get registered user
                public Cursor getDataForLogin(String email,String password) {
                    SQLiteDatabase db = this.getWritableDatabase();
                    String qry = "select * from " + TABLE_REGISTRATION + " where " + KEY_EMAIL + "='" + email +"'" + " AND "+ KEY_PASSWORD +"='" +password + "'";
                    Cursor res = db.rawQuery(qry, null);
                    return res;
                }
                //delete user
                public Cursor getDeleteForRegistration(String email) {
                    SQLiteDatabase db = this.getWritableDatabase();
                    String qry = "delete from " + TABLE_REGISTRATION + " where " + KEY_EMAIL + "='" + email + "'";
                    Cursor res = db.rawQuery(qry, null);
                    return res;
                }
            }



            **Adapter**


            import android.app.AlertDialog;
            import android.content.Context;
            import android.content.DialogInterface;
            import android.content.Intent;
            import android.database.Cursor;
            import android.view.LayoutInflater;
            import android.view.View;
            import android.view.ViewGroup;
            import android.widget.BaseAdapter;
            import android.widget.ImageView;
            import android.widget.TextView;

            import com.example.san.mydb.R;
            import com.example.san.mydb.model.User;
            import com.example.san.mydb.ui.UpdateprofileActivity;
            import com.example.san.mydb.utils.DatabaseHelper;

            import java.util.ArrayList;
            import java.util.List;

            /**
             * Created by san on 7/26/2017.
             */

            public class UserAdapter extends BaseAdapter {
                List<User> myList = new ArrayList();
                LayoutInflater inflater;
                Context context;
                DatabaseHelper db;
                public UserAdapter(Context context, List<User> listcart) {
                    this.myList = listcart;
                    this.context = context;
                    inflater = LayoutInflater.from(this.context);
                }
                @Override
                public int getCount() {
                    return myList.size();
                }
                @Override
                public User getItem(int position) {
                    return myList.get(position);
                }
                public void addAll(List<User> myList1) {
                    myList.clear();
                    myList.addAll(myList1);
                    notifyDataSetChanged();
                }
                @Override
                public long getItemId(int position) {
                    return 0;
                }
                @Override
                public View getView(final int position, View convertView, ViewGroup parent) {
                    MyViewHolder mViewHolder;
                    if (convertView == null) {
                        convertView = inflater.inflate(R.layout.listitem_user, parent, false);
                        mViewHolder = new MyViewHolder(convertView);
                        convertView.setTag(mViewHolder);
                    } else {
                        mViewHolder = (MyViewHolder) convertView.getTag();
                    }
                    mViewHolder.tvTitle.setText(myList.get(position).userName);
                    mViewHolder.tvTitle.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                            Intent intent=new Intent(context, UpdateprofileActivity.class);
                            intent.putExtra("email",myList.get(position).email);
                            context.startActivity(intent);
                        }
                    });
                    return convertView;
                }
                private class MyViewHolder {
                    TextView tvTitle;
                    TextView txtPrice;
                    ImageView ivDelete;
                    public MyViewHolder(View item) {

                        tvTitle = (TextView) item.findViewById(R.id.tv_username);
                    }
                }
            }



            **Model**

            public class User {
                public String userName;
                public String email;
            }


            **Register**

             private String TAG="RegistrationActivity";
                private TextView tvRegistration;
                private EditText etFirstname;
                private EditText etLastname;
                private EditText etEmail;
                private EditText etMobile;
                private EditText etPassword;
                private EditText etRepassword;
                DatabaseHelper db;

                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_registration);

                    db = new DatabaseHelper(RegistrationActivity.this);
                    etFirstname=(EditText) findViewById(R.id.et_firstname);
                    etLastname=(EditText) findViewById(R.id.et_lastname);
                    etEmail=(EditText) findViewById(R.id.et_email);
                    etMobile=(EditText) findViewById(R.id.et_mobile);
                    etPassword=(EditText) findViewById(R.id.et_password);
                    etRepassword=(EditText) findViewById(R.id.et_repassword);
                    tvRegistration=(TextView)findViewById(R.id.tv_registration);
                    tvRegistration.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
                                    + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
                            String MobilePattern = "[0-9]{10}";
                            if (etFirstname.getText().toString().isEmpty())
                            {
                                etFirstname.setError("Please Enter First Name!");
                                etFirstname.requestFocus();
                            }
                            else if (etLastname.getText().toString().isEmpty())
                            {
                                etLastname.setError("Please Enter Last Name!");
                                etLastname.requestFocus();
                            }
                            else if (etEmail.getText().toString().trim().isEmpty() || !etEmail.getText().toString().trim().matches(EMAIL_PATTERN)) {

                                etEmail.setError("Please Enter valid Email");
                                etEmail.requestFocus();
                            }
                            else if(!etMobile.getText().toString().matches(MobilePattern)) {
                                etMobile.setError("Please enter valid phone number");
                                etMobile.requestFocus();
                            }
                            else if (etPassword.getText().toString().trim().isEmpty()) {
                                etPassword.setError("Please Enter Password!");
                                etPassword.requestFocus();

                            } else if (etRepassword.getText().toString().isEmpty()) {
                                etRepassword.setError("Please Enter Confirm Password!");
                                etRepassword.requestFocus();
                            } else if (!etPassword.getText().toString().trim().equals(etRepassword.getText().toString().trim())) {
                                etRepassword.setError("Password Does Not Match!");
                                etRepassword.requestFocus();
                            }
                            else
                            {
                                getRegistration();
                            }
                        }
                    });
                }

                //this method for user registration
                private void getRegistration()
                {
                    Cursor cursor = db.getDataForRegistration(etEmail.getText().toString());
                    if (cursor.moveToFirst()) {

                        Toast.makeText(RegistrationActivity.this, "User All ready register", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(RegistrationActivity.this, LoginActivity.class);
                        startActivity(intent);
                        finish();
                    }
                    else {
                        boolean isInserted = db.insertRegistration(etFirstname.getText().toString(), etLastname.getText().toString(), etEmail.getText().toString(), etMobile.getText().toString(), etPassword.getText().toString(), 0);
                        if (isInserted) {
                            Log.e(TAG, "RECORD INSERTED==>" + isInserted);
                        }
                        Intent intent = new Intent(RegistrationActivity.this, LoginActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }
            }




            **List**

            private String TAG="UserListActivity";
                private ListView lvUser;
                DatabaseHelper db;
                ArrayList<User> listCartItems = new ArrayList<>();
                private UserAdapter adapter;

                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_user_list);

                    lvUser=(ListView)findViewById(R.id.lv_user);
                    db = new DatabaseHelper(UserListActivity.this);
                    final Cursor cursor = db.getData();
                    cursor.moveToFirst();
                    Log.e(TAG, "CURSOR SIZE==>" + cursor.getCount());
                    //get user from DB
                    if (cursor.getCount() > 0) {
                        cursor.moveToFirst();
                        do {
                            User user = new User();
                            user.userName = cursor.getString(1)+" " +cursor.getString(2);
                            user.email=cursor.getString(3);
                            listCartItems.add(user);
                        } while (cursor.moveToNext());
                    }
                    else
                    {
                        Toast.makeText(this, "User not found!", Toast.LENGTH_SHORT).show();
                    }

                    adapter = new UserAdapter(UserListActivity.this, listCartItems);
                    lvUser.setAdapter(adapter);
                }
            }

        Hope this helps.




        is capital

        private static String capitalize(String s) {
                if (s == null || s.length() == 0) {
                    return "";
                }
                char first = s.charAt(0);
                if (Character.isUpperCase(first)) {
                    return s;
                } else {
                    return Character.toUpperCase(first) + s.substring(1);
                }
            }



    public static void hideSoftKeyboard(Activity activity) {
            InputMethodManager inputMethodManager =
                    (InputMethodManager) activity.getSystemService(
                            Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(
                    activity.getCurrentFocus().getWindowToken(), 0);
        }


MULTIPLE FORM VALIDATIOn FUNCITONALITY

    In Adapter 
    -----------------------------

    OnDeleteItemClickListener onDeleteItemClickListener;

    // Pass the Consructor  Adapter To Activity
      this.onDeleteItemClickListener = monDeleteItemClickedListener;


      // Call the Event  When Chnage Or ClickLisner .. 
     onDeleteItemClickListener.onDeleteClicked();


     Interface Defin in Adapter
     ------------------------------
     public interface OnDeleteItemClickListener {

        public void onDeleteClicked();

    }

    In Activity
    -------------------------------
    implements Adapter.OnDeleteItemClickListener       // Implement Interface


       @Override
    public void onDeleteClicked() {

        refresList();  

    }










    // // TODO: 30/1/18  This Code for Calling a Whatsapp ...
    @RequiresApi(api = Build.VERSION_CODES.DONUT)
    private void getOpenWhatsppIntent() {
        String smsNumber = "7****";
        Intent sendIntent = new Intent(Intent.ACTION_SEND);
        sendIntent.setType("text/plain");
        sendIntent.putExtra(Intent.EXTRA_TEXT, "This Is The Text");
        sendIntent.putExtra("jid", smsNumber + "@s.whatsapp.net"); //phone number without "+" prefix
        sendIntent.setPackage("com.whatsapp");
        if (sendIntent.resolveActivity(getPackageManager()) == null) {
            Toast.makeText(this, "Whatsapp is not installed on this device", Toast.LENGTH_SHORT).show();
            return;
        }
        startActivity(sendIntent);
        finish();
    }


    Facebook

       linear_fblogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {
                if (Util.ReadSharePrefrence(ShareAppActivity.this, Constant.SHRED_PR.IS_FBLOGIN_STATUS).equalsIgnoreCase("")) {
                    loginButton.performClick();
                }
                else
                {
                    Intent intent = new Intent(ShareAppActivity.this,
                            FacebookPostActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        });



            loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>()
        {
            @Override
            public void onSuccess(LoginResult loginResult)
            {
                getUserDetails(loginResult);
            }

            @Override
            public void onCancel() {
                // App code
            }

            @Override
            public void onError(FacebookException exception) {
                // App code
            }
        });


Oncreate  before contentview
  AppEventsLogger.activateApp(this);
        callbackManager = CallbackManager.Factory.create();
        shareDialog = new ShareDialog(this);
        shareDialog.registerCallback(
                callbackManager,
                shareCallback);


                 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onResume() {
        super.onResume();
        AppEventsLogger.activateApp(this);
    }

    private boolean hasPublishPermission() {
        AccessToken accessToken = AccessToken.getCurrentAccessToken();
        return accessToken != null && accessToken.getPermissions().contains("publish_actions");
    }

    private void postPhoto() {
        Bitmap image = BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_whatsapp);
        SharePhoto sharePhoto = new SharePhoto.Builder().setBitmap(image).build();
        ArrayList<SharePhoto> photos = new ArrayList<>();
        photos.add(sharePhoto);
        SharePhotoContent sharePhotoContent =
                new SharePhotoContent.Builder().setPhotos(photos).build();
        if (!canPresentShareDialogWithPhotos) {
            //shareDialog.show(sharePhotoContent);
            ShareApi.share(sharePhotoContent, shareCallback);
        } else if (hasPublishPermission()) {
            ShareApi.share(sharePhotoContent, shareCallback);
        } else {
            pendingAction = PendingAction.POST_PHOTO;
            // We need to get new permissions, then complete the action when we get called back.

            image = BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_launcher);
            sharePhoto = new SharePhoto.Builder().setBitmap(image).build();
            photos = new ArrayList<>();
            photos.add(sharePhoto);

            sharePhotoContent = new SharePhotoContent.Builder().setPhotos(photos).build();
            if (canPresentShareDialogWithPhotos) {
                shareDialog.show(sharePhotoContent);
            } else if (hasPublishPermission()) {
                ShareApi.share(sharePhotoContent, shareCallback);
            } else {
                pendingAction = PendingAction.POST_PHOTO;
                LoginManager.getInstance().logInWithPublishPermissions(
                        this,
                        Arrays.asList(PERMISSION));
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        AppEventsLogger.deactivateApp(this);
    }

    protected void getUserDetails(LoginResult loginResult) {
        GraphRequest data_request = GraphRequest.newMeRequest(
                loginResult.getAccessToken(),
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted
                            (
                                    JSONObject json_object,
                                    GraphResponse response) {
                                Intent intent = new Intent(ShareAppActivity.this,
                                        FacebookPostActivity.class);
                                intent.putExtra("userProfile", json_object.toString());
                                startActivity(intent);
                                finish();

                    }
                });

        Bundle permission_param = new Bundle();
        permission_param.putString("fields", "id,name,email, picture.width(120).height(120)");
        data_request.setParameters(permission_param);
        data_request.executeAsync();
    }

    private enum PendingAction {
        NONE,
        POST_PHOTO,
        POST_STATUS_UPDATE
    }

}


 private ShareDialog shareDialog;
    private PendingAction pendingAction = PendingAction.NONE;
    private FacebookCallback<Sharer.Result> shareCallback = new FacebookCallback<Sharer.Result>() {
        @Override
        public void onCancel() {
            Log.d("FacebookFragment", "Canceled");
        }

        @Override
        public void onError(FacebookException error) {
            Log.d("FacebookFragment", String.format("Error: %s", error.toString()));
            String title = getString(R.string.error);
            String alertMessage = error.getMessage();
            showResult(title, alertMessage);
        }

        @Override
        public void onSuccess(Sharer.Result result) {
            Log.d("FacebookFragment", "Success!");
            if (result.getPostId() != null) {
                String title = getString(R.string.success);
                String id = result.getPostId();
                String alertMessage = getString(R.string.successfully_posted_post);
                showResult(title, alertMessage);
            }
        }

        private void showResult(String title, String alertMessage) {
            new AlertDialog.Builder(ShareAppActivity.this)
                    .setTitle(title)
                    .setMessage(alertMessage)
                    .setCancelable(true)
                    .setPositiveButton(R.string.ok, null)
                    .show();
        }
    };