When I click the chat tab the recycler view doesn't show the items inside the fragment. It was working before when I had it in a activity. Now it doesnt seem to show the items when running the app. I have tried debugging and the likes and still can't seem to find out the problem. Any help will be grateful, thanks!
ChatFragment.java
package com.swampass.nauticalapp;
import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
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 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.ValueEventListener;
import com.swampass.nauticalapp.model.ActiveChatConvo;
import com.swampass.nauticalapp.model.User;
import java.util.ArrayList;
public class ChatsFragment extends Fragment {
private RecyclerView recyclerView;
private DatabaseReference mRef;
private LinearLayoutManager mLinearLayoutManager;
private ArrayList<User> users;
private FirebaseAuth mAuth;
private ActiveChatConvo adapter;
public ChatsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View penis = inflater.inflate(R.layout.fragment_chats, container, false);
// Inflate the layout for this fragment
mRef = FirebaseDatabase.getInstance().getReference("Users");
mRef.keepSynced(true);
mAuth = FirebaseAuth.getInstance();
users = new ArrayList<>();
adapter = new ActiveChatConvo(users,getContext());
mRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
for (DataSnapshot postSnapshot: dataSnapshot.getChildren())
{
String name = postSnapshot.child("Name").getValue(String.class);
String email = postSnapshot.child("Email").getValue(String.class);
String pic = postSnapshot.child("image").getValue(String.class);
users.add(new User(name,email,pic));
}
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Recycler View
recyclerView = (RecyclerView) penis.findViewById(R.id.active_chats);
//ActiveChatConvo adapter = new ActiveChatConvo(users,this);
Context c = getContext();
mLinearLayoutManager = new LinearLayoutManager(getActivity());
//mLinearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(mLinearLayoutManager);
recyclerView.setAdapter(adapter);
//adapter.notifyDataSetChanged();
return inflater.inflate(R.layout.fragment_chats, container, false);
}
}
ActiveChatConvo.java
package com.swampass.nauticalapp.model;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import com.swampass.nauticalapp.ChatConversationActivity;
import com.swampass.nauticalapp.R;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Peter on 6/6/2017.
*/
public class ActiveChatConvo extends RecyclerView.Adapter<ActiveChatConvo.ViewHolder> {
private ArrayList<User> mUsers;
private Context mContext;
public ActiveChatConvo(ArrayList<User> users, Context dick) {
mUsers = users;
mContext = dick;
}
private Context getContext() {
return mContext;
}
#Override
public ActiveChatConvo.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View contactView = inflater.inflate(R.layout.chat_single_item, parent, false);
// Return a new holder instance
ViewHolder viewHolder = new ViewHolder(contactView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// Get the data model based on position
User user = mUsers.get(position);
// Set item views based on your views and data model
TextView name = holder.mItemName;
name.setText(user.getName());
TextView description = holder.mItemDescription;
description.setText(user.getEmail());
ImageView pic = holder.mItemImage;
Picasso.with(pic.getContext()).load(Uri.parse(user.getPic())).into(pic);
}
#Override
public int getItemCount() {
return mUsers.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView mItemImage;
private TextView mItemName;
private TextView mItemDescription;
private LinearLayout layout;
final LinearLayout.LayoutParams params;
public ViewHolder(View v) {
super(v);
mItemImage = (ImageView) v.findViewById(R.id.chat_persion_image);
mItemName = (TextView) v.findViewById(R.id.chat_persion_name);
mItemDescription = (TextView) v.findViewById(R.id.chat_persion_email);
layout = (LinearLayout) itemView.findViewById(R.id.show_chat_single_item_layout);
params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
v.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Context context = itemView.getContext();
Intent intent = new Intent(context, ChatConversationActivity.class);
// intent.putExtra("image_id", );
intent.putExtra("descripion", mItemDescription.getText().toString());
intent.putExtra("name", mItemName.getText().toString());
context.startActivity(intent);
}
}
}
fragment_chat.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.swampass.nauticalapp.ChatsFragment">
<!-- TODO: Update blank fragment layout -->
<android.support.v7.widget.RecyclerView
android:id="#+id/active_chats"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#color/colorAccent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
In the ChatFragment.java, you should be returning the view you have created - penis, and not inflater.inflate(R.layout.fragment_chats, container, false). In this case, an empty view is returned and not the one you are creating.
Related
'Here is my adapter class code and when i long pressed on an item it should show a alert dialog box to delete that item ..I want to call DialogFragmnent from recycled view. How to resolve this show method from Recyclerview adapter. How is it possible?
Adaptorclass
package com.example.recyclerview1;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.LinkedList;
import androidx.appcompat.app.AppCompatActivity;
public class MyAdaptor extends RecyclerView.Adapter<MyAdaptor.MyViewHolder>{
ArrayList<Student> l;
Context c;
public MyAdaptor (Context ctx,ArrayList<Student> list)
{
l=list;
c =ctx;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row,parent,false);
strong textMyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
final Student s = l.get(position);
holder.t1.setText(s.getName());
holder.t2.setText(s.getCnic());
int currentposition=position;
final Student infodata= l.get(position);
holder.linearLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view)
{
Dialogclass dialog = new Dialogclass();
dialog.show(((AppCompatActivity)c).getSupportFragmentManager(), "Fragment");
removieitem(infodata);
Toast.makeText(c," Removed item "+position,Toast.LENGTH_LONG).show();
return false;
}
});
holder.linearLayout.setOnClickListener(new View.OnClickListener () {
#Override
public void onClick(View view)
{
Toast.makeText(c,s.getName()+" "+s.getCnic(),Toast.LENGTH_LONG).show();
}
});
}
private void removieitem(Student infodata) {
int position=l.indexOf(infodata);
l.remove(position);
notifyItemRemoved(position);
}
#Override
public int getItemCount() {
return l.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView t1,t2;
LinearLayout linearLayout;
public MyViewHolder(#NonNull View itemView)
{
super(itemView);
t1 = itemView.findViewById(R.id.txtname);
t2 = itemView.findViewById(R.id.txtcnic);
linearLayout = itemView.findViewById(R.id.mylayout);
}
}
}
Dialogclass
package com.example.recyclerview1;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDialogFragment;
import androidx.fragment.app.DialogFragment;
public class Dialogclass extends AppCompatDialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_fire_missiles)
.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES!
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
It show the Error as....java.lang.ClassCastException: android.app.Application cannot be cast to androidx.appcompat.app.AppCompatActivity
at com.example.recyclerview1.MyAdaptor$1.onLongClick(MyAdaptor.java:49)
MainActivity.java
package com.example.recyclerview1;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<Student> list= list = new ArrayList<>();
RecyclerView rc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rc = findViewById(R.id.myrec);
Student s1 = new Student("Ahmed","34198723482");
Student s2 = new Student("Ahmed","34198723482");
Student s3 = new Student("Ahmed","34198723482");
Student s4 = new Student("Ahmed","34198723482");
Student s5 = new Student("Ahmed","34198723482");
Student s6 = new Student("Ahmed","34198723482");
Student s7 = new Student("Ahmed","34198723482");
Student s8 = new Student("Ahmed","34198723482");
Student s9 = new Student("Ahmed","34198723482");
Student s0 = new Student("Ahmed","34198723482");
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
list.add(s6);
list.add(s7);
list.add(s8);
list.add(s9);
list.add(s0);
MyAdaptor myAdaptor = new MyAdaptor(getApplicationContext(),list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
rc.setLayoutManager(linearLayoutManager);
rc.setAdapter(myAdaptor);
}
}
You can create custom dialog.
Add RecyclerView in your XML file layout if don't have any layout create it.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fl_dialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="300dp">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rv_dialog"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</FrameLayout>
Then initialize your RecyclerView and any other view in onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//TODO Change 'frag_mdialog' to your custom view XML layout
View v = inflater.inflate(R.layout.frag_mdialog, container, false);
view = v;
// Do all the stuff to initialize your custom view
RecyclerView recyclerView = view.findViewById(R.id.rv_dialog);
return v;
}
I hope this help you.
Problem at line below
dialog.show(((AppCompatActivity)c).getSupportFragmentManager()
c is Context so cannot be cast to AppCombatActivity
Try Sending Activity object in MyAdaptor class like below
public MyAdaptor (Activity ctx,ArrayList<Student> list)
and In MainActivity.java class you need to pass Activity object like this below -
MyAdaptor myAdaptor = new MyAdaptor(MainActivity.this,list);
I am Using a Tab Layout with two fragments both have Recycler View and also added Search View in Tab Layout but here I am facing a problem, I want Search View to work on Both Fragment that I added As Tab but Search View is in another activity(Toolbar) and both fragments are different
Activity Having Tabs(LanguageChooser Activity)
package com.piyushjaiswal.lyricswala;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.material.tabs.TabLayout;
public class LanguageChooser extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_language_chooser);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
SectionPagerAdapter pagerAdapter = new SectionPagerAdapter(getSupportFragmentManager(),FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
ViewPager pager = findViewById(R.id.pager);
pager.setAdapter(pagerAdapter);
TabLayout tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(pager);
}
private class SectionPagerAdapter extends FragmentPagerAdapter {
public SectionPagerAdapter(#NonNull FragmentManager fm, int behaviour) {
super(fm,behaviour);
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new Hindi();
case 1:
return new Punjabi();
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
switch (position)
{
case 0: return getResources().getText(R.string.Hindi);
case 1:return getResources().getText(R.string.Punjabi);
}
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.toolbar,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
System.exit(1);
}
}
XML CODE OF LanguageChooserActivity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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:orientation="vertical"
tools:context=".LanguageChooser">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:id="#+id/toolbar"
android:background="#color/colorAccent"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
app:elevation="0dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tabs"/>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:id="#+id/pager"
android:layout_height="match_parent" />
</LinearLayout>
My Toolbar having Search View
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_Search"
android:title="#string/search"
android:icon="#android:drawable/ic_menu_search"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.widget.SearchView"
/>
</menu>
XML code of first Tab(Fragment) named as Hindi
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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:orientation="vertical"
tools:context=".Hindi">
<ProgressBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/progressbar"
android:visibility="visible"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
Java Code of Tab(Fragment) named as Hindi
package com.piyushjaiswal.lyricswala;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.app.SearchManager;
import android.widget.ProgressBar;
import androidx.appcompat.widget.SearchView;
import android.widget.Toast;
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.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class Hindi extends Fragment {
View v;
private RecyclerView myRecyclerview;
private List<Contact> listContact = new ArrayList<>();
private FirebaseDatabase database = FirebaseDatabase.getInstance();
private DatabaseReference myRef = database.getReference();
private RecyclerViewAdapter recyclerViewAdapter;
private ProgressBar progressBar;
public Hindi() {
// Required empty public constructor
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_hindi,container,false);
progressBar= v.findViewById(R.id.progressbar);
progressBar.setVisibility(View.VISIBLE);
myRecyclerview = v.findViewById(R.id.recyclerView);
myRecyclerview.setHasFixedSize(true);
myRecyclerview.setItemViewCacheSize(10);
recyclerViewAdapter = new RecyclerViewAdapter(getContext(),listContact);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
myRecyclerview.setLayoutManager(layoutManager);
myRecyclerview.setAdapter(recyclerViewAdapter);
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myRef.child("Hindi").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1:dataSnapshot.getChildren()){
listContact.add(dataSnapshot1.getValue(Contact.class));
}
recyclerViewAdapter.notifyDataSetChanged();
progressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(),databaseError.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
}
Recycler View Adapter
package com.piyushjaiswal.lyricswala;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private Context mContext;
private List<Contact> mData;
private List<Contact> mDataFull;
public RecyclerViewAdapter(Context mContext, List<Contact> mData) {
this.mContext = mContext;
this.mData = mData;
mDataFull = new ArrayList<>(mData);
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(mContext).inflate(R.layout.item_songs,parent,false);
MyViewHolder vHolder= new MyViewHolder(v);
return vHolder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.setData(mData.get(position).getName(),mData.get(position).getPhone(),mData.get(position).getUrl(),mData.get(position).getLyrics());
}
#Override
public int getItemCount() {
return mData.size();
}
static class MyViewHolder extends RecyclerView.ViewHolder
{
private TextView tv_name;
private TextView tv_phone;
private ImageView imageView;
MyViewHolder(#NonNull View itemView) {
super(itemView);
tv_name = (TextView) itemView.findViewById(R.id.name_contact);
tv_phone = (TextView) itemView.findViewById(R.id.phone_contact);
imageView = (ImageView) itemView.findViewById(R.id.img_contact);
}
private void setData(final String name, final String phone, String url, final String Lyrics){
Glide.with(itemView.getContext()).load(url).into(imageView);
this.tv_phone.setText(phone);
this.tv_name.setText(name);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(itemView.getContext(),LyricsActivit.class);
intent.putExtra("Lyrics",Lyrics);
intent.putExtra("albumname",phone);
intent.putExtra("songname",name);
itemView.getContext().startActivity(intent);
}
});
}
}
}
Screen Shot of My ActivityApp Output
I want above toolbar search view to work on tabs(fragment) Hope I explain my problem
Create a view pager and tab layout together. it will be resolved.Here is an example.
I am new to android development. Here is a picture of my firebase database.
I am showing the name and an image of the movie in my android application in a custom list view.
Here is my ModelClass
public class ModelClass {
String name,imagelink;
public ModelClass() {
}
public ModelClass(String name, String imagelink) {
this.name = name;
this.imagelink = imagelink;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImagelink() {
return imagelink;
}
public void setImagelink(String imagelink) {
this.imagelink = imagelink;
}
}
Here is my Adapter Class
import android.app.Activity;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.List;
public class MyAdapter extends ArrayAdapter<ModelClass> {
private Activity context;
private int resource;
private List<ModelClass> listImage;
private DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("MovieDetails");
public MyAdapter(#NonNull Activity context, #LayoutRes int resource, #NonNull List<ModelClass> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
listImage = objects;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View v = inflater.inflate(resource, null);
TextView tvName = (TextView) v.findViewById(R.id.movie_name_view);
ImageView img = (ImageView) v.findViewById(R.id.movie_image_view);
tvName.setText(listImage.get(position).getName());
Glide.with(context).load(listImage.get(position).getImagelink()).into(img);
return v;
}
public void addElement(ModelClass element) {
listImage.add(element);
}
}
And This is my Activity
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;
import com.google.firebase.database.ChildEventListener;
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.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class CheckMovieInfoActivity extends AppCompatActivity {
private DatabaseReference mDatabaseRef;
private List<ModelClass> imgList;
private ListView lv;
private MyAdapter myAdapter;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_movie_info);
imgList = new ArrayList<>();
lv = (ListView) findViewById(R.id.messagelist);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please wait loading Images...");
progressDialog.show();
mDatabaseRef = FirebaseDatabase.getInstance().getReference("MovieDetails");
myAdapter = new MyAdapter(CheckMovieInfoActivity.this, R.layout.customlistview, imgList);
lv.setAdapter(myAdapter);
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
progressDialog.dismiss();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
ModelClass img = snapshot.getValue(ModelClass.class);
myAdapter.addElement(img);
}
myAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
}
}
And this is my Custom List View XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="6dp">
<ImageView
android:id="#+id/movie_image_view"
android:layout_width="140dp"
android:layout_height="140dp"
android:src="#drawable/upload_image_small"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/movie_name_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MOVIE NAME"
android:layout_gravity="center"
android:textSize="20dp"/>
</LinearLayout>
</LinearLayout>
<Button
android:layout_marginTop="8dp"
android:id="#+id/btndel"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Delete Movie"
android:background="#drawable/roundedbutton"/>
</LinearLayout>
I want to add a delete button in the custom listview to delete the data and also the image from the database.
I am not getting any errors I just want to add a delete button to delete the data. Thanks in advance.
I did not add spinner on my layout
I did not use addView function
code
Spinner spinner = new Spinner(MainActivity.this);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, myArray);
spinner.setAdapter(spinnerArrayAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
//this place is never called
}
public void onNothingSelected(AdapterView<?> parent)
{
}
});
I called spinner like this:
spinner.performClick();
After this I click one of my item which in my array and then I expect to fire onItemSelected but it never fires.
the problem is
onitemselected is never called.
thanks in advance
Try this,
1.Create a custom adapter.
2.set click Listener to textview in adapter.(so you can get position in adapter)
3.according to positon do whatever u feel like.
CustomModel.
public class CustomModel {
private String id;
private String description;
public char[] name;
public CustomModel() {
}
public CustomModel(String id, String description) {
this.id = id;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return description;
}
public void setName(String description) {
this.description = description;
}
}
Activity.
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CursorAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import adapter.CustomAdapter;
import models.CustomModel;
import utils.SessionManager;
import static android.R.attr.id;
import static android.R.id.text1;
public class spinner extends AppCompatActivity {
private SessionManager sessionManager;
private List<CustomModel> myArray=new ArrayList<CustomModel>();
CustomModel customModel;
LinearLayout container;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinnre);
container = (LinearLayout) findViewById(R.id.container);
customModel=new CustomModel();
customModel.setName("Select a number");
myArray.add(customModel);
for(int i=0;i<10;i++)
{
customModel=new CustomModel();
customModel.setName(String.valueOf(i));
myArray.add(customModel);
}
LinearLayout.LayoutParams spinnerParamas = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams textParamas = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
spinnerParamas.setMargins(0,50,0,0);
Spinner spinner = new Spinner(spinner.this);
spinner.setLayoutParams(spinnerParamas);
spinner.setId(0);
CustomAdapter customAdapter=new CustomAdapter(spinner.this,myArray,spinner);
spinner.setAdapter(customAdapter);
container.addView(spinner);
}
}
Adapter
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.ciomp.global.R;
import models.CustomModel;
/**
* Created by ciomp on 11/23/2016.
*/
public class CustomAdapter extends BaseAdapter {
private Context mContext;
private List<CustomModel> mList=new ArrayList<CustomModel>();
private LayoutInflater mLayoutInflater;
private String mType=null;
private Spinner mSpinner;
int one=0;
public CustomAdapter(Context mContext, List<CustomModel> list, Spinner spin) {
this.mContext=mContext;
this.mList=list;
mSpinner=spin;
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
CustomAdapter.ViewHolder holder=null;
LayoutInflater layoutInflater=(LayoutInflater)mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if(convertView==null){
convertView = layoutInflater.inflate(R.layout.customlayout, null);
holder = new CustomAdapter.ViewHolder();
holder.textView2=(TextView)convertView.findViewById(R.id.txt_text1);
convertView.setTag(holder);
}
else {
holder = (CustomAdapter.ViewHolder) convertView.getTag();
}
CustomModel classModel=mList.get(position);
holder.textView2.setText(classModel.getName());
holder.textView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(one==0)
{
mSpinner.performClick();
one=1;
}
else if(one==1)
{
Toast.makeText(mContext, mList.get(position).getName(), Toast.LENGTH_SHORT).show();
try {
Method method = Spinner.class.getDeclaredMethod("onDetachedFromWindow");
method.setAccessible(true);
method.invoke(mSpinner);
} catch (Exception e) {
e.printStackTrace();
}
one=0;
}
}
});
return convertView;
}
static class ViewHolder{
TextView textView2;
}
}
spinnre.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_marginRight="5dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="5dp"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
customlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/txt_text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14sp"
android:layout_marginBottom="13dp"
android:gravity="center"
android:layout_marginTop="13dp"
android:layout_marginLeft="5dp"
android:paddingLeft="5dp"
android:textColor="#000"
/>
/>
</LinearLayout>
hope it may help you.
In order to programatically select item from spinner. you need to call
spinner.setSelection(1);
Whereas 1 in the index, you want to select
I've got some problem with my RecyclerView. I want to add a bubble widget that creates a new circle with message (just like in messanger). Problem is that bubble must be placed in separate XML layout file so I cannot add it to the "item" layout that I have in my adapter. Inside bubble layout I have simply TextView, however I don't want to display normal text - it would be too easy ;) I want to display data I get from API. Another words - I need access to TextView that is inside Bubble layout in my adapter. Please, help! :)
Here's my Adapter class
package pl.krakowskascenamuzyczna.ksmcalendar.Adapter;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Days;
import org.w3c.dom.Text;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.txusballesteros.bubbles.BubbleLayout;
import com.txusballesteros.bubbles.BubblesManager;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import pl.krakowskascenamuzyczna.ksmcalendar.Activities.CalendarActivity;
import pl.krakowskascenamuzyczna.ksmcalendar.Activities.DisplayConcertActivity;
import pl.krakowskascenamuzyczna.ksmcalendar.MySingleton;
import pl.krakowskascenamuzyczna.ksmcalendar.R;
import pl.krakowskascenamuzyczna.ksmcalendar.data.Concert;
import pl.krakowskascenamuzyczna.ksmcalendar.data.Thumbnail;
public class ConcertAdapter extends RecyclerView.Adapter<ConcertAdapter.MyViewHolder> {
private LayoutInflater inflater;
private Context context;
NetworkImageView mNetworkImageView;
private MySingleton mySingleton;
private List<Concert> concertList = new ArrayList();
public ConcertAdapter(Context context, List<Concert> concerts) {
this.inflater = LayoutInflater.from(context);
this.concertList = concerts;
this.context = context;
}
public void setListConcert(ArrayList<Concert> concertList) {
this.concertList = concertList;
notifyItemRangeChanged(0, concertList.size());
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.concert_item, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
final float screenWidthPx = holder.itemView.getResources().getDisplayMetrics().widthPixels;
Concert current = concertList.get(position);
Log.d("mLog", current.getUrl());
holder.image.setImageUrl(current.getUrl(), MySingleton.getInstance().getImageLoader());
holder.image.getLayoutParams().height = (int) (screenWidthPx * 0.75);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date concertDate = new Date();
try {
concertDate = format.parse(current.getDate());
} catch (ParseException e) {
e.printStackTrace();
}
DateTime dt = new DateTime();
DateTime currentDate = dt.withZone(DateTimeZone.forID("Europe/Warsaw"));
int days = Days.daysBetween(new DateTime(currentDate), new DateTime(concertDate)).getDays();
holder.date_btn.setText(String.valueOf(days));
}
#Override
public int getItemCount () {
return concertList.size();
}
public void showDisplay(int position){
Intent intent = new Intent(context, DisplayConcertActivity.class);
intent.putExtra("position", position);
intent.putExtra("content", concertList.get(position).getContent());
intent.putExtra("date", concertList.get(position).getDate());
intent.putExtra("url", concertList.get(position).getUrl());
context.startActivity(intent);
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private NetworkImageView image;
private Button date_btn;
public MyViewHolder(View itemView) {
super(itemView);
image = (NetworkImageView) itemView.findViewById(R.id.concerts_niv);
date_btn = (Button) itemView.findViewById(R.id.date_btn);
image.setOnClickListener(this);
}
#Override
public void onClick(View v) {showDisplay(getAdapterPosition());
}
}
}
And here's my Bubble layout:
<com.txusballesteros.bubbles.BubbleLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/bubble_tv"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_gravity="center"
android:background="#drawable/profile_decorator"
android:scaleType="centerCrop"
android:src="#drawable/profile_decorator"
android:textColor="#fff"
/>
</com.txusballesteros.bubbles.BubbleLayout>
You can pass your bubble TextView as aprameter to the adapter constructor.
private TextView mBubbleTextView;
public ConcertAdapter(Context context, List<Concert> concerts, TextView bubbleTextView) {
this.inflater = LayoutInflater.from(context);
this.concertList = concerts;
this.context = context;
this.mBubbleTextView = bubbleTextView;
}
Now you have the bubble TextView in your adapter, so can update it from any method.