Guest User

Untitled

a guest
Mar 8th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.36 KB | None | 0 0
  1. public class MainActivity extends AppCompatActivity {
  2.  
  3. private AppCompatActivity activity = MainActivity.this;
  4. private RecyclerView recyclerViewNews;
  5. private List<Noticia> listNoticias;
  6. private NewsRecyclerAdapter newsRecyclerAdapter;
  7. private DBNoticias databaseHelper;
  8. private Button btnLogout;
  9. private LinearLayoutManager mLayoutManager;
  10. UserSession userSession;
  11.  
  12. @Override
  13. protected void onCreate(Bundle savedInstanceState) {
  14. super.onCreate(savedInstanceState);
  15. setContentView(R.layout.activity_main);
  16. userSession = new UserSession(getApplicationContext());
  17.  
  18. recyclerViewNews = findViewById(R.id.recyclerViewNews);
  19. btnLogout = findViewById(R.id.btlogout);
  20.  
  21. TextView usuario = findViewById(R.id.textView5);
  22.  
  23.  
  24. /**
  25. * Olá mundo by Alciomar
  26. */
  27. SharedPreferences sharedPreferences = getSharedPreferences("Reg", Context.MODE_PRIVATE);
  28. String uName = sharedPreferences.getString("Name", "");
  29. usuario.setText(uName.toUpperCase());
  30.  
  31.  
  32. try {
  33. btnLogout.setOnClickListener(new View.OnClickListener() {
  34. @Override
  35. public void onClick(View v) {
  36. userSession.logoutUser();
  37. }
  38. });
  39. } catch (Exception e) {
  40. e.printStackTrace();
  41. }
  42.  
  43. initStuff();
  44. getDataFromPostgres();
  45.  
  46. FloatingActionButton fab = findViewById(R.id.fabNews);
  47. fab.setOnClickListener(new View.OnClickListener() {
  48. @Override
  49. public void onClick(View view) {
  50. Intent intent = new Intent(MainActivity.this, PostNews.class);
  51. startActivity(intent);
  52. }
  53. });
  54.  
  55. }
  56.  
  57.  
  58. /**
  59. * This method is to initialize objects to be used
  60. */
  61. private void initStuff() {
  62.  
  63. try {
  64. listNoticias = new ArrayList<>();
  65. newsRecyclerAdapter = new NewsRecyclerAdapter(listNoticias);
  66.  
  67. mLayoutManager = new LinearLayoutManager(getApplicationContext());
  68. mLayoutManager.setReverseLayout(true);
  69. mLayoutManager.setStackFromEnd(true);
  70. recyclerViewNews.setLayoutManager(mLayoutManager);
  71. recyclerViewNews.setItemAnimator(new DefaultItemAnimator());
  72. recyclerViewNews.setHasFixedSize(true);
  73. recyclerViewNews.setAdapter(newsRecyclerAdapter);
  74. databaseHelper = new DBNoticias(activity);
  75.  
  76. } catch (Exception e) {
  77. e.printStackTrace();
  78. }
  79. }
  80.  
  81. /**
  82. * This method is to fetch all user records from SQLite
  83. */
  84. private void getDataFromPostgres() {
  85. // AsyncTask is used that SQLite operation not blocks the UI Thread.
  86. new AsyncTask<Void, Void, Void>() {
  87. @Override
  88. protected Void doInBackground(Void... params) {
  89. listNoticias.clear();
  90. for (DBNoticias dbNoticias : databaseHelper.getNewsList()) {
  91. Noticia noticia = new Noticia();
  92. noticia.setUser_id(dbNoticias.getId());
  93. noticia.setNewsTitle(dbNoticias.getNewsTitle());
  94. noticia.setNewsMessage(dbNoticias.getNewsPost());
  95.  
  96. listNoticias.add(noticia);
  97. }
  98. return null;
  99. }
  100.  
  101. @Override
  102. protected void onPostExecute(Void aVoid) {
  103. newsRecyclerAdapter.notifyDataSetChanged();
  104. }
  105. }.execute();
  106. }
  107.  
  108. public class UserSession {
  109. // Shared Preferences reference
  110. SharedPreferences pref;
  111.  
  112. // Editor reference for Shared preferences
  113. Editor editor;
  114.  
  115. // Context
  116. Context _context;
  117.  
  118. // Shared preferences mode
  119. int PRIVATE_MODE = 0;
  120.  
  121. // Shared preferences file name
  122. public static final String PREFER_NAME = "Reg";
  123.  
  124. // All Shared Preferences Keys
  125. public static final String IS_USER_LOGIN = "IsUserLoggedIn";
  126.  
  127. // User name (make variable public to access from outside)
  128. public static final String KEY_NAME = "Name";
  129.  
  130. // Email address (make variable public to access from outside)
  131. public static final String KEY_EMAIL = "Email";
  132.  
  133. public static final String KEY_ID = "IdUser";
  134.  
  135. // password
  136. public static final String KEY_PASSWORD = "txtPassword";
  137.  
  138. // Constructor
  139. public UserSession(Context context){
  140. this._context = context;
  141. pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
  142. editor = pref.edit();
  143. }
  144.  
  145. //Create login session
  146. public void createUserLoginSession(String uName, String uEmail, int uIdUser){
  147. // Storing login value as TRUE
  148. editor.putBoolean(IS_USER_LOGIN, true);
  149.  
  150. // Storing name in preferences
  151. editor.putString(KEY_NAME, uName);
  152.  
  153. // Storing email in preferences
  154. editor.putString(KEY_EMAIL, uEmail);
  155.  
  156. editor.putInt(KEY_ID, uIdUser);
  157.  
  158.  
  159. // commit changes
  160. editor.commit();
  161. }
  162.  
  163. /**
  164. * Check login method will check user login status
  165. * If false it will redirect user to login page
  166. * Else do anything
  167. * */
  168. public boolean checkLogin(){
  169. // Check login status
  170. if(!this.isUserLoggedIn()){
  171.  
  172. // user is not logged in redirect him to Login Activity
  173. Intent i = new Intent(_context, Login.class);
  174.  
  175. // Closing all the Activities from stack
  176. i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  177.  
  178. // Add new Flag to start new Activity
  179. i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  180.  
  181. // Staring Login Activity
  182. _context.startActivity(i);
  183.  
  184. return true;
  185. } else {
  186. Intent f = new Intent(_context, MainActivity.class);
  187. _context.startActivity(f);
  188. }
  189. return false;
  190. }
  191.  
  192.  
  193.  
  194. /**
  195. * Get stored session data
  196. * */
  197. public HashMap<String, String> getUserDetails(){
  198.  
  199. //Use hashmap to store user credentials
  200. HashMap<String, String> user = new HashMap<String, String>();
  201.  
  202. // user name
  203. user.put(KEY_NAME, pref.getString(KEY_NAME, null));
  204.  
  205. // user email id
  206. user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
  207.  
  208. // return user
  209. return user;
  210. }
  211.  
  212. /**
  213. * Clear session details
  214. * */
  215. public void logoutUser(){
  216.  
  217. // Clearing all user data from Shared Preferences
  218. editor.clear();
  219. editor.commit();
  220.  
  221. // After logout redirect user to MainActivity
  222. Intent i = new Intent(_context, Login.class);
  223.  
  224. // Closing all the Activities
  225. i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  226.  
  227. // Add new Flag to start new Activity
  228. i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  229.  
  230. // Staring Login Activity
  231. _context.startActivity(i);
  232. }
  233.  
  234.  
  235. // Check for login
  236. public boolean isUserLoggedIn(){
  237. return pref.getBoolean(IS_USER_LOGIN, false);
  238. }
  239.  
  240. public class PostNews extends AppCompatActivity {
  241.  
  242. private DBNoticias dbNoticias;
  243. private Button btnpostar;
  244. private EditText editTextCDNewsTitle;
  245. private EditText editTextCDNewsPost;
  246. private Noticia noticia;
  247. private SharedPreferences sharedPreferences;
  248.  
  249. public void alert(String titulo, String txt){
  250. AlertDialog alertDialog = new AlertDialog.Builder(PostNews.this).create();
  251. alertDialog.setTitle(titulo);
  252. alertDialog.setMessage(txt);
  253. alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
  254. new DialogInterface.OnClickListener() {
  255. public void onClick(DialogInterface dialog, int which) {
  256. dialog.dismiss();
  257. }
  258. });
  259. alertDialog.show();
  260. }
  261.  
  262. @Override
  263. protected void onCreate(Bundle savedInstanceState) {
  264. super.onCreate(savedInstanceState);
  265. setContentView(R.layout.activity_post_news);
  266.  
  267. btnpostar = findViewById(R.id.btn_postar);
  268. dbNoticias = new DBNoticias();
  269.  
  270. editTextCDNewsTitle = findViewById(R.id.EditTextNewsTitle);
  271. editTextCDNewsPost = findViewById(R.id.EditTextNewsPost);
  272.  
  273. }
  274.  
  275. public void salvarNoticia(View view) {
  276. try {
  277. {
  278. String newsTitle = editTextCDNewsTitle.getText().toString();
  279. String newsPost = editTextCDNewsPost.getText().toString();
  280.  
  281. if (!(editTextCDNewsTitle.getText().toString().equals("") || editTextCDNewsTitle.getText() == null ||
  282. editTextCDNewsPost.getText().toString().equals("") || editTextCDNewsPost.getText() == null
  283.  
  284. )) {
  285.  
  286. sharedPreferences = getSharedPreferences("Reg", Context.MODE_PRIVATE);
  287. String uName = sharedPreferences.getString("Name", "");
  288. String uEmail = sharedPreferences.getString("Email", "");
  289. int uIdUser = sharedPreferences.getInt("IdUser", 0);
  290.  
  291. dbNoticias.setNewsTitle(newsTitle);
  292. dbNoticias.setNewsPost(newsPost);
  293. dbNoticias.setIdUser(uIdUser);
  294.  
  295.  
  296. dbNoticias.salvar();
  297.  
  298. noticia = new Noticia();
  299.  
  300.  
  301. Toast.makeText(getApplicationContext(), "Notícia postada com sucesso",
  302. Toast.LENGTH_LONG).show();
  303.  
  304. editTextCDNewsTitle.setText("");
  305. editTextCDNewsPost.setText("");
  306. }
  307.  
  308. }
  309. }
  310. catch (Exception e){
  311. alert("Erro", e.getMessage());
  312. }
  313. }
  314.  
  315. public class DBNoticias {
  316.  
  317. private int id;
  318. private int idUser;
  319. public String newsTitle;
  320. public String newsPost;
  321. public boolean _status;
  322. public String _message;
  323.  
  324.  
  325.  
  326. public DBNoticias(){
  327. this.id = -1;
  328. this.newsTitle = "";
  329. this.newsPost = "";
  330.  
  331. }
  332.  
  333. public DBNoticias(AppCompatActivity activity) {
  334.  
  335. }
  336.  
  337. public ArrayList<DBNoticias> getNewsList(){
  338. ArrayList<DBNoticias> lista = new ArrayList<>();
  339. try {
  340. ResultSet resultSet = DB.select("SELECT * FROM news");
  341. if (resultSet != null){
  342. while (resultSet.next()){
  343.  
  344. DBNoticias obj = new DBNoticias();
  345.  
  346. obj.setId(resultSet.getInt("id_news"));
  347. obj.setNewsTitle(resultSet.getString("news_title"));
  348. obj.setNewsPost(resultSet.getString("news_message"));
  349. lista.add(obj);
  350. }
  351. }
  352. }catch (Exception ex){
  353. this._message = ex.getMessage();
  354. this._status = false;
  355. this._status = false;
  356. }
  357. return lista;
  358. }
  359.  
  360. public void salvar() throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException{
  361. String comando = "";
  362. if (this.getId() == -1){
  363.  
  364.  
  365. comando = String.format("INSERT INTO news (news_title, news_message, fk_user_id) VALUES ('%s','%s',%d);",
  366. this.getNewsTitle(), this.getNewsPost(), this.idUser);
  367. }else {
  368. comando = String.format("UPDATE news SET news_title ='%s', news_post = '%s', id_news = %d WHERE id = %d;",
  369. this.getNewsTitle(), this.getNewsPost(), this.getId());
  370. }
  371. DB db = new DB();
  372. db.executeQuery(comando);
  373. }
  374.  
  375. public void apagar() throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException{
  376. String comando = String.format("DELETE FROM news WHERE id = %d;", this.getId());
  377.  
  378. DB db = new DB();
  379. db.execute(comando);
  380. }
Add Comment
Please, Sign In to add comment