I have an activity with tow tabs(with viewPager). inside viewPager is a fragment that have RecyclerView.
first tab is for (Monday-Friday) and second tab is for (Saturday-Sunday)
I want to retrieve data from database and show in recyclerview on each tab. but i cant update my recyclerView. Please help me to do that.And another problem is that when RecyclerView show data only show first row, but the number of rows in the table.like this:
10:06:00
10:06:00
10:06:00
10:06:00
10:06:00
10:06:00
here is my code:
this is my Fragment code:
public class toDastgheybFragment extends BaseFragment {
private List<DatabaseModel> Times = new ArrayList<DatabaseModel>();
DatabaseHelper databaseHelper;
private View mView;
RecyclerView mRecyclerView;
RecyclerView.Adapter mAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_to_dastgheyb, container,
false);
databaseHelper = new DatabaseHelper(getContext());
Times = databaseHelper.getAllUsers();
mRecyclerView = mView.findViewById(R.id.myRecycler);
mAdapter = new DataAdapter(Times);
mRecyclerView.setLayoutManager(new
LinearLayoutManager(getContext()));
mRecyclerView.setAdapter(mAdapter);
return mView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayList<DatabaseModel> LineList = new ArrayList<>();
LineList.clear();
mAdapter = new DataAdapter(LineList);
DatabaseHelper db = new DatabaseHelper(getContext());
final List<DatabaseModel> m = db.getAllUsers();
if (m.size() > 0) {
for (int i = 0; i < m.size(); i++) {
LineList.add(m.get(i));
mAdapter.notifyDataSetChanged();
}
}
db.close();
}
}
and this is my DataHelper code:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "MetroDB";//name of the
database
private static final String TABLE_NAME = "stationtime";//name for the
table
static String db_path = "/data/data/ir.shirazmetro/databases/";
private static final String Station = "station";
private static final String Time = "time";
private static final String Line = "line";
private final Context context;
private SQLiteDatabase database;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE IF NOT EXISTS " +
TABLE_NAME + "(" + Station + " TEXT," + Time + " TEXT," + Line + " TEXT)";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
private boolean checkExist() {
SQLiteDatabase db = null;
try {
db = SQLiteDatabase.openDatabase(db_path + DATABASE_NAME, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLException e) {
}
return db != null;
}
private void copyDatabase() throws IOException {
OutputStream myOutput = new FileOutputStream(db_path +
DATABASE_NAME);
byte[] buffer = new byte[1024];
int length;
InputStream myInput = context.getAssets().open(DATABASE_NAME +
".db");
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myInput.close();
myOutput.flush();
myOutput.close();
}
public void importIfNotExist() throws IOException {
boolean dbExist = checkExist();
if (!dbExist) {
this.getReadableDatabase();
try {
copyDatabase();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void open() {
database = SQLiteDatabase.openDatabase(db_path + DATABASE_NAME, null,
SQLiteDatabase.OPEN_READWRITE);
}
public List<DatabaseModel> getAllUsers() {
List<DatabaseModel> contactList = new ArrayList<DatabaseModel>();
String whatStation = C.whatStation;
String whatLine = C.whatLine;
String selectQuery = "SELECT " + Time + " FROM " + TABLE_NAME + "
WHERE " + Station + " LIKE '%" + whatStation + "%' AND " + Line + " LIKE '%"
+ whatLine + "%'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
if (cursor.getCount() > 0) {
do {
DatabaseModel m = new DatabaseModel();
m.setTime(cursor.getString(cursor.getColumnIndex(Time)));
contactList.add(m);
} while (cursor.moveToNext());
}
return contactList;
}
}
and finally this is my activity code:
public class station extends BaseActivity {
Toolbar mToolbar;
private TabLayout tbLayout;
private ViewPager vPager;
RecyclerView.Adapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_station);
final DatabaseHelper helper = new DatabaseHelper(this);
try {
helper.importIfNotExist();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
mToolbar = findViewById(R.id.tlbr1);
setSupportActionBar(mToolbar);
initView();
setupWithViewPager();
tbLayout.addOnTabSelectedListener(new
TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
public void line1(View view) {
Intent line1 = new Intent(this, line1.class);
startActivity(line1);
}
private void setupWithViewPager() {
BasePagerAdapter basePagerAdapter = new BasePagerAdapter(this,
getSupportFragmentManager());
vPager.setAdapter(basePagerAdapter);
tbLayout.setupWithViewPager(vPager);
}
private void initView() {
vPager = findViewById(R.id.view_pager);
tbLayout = findViewById(R.id.tab_layout);
backBtn = findViewById(R.id.backBtn);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.backBtn:
line1(view);
return;
}
}
}
Related
so im trying to get recyclerview data list added and send it to ion lib when i use method below i only get one element as ill have to change string inside for() to String fav =null ouside of for() and log.d only shows the last result. i need get all so i can send to senddata() to ion lib
FavModelClass
private String fav;
private String user_id;
public FavModelClass(String fav, String user_id) {
this.fav = fav;
this.user_id = user_id;
}
public String getFav() {
return fav;
}
public void setFav(String fav) {
this.fav = fav;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
}
adapter
public class FavAdapter extends
RecyclerView.Adapter<FavAdapter .MyViewHolder> {
private List<FavModelClass> favModelClassList;
private Context beddingContext;
public FavAdapter (List<FavModelClass> favModelClassList, Context
beddingContext) {
this.favModelClassList= favModelClassList;
this.beddingContext = beddingContext;
}
#NonNull
#Override
public FavAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup
parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.amenitylayout,parent,false);
FavAdapter .MyViewHolder holder = new FavAdapter .MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull FavAdapter.MyViewHolder holder, int i) {
final FavModelClassdata = favModelClassList.get(i);
holder.ac_bedding_type.setText(data.getFav()+" "+"MAX:"+data.getUser_id());
holder.delete_entry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
removeAt(holder.getAdapterPosition());
}
});
}
public void removeAt(int position) {
favModelClassList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, favModelClassList.size());
}
#Override
public int getItemCount() {
return favModelClassList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView ac_bedding_type;
private ImageButton delete_entry;
public MyViewHolder(#NonNull View v) {
super(v);
ac_bedding_type = v.findViewById(R.id.ac_amenity_name);
delete_entry = v.findViewById(R.id.delete_amenity_entry);
}
}
}
Main activity
fav_recycler = findViewById(R.id.fave_recycler);
GridLayoutManager layoutManager1 = new GridLayoutManager(getApplicationContext(), 2,GridLayoutManager.VERTICAL, false);
fav_recycler.setHasFixedSize(true);
fav_recycler.setLayoutManager(layoutManager1);
favModelClassList= new ArrayList<>();
addfavamenity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
favModelClassList.add(new FavModelClass(
amenityET.getText().toString(),
user_idET.getText().toString()
));
amenityET.setText("");
user_idET.setText("");
FavAdapter adapter = new FavAdapter (favModelClassList, getApplicationContext());
adapter.notifyDataSetChanged();
fav_recycler.setAdapter(adapter);
for (int i = 0; i < favModelClassList.size(); i++) {
final FavModelClassList data = favModelClassList.get(i);
final String fav= data.getFav();
final String user_id = data.getUser_id();
Log.d(TAG, "onClick: "+ fav);
}
}
});
ArrayList d = new ArrayList();
for (int i = 0; i < favModelClassList.size(); i++) {
final FavModelClassList data = favModelClassList.get(i);
d.add(data.getFav());
}
Log.d(TAG, "onClick: " + d);
I'm facing an issue with my viewpager2 adapter. The adapter contains a share button which starts an new activity with a create chooser Intent. The problem is if swipe down or press the android back button the current item layout is flattened or sometime it changes the current item to the next one.
However if go through the sharing process completely the app works fine.
ViewPager2.JAVA*
public class StreamPostDetailAdapter extends RecyclerView.Adapter<StreamPostDetailAdapter.TestPagerViewHolder> {
public Context mContext;
public List<Post> mPost;
private FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
String mUid ;
public IpagerAdapter mListener;
private CommentAdapter commentAdapter;
private List<Comment> commentList;
public StreamPostDetailAdapter(Context mContext, List<Post> mPost, IpagerAdapter mListener) {
this.mListener = mListener;
this.mContext = mContext;
this.mPost = mPost;
mUid = firebaseUser.getUid();
}
#NonNull
#Override
public TestPagerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_post_swipe_item, parent, false);
return new TestPagerViewHolder(view,mListener);
}
#Override
public void onBindViewHolder(#NonNull TestPagerViewHolder holder, int position) {
Post post = mPost.get(holder.getBindingAdapterPosition());
String post_publisher = post.getPublisher();
String post_id = post.getPostid() ;
String post_image = post.getPostimage() ;
String post_timeStamp = post.getTimestamp();
String tag_list = post.getTagList();
String postTitle = post.getDescription();
boolean personal = post.getPersonal_tattoo();
commentList = new ArrayList<>();
commentAdapter = new CommentAdapter(mContext,commentList);
GlideApp.with(mContext).load(post_image)
.placeholder(R.mipmap.loading_img_placeholder)
.into(holder.image_post);
holder.title.setText(post.getDescription());
if (post.getTagList().equals("")) {
holder.tagList.setVisibility(View.GONE);
} else {
holder.tagList.setVisibility(View.VISIBLE);
holder.tagList.setText(post.getTagList());
}
holder.comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.bsCommentsController(post_id, holder.commentRv);
BottomSheetBehavior.from(holder.bsComments).setState(BottomSheetBehavior.STATE_EXPANDED);
}
});
holder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.like.getTag().equals("like")) {
FirebaseDatabase.getInstance().getReference().child("Likes")
.child(post_id)
.child(mUid).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Likes")
.child(post_id)
.child(mUid).removeValue();
}
}
});
holder.image_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", Context.MODE_PRIVATE).edit();
editor.putString("id", post_publisher);
editor.apply();
Intent intent = new Intent(mContext,HomeActivity.class);
intent.putExtra("origin","ViewPager");
mContext.startActivity(intent);
((StreamPostDetailActivity)mContext).finish();
}
});
holder.save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mContext instanceof SavedPostActivity) {
mListener.removePost(post_id,post_image,position);
}
if (holder.save.getTag().equals("save")) {
FirebaseDatabase.getInstance().getReference().child("Saved").child(firebaseUser.getUid())
.child(post_id).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Saved").child(firebaseUser.getUid())
.child(post_id).removeValue();
}
}
});
holder.share_post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BitmapDrawable drawable = (BitmapDrawable)holder.image_post.getDrawable();
Bitmap bitmap = drawable.getBitmap();
String path = MediaStore.Images.Media.insertImage(mContext.getContentResolver(), bitmap, UUID.randomUUID().toString() + ".jpeg", "drawing");
Uri uri = Uri.parse(path);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM,uri);
intent.putExtra(Intent.EXTRA_TEXT, "Playstore Link : put app link in store ");
mContext.startActivity(Intent.createChooser(intent,"Share2"));
}
});
if (mContext instanceof SearchTattooDetailsActivity) {
holder.btn_post_options.setVisibility(View.GONE);
}else {
holder.btn_post_options.setVisibility(View.VISIBLE);
holder.btn_post_options.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showMoreOptions(holder.btn_post_options, post_publisher, mUid, post_id, post_image, position, postTitle
, tag_list, personal);
}
});
}
// Add a new comment
holder.sendComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!holder.comment_bar_edt.getText().toString().equals("")){
mListener.addComment(post_id, holder.comment_bar_edt.getText().toString());
holder.comment_bar_edt.setText("");
holder.comment_bar_edt.clearFocus();
}
}
});
holder.commentRv.setHasFixedSize(true);
holder.commentRv.setAdapter(commentAdapter);
}
#Override
public int getItemCount() {
return mPost.size();
}
private void showMoreOptions(ImageButton btn_post_options, String post_publisher, String mUid, String post_id, String post_image,int posItem, String postTitle, String tagList, boolean personal) {
PopupMenu popupMenu = new PopupMenu(mContext,btn_post_options, Gravity.END);
if (!post_publisher.equals(mUid)) {
popupMenu.getMenu().add(Menu.NONE,0,0,"Report post");
}
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
if (id == 0){
Toast.makeText(mContext, "CreateReportPost/UserNewCategoryRequestEmail", Toast.LENGTH_SHORT).show();
} else if (id == 1) {
//not working
Intent intentEdit = new Intent(mContext, EditPostActivity.class);
intentEdit.putExtra("title",postTitle);
intentEdit.putExtra("imageUrl", post_image);
intentEdit.putExtra("tagList", tagList );
intentEdit.putExtra("personal", personal );
intentEdit.putExtra("postId", post_id);
intentEdit.putExtra("posEditedPost", posItem);
((Activity)mContext).finish();
mContext.startActivity(intentEdit);
}
return false;
}
});
popupMenu.show();
}
//View Holder Class
public static class TestPagerViewHolder extends RecyclerView.ViewHolder {
public ImageView image_profile, image_post, like, comment, save,share_post;
public TextView username, likes, comments, title, time,tagList;
public ImageButton btn_post_options;
public IpagerAdapter mListener;
//Comments Bottom sheet
EditText comment_bar_edt;
public RecyclerView commentRv ;
ImageView sendComment,userImgComment;
public ConstraintLayout bsComments;
public LinearLayoutManager layoutManager;
public TestPagerViewHolder(#NonNull View itemView, IpagerAdapter mListener) {
super(itemView);
this.mListener = mListener;
image_post = itemView.findViewById(R.id.post_image);
image_profile = itemView.findViewById(R.id.image_profile);
like = itemView.findViewById(R.id.like_ic);
share_post= itemView.findViewById(R.id.share_post);
comment = itemView.findViewById(R.id.comment_ic);
save = itemView.findViewById(R.id.save);
username = itemView.findViewById(R.id.username);
likes = itemView.findViewById(R.id.likes);
comments = itemView.findViewById(R.id.comments);
tagList = itemView.findViewById(R.id.tagList);
title = itemView.findViewById(R.id.title);
time = itemView.findViewById(R.id.time);
btn_post_options = itemView.findViewById(R.id.post_options);
bsComments= itemView.findViewById(R.id.bsComments);
comment_bar_edt = itemView.findViewById(R.id.comment_bar_edt);
sendComment = itemView.findViewById(R.id.sendComment);
commentRv = itemView.findViewById(R.id.comments_rv);
BottomSheetBehavior.from(bsComments).setState(BottomSheetBehavior.STATE_HIDDEN);
}
}
public interface IpagerAdapter {
void removePost(String post_id, String post_image, int position);
void bsCommentsController(String post_id, RecyclerView commentRecyclerView);
void addComment(String post_id,String comment_txt);
}
public void removeItem(int position) {
if (position > -1 && position < mPost.size()) {
mPost.remove(position);
notifyDataSetChanged();
notifyItemRemoved(position);
}
}
}
#Francis,
Since It has been a while, I just remember that I've made changes in how I handled the BottomSheet which was containing the Comments RecyclerView. I extracted it from the StreamPostDetailAdapter (ViewPager2) and moved it to the corresponding activity. Therefore I have only one BottomSheet for all viewpager2 items. Then recyclerView data (comments fetch from firebase) is updated using interface listener methods to populate each items.
You will find the code of the ViewPager2 below:
public class StreamPostDetailAdapter extends RecyclerView.Adapter<StreamPostDetailAdapter.TestPagerViewHolder> {
public Context mContext;
public List<Post> mPost;
private FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
String mUid ;
public IpagerAdapter mListener;
private CommentAdapter commentAdapter;
private List<Comment> commentList;
public StreamPostDetailAdapter(Context mContext, List<Post> mPost, IpagerAdapter mListener) {
this.mListener = mListener;
this.mContext = mContext;
this.mPost = mPost;
mUid = firebaseUser.getUid();
}
#NonNull
#Override
public TestPagerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_post_swipe_item, parent, false);
return new TestPagerViewHolder(view,mListener);
}
#Override
public void onBindViewHolder(#NonNull TestPagerViewHolder holder, int position) {
Post post = mPost.get(holder.getBindingAdapterPosition());
String post_publisher = post.getPublisher();
String post_id = post.getPostid() ;
String post_image = post.getPostimage() ;
String post_timeStamp = post.getTimestamp();
String tag_list = post.getTagList();
String postTitle = post.getDescription();
boolean personal = post.getPersonal_tattoo();
GlideApp.with(mContext).load(post_image)
.placeholder(R.mipmap.loading_img_placeholder)
.into(holder.image_post);
holder.title.setText(post.getDescription());
if (post.getTagList().equals("")) {
holder.tagList.setVisibility(View.GONE);
} else {
holder.tagList.setVisibility(View.VISIBLE);
holder.tagList.setText(post.getTagList());
}
publisherInfo(holder.image_profile, holder.username, post_publisher);
asLiked(post_id, holder.like);
nLikes(holder.likes, post_id);
//getComments(post_id, holder.comments);
isSaved(post_id, holder.save);
getTimeAgo(holder.time, post_timeStamp);
holder.comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.openBsComment();
}
});
holder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.like.getTag().equals("like")) {
FirebaseDatabase.getInstance().getReference().child("Likes")
.child(post_id)
.child(mUid).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Likes")
.child(post_id)
.child(mUid).removeValue();
}
}
});
holder.image_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", Context.MODE_PRIVATE).edit();
editor.putString("id", post_publisher);
editor.apply();
Intent intent = new Intent(mContext,HomeActivity.class);
intent.putExtra("origin","ViewPager");
mContext.startActivity(intent);
((StreamPostDetailActivity)mContext).finish();
}
});
holder.save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mContext instanceof SavedPostActivity) {
mListener.removePost(post_id,post_image,position);
}
if (holder.save.getTag().equals("save")) {
FirebaseDatabase.getInstance().getReference().child("Saved").child(firebaseUser.getUid())
.child(post_id).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Saved").child(firebaseUser.getUid())
.child(post_id).removeValue();
}
}
});
holder.share_post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BitmapDrawable drawable = (BitmapDrawable)holder.image_post.getDrawable();
Bitmap bitmap = drawable.getBitmap();
mListener.sharePost(bitmap);
}
});
if (mContext instanceof TaggedTattooDetailsActivity) {
holder.btn_post_options.setVisibility(View.GONE);
}else {
holder.btn_post_options.setVisibility(View.VISIBLE);
holder.btn_post_options.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showMoreOptions(holder.btn_post_options, post_publisher, mUid, post_id, post_image, position, postTitle
, tag_list, personal);
}
});
}
// Add a new comment
}
#Override
public int getItemCount() {
return mPost.size();
}
private void showMoreOptions(ImageButton btn_post_options, String post_publisher, String mUid, String post_id, String post_image,int posItem, String postTitle, String tagList, boolean personal) {
PopupMenu popupMenu = new PopupMenu(mContext,btn_post_options, Gravity.END);
if (!post_publisher.equals(mUid)) {
popupMenu.getMenu().add(Menu.NONE,0,0,"Report post");
}
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
if (id == 0){
Toast.makeText(mContext, "CreateReportPost/UserNewCategoryRequestEmail", Toast.LENGTH_SHORT).show();
} else if (id == 1) {
//not working
Intent intentEdit = new Intent(mContext, EditPostActivity.class);
intentEdit.putExtra("title",postTitle);
intentEdit.putExtra("imageUrl", post_image);
intentEdit.putExtra("tagList", tagList );
intentEdit.putExtra("personal", personal );
intentEdit.putExtra("postId", post_id);
intentEdit.putExtra("posEditedPost", posItem);
((Activity)mContext).finish();
mContext.startActivity(intentEdit);
}
return false;
}
});
popupMenu.show();
}
//View Holder Class
public static class TestPagerViewHolder extends RecyclerView.ViewHolder {
public ImageView image_profile, image_post, like, comment, save,share_post;
public TextView username, likes, comments, title, time,tagList;
public ImageButton btn_post_options;
public IpagerAdapter mListener;
//Comments Bottom sheet
public LinearLayoutManager layoutManager;
public TestPagerViewHolder(#NonNull View itemView, IpagerAdapter mListener) {
super(itemView);
this.mListener = mListener;
image_post = itemView.findViewById(R.id.post_image);
image_profile = itemView.findViewById(R.id.image_profile);
like = itemView.findViewById(R.id.like_ic);
share_post= itemView.findViewById(R.id.share_post);
comment = itemView.findViewById(R.id.comment_ic);
save = itemView.findViewById(R.id.save);
username = itemView.findViewById(R.id.username);
likes = itemView.findViewById(R.id.likes);
comments = itemView.findViewById(R.id.comments);
tagList = itemView.findViewById(R.id.tagList);
title = itemView.findViewById(R.id.title);
time = itemView.findViewById(R.id.time);
btn_post_options = itemView.findViewById(R.id.post_options);
}
}
public interface IpagerAdapter {
void removePost(String post_id, String post_image, int position);
void openBsComment();
void sharePost(Bitmap postImage);
}
private void getComments(String postid, TextView comments) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Comments").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.getChildrenCount() != 0) {
comments.setText(" " + snapshot.getChildrenCount());
} else {
comments.setVisibility(View.GONE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void getTimeAgo(TextView time, String stamp_post) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");;
Log.i(TAG, "timestamp value in format date: "+ stamp_post);
try {
long timeStamp = sdf.parse(stamp_post).getTime();
long now = System.currentTimeMillis();
CharSequence ago = DateUtils.getRelativeTimeSpanString(timeStamp, now, DateUtils.MINUTE_IN_MILLIS);
Log.i(TAG, "timestamp milli value is: " + timeStamp);
time.setText(ago);
} catch (ParseException e) {
e.printStackTrace();
}
}
private void asLiked(String postid, final ImageView imageView) {
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Likes").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.child(firebaseUser.getUid()).exists()) {
imageView.setImageResource(R.drawable.liked);
imageView.setTag("liked");
} else {
imageView.setImageResource(R.drawable.ic_like);
imageView.setTag("like");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void nLikes(final TextView likes, String postid) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Likes").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
likes.setText(" "+ snapshot.getChildrenCount());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void isSaved(String postid, final ImageView imageView) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Saved").child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.child(postid).exists()) {
imageView.setImageResource(R.drawable.ic_bookmark_colored);
imageView.setTag("saved");
} else {
imageView.setImageResource(R.drawable.ic_save_post);
imageView.setTag("save");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void publisherInfo(ImageView image_profile, TextView username, String userid) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("App_users")
.child(userid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
Glide.with(mContext.getApplicationContext()).load(user.getimageUrl()).into(image_profile);
username.setText(user.getUsername());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
public void removeItem(int position) {
if (position > -1 && position < mPost.size()) {
mPost.remove(position);
notifyDataSetChanged();
notifyItemRemoved(position);
}
}
}
I have a button in recycleview(part of cardview, which is generated for each insertion) which increments an specific column with id in SQLite, the data gets changed but I have to relaunch the activity for it to change.
The changed data has to be shown in textview.
I am new to this, how can I make them change dynamically?
public class attendence_recycleadapter extends RecyclerView.Adapter<attendence_recycleadapter.ViewHolder> {
private List<attendence> mattendence_list;
private Context mcontext;
public RecyclerView mrecycleview;
#NonNull
#Override
public attendence_recycleadapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater= LayoutInflater.from(parent.getContext());
View v=inflater.inflate(R.layout.attendence_recycleview_card,parent,false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull attendence_recycleadapter.ViewHolder holder, final int position) {
final attendence attendence= mattendence_list.get(position);
holder.subname.setText("NAME: " + attendence.getSubname());
holder.subcredit.setText("CREDIT: " + attendence.getCredit());
holder.bunks.setText("BUNKS: " + attendence.getBunks());
holder.deletesub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Myhelper myhelper = new Myhelper(mcontext);
myhelper.delete(attendence.getId(),mcontext);
notifyItemRemoved(position);
notifyItemRangeChanged(position,mattendence_list.size());
notifyDataSetChanged();
delete(position);
}
});
holder.addbunk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Myhelper myhelper = new Myhelper(mcontext);
myhelper.updatebunk(attendence.getId());
Toast.makeText(mcontext,"+1 class bunked",Toast.LENGTH_SHORT).show();
}
});
holder.deletebunk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Myhelper myhelper=new Myhelper(mcontext);
myhelper.updatebunkdelete(attendence.getId());
Toast.makeText(mcontext,"Bunk deleted",Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return mattendence_list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView subname;
public TextView subcredit;
public TextView bunks;
public View layout;
public TextView addbunk;
public TextView deletebunk;
public TextView deletesub;
public ViewHolder(View itemView) {
super(itemView);
layout=itemView;
subname=(TextView)itemView.findViewById(R.id.attendernce_subname);
subcredit=(TextView)itemView.findViewById(R.id.attendernce_credit);
bunks=(TextView)itemView.findViewById(R.id.attendernce_bunks);
deletebunk =(TextView)itemView.findViewById(R.id.attendence_deletebunk);
addbunk = (TextView) itemView.findViewById(R.id.attendence_addbunk);
deletesub = (TextView) itemView.findViewById(R.id.attendence_deletesub);
}
}
public void add(int position,attendence attendence2){
mattendence_list.add(position,attendence2);
notifyItemInserted(position);
}
public void delete(int position){
mattendence_list.remove(position);
notifyItemRemoved(position);
}
public attendence_recycleadapter(List<attendence> mydataset, Context context, RecyclerView recyclerView){
mattendence_list = mydataset;
mcontext = context;
mrecycleview= recyclerView;
}
}
myactivity:
public class Manage_attendence extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private attendence_recycleadapter attendence_recycleadapter;
String filter="";
TextView add_subject;
Dialog mycustomDialog;
Myhelper myhelper;
SQLiteDatabase sqLiteDatabase;
Spinner nema_of_credit;
EditText name_of_subject;
String spinner_string = new String();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_attendence);
add_subject=(TextView)findViewById(R.id.add_subject_dialog);
mycustomDialog = new Dialog(this);
myhelper = new Myhelper(this);
sqLiteDatabase = myhelper.getWritableDatabase();
add_subject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setupDialog();
}
});
recyclerView= (RecyclerView)findViewById(R.id.attendence_recycleview);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
attendence_recycleadapter= new attendence_recycleadapter(myhelper.list(filter),this,recyclerView);
recyclerView.setAdapter(attendence_recycleadapter);
name_of_subject = (EditText) mycustomDialog.findViewById(R.id.name_of_subject);
nema_of_credit = (Spinner) mycustomDialog.findViewById(R.id.subject_credit);
}
public void setupDialog() {
mycustomDialog.setContentView(R.layout.dialog_add_subject);
TextView close = (TextView) mycustomDialog.findViewById(R.id.subject_delete);
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mycustomDialog.dismiss();
}
});
exqButton();
mycustomDialog.setCancelable(false);
mycustomDialog.show();
mycustomDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
private void exqButton() {
TextView add =(TextView)mycustomDialog.findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name_of_subject = (EditText) mycustomDialog.findViewById(R.id.name_of_subject);
nema_of_credit = (Spinner) mycustomDialog.findViewById(R.id.subject_credit);
String xValues=String.valueOf(name_of_subject.getText());
spinner_string=nema_of_credit.getSelectedItem().toString();
String yValues= ((String.valueOf(spinner_string)));
boolean insertData = myhelper.insertData(xValues,yValues,0);
if (insertData==true){
Toast.makeText(Manage_attendence.this,"data inserted sucessfully",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(Manage_attendence.this,"data inserted failed",Toast.LENGTH_SHORT).show();
}
name_of_subject.setText("");
mycustomDialog.dismiss();
}
});
}
}
mysqlitehelper:
public class Myhelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="mydatabase.db";
public static final String TABLE_NAME="mytable";
public static final String COLUMN_ID="_id";
public static final String COL_1="NAME";
public static final String COL_2="CREDIT";
public static final String COL_3="BUNKS";
public static final String[] COLUMNS ={COLUMN_ID,COL_1,COL_2,COL_3};
Context con;
public Myhelper(Context context) {
super(context, DATABASE_NAME, null, 1);
con = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable= "CREATE TABLE " + TABLE_NAME + " (" + COLUMN_ID +" INTEGER PRIMARY KEY AUTOINCREMENT, " + " NAME TEXT, CREDIT TEXT, BUNKS INTEGER )";
db.execSQL(createTable);
Toast.makeText(con,"table created",Toast.LENGTH_SHORT).show();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
onCreate(db);
}
public boolean insertData(String x,String y,int z){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1, String.valueOf(x));
contentValues.put(COL_2,String.valueOf(y));
contentValues.put(COL_3,z);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
public ArrayList<String> queryXdata(){
ArrayList<String> xnewdata= new ArrayList<String>();
String query = "SELECT "+ COL_1 + " FROM " + TABLE_NAME;
SQLiteDatabase db=this.getWritableDatabase();
Cursor cursor= db.rawQuery(query,null);
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
xnewdata.add(cursor.getString(cursor.getColumnIndex(COL_1)));
}
cursor.close();
return xnewdata;
}
public ArrayList<Integer> queryYdata(){
ArrayList<Integer> ynewdata= new ArrayList<Integer>();
String query = "SELECT "+ COL_3+ " FROM " + TABLE_NAME;
SQLiteDatabase db=this.getWritableDatabase();
Cursor cursor= db.rawQuery(query,null);
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
ynewdata.add(cursor.getInt(cursor.getColumnIndex(COL_3)));
}
cursor.close();
return ynewdata;
}
public ArrayList<Integer> queryZdata(){
ArrayList<Integer> znewdata= new ArrayList<Integer>();
String query = "SELECT "+ COL_2+ " FROM " + TABLE_NAME;
SQLiteDatabase db=this.getWritableDatabase();
Cursor cursor= db.rawQuery(query,null);
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
znewdata.add(((cursor.getColumnIndex(COL_2))));
}
cursor.close();
return znewdata;
}
public attendence getdetails(long id){
SQLiteDatabase db = this.getWritableDatabase();
String query= "SELECT" + COL_2+" FROM " + TABLE_NAME +" WHERE _id=" + id;
Cursor cursor= db.rawQuery(query,null);
attendence attendence1= new attendence();
if (cursor.getCount()>0){
cursor.moveToFirst();
attendence1.setSubname(cursor.getString(cursor.getColumnIndex(COL_1)));
attendence1.setCredit(cursor.getString(cursor.getColumnIndex(COL_2)));
attendence1.setBunks(cursor.getInt(cursor.getColumnIndex(COL_3)));
}
return attendence1;
}
public void delete(long id,Context context){
SQLiteDatabase db=this.getWritableDatabase();
db.execSQL("DELETE FROM "+TABLE_NAME+" WHERE _id='"+id+"'");
Toast.makeText(context,"delted",Toast.LENGTH_SHORT).show();
}
public List<attendence> list(String filter){
String query;
if (filter.equals("")){
query = "SELECT * FROM " + TABLE_NAME ;
}
else {
query= " SELECT * FROM " + TABLE_NAME ;
}
List<attendence> linkedlist = new LinkedList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query,null);
attendence attendence;
if (cursor.moveToFirst()){
do {
attendence = new attendence();
attendence.setId(cursor.getLong(cursor.getColumnIndex(COLUMN_ID)));
attendence.setSubname(cursor.getString(cursor.getColumnIndex(COL_1)));
attendence.setCredit(cursor.getString(cursor.getColumnIndex(COL_2)));
attendence.setBunks(cursor.getInt(cursor.getColumnIndex(COL_3)));
linkedlist.add(attendence);
}
while (cursor.moveToNext());
}
return linkedlist;
}
public int getbunk(long id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + COLUMN_ID + " = " + String.valueOf(id), null);
int output = -1;
if (cursor != null) {
if (cursor.moveToFirst()) {
output = cursor.getInt(cursor.getColumnIndex(COL_3));
}
cursor.close();
}
return output;
}
public void updatebunk(long id){
SQLiteDatabase db = this.getWritableDatabase();
int bunk = getbunk(id);
int bunkinc= ++bunk;
ContentValues contentValues= new ContentValues();
contentValues.put(COL_3,bunkinc);
db.update(TABLE_NAME,contentValues,COLUMN_ID+ "=?",new String[]{String.valueOf(id)});
db.close();
}
public void updatebunkdelete(long id){
SQLiteDatabase db = this.getWritableDatabase();
int bunk = getbunk(id);
int bunkinc= --bunk;
ContentValues contentValues= new ContentValues();
contentValues.put(COL_3,bunkinc);
db.update(TABLE_NAME,contentValues,COLUMN_ID+ "=?",new String[]{String.valueOf(id)});
db.close();
}
}
Change the updatebunk method:
public int updatebunk(long id){
SQLiteDatabase db = this.getWritableDatabase();
int bunk = getbunk(id);
int bunkinc= ++bunk;
ContentValues contentValues= new ContentValues();
contentValues.put(COL_3, bunkinc);
db.update(TABLE_NAME,contentValues,COLUMN_ID+ "=?",new String[]{String.valueOf(id)});
db.close();
return bunkinc;
}
then in your adapter change the listener of addbunk
holder.addbunk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Myhelper myhelper = new Myhelper(mcontext);
int newbunk = myhelper.updatebunk(attendence.getId());
attendence.setBunks(newbunk);
mattendence_list.set(position, attendence);
notifyDataSetChanged();
Toast.makeText(mcontext,"+1 class bunked",Toast.LENGTH_SHORT).show();
}
});
I want to refresh the getview() of baseadapter each time when user click on multispinner. Also wants to deselect all the selected checkbox.
Anybody please help.
Blockquote
Below is my multispinner java class
public class MultiSpinnerSearch extends Spinner implements OnCancelListener {
private static final String TAG = MultiSpinnerSearch.class.getSimpleName();
private List<KeyPairBoolData> items;
private String defaultText = "";
private String spinnerTitle = "";
private SpinnerListener listener;
private int limit = 0;
private int selected = 0;
private LimitExceedListener limitListener;
MyAdapter adapter;
public static AlertDialog.Builder builder;
public static AlertDialog ad;
public MultiSpinnerSearch(Context context) {
super(context);
}
public MultiSpinnerSearch(Context arg0, AttributeSet arg1) {
super(arg0, arg1);
TypedArray a = arg0.obtainStyledAttributes(arg1, R.styleable.MultiSpinnerSearch);
limit = a.getIndexCount();
for (int i = 0; i < limit; ++i) {
int attr = a.getIndex(i);
if (attr == R.styleable.MultiSpinnerSearch_hintText) {
spinnerTitle = a.getString(attr);
defaultText = spinnerTitle;
break;
}
}
Log.i(TAG, "spinnerTitle: " + spinnerTitle);
a.recycle();
}
public MultiSpinnerSearch(Context arg0, AttributeSet arg1, int arg2) {
super(arg0, arg1, arg2);
}
public void setLimit(int limit, LimitExceedListener listener) {
this.limit = limit;
this.limitListener = listener;
}
public List<KeyPairBoolData> getSelectedItems() {
List<KeyPairBoolData> selectedItems = new ArrayList<>();
for (KeyPairBoolData item : items) {
if (item.isSelected()) {
selectedItems.add(item);
}
}
return selectedItems;
}
public List<Long> getSelectedIds() {
List<Long> selectedItemsIds = new ArrayList<>();
for (KeyPairBoolData item : items) {
if (item.isSelected()) {
selectedItemsIds.add(item.getId());
}
}
return selectedItemsIds;
}
#Override
public void onCancel(DialogInterface dialog) {
// refresh text on spinner
StringBuilder spinnerBuffer = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
if (items.get(i).isSelected()) {
spinnerBuffer.append(items.get(i).getName());
spinnerBuffer.append(", ");
}
}
String spinnerText = spinnerBuffer.toString();
if (spinnerText.length() > 2)
spinnerText = defaultText;
else
spinnerText = defaultText;
ArrayAdapter<String> adapterSpinner = new ArrayAdapter<>(getContext(), R.layout.textview_for_spinner, new String[]{spinnerText});
setAdapter(adapterSpinner);
if (adapter != null)
adapter.notifyDataSetChanged();
listener.onItemsSelected(items);
}
#Override
public boolean performClick() {
builder = new AlertDialog.Builder(new ContextThemeWrapper(getContext(), R.style.Material_App_Dialog));
builder.setTitle(spinnerTitle);
final LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view = inflater.inflate(R.layout.alert_dialog_listview_search, null);
builder.setView(view);
final ListView listView = (ListView) view.findViewById(R.id.alertSearchListView);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setFastScrollEnabled(false);
adapter = new MyAdapter(getContext(), items);
listView.setAdapter(adapter);
final TextView emptyText = (TextView) view.findViewById(R.id.empty);
listView.setEmptyView(emptyText);
final EditText editText = (EditText) view.findViewById(R.id.alertSearchEditText);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
builder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.i(TAG, " ITEMS : " + items.size());
dialog.cancel();
}
});
builder.setOnCancelListener(this);
ad = builder.show();
return true;
}
public void setItems(List<KeyPairBoolData> items, int position, SpinnerListener listener) {
this.items = items;
this.listener = listener;
StringBuilder spinnerBuffer = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
if (items.get(i).isSelected()) {
spinnerBuffer.append(items.get(i).getName());
spinnerBuffer.append(", ");
}
}
if (spinnerBuffer.length() > 2)
defaultText = spinnerBuffer.toString().substring(0, spinnerBuffer.toString().length() - 2);
ArrayAdapter<String> adapterSpinner = new ArrayAdapter<>(getContext(), R.layout.textview_for_spinner, new String[]{defaultText});
setAdapter(adapterSpinner);
if (position != -1) {
items.get(position).setSelected(true);
//listener.onItemsSelected(items);
onCancel(null);
}
}
public interface LimitExceedListener {
void onLimitListener(KeyPairBoolData data);
}
//Adapter Class
public class MyAdapter extends BaseAdapter implements Filterable {
List<KeyPairBoolData> arrayList;
List<KeyPairBoolData> mOriginalValues; // Original Values
LayoutInflater inflater;
public MyAdapter(Context context, List<KeyPairBoolData> arrayList) {
this.arrayList = arrayList;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
TextView textView;
CheckBox checkBox;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Log.i(TAG, "getView() enter");
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.item_listview_multiple, parent, false);
holder.textView = (TextView) convertView.findViewById(R.id.alertTextView);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.alertCheckbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final int backgroundColor = (position % 2 == 0) ? R.color.list_background : R.color.list_background;
convertView.setBackgroundColor(ContextCompat.getColor(getContext(), backgroundColor));
if (position==0)
{
holder.textView.setTextColor(Color.BLACK);
}
if (position==3)
{
holder.textView.setTextColor(Color.GREEN);
convertView.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.list_selected));
}
final KeyPairBoolData data = arrayList.get(position);
holder.textView.setText(data.getName());
holder.textView.setTypeface(null, Typeface.NORMAL);
holder.checkBox.setChecked(data.isSelected());
convertView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (data.isSelected()) { // unselect
selected--;
} else if (selected == limit) { // select with limit
if (limitListener != null)
limitListener.onLimitListener(data);
return;
} else { // selected
selected++;
}
final ViewHolder temp = (ViewHolder) v.getTag();
temp.checkBox.setChecked(!temp.checkBox.isChecked());
data.setSelected(!data.isSelected());
Log.i(TAG, "On Click Selected Item : " + data.getName() + " : " + data.isSelected());
}
});
holder.checkBox.setTag(holder);
return convertView;
}
#SuppressLint("DefaultLocale")
#Override
public Filter getFilter() {
return new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
arrayList = (List<KeyPairBoolData>) results.values; // has the filtered values
notifyDataSetChanged(); // notifies the data with new filtered values
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
List<KeyPairBoolData> FilteredArrList = new ArrayList<>();
if (mOriginalValues == null) {
mOriginalValues = new ArrayList<>(arrayList); // saves the original data in mOriginalValues
}
/********
*
* If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values
* else does the Filtering and returns FilteredArrList(Filtered)
*
********/
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = mOriginalValues.size();
results.values = mOriginalValues;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mOriginalValues.size(); i++) {
Log.i(TAG, "Filter : " + mOriginalValues.get(i).getName() + " -> " + mOriginalValues.get(i).isSelected());
String data = mOriginalValues.get(i).getName();
if (data.toLowerCase().contains(constraint.toString())) {
FilteredArrList.add(mOriginalValues.get(i));
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
}
}
}
And from my main activity
MultiSpinnerSearch searchSpinner = (MultiSpinnerSearch) findViewById(R.id.searchMultiSpinner);
searchSpinner.setItems(listArray, -1, new SpinnerListener() {
#Override
public void onItemsSelected(List<KeyPairBoolData> items) {
for (int i = 0; i < items.size(); i++) {
if (items.get(i).isSelected()) {
Log.i("TAG", i + " : " + items.get(i).getName() + " : " + items.get(i).isSelected());
FlashMessage(i + " : " + items.get(i).getName() + " : " + items.get(i).isSelected());
if (GroupName.equals(""))
{
GroupName=GroupName+items.get(i).getName();
Group_stuid=Group_stuid+student_idlist[i+1];
}
else
{
GroupName=GroupName+","+items.get(i).getName();
Group_stuid=Group_stuid+"#"+student_idlist[i+1];
}
}
}
FlashMessage("grp name : "+GroupName);
FlashMessage("grp id : "+Group_stuid);
Audiofilename=appfunct.checkfile(eventType,acdses_sct,class_sct,category_sct,subject_sct,test_sct,Group_stuid,GroupName);
outfolder=appfunct.outfldr();
Group_stuid=Group_stuid.replaceAll("/","-");
File create_stuid=new File(outfolder.toString()+"/"+Group_stuid);
if(!create_stuid.exists()) {
create_stuid.mkdirs();
}
FlashMessage(""+GroupFoldername);
Group_listFiles=appfunct.showlistfiles(GroupFoldername);
if (Group_listFiles != null)
{
final CustomGroupFolder_ListDispaly adapter1 = new CustomGroupFolder_ListDispaly(Group_recording.this,R.layout.group_item_listview,Group_listFiles);
group_listview.setAdapter(adapter1);
}
GroupName="";
Group_stuid="";
selected_students=appfunct.getSelectedNamesGroup(GroupFoldername);
}
});
FlashMessage("out : grp id "+Group_stuid);
searchSpinner.setLimit(2, new MultiSpinnerSearch.LimitExceedListener() {
#Override
public void onLimitListener(KeyPairBoolData data) {
Toast.makeText(getApplicationContext(),
"Limit exceed ", Toast.LENGTH_LONG).show();
}
});
apply this to your adapter adapter.notifyDataSetChanged();
public class MainActivityFragment extends Fragment {
static String[] str1;
GridView gridview;
public MainActivityFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.refresh_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if (id == R.id.action_refresh) {
updateWeather();
return true;
}
return super.onOptionsItemSelected(item);
}
private void updateWeather() {
fetchMovies movieTask=new fetchMovies();
movieTask.execute("hi");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview=inflater.inflate(R.layout.fragment_main, container, false);
gridview=(GridView)rootview.findViewById(R.id.gridview);
//gridview.setAdapter(new ImageAdapter(getActivity()));
return rootview;
}
public class fetchMovies extends AsyncTask<String,Void,String[]> {
private final String LOG_TAG = fetchMovies.class.getSimpleName();
private String[] getMovieDataFromJson(String forecastJsonStr, int numDays)
throws JSONException {
JSONObject movieJson = new JSONObject(forecastJsonStr);
JSONArray movieArray = movieJson.getJSONArray("results");
String[] resultStrs = new String[movieArray.length()];
for(int i = 0; i < movieArray.length(); i++) {
JSONObject getMovie = movieArray.getJSONObject(i);
String moviePosterPathImage=getMovie.getString("poster_path");
String movieOverview=getMovie.getString("overview");
String split_release_date=getMovie.getString("release_date");
String[] Segments = split_release_date.split("-");
String release_date=Segments[1]+"-"+Segments[2]+"-"+Segments[0];
String title=getMovie.getString("title");
Double vote_Average=getMovie.getDouble("vote_average");
resultStrs[i] = moviePosterPathImage + " - " + movieOverview + " - " + release_date + " - " + title + " - " + vote_Average;
}
for (String s : resultStrs) {
Log.v(LOG_TAG, "Forecast entry: " + s);
}
return resultStrs;
}
#Override
protected String[] doInBackground(String... params) {
HttpURLConnection urlConnection=null;
BufferedReader reader=null;
//will contain the raw json response as a string
String forecastJsonStr=null;
int Format_Cnt_Value=7;
String Format_Api="api_key";
try {
String Format_Mode="sort_by";
String Format_Mode_Val="popularity.desc";
String OPEN_MOVIES_API_KEY="-----My Api Key------";
String baseUrl="http://api.themoviedb.org/3/discover/movie?";
Uri builtUri=Uri.parse(baseUrl).buildUpon()
.appendQueryParameter(Format_Mode,Format_Mode_Val)
.appendQueryParameter(Format_Api,OPEN_MOVIES_API_KEY)
.build();
URL url=new URL(builtUri.toString());
Log.v(LOG_TAG,"test_Uri= " + builtUri);
urlConnection= (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream=urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG, "Forecast JsonString:=" + forecastJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
};
try {
return getMovieDataFromJson(forecastJsonStr,Format_Cnt_Value);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] Strings) {
if (Strings != null) {
//adp.clear();
str1 = new String[Strings.length];
for (int i = 0; i < Strings.length; i++) {
String[] getImage=Strings[i].split("-");
str1[i] = "http://image.tmdb.org/t/p/w185/" + getImage[0];
}
adp=new ImageAdapter(getActivity(),str1);
gridview.setAdapter(adp); //error
}
}
}
}
what should I do now....
I also have ImageAdapter class
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private String[] mThumbIds;
public ImageAdapter(Context c,String[] str2) {
mContext = c;
mThumbIds=str2;
}
#Override
public int getCount() {
if(mThumbIds!=null)
{
return mThumbIds.length;
}
else
{
return 0;
}
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(500,500));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(4, 4, 4, 4);
} else {
imageView = (ImageView) convertView;
}
// imageView.setImageResource(Integer.parseInt(mThumbIds[position]));
imageView.setImageResource(Integer.parseInt(mThumbIds[position]));
return imageView;
}
}
Please help.
I have loaded data from api and want to fill the gridview.
I am getting images in string[]...how to populate gridview..
I need your help to populate gridview using adapter
billions of thanks in advance.
Use Picasso library to load url images in your grid view.Check out this link on how to use picasso.
In your adapter getView() method add this line:
Picasso.with(mContext).load(mThumbIds[position]).into(imageView);