Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MainActivity extends AppCompatActivity {
- private AppCompatActivity activity = MainActivity.this;
- private RecyclerView recyclerViewNews;
- private List<Noticia> listNoticias;
- private NewsRecyclerAdapter newsRecyclerAdapter;
- private DBNoticias databaseHelper;
- private Button btnLogout;
- private LinearLayoutManager mLayoutManager;
- UserSession userSession;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- userSession = new UserSession(getApplicationContext());
- recyclerViewNews = findViewById(R.id.recyclerViewNews);
- btnLogout = findViewById(R.id.btlogout);
- TextView usuario = findViewById(R.id.textView5);
- /**
- * Olá mundo by Alciomar
- */
- SharedPreferences sharedPreferences = getSharedPreferences("Reg", Context.MODE_PRIVATE);
- String uName = sharedPreferences.getString("Name", "");
- usuario.setText(uName.toUpperCase());
- try {
- btnLogout.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- userSession.logoutUser();
- }
- });
- } catch (Exception e) {
- e.printStackTrace();
- }
- initStuff();
- getDataFromPostgres();
- FloatingActionButton fab = findViewById(R.id.fabNews);
- fab.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- Intent intent = new Intent(MainActivity.this, PostNews.class);
- startActivity(intent);
- }
- });
- }
- /**
- * This method is to initialize objects to be used
- */
- private void initStuff() {
- try {
- listNoticias = new ArrayList<>();
- newsRecyclerAdapter = new NewsRecyclerAdapter(listNoticias);
- mLayoutManager = new LinearLayoutManager(getApplicationContext());
- mLayoutManager.setReverseLayout(true);
- mLayoutManager.setStackFromEnd(true);
- recyclerViewNews.setLayoutManager(mLayoutManager);
- recyclerViewNews.setItemAnimator(new DefaultItemAnimator());
- recyclerViewNews.setHasFixedSize(true);
- recyclerViewNews.setAdapter(newsRecyclerAdapter);
- databaseHelper = new DBNoticias(activity);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * This method is to fetch all user records from SQLite
- */
- private void getDataFromPostgres() {
- // AsyncTask is used that SQLite operation not blocks the UI Thread.
- new AsyncTask<Void, Void, Void>() {
- @Override
- protected Void doInBackground(Void... params) {
- listNoticias.clear();
- for (DBNoticias dbNoticias : databaseHelper.getNewsList()) {
- Noticia noticia = new Noticia();
- noticia.setUser_id(dbNoticias.getId());
- noticia.setNewsTitle(dbNoticias.getNewsTitle());
- noticia.setNewsMessage(dbNoticias.getNewsPost());
- listNoticias.add(noticia);
- }
- return null;
- }
- @Override
- protected void onPostExecute(Void aVoid) {
- newsRecyclerAdapter.notifyDataSetChanged();
- }
- }.execute();
- }
- public class UserSession {
- // Shared Preferences reference
- SharedPreferences pref;
- // Editor reference for Shared preferences
- Editor editor;
- // Context
- Context _context;
- // Shared preferences mode
- int PRIVATE_MODE = 0;
- // Shared preferences file name
- public static final String PREFER_NAME = "Reg";
- // All Shared Preferences Keys
- public static final String IS_USER_LOGIN = "IsUserLoggedIn";
- // User name (make variable public to access from outside)
- public static final String KEY_NAME = "Name";
- // Email address (make variable public to access from outside)
- public static final String KEY_EMAIL = "Email";
- public static final String KEY_ID = "IdUser";
- // password
- public static final String KEY_PASSWORD = "txtPassword";
- // Constructor
- public UserSession(Context context){
- this._context = context;
- pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
- editor = pref.edit();
- }
- //Create login session
- public void createUserLoginSession(String uName, String uEmail, int uIdUser){
- // Storing login value as TRUE
- editor.putBoolean(IS_USER_LOGIN, true);
- // Storing name in preferences
- editor.putString(KEY_NAME, uName);
- // Storing email in preferences
- editor.putString(KEY_EMAIL, uEmail);
- editor.putInt(KEY_ID, uIdUser);
- // commit changes
- editor.commit();
- }
- /**
- * Check login method will check user login status
- * If false it will redirect user to login page
- * Else do anything
- * */
- public boolean checkLogin(){
- // Check login status
- if(!this.isUserLoggedIn()){
- // user is not logged in redirect him to Login Activity
- Intent i = new Intent(_context, Login.class);
- // Closing all the Activities from stack
- i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
- // Add new Flag to start new Activity
- i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- // Staring Login Activity
- _context.startActivity(i);
- return true;
- } else {
- Intent f = new Intent(_context, MainActivity.class);
- _context.startActivity(f);
- }
- return false;
- }
- /**
- * Get stored session data
- * */
- public HashMap<String, String> getUserDetails(){
- //Use hashmap to store user credentials
- HashMap<String, String> user = new HashMap<String, String>();
- // user name
- user.put(KEY_NAME, pref.getString(KEY_NAME, null));
- // user email id
- user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
- // return user
- return user;
- }
- /**
- * Clear session details
- * */
- public void logoutUser(){
- // Clearing all user data from Shared Preferences
- editor.clear();
- editor.commit();
- // After logout redirect user to MainActivity
- Intent i = new Intent(_context, Login.class);
- // Closing all the Activities
- i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
- // Add new Flag to start new Activity
- i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- // Staring Login Activity
- _context.startActivity(i);
- }
- // Check for login
- public boolean isUserLoggedIn(){
- return pref.getBoolean(IS_USER_LOGIN, false);
- }
- public class PostNews extends AppCompatActivity {
- private DBNoticias dbNoticias;
- private Button btnpostar;
- private EditText editTextCDNewsTitle;
- private EditText editTextCDNewsPost;
- private Noticia noticia;
- private SharedPreferences sharedPreferences;
- public void alert(String titulo, String txt){
- AlertDialog alertDialog = new AlertDialog.Builder(PostNews.this).create();
- alertDialog.setTitle(titulo);
- alertDialog.setMessage(txt);
- alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- }
- });
- alertDialog.show();
- }
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_post_news);
- btnpostar = findViewById(R.id.btn_postar);
- dbNoticias = new DBNoticias();
- editTextCDNewsTitle = findViewById(R.id.EditTextNewsTitle);
- editTextCDNewsPost = findViewById(R.id.EditTextNewsPost);
- }
- public void salvarNoticia(View view) {
- try {
- {
- String newsTitle = editTextCDNewsTitle.getText().toString();
- String newsPost = editTextCDNewsPost.getText().toString();
- if (!(editTextCDNewsTitle.getText().toString().equals("") || editTextCDNewsTitle.getText() == null ||
- editTextCDNewsPost.getText().toString().equals("") || editTextCDNewsPost.getText() == null
- )) {
- sharedPreferences = getSharedPreferences("Reg", Context.MODE_PRIVATE);
- String uName = sharedPreferences.getString("Name", "");
- String uEmail = sharedPreferences.getString("Email", "");
- int uIdUser = sharedPreferences.getInt("IdUser", 0);
- dbNoticias.setNewsTitle(newsTitle);
- dbNoticias.setNewsPost(newsPost);
- dbNoticias.setIdUser(uIdUser);
- dbNoticias.salvar();
- noticia = new Noticia();
- Toast.makeText(getApplicationContext(), "Notícia postada com sucesso",
- Toast.LENGTH_LONG).show();
- editTextCDNewsTitle.setText("");
- editTextCDNewsPost.setText("");
- }
- }
- }
- catch (Exception e){
- alert("Erro", e.getMessage());
- }
- }
- public class DBNoticias {
- private int id;
- private int idUser;
- public String newsTitle;
- public String newsPost;
- public boolean _status;
- public String _message;
- public DBNoticias(){
- this.id = -1;
- this.newsTitle = "";
- this.newsPost = "";
- }
- public DBNoticias(AppCompatActivity activity) {
- }
- public ArrayList<DBNoticias> getNewsList(){
- ArrayList<DBNoticias> lista = new ArrayList<>();
- try {
- ResultSet resultSet = DB.select("SELECT * FROM news");
- if (resultSet != null){
- while (resultSet.next()){
- DBNoticias obj = new DBNoticias();
- obj.setId(resultSet.getInt("id_news"));
- obj.setNewsTitle(resultSet.getString("news_title"));
- obj.setNewsPost(resultSet.getString("news_message"));
- lista.add(obj);
- }
- }
- }catch (Exception ex){
- this._message = ex.getMessage();
- this._status = false;
- this._status = false;
- }
- return lista;
- }
- public void salvar() throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException{
- String comando = "";
- if (this.getId() == -1){
- comando = String.format("INSERT INTO news (news_title, news_message, fk_user_id) VALUES ('%s','%s',%d);",
- this.getNewsTitle(), this.getNewsPost(), this.idUser);
- }else {
- comando = String.format("UPDATE news SET news_title ='%s', news_post = '%s', id_news = %d WHERE id = %d;",
- this.getNewsTitle(), this.getNewsPost(), this.getId());
- }
- DB db = new DB();
- db.executeQuery(comando);
- }
- public void apagar() throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException{
- String comando = String.format("DELETE FROM news WHERE id = %d;", this.getId());
- DB db = new DB();
- db.execute(comando);
- }
Add Comment
Please, Sign In to add comment