am_dot_com

DDM 2021-12-14

Dec 14th, 2021 (edited)
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.23 KB | None | 0 0
  1. package com.joythis.android.simplestsqlite;
  2.  
  3. import android.content.ContentValues;
  4. import android.content.Context;
  5. import android.database.Cursor;
  6. import android.database.sqlite.SQLiteDatabase;
  7. import android.database.sqlite.SQLiteOpenHelper;
  8. import android.util.Log;
  9.  
  10. import androidx.annotation.Nullable;
  11.  
  12. import java.util.ArrayList;
  13.  
  14. public class MyContactsDB extends SQLiteOpenHelper {
  15.  
  16. public final static String DB_NAME = "my_contacts.DB";
  17. //increases in DB_VERSION should cause "onUpgrade"
  18. public final static int DB_VERSION = 2;//onUpgrade
  19.  
  20. public final static String TABLE_CONTACTS = "tContacts";
  21. public final static String COL_ID = "_id";
  22. public final static String COL_NAME = "cName";
  23. public final static String COL_PHONE = "cPhone";
  24. //public final static String COL_EMAIL = "cEmail";
  25.  
  26. /*
  27. create table if not exists tContacts(
  28. _id INTEGER PRIMARY KEY NOT NULL,
  29. cName TEXT NOT NULL,
  30. cPhone TEXT NOT NULL,
  31. //cEmail TEXT NOT NULL
  32. );
  33. */
  34. public final static String CREATE_TABLE_CONTACTS =
  35. "create table if not exists "+TABLE_CONTACTS+"(\n"+
  36. COL_ID+" INTEGER PRIMARY KEY NOT NULL,\n"+
  37. COL_NAME+" TEXT NOT NULL,\n"+
  38. COL_PHONE+" TEXT NOT NULL\n);";
  39.  
  40. public final static String DROP_TABLE_CONTACTS =
  41. "drop table if exists "+TABLE_CONTACTS+";";
  42.  
  43. public MyContactsDB(
  44. @Nullable Context context, //context
  45. @Nullable String name, //DB_NAME
  46. @Nullable SQLiteDatabase.CursorFactory factory, //
  47. int version //DB_VERSION
  48. ) {
  49. super(context, name, factory, version);
  50. }//MyContactDB
  51.  
  52. public MyContactsDB(
  53. @Nullable Context context //context
  54. ){
  55. super(
  56. context,
  57. DB_NAME,
  58. null,//Cursor are the result of select statement
  59. DB_VERSION
  60. );
  61. }//MyContact
  62.  
  63.  
  64. @Override
  65. public void onCreate(SQLiteDatabase db) {
  66. //automatically called by the framework
  67. //when the need to work with still non-existing
  68. //tables
  69. installDB(db);
  70. }//onCreate
  71.  
  72. void installDB(SQLiteDatabase pDB){
  73. if (pDB!=null){
  74. try {
  75. pDB.execSQL(CREATE_TABLE_CONTACTS);
  76. }
  77. catch (Exception e){
  78. Log.e(
  79. "@MyContactDB",
  80. e.toString()
  81. );
  82. }
  83. }
  84. }//installDB
  85.  
  86. @Override
  87. public void onUpgrade(
  88. SQLiteDatabase db,
  89. int oldVersion, //1
  90. int newVersion //2
  91. )
  92. {
  93. //automatically called when
  94. //the database changes
  95. //that is signaled by the database "version"
  96. if (newVersion>oldVersion){
  97. try{
  98. //destroy
  99. db.execSQL(
  100. DROP_TABLE_CONTACTS
  101. );
  102. //reconstruct
  103. installDB(db);
  104. }//try
  105. catch (Exception e){
  106. Log.e(
  107. "@MyContactsDB",
  108. e.toString()
  109. );
  110. }//catch
  111. }//if
  112. }//onUpgrade
  113.  
  114. public final int DOES_NOT_EXIST = -1;
  115. /*
  116. receives a MyContact
  117. returns the _id >= 1 in TABLE_CONTACTS
  118. where that MyContact already exists
  119. or
  120. -1, if it does not exist
  121. */
  122. public long getIdForContact(MyContact pC){
  123. SQLiteDatabase db = this.getReadableDatabase();
  124. if (db!=null){
  125. //select * from tContacts where (cName='Rita' and cPhone='123')
  126. String strQ = String.format(
  127. "select %s from %s where (%s='%s' and %s='%s')",
  128. //COL_NAME+","+COL_PHONE
  129. "*",
  130. TABLE_CONTACTS,
  131. COL_NAME,
  132. pC.mName,
  133. COL_PHONE,
  134. pC.mPhone
  135. );
  136. Cursor cursorResults =
  137. db.rawQuery(
  138. strQ,
  139. null
  140. );
  141.  
  142. if (cursorResults!=null){
  143. int iHowMany = cursorResults.getCount();
  144. if (iHowMany>0){
  145. //a contact with that name and phone
  146. //already exists
  147. cursorResults.moveToFirst();
  148. int indexOfIdColumn =
  149. cursorResults.getColumnIndex(
  150. "_id"
  151. );
  152. long idOfAlreadyExistingContact =
  153. cursorResults.getLong(
  154. //0
  155. indexOfIdColumn
  156. );
  157. return idOfAlreadyExistingContact;
  158. }//if
  159. }
  160. }
  161. return DOES_NOT_EXIST;
  162. }//getIdForContact
  163.  
  164. long insertNewContact(MyContact pC){
  165. long iCurrentIdForContact =
  166. getIdForContact(pC);
  167.  
  168. boolean bWillBeNew =
  169. iCurrentIdForContact == DOES_NOT_EXIST;
  170.  
  171. if (bWillBeNew){
  172. SQLiteDatabase db =
  173. this.getWritableDatabase();
  174. if (db!=null){
  175. ContentValues cvs = new ContentValues();
  176. cvs.put(COL_NAME, pC.mName);
  177. cvs.put(COL_PHONE, pC.mPhone);
  178.  
  179. long lWhereInserted =
  180. db.insert(
  181. TABLE_CONTACTS,
  182. null,//we have no columns allowing null
  183. cvs
  184. );
  185.  
  186. return lWhereInserted;
  187. }
  188. }
  189.  
  190. return iCurrentIdForContact;
  191. }//insertNewContact
  192.  
  193. public ArrayList<MyContact> selectByQuery(
  194. String pQ
  195. ){
  196. ArrayList<MyContact> alRet = new ArrayList<>();
  197.  
  198. SQLiteDatabase db = getReadableDatabase();
  199. if (db!=null){
  200. try{
  201. Cursor results =
  202. db.rawQuery(
  203. pQ,
  204. null
  205. );
  206. if (results!=null && results.getCount()>0){
  207. results.moveToFirst();
  208. while(!results.isAfterLast()){
  209. //read the fields of the present record from the database
  210. String strName, strPhone;
  211. int idxColName, idxColNumber;
  212. idxColName =
  213. results.getColumnIndex(COL_NAME);
  214. idxColNumber =
  215. results.getColumnIndex(COL_PHONE);
  216.  
  217. strName = results.getString(idxColName);
  218. strPhone = results.getString(idxColNumber);
  219. //database reading ends here
  220.  
  221. //accessory ops related to the method's return value
  222. MyContact c = new MyContact(strName, strPhone);
  223. alRet.add(c);
  224.  
  225. results.moveToNext();
  226. }//while
  227. return alRet;
  228. }//if
  229. }
  230. catch (Exception e){
  231. Log.e(
  232. "@MyContactsDB",
  233. e.toString()
  234. );
  235. }
  236. }//if
  237. return alRet;//via this exit, this will be an empty list
  238. }//selectByQuery
  239.  
  240. public ArrayList<MyContact> selectAllByDescId(){
  241. String q = String.format(
  242. "select %s from %s order by %s DESC",
  243. "*",
  244. TABLE_CONTACTS,
  245. COL_ID
  246. );
  247. return selectByQuery (q);
  248. }//selectAllByDescId
  249.  
  250. public ArrayList<MyContact> selectAllByAscId(){
  251. String q = String.format(
  252. "select %s from %s order by %s ASC",
  253. //"*",
  254. COL_ID+","+COL_NAME+","+COL_PHONE,
  255. TABLE_CONTACTS,
  256. COL_ID
  257. );
  258. return selectByQuery (q);
  259. }//selectAllByAscId
  260.  
  261. /*
  262. selects every record whose name starts with "art"
  263. select * from tContacts where cName like 'art%'
  264.  
  265. selects every record whose name ends with "art"
  266. select * from tContacts where cName like '%art'
  267.  
  268. selects every record whose name containing "art"
  269. select * from tContacts where cName like '%art%'
  270. */
  271. public ArrayList<MyContact> selectAllWithNameLike(
  272. String pName
  273. ){
  274. String q = String.format(
  275. "select %s from %s where (%s like '%%%s%%') order by %s DESC",
  276. "*",
  277. TABLE_CONTACTS,
  278. COL_NAME,
  279. pName,
  280. COL_ID
  281. );
  282. return selectByQuery (q);
  283. }//selectAllWithNameLike
  284.  
  285. }//MyContactDB
  286.  
  287. ****
  288.  
  289.  
  290. package com.joythis.android.simplestsqlite;
  291.  
  292. import androidx.appcompat.app.AppCompatActivity;
  293.  
  294. import android.content.Context;
  295. import android.os.Bundle;
  296. import android.view.View;
  297. import android.widget.ArrayAdapter;
  298. import android.widget.Button;
  299. import android.widget.EditText;
  300. import android.widget.ListView;
  301. import android.widget.Spinner;
  302.  
  303. import java.util.ArrayList;
  304.  
  305. public class MainActivity extends AppCompatActivity {
  306. MyContactsDB mDB;
  307.  
  308. AmUtil mUtil;
  309.  
  310. Context mContext;
  311. EditText mEtName, mEtPhone;
  312. Spinner mSpnActionOptions;
  313. Button mBtnAction;
  314.  
  315. ListView mLv;
  316. ArrayList<MyContact> mAl;
  317. ArrayAdapter<MyContact> mAd;
  318.  
  319. View.OnClickListener mClickHandler = new View.OnClickListener() {
  320. @Override
  321. public void onClick(View v) {
  322. switch(v.getId()){
  323. case R.id.idBtnAction:
  324. performSelectedAction();
  325. break;
  326. }
  327. }
  328. };
  329.  
  330. void performSelectedAction(){
  331. switch(mSpnActionOptions.getSelectedItemPosition()){
  332. case 0:
  333. //insert
  334. actionInsert();
  335. break;
  336. case 1:
  337. //select all by id desc
  338. actionSelectAll();
  339. break;
  340. case 2:
  341. //select like name
  342. actionSelectLikeName();
  343. break;
  344. }//switch
  345. }//performSelectedAction
  346.  
  347. void actionSelectLikeName(){
  348. String strName = mEtName.getText().toString().trim();
  349. if (strName!=null && strName.length()>0) {
  350. ArrayList<MyContact> res =
  351. mDB.selectAllWithNameLike(strName);
  352. displayResults(res);
  353. }
  354. else{
  355. mUtil.fb("Name should not be empty!");
  356. }
  357. }
  358.  
  359. void actionInsert(){
  360. String strName, strPhone;
  361. strName = mEtName.getText().toString();
  362. strPhone = mEtPhone.getText().toString();
  363.  
  364. MyContact c = new MyContact(strName, strPhone);
  365. long idForExistingContactOrMinus1 =
  366. mDB.getIdForContact(c);
  367.  
  368. if (idForExistingContactOrMinus1== mDB.DOES_NOT_EXIST){
  369. mUtil.fb("New contact about to the inserted.");
  370. long idxWhereInserted = mDB.insertNewContact(c);
  371. String strWhereInserted = String.format(
  372. "New MyContact created @%d",idxWhereInserted
  373. );
  374. mUtil.fb(strWhereInserted);
  375.  
  376. /*
  377. to have the ListView displaying all the MyContacts
  378. including this last one, just inserted
  379. */
  380. actionSelectAll();
  381. }
  382. else{
  383. mUtil.fb("Contact already exists. Nothing done.");
  384. }
  385. }//actionInsert
  386.  
  387. /*
  388. 1)
  389. must read the existing MyContacts from the database
  390. via mDB
  391. 2)
  392. display the existing MyContact in the ListView (mLv)
  393. */
  394. void actionSelectAll(){
  395. //1
  396. ArrayList<MyContact> alRet =
  397. mDB.selectAllByDescId();
  398.  
  399. if (alRet!=null && alRet.size()>0){
  400. displayResults(alRet);
  401. }
  402. else{
  403. mUtil.fb("No records in database.");
  404. }
  405. }//actionSelectAll
  406.  
  407. void displayResults(ArrayList<MyContact> pAl){
  408. if (pAl!=null && pAl.size()>0){
  409. this.mAl.clear(); //keep the data mem address
  410. for (MyContact c : pAl){
  411. mAl.add(c);
  412. }//for
  413. mAd.notifyDataSetChanged();
  414. }//if
  415. }//displayResults
  416.  
  417. @Override
  418. protected void onCreate(Bundle savedInstanceState) {
  419. super.onCreate(savedInstanceState);
  420. setContentView(R.layout.contact_input);
  421.  
  422. init();
  423. }//onCreate
  424.  
  425. void init(){
  426. this.mDB = new MyContactsDB(this);
  427.  
  428. mUtil = new AmUtil(this);
  429.  
  430. mContext = MainActivity.this;
  431. mEtName = findViewById(R.id.idEtName);
  432. mEtPhone = findViewById(R.id.idEtNumber);
  433. mSpnActionOptions = findViewById(R.id.idSpnActionOptions);
  434. mBtnAction = findViewById(R.id.idBtnAction);
  435.  
  436. mLv = findViewById(R.id.idLv);
  437. mAl = new ArrayList<>();
  438. mAd = new ArrayAdapter<MyContact>(
  439. mContext, //from the Activity
  440. android.R.layout.simple_list_item_1, //layout for each element that the data source provides
  441. mAl //data source
  442. );
  443.  
  444. //behaviors
  445. mBtnAction.setOnClickListener(mClickHandler);
  446. mLv.setAdapter(mAd);
  447.  
  448. actionSelectAll();
  449. }//init
  450. }
Add Comment
Please, Sign In to add comment