evgeni3

MyTask java

Jan 5th, 2018
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 19.54 KB | None | 0 0
  1. MainActivity
  2.  
  3. package com.example.teacher.mytasks;
  4.  
  5. import android.content.Context;
  6. import android.content.Intent;
  7. import android.support.v7.app.AppCompatActivity;
  8. import android.os.Bundle;
  9. import android.view.View;
  10. import android.widget.Button;
  11. import android.widget.EditText;
  12. import android.widget.Toast;
  13.  
  14. public class MainActivity extends AppCompatActivity {
  15.     EditText txtUser, txtPass;
  16.     Button btnLogin, btnRegister;
  17.     Context context;
  18.     UtlUserSP userSP = new UtlUserSP();
  19.  
  20.     @Override
  21.     protected void onCreate(Bundle savedInstanceState) {
  22.         super.onCreate(savedInstanceState);
  23.         setContentView(R.layout.activity_main);
  24.         setPointer();
  25.     }
  26.  
  27.     private void setPointer() {
  28.         this.context = this;
  29.         userSP.setContext(this);
  30.         txtUser = findViewById(R.id.txtUser);
  31.         txtPass = findViewById(R.id.txtPass);
  32.         btnLogin = findViewById(R.id.btnLogin);
  33.         btnRegister = findViewById(R.id.btnRegister);
  34.  
  35.         btnRegister.setOnClickListener(new View.OnClickListener() {
  36.             @Override
  37.             public void onClick(View view) {
  38.                 startActivity(new Intent(context, RegisterActivity.class));
  39.             }
  40.         });
  41.         btnLogin.setOnClickListener(new View.OnClickListener() {
  42.             @Override
  43.             public void onClick(View view) {/*
  44.                 String userName = txtUser.getText().toString();
  45.                 String userPass = txtPass.getText().toString();
  46.                 if (userSP.checkUser(userName, userPass)) {
  47.                     //Toast.makeText(context, "User o.k.", Toast.LENGTH_SHORT).show();
  48.                     Intent myIntent = new Intent(context,TaskActivity.class);
  49.                     //insert data for the intent that we goint to start
  50.                     myIntent.putExtra("userName",userName);
  51.                     //start intent
  52.                     startActivity(myIntent);
  53.  
  54.  
  55.  
  56.                 }
  57.                 else
  58.                 {
  59.                     Toast.makeText(context, "Error in user name or password", Toast.LENGTH_SHORT).show();
  60.                     txtUser.setText("");
  61.                     txtPass.setText("");
  62.                 }
  63.                  */
  64.                 //for byPass the login
  65.                 Intent myIntent = new Intent(context, TaskActivity.class);
  66.                 myIntent.putExtra("userName","Zeev");
  67.                 startActivity(myIntent);
  68.             }
  69.         });
  70.     }
  71. }
  72. -------------------------------------------
  73. RegisterActivity
  74.  
  75. package com.example.teacher.mytasks;
  76.  
  77. import android.content.Context;
  78. import android.os.Bundle;
  79. import android.support.annotation.Nullable;
  80. import android.support.v7.app.AppCompatActivity;
  81. import android.view.View;
  82. import android.widget.Button;
  83. import android.widget.EditText;
  84. import android.widget.Toast;
  85.  
  86. /**
  87.  * Created by teacher on 12/21/2017.
  88.  */
  89.  
  90. public class RegisterActivity extends AppCompatActivity {
  91.     Context context;
  92.     EditText regUser,regPass1,regPass2;
  93.     Button btnRegister,btnCancel;
  94.     UtlUserSP userUtil=new UtlUserSP();
  95.  
  96.     @Override
  97.     protected void onCreate(@Nullable Bundle savedInstanceState) {
  98.         super.onCreate(savedInstanceState);
  99.         setContentView(R.layout.activity_register);
  100.         setPointer();
  101.     }
  102.  
  103.     private void setPointer() {
  104.         this.context=this;
  105.         userUtil.setContext(context);
  106.         regUser=findViewById(R.id.regUserName);
  107.         regPass1=findViewById(R.id.regPass1);
  108.         regPass2=findViewById(R.id.regPass2);
  109.         btnCancel=findViewById(R.id.btnRegCancel);
  110.         btnCancel.setOnClickListener(new View.OnClickListener() {
  111.             @Override
  112.             public void onClick(View view) {
  113.                 finish();
  114.             }
  115.         });
  116.         btnRegister =findViewById(R.id.btnRegRegister);
  117.         btnRegister.setOnClickListener(new View.OnClickListener() {
  118.             @Override
  119.             public void onClick(View view) {
  120.                 //check if password o.k.
  121.                 if (!regPass1.getText().toString().equals(regPass2.getText().toString()))
  122.                 {
  123.                     Toast.makeText (context, "Password not match", Toast.LENGTH_SHORT).show();
  124.                     return;
  125.                 }
  126.                 if (regPass1.getText().toString().length()<3)
  127.                 {
  128.                     Toast.makeText(context, "Password must be 3 letter minimum", Toast.LENGTH_SHORT).show();
  129.                     return;
  130.                 }
  131.                 if(!userUtil.registerUser(regUser.getText().toString(),regPass1.getText().toString()))
  132.                 {
  133.                     Toast.makeText(context, "Error in user registration....", Toast.LENGTH_SHORT).show();
  134.                     return;
  135.                 }
  136.                 Toast.makeText(context, "new user is add...", Toast.LENGTH_SHORT).show();
  137.                 finish();
  138.             }
  139.         });
  140.  
  141.     }
  142. }
  143.  
  144. -----------------------------------------------
  145. SQLite
  146.  
  147. package com.example.teacher.mytasks;
  148.  
  149. import android.content.ContentValues;
  150. import android.content.Context;
  151. import android.database.Cursor;
  152. import android.database.sqlite.SQLiteDatabase;
  153. import android.database.sqlite.SQLiteException;
  154. import android.database.sqlite.SQLiteOpenHelper;
  155. import android.database.sqlite.SQLiteStatement;
  156. import android.util.Log;
  157.  
  158. import java.util.Date;
  159.  
  160. /**
  161.  * Created by teacher on 1/4/2018.
  162.  */
  163.  
  164. public class SQLite extends SQLiteOpenHelper implements TaskAble {
  165.  
  166.     //name of the DB file in our phone
  167.     public static final String DB_NAME = "task.db";
  168.     //name of the table
  169.     private String tableName = "myTask";
  170.     //as instance of the SQLiteDataBase
  171.     SQLiteDatabase db;
  172.  
  173.     public SQLite(Context context) {
  174.         super(context, DB_NAME, null, 1);
  175.         //open our db for read write
  176.         db = this.getWritableDatabase();
  177.     }
  178.  
  179.     @Override
  180.     public void onCreate(SQLiteDatabase db) {
  181.         String sql = "CREATE TABLE IF NOT EXISTS " + this.tableName + " ";
  182.         // type - INTEGER , TEXT
  183.         // key (index) - PRIMARY KEY
  184.         // +=1 - AUTOINCREMENT
  185.         sql += "(id INTEGER PRIMARY KEY AUTOINCREMENT, taskName TEXT, isDone INTEGER, date TEXT)";
  186.         db.execSQL(sql);
  187.     }
  188.  
  189.     @Override
  190.     public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
  191.         //do not touch
  192.     }
  193.  
  194.  
  195.     //METHOD I - using content values (preventing SQL injection)
  196.     public boolean newTask(String taskName) {
  197.         //create instance of content values to hold our value
  198.         ContentValues myValues = new ContentValues();
  199.         //insert data by key and value
  200.         myValues.put("taskName", taskName);
  201.         myValues.put("isDone", 0);
  202.         myValues.put("date", new Date().toString());
  203.         //putting our values into table and getting a result which reflact record id(-1 indicates an error)
  204.         long res = db.insert(this.tableName, null, myValues);
  205.         return res != (-1);
  206.     }
  207.  
  208.     //METHOD II - using SQL statment
  209.     public boolean newTaskSQL(String taskName) {
  210.         //create sql String -> INSERT INTO [table name] (taskName,isDone,date) value ('buy milk',0,current date)
  211.         String sql = "INSERT INTO " + this.tableName + " (taskName,isDone,date) VALUES('" + taskName + "' 0,'" + new Date().toString() + "')";
  212.         //we need to compile the SQL string to SQL statment
  213.         SQLiteStatement statement = db.compileStatement(sql);
  214.         //we need the sql command, result of (01) is an error
  215.         Long res = statement.executeInsert();
  216.         //check if we have an error
  217.         return res != (-1);
  218.     }
  219.  
  220.     //METHOD III - Pure SQL
  221.     public boolean newTaskRawSQL(String taskName) {
  222.         try {
  223.             //create sql String -> INSERT INTO [table name] (taskName,isDone,date) value ('buy milk',0,current date)
  224.             String sql = "INSERT INTO " + this.tableName + " (taskName,isDone,date) VALUES('" + taskName + "' 0,'" + new Date().toString() + "')";
  225.             //execute SQL
  226.             db.execSQL(sql);
  227.             return true;
  228.         } catch (SQLiteException error) {
  229.             Log.e("SQL", "newTaskRawSQL: " + error.getMessage());
  230.             return false;
  231.         }
  232.     }
  233.  
  234.     //get data from our database by table name
  235.     public Cursor getAllTasks() {
  236.         //get all the tasks into cursor
  237.         Cursor res = db.rawQuery("SELECT * FROM " + this.tableName, null);
  238.         //return the data to the user
  239.         return res;
  240.     }
  241.  
  242.     //get done/undone tasks
  243.     public Cursor getTaskUnDone(boolean isDone) {
  244.         String sql = "SELECT * FROM " + this.tableName + " WHERE isDone=" + (isDone ? 1 : 0);
  245.         Cursor res = db.rawQuery(sql, null);
  246.         //return the user the information
  247.         return res;
  248.     }
  249.  
  250.     //get task by name
  251.     //make hani get electrified
  252.     //make%
  253.     //%electrified
  254.     //%get%
  255.     public Cursor getTaskByPartialName(String taskName) {
  256.         String sql = "SELECT * FROM " + this.tableName + " WHERE taskName LIKE %'" + taskName + "'% AND isDone=0";
  257.         Cursor res = db.rawQuery(sql, null);
  258.         return res;
  259.     }
  260.  
  261.     //delete task by ID
  262.     public void deleteTaskByID(int taskID) {
  263.         db.execSQL("DELETE FROM " + this.tableName + " WHERE id=" + taskID);
  264.     }
  265.  
  266.     //delte task by task name
  267.     public void deleteTaskByName(String taskName) {
  268.         db.execSQL("DELETE FROM " + this.tableName + " WHERE taskName='" + taskName + "'");
  269.     }
  270.  
  271.     @Override
  272.     public boolean changeTaskLeStatus(int taskId, boolean isDone) {
  273.         try {
  274.             db.execSQL("UPDATE " + this.tableName + " SET isDone=" + (isDone ? 1 : 0) + " WHERE id=" + taskId);
  275.             return true;
  276.         } catch (SQLiteException error) {
  277.             Log.e("SQLite", "changeTaskLeStatus: "+error.getMessage() );
  278.         }
  279.         return false;
  280.     }
  281. }
  282. -----------------------------------------------
  283. TaskAble
  284.  
  285. package com.example.teacher.mytasks;
  286.  
  287. import android.database.Cursor;
  288.  
  289. /**
  290.  * Created by teacher on 1/4/2018.
  291.  */
  292.  
  293. public interface TaskAble {
  294.     boolean newTask(String taskName);
  295.     Cursor getAllTasks();
  296.     Cursor getTaskUnDone(boolean isDone);
  297.     Cursor getTaskByPartialName(String taskName);
  298.     void deleteTaskByID(int taskID);
  299.     void deleteTaskByName(String taskName);
  300.     boolean changeTaskLeStatus(int taskId,boolean isDone);
  301. }
  302. ---------------------------------------------------
  303. TaskActivity
  304.  
  305. package com.example.teacher.mytasks;
  306.  
  307. import android.content.Context;
  308. import android.content.Intent;
  309. import android.support.v7.app.AppCompatActivity;
  310. import android.os.Bundle;
  311. import android.view.View;
  312. import android.widget.Button;
  313. import android.widget.EditText;
  314. import android.widget.ListView;
  315. import android.widget.TextView;
  316.  
  317. import java.util.ArrayList;
  318. import java.util.List;
  319.  
  320. public class TaskActivity extends AppCompatActivity {
  321.     private String currentUser;
  322.     private Context context;
  323.     TextView taskUser;
  324.     EditText newTask;
  325.     Button addTask;
  326.     ListView taskList;
  327.     List<String> myTasks;
  328.     TaskAdapter myAdapter;
  329.  
  330.     @Override
  331.     protected void onCreate(Bundle savedInstanceState) {
  332.         super.onCreate(savedInstanceState);
  333.         setContentView(R.layout.activity_task);
  334.         setPointer();
  335.     }
  336.  
  337.     private void setPointer() {
  338.         this.context=this;
  339.         //we getting the current intent
  340.         Intent intent=getIntent();
  341.         //get the data from the intent
  342.         this.currentUser=intent.getStringExtra("userName");
  343.         taskUser=findViewById(R.id.txtUserName);
  344.         taskUser.setText(currentUser);
  345.         newTask=findViewById(R.id.etMyTask);
  346.         addTask=findViewById(R.id.btnAddTask);
  347.         addTask.setOnClickListener(new View.OnClickListener() {
  348.             @Override
  349.             public void onClick(View view) {
  350.                 if (newTask.getText().toString().isEmpty()){return;}
  351.                 myAdapter.addTask(newTask.getText().toString());
  352.                 newTask.setText("");
  353.             }
  354.         });
  355.         taskList=findViewById(R.id.lstTask);
  356.         myAdapter=new TaskAdapter(context);
  357.         taskList.setAdapter(myAdapter);
  358.     }
  359. }
  360. TaskAdapter
  361. ------------------------------------------------
  362. package com.example.teacher.mytasks;
  363.  
  364. import android.app.AlertDialog;
  365. import android.content.Context;
  366. import android.content.DialogInterface;
  367. import android.database.Cursor;
  368. import android.util.Log;
  369. import android.view.View;
  370. import android.view.ViewGroup;
  371. import android.widget.BaseAdapter;
  372. import android.widget.CompoundButton;
  373. import android.widget.ImageView;
  374. import android.widget.Switch;
  375. import android.widget.TextView;
  376. import android.widget.Toast;
  377.  
  378. import java.util.ArrayList;
  379. import java.util.Date;
  380. import java.util.List;
  381. import java.util.zip.Inflater;
  382.  
  383. /**
  384.  * Created by teacher on 12/25/2017.
  385.  */
  386.  
  387. public class TaskAdapter extends BaseAdapter {
  388.  
  389.     Context context;
  390.     List<Tasks> myTasks;
  391.     SQLite sql;
  392.     //Backendless sql
  393.  
  394.     public TaskAdapter(Context context) {
  395.         this.context=context;
  396.         sql = new SQLite(context);
  397.         //sql = new Backendless(context)
  398.         myTasks = new ArrayList<>();
  399.         getData();
  400.     }
  401.  
  402.     private void getData() {
  403.         notifyDataSetChanged();
  404.     }
  405.  
  406.     @Override
  407.     public int getCount() {
  408.         //get data from our SQLite
  409.         Cursor cursor = sql.getAllTasks();
  410.         if (cursor.getCount()>0)
  411.         {
  412.             myTasks = new ArrayList<>();
  413.             while (cursor.moveToNext())
  414.             {
  415.                 int taskId = cursor.getInt(0); //0-taskId
  416.                 String taskName = cursor.getString(1);
  417.                 boolean isDone= cursor.getInt(2)==1; //0-false 1-true
  418.                 Date taskDate = new Date();
  419.  
  420.                 myTasks.add(new Tasks(taskId,taskName,isDone,taskDate));
  421.             }
  422.         }
  423.         return myTasks.size();
  424.     }
  425.  
  426.     @Override
  427.     public Object getItem(int i) {return null;}
  428.  
  429.     @Override
  430.     public long getItemId(int i) {return 0;}
  431.  
  432.     @Override
  433.     public View getView(final int i, View view, ViewGroup viewGroup) {
  434.         View taskView = View.inflate(context,R.layout.task_item,null);
  435.         Switch taskDone = taskView.findViewById(R.id.taskDone);
  436.         TextView taskName = taskView.findViewById(R.id.taskName);
  437.         ImageView taskDelete = taskView.findViewById(R.id.taskDelete);
  438.  
  439.         //set task name
  440.         taskName.setText(myTasks.get(i).getTaskName());
  441.  
  442.         //set taskDone
  443.         taskDone.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
  444.             @Override
  445.             public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
  446.                 sql.changeTaskLeStatus(myTasks.get(i).getTaskId(),b);
  447.             }
  448.         });
  449.         taskDone.setChecked(myTasks.get(i).isDone());
  450.         Log.e("isDone", "getView: "+ myTasks.get(i).isDone());
  451.         //delete task
  452.         taskDelete.setOnClickListener(new View.OnClickListener() {
  453.             @Override
  454.             public void onClick(View view) {
  455.                 // Toast.makeText(context, myTasks.get(i), Toast.LENGTH_SHORT).show();
  456.                 AlertDialog.Builder confirmDelete = new AlertDialog.Builder(context);
  457.                 confirmDelete.setTitle("Delete a task");
  458.                 confirmDelete.setMessage("Are you sure to delete \n"+myTasks.get(i).getTaskName());
  459.                 confirmDelete.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
  460.                     @Override
  461.                     public void onClick(DialogInterface dialogInterface, int idx) {
  462.                         sql.deleteTaskByID(myTasks.get(i).getTaskId());
  463.                         myTasks.remove(i);
  464.                         dialogInterface.dismiss();
  465.                         notifyDataSetChanged();
  466.                     }
  467.                 });
  468.                 confirmDelete.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
  469.                     @Override
  470.                     public void onClick(DialogInterface dialogInterface, int idx) {
  471.                         dialogInterface.dismiss();
  472.                     }
  473.                 });
  474.                 confirmDelete.show();
  475.             }
  476.         });
  477.  
  478.         return taskView;
  479.     }
  480.  
  481.     public boolean addTask(String taskName)
  482.     {
  483.         boolean success = sql.newTask(taskName);
  484.         notifyDataSetChanged();
  485.         return success;
  486.     }
  487.  
  488. }
  489. ----------------------------------------------------
  490. Tasks
  491.  
  492. package com.example.teacher.mytasks;
  493.  
  494. import java.util.Date;
  495.  
  496. /**
  497.  * Created by teacher on 1/4/2018.
  498.  */
  499.  
  500. public class Tasks {
  501.     private int taskId;
  502.     private String taskName;
  503.     private boolean isDone;
  504.     private Date taskDate;
  505.  
  506.     public Tasks(int taskId, String taskName, boolean isDone, Date taskDate) {
  507.         this.taskId = taskId;
  508.         this.taskName = taskName;
  509.         this.isDone = isDone;
  510.         this.taskDate = taskDate;
  511.     }
  512.  
  513.     public void setDone(boolean done) {
  514.         isDone = done;
  515.     }
  516.  
  517.     public String getTaskName() {
  518.         return taskName;
  519.     }
  520.  
  521.     public boolean isDone() {
  522.         return isDone;
  523.     }
  524.  
  525.     public int getTaskId() {
  526.         return taskId;
  527.     }
  528.  
  529. }
  530. --------------------------------------------------
  531. UserAble
  532.  
  533. package com.example.teacher.mytasks;
  534.  
  535. import android.content.Context;
  536.  
  537. /**
  538.  * Created by teacher on 12/21/2017.
  539.  */
  540.  
  541. public interface UserAble {
  542.     boolean registerUser(String userName, String userPass);
  543.     boolean userExists(String userName);
  544.     boolean checkUser(String userName,String userPass);
  545.     void setContext(Context context);
  546. }
  547. -----------------------------------------------------
  548. UtlUserSP
  549.  
  550. package com.example.teacher.mytasks;
  551.  
  552. import android.content.Context;
  553. import android.content.SharedPreferences;
  554. import android.widget.Toast;
  555.  
  556. /**
  557.  * Created by teacher on 12/21/2017.
  558.  */
  559.  
  560. public class UtlUserSP implements UserAble {
  561.     Context context;
  562.  
  563.     public UtlUserSP() { }
  564.  
  565.     @Override
  566.     public void setContext(Context context) {
  567.         this.context=context;
  568.     }
  569.  
  570.     @Override
  571.     public boolean registerUser(String userName, String userPass) {
  572.         //User Exists
  573.         if (userExists(userName)) {
  574.             Toast.makeText(context, "user already exists...", Toast.LENGTH_SHORT).show();
  575.             return false;
  576.         }
  577.         //save user and password
  578.  
  579.         //declaration of shared preference
  580.         SharedPreferences prefs = context.getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
  581.  
  582.         //declaration of shared preference editor
  583.         SharedPreferences.Editor editor = prefs.edit();
  584.  
  585.         //put data inside, we use hash map, so we need KEY,VALUE (k,v)
  586.         editor.putString(userName, userPass);
  587.  
  588.         //sending data to my shared preferences file.
  589.         editor.commit();
  590.         return true;
  591.     }
  592.  
  593.     @Override
  594.     public boolean userExists( String userName) {
  595.         //declaration of shared prefernces
  596.         SharedPreferences prefs=context.getSharedPreferences("myPrefs",Context.MODE_PRIVATE);
  597.  
  598.         //get user pass
  599.         String spPass=prefs.getString(userName,"na");
  600.  
  601.         //return if users exists, if not (na) return false
  602.         return !spPass.equals("na");
  603.     }
  604.  
  605.     @Override
  606.     public boolean checkUser( String userName, String userPass) {
  607.         //declaration of shared prefernces
  608.         SharedPreferences prefs=context.getSharedPreferences("myPrefs",Context.MODE_PRIVATE);
  609.  
  610.         //get user password
  611.         String spPass=prefs.getString(userName,"na");
  612.  
  613.         //return the result if the passwords are match
  614.         return spPass.equals(userPass);
  615.     }
  616. }
Advertisement
Add Comment
Please, Sign In to add comment