Book Library Link
Currently, I am creating a note application with reference to the above link, but when I move from MainActivity to UpdateAcitivity, the content of the note I should have clicked is not displayed
Since the data is displayed in MainActivity, there is no problem in saving the data itself. However, the reason why the data is not displayed in UpdateActivity is that the withdrawal from the DB has failed. not. Please help.
UpdateActivity
package com.example.noteapp;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.MultiAutoCompleteTextView;
import android.widget.Toast;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
public class UpdateActivity extends AppCompatActivity {
EditText title_input;
Button update_button, delete_button;
//↓What I Add
MultiAutoCompleteTextView message_input;
//MultiAutoCompleteTextView message_input = (MultiAutoCompleteTextView)findViewById(R.id.me);
String id, title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
title_input = findViewById(R.id.title_input2);
update_button = findViewById(R.id.ub);
delete_button = findViewById(R.id.db);
//↓What I add
message_input = findViewById(R.id.me);
//First we call this
getAndSetIntentData();
//Set actionbar title after getAndSetIntentData method
ActionBar ab = getSupportActionBar();
if (ab != null) {
ab.setTitle(title);
}
update_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//And only then we call this
MyDatabaseHelper myDB = new MyDatabaseHelper(UpdateActivity.this);
title = title_input.getText().toString().trim();
String message = message_input.getText().toString().trim();
myDB.updateData(id, title, message);
}
});
delete_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
confirmDialog();
}
});
}
void getAndSetIntentData(){
if(getIntent().hasExtra("id") && getIntent().hasExtra("title") && getIntent().hasExtra("message")){
//Getting Data from Intent
id = getIntent().getStringExtra("id");
title = getIntent().getStringExtra("title");
String message = getIntent().getStringExtra("message");
//Setting Intent Data
title_input.setText(title);
message_input.setText(message);
Log.d("stev", title);
}else{
Toast.makeText(this, "No data.", Toast.LENGTH_SHORT).show();
}
}
void confirmDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Delete " + title + " ?");
builder.setMessage("Are you sure you want to delete " + title + " ?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MyDatabaseHelper myDB = new MyDatabaseHelper(UpdateActivity.this);
myDB.deleteOneRow(id);
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.create().show();
}
}
activity_updateXML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="30dp"
tools:context=".UpdateActivity">
<EditText
android:id="#+id/title_input2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="84dp"
android:ems="10"
android:hint="Title"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.266"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<MultiAutoCompleteTextView
android:id="#+id/me"
android:layout_width="355dp"
android:layout_height="148dp"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="Message"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/title_input2" />
<Button
android:id="#+id/ub"
android:layout_width="match_parent"
android:layout_height="70dp"
android:text="Update"
android:textAllCaps="false"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="321dp" />
<Button
android:id="#+id/db"
android:layout_width="match_parent"
android:layout_height="70dp"
android:background="#color/red"
android:text="Delete"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.483"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="421dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
MyDatabaseHelper
package com.example.noteapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import androidx.annotation.Nullable;
class MyDatabaseHelper extends SQLiteOpenHelper {
private Context context;
private static final String DATABASE_NAME = "note.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "my_note";
private static final String COLUMN_ID = "_id";
private static final String COLUMN_TITLE = "title";
private static final String COLUMN_MESSAGE = "message";
MyDatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_NAME +
" (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_TITLE + " TEXT, " +
COLUMN_MESSAGE + " TEXT);";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
void addNote(String title, String message){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_TITLE, title);
cv.put(COLUMN_MESSAGE, message);
long result = db.insert(TABLE_NAME,null, cv);
if(result == -1){
Toast.makeText(context, "Failed", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context, "Added Successfully!", Toast.LENGTH_SHORT).show();
}
}
Cursor readAllData(){
String query = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
if(db != null){
cursor = db.rawQuery(query, null);
}
return cursor;
}
void updateData(String row_id, String title, String message){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_TITLE, title);
cv.put(COLUMN_MESSAGE, message);
long result = db.update(TABLE_NAME, cv, "_id=?", new String[]{row_id});
if(result == -1){
Toast.makeText(context, "Failed", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context, "Updated Successfully!", Toast.LENGTH_SHORT).show();
}
}
void deleteOneRow(String row_id){
SQLiteDatabase db = this.getWritableDatabase();
long result = db.delete(TABLE_NAME, "_id=?", new String[]{row_id});
if(result == -1){
Toast.makeText(context, "Failed to Delete.", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Successfully Deleted.", Toast.LENGTH_SHORT).show();
}
}
void deleteAllData(){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME);
}
}
MainActivity
package com.example.noteapp;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
FloatingActionButton add_button;
ImageView empty_imageview;
TextView no_data;
MyDatabaseHelper myDB;
ArrayList<String> note_id, note_title, note_message;
//CustomAdapter customAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
add_button = findViewById(R.id.add_button);
empty_imageview = findViewById(R.id.empty_imageview);
no_data = findViewById(R.id.no_data);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, InsertActivity.class);
startActivity(intent);
}
});
myDB = new MyDatabaseHelper(MainActivity.this);
note_id = new ArrayList<>();
note_title = new ArrayList<>();
note_message = new ArrayList<>();
storeDataInArrays();
CustomAdapter customAdapter = new CustomAdapter(MainActivity.this, this, note_id, note_title, note_message);
recyclerView.setAdapter(customAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1){
recreate();
}
}
void storeDataInArrays(){
Cursor cursor = myDB.readAllData();
if(cursor.getCount() == 0){
empty_imageview.setVisibility(View.VISIBLE);
no_data.setVisibility(View.VISIBLE);
}else{
while (cursor.moveToNext()){
note_id.add(cursor.getString(0));
note_title.add(cursor.getString(1));
note_message.add(cursor.getString(2));
}
empty_imageview.setVisibility(View.GONE);
no_data.setVisibility(View.GONE);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.delete_all){
confirmDialog();
}
return super.onOptionsItemSelected(item);
}
void confirmDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Delete All?");
builder.setMessage("Are you sure you want to delete all Data?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MyDatabaseHelper myDB = new MyDatabaseHelper(MainActivity.this);
myDB.deleteAllData();
//Refresh Activity
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.create().show();
}
}
================CustomeAdapter====================
CustomeAdapter
package com.example.noteapp;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private Context context;
private Activity activity;
private ArrayList note_id, note_title, note_message;
CustomAdapter(Activity activity, Context context, ArrayList note_id, ArrayList note_title, ArrayList note_message){
this.activity = activity;
this.context = context;
this.note_id = note_id;
this.note_title = note_title;
this.note_message = note_message;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.my_row, parent, false);
return new MyViewHolder(view);
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, final int position) {
holder.note_id_txt.setText(String.valueOf(note_id.get(position)));
holder.note_title_txt.setText(String.valueOf(note_title.get(position)));
holder.note_message_txt.setText(String.valueOf(note_message.get(position)));
//Recyclerview onClickListener
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, UpdateActivity.class);
intent.putExtra("id", String.valueOf(note_id.get(position)));
intent.putExtra("title", String.valueOf(note_title.get(position)));
intent.putExtra("author", String.valueOf(note_message.get(position)));
activity.startActivityForResult(intent, 1);
}
});
}
#Override
public int getItemCount() {
return note_id.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView note_id_txt, note_title_txt, note_message_txt;
LinearLayout mainLayout;
MyViewHolder(#NonNull View itemView) {
super(itemView);
note_id_txt = itemView.findViewById(R.id.note_id_txt);
note_title_txt = itemView.findViewById(R.id.note_title_txt);
note_message_txt = itemView.findViewById(R.id.note_message_txt);
mainLayout = itemView.findViewById(R.id.mainLayout);
//Animate Recyclerview
Animation translate_anim = AnimationUtils.loadAnimation(context, R.anim.translate_anim);
mainLayout.setAnimation(translate_anim);
}
}
}
I think your problem in the CustomeAdapter exactly in onBindViewHolder.
replace this code from onBindViewHolder:
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, UpdateActivity.class);
intent.putExtra("id", holder.note_id_txt.getText().toString());
intent.putExtra("title",holder.note_title_txt.getText().toString() );
intent.putExtra("author", holder.note_message_txt.getText().toString());
activity.startActivityForResult(intent, 1);
}
});
and put this inside your viewHolder class:
MyViewHolder(#NonNull View itemView) {
super(itemView);
note_id_txt = itemView.findViewById(R.id.note_id_txt);
note_title_txt = itemView.findViewById(R.id.note_title_txt);
note_message_txt = itemView.findViewById(R.id.note_message_txt);
mainLayout = itemView.findViewById(R.id.mainLayout);
//Animate Recyclerview
Animation translate_anim = AnimationUtils.loadAnimation(context, R.anim.translate_anim);
mainLayout.setAnimation(translate_anim);
mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, UpdateActivity.class);
intent.putExtra("id", note_id_txt.getText().toString());
intent.putExtra("title",note_title_txt.getText().toString() );
intent.putExtra("author", note_message_txt.getText().toString());
activity.startActivityForResult(intent, 1);
}
});
}
Related
Guys the Adapter in that case is showing the images but not the name(note im using the caption in the data but that is cuz is not repaired but it is still String)
layout_grid_imageview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.test.mine.Utils.SquareImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:id="#+id/gridImageView"/>
<ProgressBar
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerInParent="true"
android:id="#+id/gridImageProgressbar"/>
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Name of The Picture"
android:id="#+id/txt_grid_name_ingredient"/>
</androidx.cardview.widget.CardView>
</RelativeLayout>
I want on the place of the "Name of the picture" to set custom name from data. But i cant do it somehow
This is my adapter GridImageAdapter.java
public class GridImageAdapter extends ArrayAdapter<String>{
private LayoutInflater mInflater;
private int layoutResource;
private String mAppend;
private ArrayList<String> imgURLs;
private ArrayList<String> imgNames;
public GridImageAdapter(Context context, int layoutResource, String append, ArrayList<String> imgURLs, ArrayList<String> imgNames){
super(context, layoutResource, imgURLs);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.layoutResource = layoutResource;
mAppend = append;
this.imgURLs = imgURLs;
this.imgNames = imgNames;
}
private static class ViewHolder{
TextView ingredientName;
SquareImageView image;
ProgressBar mProgressBar;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
/*
Viewholder build pattern (Similar to recyclerview)
*/
final ViewHolder holder;
if(convertView == null){
convertView = mInflater.inflate(layoutResource, parent, false);
holder = new ViewHolder();
holder.ingredientName = convertView.findViewById(R.id.txt_grid_name_ingredient);
holder.image = (SquareImageView) convertView.findViewById(R.id.gridImageView);
holder.mProgressBar = (ProgressBar) convertView.findViewById(R.id.gridImageProgressbar);
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
}
String imgURL = getItem(position);
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(mAppend + imgURL, holder.image, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.VISIBLE);
}
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.GONE);
}
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.GONE);
}
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.GONE);
}
}
});
return convertView;
}
}
And this is the profile where everything shoud be shown
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.bumptech.glide.Glide;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.test.mine.R;
import com.test.mine.Utils.GridImageAdapter;
import com.test.mine.models.Comments;
import com.test.mine.models.Likes;
import com.test.mine.models.Photo;
import com.test.mine.models.Users;
public class ProfileFragment extends Fragment {
private static final int NUM_GRID_COLUMNS = 2;
private static final String TAG ="mProfileFragment" ;
ImageView account_setting_menu;
Button editProfile;
ImageView profilePhoto;
GridView mGridRecipesView;
TextView posts,followers,followings,name, description,website,username;
LinearLayout follower,following;
String noFollowers,noFollowings;
DatabaseReference databaseReference;
private ProgressBar mProgressBar;
private LinearLayout profileItemsView;
#Nullable
#Override
public View onCreateView(#NonNull final LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profile,null);
return v;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
account_setting_menu = (ImageView) view.findViewById(R.id.account_settingMenu);
editProfile = (Button)view.findViewById(R.id.edit_profile);
profilePhoto = (ImageView)view.findViewById(R.id.user_img);
mGridRecipesView = (GridView) view.findViewById(R.id.gridview1);
posts = (TextView)view.findViewById(R.id.txtPosts);
followers = (TextView)view.findViewById(R.id.txtFollowers);
followings = (TextView)view.findViewById(R.id.txtFollowing);
name = (TextView)view.findViewById(R.id.display_name);
description = (TextView)view.findViewById(R.id.description);
website = (TextView)view.findViewById(R.id.website);
username = (TextView)view.findViewById(R.id.profileName);
follower = (LinearLayout)view.findViewById(R.id.FragmentProfile_followerLinearLayout);
following = (LinearLayout)view.findViewById(R.id.FragmentProfile_followingLinearLayout);
mProgressBar = (ProgressBar) view.findViewById(R.id.profileProgressBar);
profileItemsView = view.findViewById(R.id.layout_profile_books_view);
// Retrieving Photos and displaying in profile
tempGridSetup();
// Retrieving data
String userid = FirebaseAuth.getInstance().getCurrentUser().getUid();
databaseReference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
databaseReference.keepSynced(true);
addEventListener();
account_setting_menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent =new Intent(getActivity(),Account_Settings.class);
startActivity(intent);
}
});
editProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),EditProfile.class);
startActivity(intent);
}
});
follower.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(),FollowersFollowing.class);
intent.putExtra("id",FirebaseAuth.getInstance().getCurrentUser().getUid());
intent.putExtra("title","Followers");
intent.putExtra("number",noFollowers);
startActivity(intent);
}
});
following.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(),FollowersFollowing.class);
intent.putExtra("id",FirebaseAuth.getInstance().getCurrentUser().getUid());
intent.putExtra("title","Following");
intent.putExtra("number",noFollowings);
startActivity(intent);
}
});
}
private void addEventListener(){
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
final Users user = snapshot.getValue(Users.class);
Log.i(TAG, "ID: " + user.getUser_id());
posts.setText(user.getPosts());
noFollowers = user.getFollowers();
noFollowings = user.getFollowing();
followers.setText(noFollowers);
followings.setText(noFollowings);
name.setText(user.getFullName());
description.setText(user.getDiscription());
website.setText(user.getWebsite());
username.setText(user.getUsername());
Glide.with(ProfileFragment.this)
.load(user.getProfilePhoto())
.into(profilePhoto);
mProgressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.i(TAG, "ID: " + "canceled");
}
});
}
private void tempGridSetup(){
Log.d(TAG, "setupGridView: Setting up image grid.");
final ArrayList<Photo> photos = new ArrayList<>();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.keepSynced(true);
Query query = reference
.child("User_Photo")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for ( DataSnapshot singleSnapshot : snapshot.getChildren()){
Photo photo = new Photo();
Map<String, Object> objectMap = (HashMap<String, Object>) singleSnapshot.getValue();
Log.d(TAG, "setupGridView(objectMap)"+objectMap.get("caption"));
photo.setCaption(objectMap.get("caption").toString());
photo.setTags(objectMap.get("tags").toString());
photo.setPhoto_id(objectMap.get("photo_id").toString());
photo.setUser_id(objectMap.get("user_id").toString());
photo.setDate_Created(objectMap.get("date_Created").toString());
photo.setImage_Path(objectMap.get("image_Path").toString());
List<Comments> comments = new ArrayList();
for (DataSnapshot dSnapshot : singleSnapshot
.child("comments").getChildren()){
Comments comment = new Comments();
comment.setUser_id(dSnapshot.getValue(Comments.class).getUser_id());
comment.setComment(dSnapshot.getValue(Comments.class).getComment());
comment.setDate_created(dSnapshot.getValue(Comments.class).getDate_created());
comments.add(comment);
}
photo.setComments(comments);
List<Likes> likesList = new ArrayList<Likes>();
for (DataSnapshot dSnapshot : singleSnapshot
.child("likes").getChildren()){
Likes like = new Likes();
like.setUser_id(dSnapshot.getValue(Likes.class).getUser_id());
likesList.add(like);
}
photo.setLikes(likesList);
photos.add(photo);
// photos.add(singleSnapshot.getValue(Photo.class));
}
//setup our image grid
int gridWidth = getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth/NUM_GRID_COLUMNS;
mGridRecipesView.setColumnWidth(imageWidth);
mGridRecipesView.setNumColumns(NUM_GRID_COLUMNS);
ArrayList<String> imgUrls = new ArrayList();
ArrayList<String> imgNames = new ArrayList<>();
for(int i = 0; i < photos.size(); i++){
imgUrls.add(photos.get(i).getImage_Path());
imgNames.add(photos.get(i).getCaption());
}
GridImageAdapter adapter = new GridImageAdapter(getActivity(),R.layout.layout_grid_imageview,
"", imgUrls, imgNames);
mGridRecipesView.setAdapter(adapter);
mGridRecipesView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ViewPostFragment fragment = new ViewPostFragment();
Bundle args = new Bundle();
args.putParcelable("PHOTO", photos.get(position));
Log.d(TAG, "getPhotoFromBundle(PHOTO): arguments: " + photos.get(position));
fragment.setArguments(args);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(ProfileFragment.this.getId(), fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d(TAG, "onCancelled: query cancelled.");
}
});
}
#Override
public void onResume() {
super.onResume();
addEventListener();
this.getView().setFocusableInTouchMode(true);
this.getView().requestFocus();
this.getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return false;
}
});
}
}
Todo app doesn't show the added task...its like not refreshing the added task. When i close and open the app again, then it shows. I am a beginner so i can,t guess out the problem.
Here is MainActivity.java
package com.ashtiv.dooo;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.ashtiv.dooo.db.TaskContract;
import com.ashtiv.dooo.db.TaskDbHelper;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private TaskDbHelper mHelper;
private ListView mTaskListView;
private ArrayAdapter<String> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHelper = new TaskDbHelper(this);
mTaskListView = (ListView) findViewById(R.id.list_todo);
updateUI();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_add_task:
final EditText taskEditText = new EditText(this);
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Add a new task")
.setMessage("What do you want to do next?")
.setView(taskEditText)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String task = String.valueOf(taskEditText.getText());
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
db.insertWithOnConflict(TaskContract.TaskEntry.TABLE,
null,
values,
SQLiteDatabase.CONFLICT_REPLACE);
db.close();
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void deleteTask(View view) {
View parent = (View) view.getParent();
TextView taskTextView = (TextView) parent.findViewById(R.id.task_title);
String task = String.valueOf(taskTextView.getText());
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(TaskContract.TaskEntry.TABLE,
TaskContract.TaskEntry.COL_TASK_TITLE + " = ?",
new String[]{task});
db.close();
updateUI();
}
private void updateUI() {
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase db = mHelper.getReadableDatabase();
Cursor cursor = db.query(TaskContract.TaskEntry.TABLE,
new String[]{TaskContract.TaskEntry._ID, TaskContract.TaskEntry.COL_TASK_TITLE},
null, null, null, null, null);
while (cursor.moveToNext()) {
int idx = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
taskList.add(cursor.getString(idx));
}
if (mAdapter == null) {
mAdapter = new ArrayAdapter<>(this,
R.layout.item_todo,
R.id.task_title,
taskList);
mTaskListView.setAdapter(mAdapter);
} else {
mAdapter.clear();
mAdapter.addAll(taskList);
mAdapter.notifyDataSetChanged();
}
cursor.close();
db.close();
}
}
Here is TaskContract.java
package com.ashtiv.dooo.db;
import android.provider.BaseColumns;
public class TaskContract {
public static final String DB_NAME = "com.ashtiv.dooo.db";
public static final int DB_VERSION = 1;
public class TaskEntry implements BaseColumns {
public static final String TABLE = "tasks";
public static final String COL_TASK_TITLE = "title";
}
}
Here is TaskDbHelper.java
package com.ashtiv.dooo.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class TaskDbHelper extends SQLiteOpenHelper {
public TaskDbHelper(Context context) {
super(context, TaskContract.DB_NAME, null, TaskContract.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TaskContract.TaskEntry.TABLE + " ( " +
TaskContract.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
TaskContract.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL);";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TaskContract.TaskEntry.TABLE);
onCreate(db);
}
}
hERE is actvity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.ashtiv.dooo.MainActivity">
<ListView
android:id="#+id/list_todo"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Here is item_todo.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical">
<TextView
android:id="#+id/task_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:text="Hello"
android:textSize="20sp" />
<Button
android:id="#+id/task_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:text="Done"
android:onClick="deleteTask"/>
</RelativeLayout>
The issue was you are not updating the UI after adding a new Todo.
To tackle the issue modify your code as follows.
Edit your onOptionsItemSelected to
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_add_task:
addTodo();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
and add this function.
private void addTodo() {
final EditText taskEditText = new EditText(this);
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Add a new task")
.setMessage("What do you want to do next?")
.setView(taskEditText)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String task = String.valueOf(taskEditText.getText());
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
db.insertWithOnConflict(TaskContract.TaskEntry.TABLE,
null,
values,
SQLiteDatabase.CONFLICT_REPLACE);
db.close();
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
updateUI();
}
The issue you are seeing is because function updateUI() only gets called when your activity is created. You would have to devise a method where updateUI() gets called for each time you make an update to the table.
You could try calling updateUI() whenever you add or remove some tasks. For example:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_add_task:
final EditText taskEditText = new EditText(this);
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Add a new task")
.setMessage("What do you want to do next?")
.setView(taskEditText)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String task = String.valueOf(taskEditText.getText());
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
db.insertWithOnConflict(TaskContract.TaskEntry.TABLE,
null,
values,
SQLiteDatabase.CONFLICT_REPLACE);
db.close();
//NEW LINE
updateUI();
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
I want to show large image in my Crud Layout. I save an image byte to database like this.
byte[] image = cursor.getBlob(3);
When i insert image in my crud layout it give me error/blank page because the BLOB is too big in the database so i want to store the path of the image into the database and the use the path to access/display the image.
I don't know how to do it since im new in java
here's my code
CRUDActivity
package foodsqlitedemo.quocnguyen.com.foodsqlitedemo;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class CrudActivity extends AppCompatActivity {
EditText edtName, edtPrice;
Button btnChoose, btnAdd, btnList;
ImageView imageView;
final int REQUEST_CODE_GALLERY = 999;
public static SQLiteHelper sqLiteHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crud);
init();
sqLiteHelper = new SQLiteHelper(this, "FoodDB.sqlite", null, 1);
sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS FOOD(Id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, price VARCHAR, image BLOB)");
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(
CrudActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_GALLERY
);
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
sqLiteHelper.insertData(
edtName.getText().toString().trim(),
edtPrice.getText().toString().trim(),
imageViewToByte(imageView)
);
Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();
edtName.setText("");
edtPrice.setText("");
imageView.setImageResource(R.mipmap.ic_launcher);
}
catch (Exception e){
e.printStackTrace();
}
}
});
btnList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(CrudActivity.this, GudangList.class);
startActivity(intent);
}
});
}
public static byte[] imageViewToByte(ImageView image) {
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
return byteArray;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == REQUEST_CODE_GALLERY){
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_CODE_GALLERY);
}
else {
Toast.makeText(getApplicationContext(), "You don't have permission to access file location!", Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE_GALLERY && resultCode == RESULT_OK && data != null){
Uri uri = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void init(){
edtName = (EditText) findViewById(R.id.edtName);
edtPrice = (EditText) findViewById(R.id.edtPrice);
btnChoose = (Button) findViewById(R.id.btnChoose);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnList = (Button) findViewById(R.id.btnList);
imageView = (ImageView) findViewById(R.id.imageView);
}
}
Gudang.java
package foodsqlitedemo.quocnguyen.com.foodsqlitedemo;
/**
* Created by Quoc Nguyen on 13-Dec-16.
*/
public class Gudang {
private int id;
private String name;
private String price;
private byte[] image;
public Gudang(String name, String price, byte[] image, int id) {
this.name = name;
this.price = price;
this.image = image;
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
}
GudangList.java
package foodsqlitedemo.quocnguyen.com.foodsqlitedemo;
import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Created by Quoc Nguyen on 13-Dec-16.
*/
public class GudangList extends AppCompatActivity {
GridView gridView;
ArrayList<Gudang> list;
GudangListAdapter adapter = null;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gudang_list_activity);
gridView = (GridView) findViewById(R.id.gridView);
list = new ArrayList<>();
adapter = new GudangListAdapter(this, R.layout.gudang_items, list);
gridView.setAdapter(adapter);
// get all data from sqlite
Cursor cursor = CrudActivity.sqLiteHelper.getData("SELECT * FROM FOOD");
list.clear();
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
String name = cursor.getString(1);
String price = cursor.getString(2);
byte[] image = cursor.getBlob(3);
list.add(new Gudang(name, price, image, id));
}
adapter.notifyDataSetChanged();
gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
CharSequence[] items = {"Update", "Delete"};
AlertDialog.Builder dialog = new AlertDialog.Builder(GudangList.this);
dialog.setTitle("Choose an action");
dialog.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
// update
Cursor c = CrudActivity.sqLiteHelper.getData("SELECT id FROM FOOD");
ArrayList<Integer> arrID = new ArrayList<Integer>();
while (c.moveToNext()){
arrID.add(c.getInt(0));
}
// show dialog update at here
showDialogUpdate(GudangList.this, arrID.get(position));
} else {
// delete
Cursor c = CrudActivity.sqLiteHelper.getData("SELECT id FROM FOOD");
ArrayList<Integer> arrID = new ArrayList<Integer>();
while (c.moveToNext()){
arrID.add(c.getInt(0));
}
showDialogDelete(arrID.get(position));
}
}
});
dialog.show();
return true;
}
});
}
ImageView imageViewFood;
private void showDialogUpdate(Activity activity, final int position){
final Dialog dialog = new Dialog(activity);
dialog.setContentView(R.layout.update_gudang_activity);
dialog.setTitle("Update");
imageViewFood = (ImageView) dialog.findViewById(R.id.imageViewFood);
final EditText edtName = (EditText) dialog.findViewById(R.id.edtName);
final EditText edtPrice = (EditText) dialog.findViewById(R.id.edtPrice);
Button btnUpdate = (Button) dialog.findViewById(R.id.btnUpdate);
// set width for dialog
int width = (int) (activity.getResources().getDisplayMetrics().widthPixels * 0.95);
// set height for dialog
int height = (int) (activity.getResources().getDisplayMetrics().heightPixels * 0.7);
dialog.getWindow().setLayout(width, height);
dialog.show();
imageViewFood.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// request photo library
ActivityCompat.requestPermissions(
GudangList.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
888
);
}
});
btnUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
CrudActivity.sqLiteHelper.updateData(
edtName.getText().toString().trim(),
edtPrice.getText().toString().trim(),
CrudActivity.imageViewToByte(imageViewFood),
position
);
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Update successfully!!!",Toast.LENGTH_SHORT).show();
}
catch (Exception error) {
Log.e("Update error", error.getMessage());
}
updateFoodList();
}
});
}
private void showDialogDelete(final int idFood){
final AlertDialog.Builder dialogDelete = new AlertDialog.Builder(GudangList.this);
dialogDelete.setTitle("Warning!!");
dialogDelete.setMessage("Are you sure you want to this delete?");
dialogDelete.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
CrudActivity.sqLiteHelper.deleteData(idFood);
Toast.makeText(getApplicationContext(), "Delete successfully!!!",Toast.LENGTH_SHORT).show();
} catch (Exception e){
Log.e("error", e.getMessage());
}
updateFoodList();
}
});
dialogDelete.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialogDelete.show();
}
private void updateFoodList(){
// get all data from sqlite
Cursor cursor = CrudActivity.sqLiteHelper.getData("SELECT * FROM FOOD");
list.clear();
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
String name = cursor.getString(1);
String price = cursor.getString(2);
byte[] image = cursor.getBlob(3);
list.add(new Gudang(name, price, image, id));
}
adapter.notifyDataSetChanged();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == 888){
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 888);
}
else {
Toast.makeText(getApplicationContext(), "You don't have permission to access file location!", Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 888 && resultCode == RESULT_OK && data != null){
Uri uri = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageViewFood.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
GudangListAdapter.java
package foodsqlitedemo.quocnguyen.com.foodsqlitedemo;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
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 java.util.ArrayList;
/**
* Created by Quoc Nguyen on 13-Dec-16.
*/
public class GudangListAdapter extends BaseAdapter {
private Context context;
private int layout;
private ArrayList<Gudang> foodsList;
public GudangListAdapter(Context context, int layout, ArrayList<Gudang> foodsList) {
this.context = context;
this.layout = layout;
this.foodsList = foodsList;
}
#Override
public int getCount() {
return foodsList.size();
}
#Override
public Object getItem(int position) {
return foodsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder{
ImageView imageView;
TextView txtName, txtPrice;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
View row = view;
ViewHolder holder = new ViewHolder();
if(row == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layout, null);
holder.txtName = (TextView) row.findViewById(R.id.txtName);
holder.txtPrice = (TextView) row.findViewById(R.id.txtPrice);
holder.imageView = (ImageView) row.findViewById(R.id.imgFood);
row.setTag(holder);
}
else {
holder = (ViewHolder) row.getTag();
}
Gudang gudang = foodsList.get(position);
holder.txtName.setText(gudang.getName());
holder.txtPrice.setText(gudang.getPrice());
byte[] foodImage = gudang.getImage();
Bitmap bitmap = BitmapFactory.decodeByteArray(foodImage, 0, foodImage.length);
holder.imageView.setImageBitmap(bitmap);
return row;
}
}
SQLiteHelper
package foodsqlitedemo.quocnguyen.com.foodsqlitedemo;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
/**
* Created by Quoc Nguyen on 13-Dec-16.
*/
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
public void queryData(String sql){
SQLiteDatabase database = getWritableDatabase();
database.execSQL(sql);
}
public void insertData(String name, String price, byte[] image){
SQLiteDatabase database = getWritableDatabase();
String sql = "INSERT INTO FOOD VALUES (NULL, ?, ?, ?)";
SQLiteStatement statement = database.compileStatement(sql);
statement.clearBindings();
statement.bindString(1, name);
statement.bindString(2, price);
statement.bindBlob(3, image);
statement.executeInsert();
}
public void updateData(String name, String price, byte[] image, int id) {
SQLiteDatabase database = getWritableDatabase();
String sql = "UPDATE FOOD SET name = ?, price = ?, image = ? WHERE id = ?";
SQLiteStatement statement = database.compileStatement(sql);
statement.bindString(1, name);
statement.bindString(2, price);
statement.bindBlob(3, image);
statement.bindDouble(4, (double)id);
statement.execute();
database.close();
}
public void deleteData(int id) {
SQLiteDatabase database = getWritableDatabase();
String sql = "DELETE FROM FOOD WHERE id = ?";
SQLiteStatement statement = database.compileStatement(sql);
statement.clearBindings();
statement.bindDouble(1, (double)id);
statement.execute();
database.close();
}
public Cursor getData(String sql){
SQLiteDatabase database = getReadableDatabase();
return database.rawQuery(sql, null);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
enter code here
I developed a word app that contains English vocabularies and users can add their favorite word by clicking on a floating button. Every time my favorite list has at list one item it is updated but when it's empty it doesn't show anything but when I run app again list updates.
if you need any code let me know to send it .
UPDATE:
Inner page :
selectDb();
if(selectFavoriteState()){
favorite.setImageResource(R.drawable.ic_favorite_like);
}else {
favorite.setImageResource(R.drawable.ic_favorite_maylike);
}
favorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (selectFavoriteState()){
favorite.setImageResource(R.drawable.ic_favorite_maylike);
updateUnfavorited();
}else {
favorite.setImageResource(R.drawable.ic_favorite_like);
updateFavorited();
}
}
});
private void selectDb(){
destpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ielts/";
database = SQLiteDatabase.openOrCreateDatabase(destpath + "/md_book.db", null);
}
private boolean selectFavoriteState(){
#SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT * FROM main WHERE id = " + id, null);
while (cursor.moveToNext()){
favoriteState = cursor.getString(cursor.getColumnIndex("fav"));
}
return favoriteState.equals("1");
}
private void updateFavorited(){
database.execSQL( "UPDATE main SET fav = 1 WHERE id = " + id);
}
private void updateUnfavorited(){
database.execSQL( "UPDATE main SET fav = 0 WHERE id = " + id);
}
Update 2:
package farmani.com.essentialwordsforielts.mainPage;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import farmani.com.essentialwordsforielts.R;
public class PageFragment extends Fragment {
private int mPage;
public static final String ARG_PAGE = "ARG_PAGE";
RecyclerView recyclerView;
AdapterFav adapterFav;
public static PageFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_page, container, false);
if (mPage == 1) {
recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
AdapterList adapter = new AdapterList(MainActivity.context);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.context));
}
if (mPage == 2) {
recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
adapterFav = new AdapterFav(MainActivity.context);
recyclerView.setAdapter(adapterFav);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.context));
}
return view;
}
#Override
public void onResume() {
super.onResume();
if (adapterFav != null){
adapterFav.notifyDataSetChanged();
}
}
}
Update 3 :AdapterFav
package farmani.com.essentialwordsforielts.mainPage;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import farmani.com.essentialwordsforielts.R;
import farmani.com.essentialwordsforielts.innerpage.ActivityInnerPage;
public class AdapterFav extends RecyclerView.Adapter<ViewHolder> {
Context context;
LayoutInflater inflater;
TextView title;
ImageView avatar;
LinearLayout cardAdapter;
public AdapterFav(Context context){
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.adapter_card_view, parent, false);
title = (TextView) view.findViewById(R.id.title1);
avatar = (ImageView) view.findViewById(R.id.avatar);
cardAdapter = (LinearLayout) view.findViewById(R.id.card_adapter);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.title.setText(MainActivity.favorite.get(position).getWord());
String img = MainActivity.favorite.get(position).getImg();
int id = MainActivity.context.getResources().getIdentifier(img, "drawable", MainActivity.context.getPackageName());
holder.avatar.setImageResource(id);
holder.cardAdapter.setOnClickListener(clickListener);
holder.cardAdapter.setId(position);
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = view.getId();
Intent intent = new Intent (MainActivity.context, ActivityInnerPage.class);
intent.putExtra("name", "favorite");
intent.putExtra("id", position + "");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainActivity.context.startActivity(intent);
}
};
#Override
public int getItemCount() {
return MainActivity.favorite.size();
}
}
Update 4: MainActivity
package farmani.com.essentialwordsforielts.mainPage;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.nabinbhandari.android.permissions.PermissionHandler;
import com.nabinbhandari.android.permissions.Permissions;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import farmani.com.essentialwordsforielts.R;
import farmani.com.essentialwordsforielts.search.ActivitySearch;
import farmani.com.essentialwordsforielts.setting.ActivitySetting;
public class MainActivity extends AppCompatActivity {
public static Context context;
public static ArrayList<Structure> list = new ArrayList<>();
public static ArrayList<Structure> favorite = new ArrayList<>();
DrawerLayout drawerLayout;
NavigationView navigationView;
ImageView hamburger;
SQLiteDatabase database;
String destPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_activity_main);
Permissions.check(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE},
" storage permissions are required to copy database", new Permissions.Options()
.setSettingsDialogTitle("Warning!").setRationaleDialogTitle("Info"),
new PermissionHandler() {
#Override
public void onGranted() {
setupDB();
selectList();
selectFavorite();
}
});
context = getApplicationContext();
setTabOption();
drawerLayout = findViewById(R.id.navigation_drawer);
navigationView = findViewById(R.id.navigation_view);
hamburger = findViewById(R.id.hamburger);
hamburger.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
drawerLayout.openDrawer(Gravity.START);
}
});
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.exit) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
alertDialog.setTitle(R.string.exit);
alertDialog.setMessage(R.string.exit_ask);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
finish();
}
});
alertDialog.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
dialog.cancel();
}
});
alertDialog.show();
}else if (id == R.id.search) {
Intent intent = new Intent(MainActivity.this, ActivitySearch.class);
MainActivity.this.startActivity(intent);
} else if (id == R.id.setting) {
Intent intent = new Intent(MainActivity.this, ActivitySetting.class);
MainActivity.this.startActivity(intent);
}
return true;
}
});
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(Gravity.START)) {
drawerLayout.closeDrawer(Gravity.START);
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
alertDialog.setTitle(R.string.exit);
alertDialog.setMessage(R.string.exit_ask);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
}
private void setTabOption() {
ViewPager viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new AdapterFragment(getSupportFragmentManager(),
context));
TabLayout tabStrip = findViewById(R.id.tabs);
tabStrip.setupWithViewPager(viewPager);
}
#Override
protected void onResume() {
super.onResume();
if (!list.isEmpty()){
list.clear();
selectList();
} if (!favorite.isEmpty()){
favorite.clear();
selectFavorite();
}
}
private void setupDB() {
try {
destPath =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/ielts/";
File file = new File(destPath);
if (!file.exists()) {
file.mkdirs();
file.createNewFile();
CopyDB(getBaseContext().getAssets().open("md_book.db"),
new FileOutputStream(destPath + "/md_book.db"));
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
private void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
private void selectFavorite() {
database = SQLiteDatabase.openOrCreateDatabase(destPath + "/md_book.db",
null);
#SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT * FROM main WHERE fav = 1",
null);
while (cursor.moveToNext()) {
String word = cursor.getString(cursor.getColumnIndex("word"));
String definition =
cursor.getString(cursor.getColumnIndex("definition"));
String trans = cursor.getString(cursor.getColumnIndex("trans"));
String img = cursor.getString(cursor.getColumnIndex("img"));
int id = cursor.getInt(cursor.getColumnIndex("id"));
Structure struct = new Structure(word, definition, trans, img, id);
struct.setWord(word);
struct.setDefinition(definition);
struct.setTrans(trans);
struct.setImg(img);
struct.setId(id);
favorite.add(struct);
}
}
private void selectList() {
database = SQLiteDatabase.openOrCreateDatabase(destPath + "/md_book.db",
null);
#SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT * FROM main", null);
while (cursor.moveToNext()) {
String word = cursor.getString(cursor.getColumnIndex("word"));
String definition =
cursor.getString(cursor.getColumnIndex("definition"));
String trans = cursor.getString(cursor.getColumnIndex("trans"));
String img = cursor.getString(cursor.getColumnIndex("img"));
int id = cursor.getInt(cursor.getColumnIndex("id"));
Structure struct = new Structure(word, definition, trans, img, id);
struct.setWord(word);
struct.setDefinition(definition);
struct.setTrans(trans);
struct.setImg(img);
struct.setId(id);
list.add(struct);
}
}
}
Update 5 innerpage activity
package farmani.com.essentialwordsforielts.innerpage;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toolbar;
import java.lang.reflect.Field;
import farmani.com.essentialwordsforielts.R;
import farmani.com.essentialwordsforielts.mainPage.AdapterFav;
public class ActivityInnerPage extends AppCompatActivity {
private TextView contentDescriptione;
private TextView moreDescriptione;
private ImageView avatar;
private ImageView imgCopy;
private ImageView imgShare;
private ImageView imgSms;
private ImageView imgGmail;
private FloatingActionButton favorite;
private CollapsingToolbarLayout collapsingToolbarLayout;
public String word;
public String definition;
public String trans;
public String img;
public int id;
private String destpath;
private SQLiteDatabase database;
private String favoriteState;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inner_page);
final android.support.v7.widget.Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
finish();
}
});
Bundle extras = getIntent().getExtras();
if (extras != null) {
int layoutId = Integer.parseInt(extras.getString("id"));
String pageName = extras.getString("name");
assert pageName != null;
if (pageName.equals("list")) {
id = MainActivity.list.get(layoutId).getId();
word = MainActivity.list.get(layoutId).getWord();
definition = MainActivity.list.get(layoutId).getDefinition();
trans = MainActivity.list.get(layoutId).getTrans();
img = MainActivity.list.get(layoutId).getImg();
} else if (pageName.equals("favorite")) {
id = MainActivity.favorite.get(layoutId).getId();
word = MainActivity.favorite.get(layoutId).getWord();
definition = MainActivity.favorite.get(layoutId).getDefinition();
trans = MainActivity.favorite.get(layoutId).getTrans();
img = MainActivity.favorite.get(layoutId).getImg();
}
}
contentDescriptione = findViewById(R.id.content_description);
moreDescriptione = findViewById(R.id.more_description);
imgCopy = findViewById(R.id.img_copy);
imgShare = findViewById(R.id.img_share);
imgSms = findViewById(R.id.img_sms);
imgGmail = findViewById(R.id.img_gmail);
avatar = findViewById(R.id.avatar);
favorite = findViewById(R.id.favorite);
collapsingToolbarLayout = findViewById(R.id.collapsing_toolbar);
collapsingToolbarLayout.getExpandedTitleMarginStart();
collapsingToolbarLayout.setTitle(word);
collapsingToolbarLayout.setExpandedTitleColor(getResources().getColor(android.R.color.holo_red_light));
contentDescriptione.setText(definition);
moreDescriptione.setText(trans);
int imgageId = MainActivity.context.getResources().getIdentifier(img, "drawable", MainActivity.context.getPackageName());
avatar.setImageResource(imgageId);
SharedPreferences prefes = getSharedPreferences("font_size", MODE_PRIVATE);
int value = prefes.getInt("fontsize", 16);
contentDescriptione.setTextSize(value);
moreDescriptione.setTextSize(value);
selectDb();
if(selectFavoriteState()){
favorite.setImageResource(R.drawable.ic_favorite_like);
}else {
favorite.setImageResource(R.drawable.ic_favorite_maylike);
}
favorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (selectFavoriteState()){
favorite.setImageResource(R.drawable.ic_favorite_maylike);
updateUnfavorited();
}else {
favorite.setImageResource(R.drawable.ic_favorite_like);
updateFavorited();
}
}
});
imgCopy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final ClipboardManager clipboardManager =
(ClipboardManager)ActivityInnerPage.this.getSystemService(Context.CLIPBOARD_SERVICE);
final ClipData clip = ClipData.newPlainText(word, trans+definition);
assert clipboardManager != null;
clipboardManager.setPrimaryClip(clip);
Snackbar.make(view,"متن کپی شد ",Snackbar.LENGTH_SHORT).show();
}
});
imgShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, definition+trans);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, word);
startActivity(Intent.createChooser(shareIntent, "Share"));
}
});
imgGmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent emailIntent = new Intent(Intent.ACTION_SENDTO
, Uri.fromParts("mailto", "", null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, word);
emailIntent.putExtra(Intent.EXTRA_TEXT, definition);
startActivity(Intent.createChooser(emailIntent, "Send email..."));
}catch (Exception e){
Snackbar.make(view,"برنامه ای برای ارسال ایمیل یافت نشد",Snackbar.LENGTH_SHORT).show();
}
}
});
imgSms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent sendSms = new Intent(Intent.ACTION_VIEW);
sendSms.putExtra("sms_body", definition + trans);
sendSms.setType("vnd.android-dir/mms-sms");
startActivity(sendSms);
}catch (Exception e){
Snackbar.make(view,"برنامه ای برای ارسال پیام یافت نشد",Snackbar.LENGTH_SHORT).show();
}
}
});
}
private void selectDb(){
destpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ielts/";
database = SQLiteDatabase.openOrCreateDatabase(destpath + "/md_book.db", null);
}
private boolean selectFavoriteState(){
#SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT * FROM main WHERE id = " + id, null);
while (cursor.moveToNext()){
favoriteState = cursor.getString(cursor.getColumnIndex("fav"));
}
return favoriteState.equals("1");
}
private void updateFavorited(){
database.execSQL( "UPDATE main SET fav = 1 WHERE id = " + id);
}
private void updateUnfavorited(){
database.execSQL( "UPDATE main SET fav = 0 WHERE id = " + id);
}
}
In your FloatingActionButton onClick method after you save the new item in your database, insert your new item into your recyclerview datasource list and call notifyDatasetChanged() on the adapter.
Choice 1: in onResume() stub of MainActivity, call selectList() and selectFavorite() and then load the PageFragment again so that the new list is loaded properly.
This is the shortest wayout but this approach is very much unoptimized and is not recommended.
Choice 2: You will have to insert the new item in database as well as add it to the List and then call notifyDatasetChanged
In MainActivity within methods selectList() and selectFavorite() after you perform list.add(struct) and favourite.add(struct) respectively, you will have to call notifyDatasetChanged() for the Adapter.
But the problem is your RecyclerView is in the PageFragment whereas you're populating the list in MainActivity.
So move your selectList() and selectFavorite() to PageFragment where you first initialize the RecylerView then, set the Adapter and then populate the list and finally call notifyDatasetChanged() on your adapters.
I'm writing an app and i try do a login page that when the user press login it will check if the username&password that he entered exists in the database, but for some reason its not getting the username on the handler
Here is the handler:
package com.example.nir.nestleapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.HashMap;
public class MyDBHandler extends SQLiteOpenHelper {
SQLiteDatabase db;
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "UsersTable.db";
public static final String Table_Name = "UsersTable";
public static final String KEY_User = "User";
public static final String KEY_Password = "Password";
public static final String KEY_FullName = "FullName";
public static final String KEY_PhoneNumber="PhoneNumber";
public static final String KEY_IDNUMBER="IDNumber";
public static final String[] DB_COL = new String[]{KEY_User,KEY_Password,KEY_FullName,KEY_PhoneNumber,KEY_IDNUMBER};
public MyDBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CreateTableSql = "Create Table " + Table_Name + " ( " +
KEY_User + " INTEGER PRIMARY KEY AUTOINCREMENT , " +
KEY_Password + " TEXT , " +
KEY_FullName + " TEXT , "+
KEY_PhoneNumber+" TEXT , "+
KEY_IDNUMBER+ " ) ";
db.execSQL(CreateTableSql);
}#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + Table_Name);
onCreate(db);
}
public String SearchPass(String Username)
{
db=this.getReadableDatabase();
String query="select User, Password from "+Table_Name;
Cursor cursor=db.rawQuery(query,null);
String a,b;
b="wrong details!";
if(cursor.moveToFirst())
{
do {
a=cursor.getString(0);
if (a.equals(Username))
{
b=cursor.getString(1);
break;
}
}
while (cursor.moveToFirst());
}
return b;
}
public void Add(UserTable NewUser) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_User,NewUser.GetUserName() );
values.put(KEY_Password, NewUser.GetPassword());
values.put(KEY_FullName,NewUser.GetFullName());
values.put(KEY_PhoneNumber,NewUser.GetPhoneNumber());
values.put(KEY_IDNUMBER,NewUser.GetID());
db.insert(Table_Name, null, values);
db.close();
}
}
Here is the login java activity:
package com.example.nir.nestleapp;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.reflect.GenericArrayType;
import java.util.ArrayList;
public class LoginActivity extends AppCompatActivity {
MyDBHandler db=new MyDBHandler(this);
public DrawerLayout mDrawer;
public ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mDrawer = (DrawerLayout) findViewById(R.id.activity_login);
mToggle = new ActionBarDrawerToggle(this, mDrawer, R.string.open, R.string.close);
mDrawer.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final TextView RegisterPage = (TextView) findViewById(R.id.textView4);
TextView Text1 = (TextView) findViewById(R.id.textView3);
final Button Login = (Button) findViewById(R.id.LoginBtn);
Button GuestLogin = (Button) findViewById(R.id.LoginGuestBtn);
final EditText LoginUser = (EditText) findViewById(R.id.LoginUser);
final EditText LoginPass = (EditText) findViewById(R.id.LoginPassword);
RegisterPage.setTextSize(17);
Text1.setTextSize(17);
RegisterPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
}
});
GuestLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, MainPageActivity.class));
}
});
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (LoginUser.getText().toString().isEmpty() || LoginPass.getText().toString().isEmpty()) {
Toast.makeText(LoginActivity.this, "", Toast.LENGTH_SHORT).show();
}
if (db.SearchPass(LoginUser.getText().toString()).equals(LoginPass.getText().toString())) {
Toast.makeText(LoginActivity.this, "!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginActivity.this,MainPageActivity.class));
}
else
{
Toast.makeText(LoginActivity.this, db.SearchPass(LoginUser.getText().toString()), Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.navigation_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.MainPage:
startActivity(new Intent(this, MainPageActivity.class));
break;
}
return super.onOptionsItemSelected(item);
}
}
here is the register java activity:
package com.example.nir.nestleapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class RegisterActivity extends AppCompatActivity {
MyDBHandler db=new MyDBHandler(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
TextView RegisterHead = (TextView) findViewById(R.id.RegisterHeadline);
RegisterHead.setTextSize(25);
Button CompleteRegister = (Button) findViewById(R.id.CompleteRegisterBtn);
final EditText RegisteredUser = (EditText) findViewById(R.id.RegisteredUser);
final EditText RegisteredPass = (EditText) findViewById(R.id.RegisteredPass);
final EditText RegisteredName = (EditText) findViewById(R.id.RegisteredFn);
final EditText RegisteredPhone = (EditText) findViewById(R.id.RegisteredPhone);
final EditText RegisteredID = (EditText) findViewById(R.id.RegisteredID);
CompleteRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String User2String = String.valueOf(RegisteredUser.getText());
final String Pass2String = String.valueOf(RegisteredPass.getText());
final String Name2String = String.valueOf(RegisteredName.getText());
final String Phone2String = String.valueOf(RegisteredPhone.getText());
String ID2String = String.valueOf(RegisteredID.getText());
db = new MyDBHandler(RegisterActivity.this);
if (User2String.equals("") || Pass2String.equals("") || Name2String.equals("") || Phone2String.equals("") || ID2String.equals("")) {
Toast.makeText(RegisterActivity.this, ", Toast.LENGTH_SHORT).show();
}
else {
UserTable NewUser = new UserTable(User2String, Pass2String, Name2String, Phone2String, ID2String);
db.Add(NewUser);
Toast.makeText(RegisterActivity.this, "", Toast.LENGTH_SHORT).show();
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
}
}
});
}
}
I think the problem is in the handler searchpass function but i cant put my finger on it, there isn't any error.