Android RecylerView Add Button gives me error - java

I'm trying to add a Button which when clicked should open a new Activity. Despite spending a long time on this, my efforts have been unsuccessful. If I add the OnClickListener and click the Button it gives me an error. Thank you for your help.
Listele.Java
package com.example.hp.myapplication;
import android.view.View;
import android.widget.Button;
public class Listele {
private String adi;
private String fiyat;
private String aciklama;
private String stok;
private String resim;
public Listele(String adi, String fiyat, String aciklama, String stok,String resim) {
this.adi = adi;
this.fiyat = fiyat;
this.aciklama = aciklama;
this.stok = stok;
this.resim = resim;
}
//getters and setters
#Override
public String toString() {
return "Listele{" +
"adi='" + adi + '\'' +
", fiyat='" + fiyat + '\'' +
", aciklama='" + aciklama + '\'' +
", stok='" + stok + '\'' +
", resim='" + resim + '\'' +
'}';
}
}
ListeleAdapter.Java
package com.example.hp.myapplication;
//imports
public class ListeleAdapter extends RecyclerView.Adapter<ListeleAdapter.urunlistem> {
private Context contexto;
private ArrayList<Listele>tortica;
public ListeleAdapter(ArrayList<Listele> tortica, Context contexto ) {
this.contexto = contexto;
this.tortica = tortica;
}
#Override
public urunlistem onCreateViewHolder(ViewGroup parent, int viewType) {
return new urunlistem(LayoutInflater.from(parent.getContext()).inflate(R.layout.list,null));
}
#Override
public void onBindViewHolder(urunlistem holder, int position) {
holder.adi.setText(tortica.get(position).getAdi());
holder.aciklama.setText(tortica.get(position).getAciklama());
holder.stok.setText(tortica.get(position).getStok());
holder.fiyat.setText(tortica.get(position).getFiyat());
Glide.with(contexto).load("http://192.168.1.33:8080/urunler/"+tortica.get(position).getResim()).into(holder.tresim);
}
#Override
public int getItemCount() {
return tortica.size();
}
public static class urunlistem extends RecyclerView.ViewHolder{
ImageView tresim;
TextView adi,fiyat,stok,aciklama;
Button sepete_ekle;
ArrayList<Listele> listeles = new ArrayList<Listele>();
public urunlistem(View itemView) {
super(itemView);
tresim=(ImageView)itemView.findViewById(R.id.resim);
adi=(TextView)itemView.findViewById(R.id.adi_urun);
fiyat=(TextView)itemView.findViewById(R.id.fiyat);
stok=(TextView)itemView.findViewById(R.id.stok);
aciklama=(TextView)itemView.findViewById(R.id.aciklama);
}
}
}
MainActivity.Java
package com.example.hp.myapplication;
//imports
public class MainActivity extends AppCompatActivity {
private static final String url="http://192.168.1.33:8080/urunler/goruntule.php";
private RecyclerView recyclerView;
private ListeleAdapter adapter;
private ArrayList<Listele>listeles = new ArrayList<>();
ProgressDialog progressDialog;
RequestQueue requestQu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestQu = Volley.newRequestQueue(getApplicationContext());
goster();
}
private void goster() {
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Bilgiler alınıyor");
recyclerView=(RecyclerView) findViewById(R.id.listado);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this,LinearLayoutManager.HORIZONTAL,false));
recyclerView.setHasFixedSize(true);
adapter = new ListeleAdapter(listeles,this);
recyclerView.setAdapter(adapter);
JsonArrayRequest request = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for(int i=0;i<response.length();i++)
{
try {
JSONObject object = response.getJSONObject(i);
String resimurl=object.getString("resim");
String adi=object.getString("adi");
String stok=object.getString("stok");
String fiyat=object.getString("fiyat");
String aciklama=object.getString("aciklama");
listeles.add(new Listele(adi,fiyat,aciklama,stok,resimurl));
} catch (JSONException e) {
Toast.makeText(MainActivity.this,""+e,Toast.LENGTH_LONG).show();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQu.add(request);
}
}

I didn't see your logcat but first of all you adding OnClickListener to your Button in wrong place. Add it in onBindViewHolder instead of ViewHolder constructor. In your code like that :
#Override
public void onBindViewHolder(urunlistem holder, int position) {
holder.adi.setText(tortica.get(position).getAdi());
holder.aciklama.setText(tortica.get(position).getAciklama());
holder.stok.setText(tortica.get(position).getStok());
holder.fiyat.setText(tortica.get(position).getFiyat());
Glide.with(contexto).load("http://192.168.1.33:8080/urunler/"+
tortica.get(position).getResim()).into(holder.tresim);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String salutation="Merhaba | Hello | Здравствуйте | Hallo | Salut";
Toast.makeText(mContext,salutation,Toast.LENGTH_SHORT).show();
}
});
}

It's because you never inflated the button in your ViewHolder class. Remember how were supposed to "find the view" when using views in java lol? Do that.

hope this help you
package com.example.hp.myapplication;
//imports
public class ListeleAdapter extends RecyclerView.Adapter<ListeleAdapter.urunlistem> {
private Context contexto;
private ArrayList<Listele>tortica;
public ListeleAdapter(ArrayList<Listele> tortica, Context contexto ) {
this.contexto = contexto;
this.tortica = tortica;
}
#Override
public urunlistem onCreateViewHolder(ViewGroup parent, int viewType) {
return new urunlistem(LayoutInflater.from(parent.getContext()).inflate(R.layout.list,null));
}
#Override
public void onBindViewHolder(urunlistem holder, int position) {
holder.adi.setText(tortica.get(position).getAdi());
holder.aciklama.setText(tortica.get(position).getAciklama());
holder.stok.setText(tortica.get(position).getStok());
holder.fiyat.setText(tortica.get(position).getFiyat());
Glide.with(contexto).load("http://192.168.1.33:8080/urunler/"+tortica.get(position).getResim()).into(holder.tresim);
}
#Override
public int getItemCount() {
return tortica.size();
}
//Step 1: Implement View.OnClickListener as below
public static class urunlistem extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView tresim;
TextView adi,fiyat,stok,aciklama;
Button sepete_ekle;
ArrayList<Listele> listeles = new ArrayList<Listele>();
public urunlistem(View itemView) {
super(itemView);
tresim=(ImageView)itemView.findViewById(R.id.resim);
adi=(TextView)itemView.findViewById(R.id.adi_urun);
fiyat=(TextView)itemView.findViewById(R.id.fiyat);
stok=(TextView)itemView.findViewById(R.id.stok);
aciklama=(TextView)itemView.findViewById(R.id.aciklama);
//Step 2: Register Your Button here below
sepete_ekle=(Button)itemView.findViewById(R.id.button);
sepete_ekle.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// Step 3: Redirect to next Activity From here
Intent intent = new Intent(contexto, NextActivity.class);
contexto.startActivity(intent);
}
}
}

Related

Not Getting Data From Firebase Realtime DataBase [duplicate]

Basically, what I am trying to do is use a FirebaseRecyclerAdapter and populate the RecyclerView with my custom designed CardView. The code for newer versions has been changed and therefore, I tried implementing it but didn't work.
This is the code I use to write a year ago, which worked fine and populated my RecyclerView:
FirebaseRecyclerAdapter<DataClass,DataViewHolder> FBRA= new FirebaseRecyclerAdapter<DataClass, DataViewHolder>(
DataClass,
R.layout.myCardView,
DataViewHolder.class,
databaseReference
) {
#Override
protected void populateViewHolder(DataViewHolder viewHolder, DataClass model, int position) {
viewHolder.setTitle(model.gettitle());
viewHolder.setDate(model.getDate());
}
};
myRecyclerView.setAdapter(FBRA);
And now we have to use something like this,
but the problem is this code is not populating my recyclerView (What changes do I need to make here to populate my recyclerView with my cardView?)
#Override
protected void onStart() {
super.onStart();
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("Official_Services");
FirebaseRecyclerOptions<ServiceClass> options = new FirebaseRecyclerOptions.Builder<ServiceClass>()
.setQuery(query, ServiceClass.class)
.build();
FirebaseRecyclerAdapter<ServiceClass, ServiceViewHolder> FBRA = new FirebaseRecyclerAdapter<ServiceClass, ServiceViewHolder>(options) {
#NonNull
#Override
public ServiceViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View view = LayoutInflater.from(HomeActivity.this).inflate(R.layout.service_card, parent, false);
return new ServiceViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull ServiceViewHolder holder, int position, #NonNull ServiceClass model) {
holder.setServiceName(model.getServiceName());
holder.setServiceCaption(model.getServiceCaption());
}
};
mServiceList.setAdapter(FBRA);
}
Here is my ViewHolder class:
public static class ServiceViewHolder extends RecyclerView.ViewHolder {
public ServiceViewHolder(View itemView) {
super(itemView);
View mView = itemView;
}
public void setServiceName(String serviceName) {
TextView sName = itemView.findViewById(R.id.serviceName);
sName.setText(serviceName);
}
public void setServiceCaption(String serviceCaption) {
TextView sCaption = itemView.findViewById(R.id.serviceCap);
sCaption.setText(serviceCaption);
}
}
And this is my Model class of getters and setters:
public class ServiceClass {
private String serviceName;
private String serviceCode;
private String serviceCaption;
private String serviceIconUrl;
public ServiceClass() {
}
public ServiceClass(String serviceName, String serviceCode, String serviceCaption, String serviceIconUrl) {
this.serviceName = serviceName;
this.serviceCode = serviceCode;
this.serviceCaption = serviceCaption;
this.serviceIconUrl = serviceIconUrl;
}
public String getServiceName() {
return serviceName;
}
public String getServiceCode() {
return serviceCode;
}
public String getServiceCaption() {
return serviceCaption;
}
public String getServiceIconUrl() {
return serviceIconUrl;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public void setServiceCode(String serviceCode) {
this.serviceCode = serviceCode;
}
public void setServiceCaption(String serviceCaption) {
this.serviceCaption = serviceCaption;
}
public void setServiceIconUrl(String serviceIconUrl) {
this.serviceIconUrl = serviceIconUrl;
}
#Override
public String toString() {
return "ServiceClass{" +
"serviceName='" + serviceName + '\'' +
", serviceCode='" + serviceCode + '\'' +
", serviceCaption='" + serviceCaption + '\'' +
", serviceIconUrl='" + serviceIconUrl + '\'' +
'}';
}
}
Now what changes do I need to do?
Here is my entire java file:
public class HomeActivity extends AppCompatActivity {
private RecyclerView mServiceList;
private FirebaseDatabase mDatabase;
private DatabaseReference myRef;
FirebaseRecyclerAdapter<ServiceClass, ServiceViewHolder> FBRA;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
BottomNavigationViewEx bottomNavigationViewEx = findViewById(R.id.navViewBar);
bottomNavigationViewEx.enableAnimation(false);
bottomNavigationViewEx.enableShiftingMode(false);
bottomNavigationViewEx.setTextVisibility(false);
Calligrapher calligrapher = new Calligrapher(this);
calligrapher.setFont(this, "Helvetica.ttf", true);
mServiceList = findViewById(R.id.serviceRV);
mServiceList.setHasFixedSize(true);
mServiceList.setLayoutManager(new LinearLayoutManager(this));
mDatabase = FirebaseDatabase.getInstance();
myRef = mDatabase.getReference().child("Official_Services");
}
#Override
protected void onStart() {
super.onStart();
FBRA.startListening();
Query query = myRef;
FirebaseRecyclerOptions<ServiceClass> options = new FirebaseRecyclerOptions.Builder<ServiceClass>()
.setQuery(query, ServiceClass.class)
.build();
FBRA = new FirebaseRecyclerAdapter<ServiceClass, ServiceViewHolder>(options) {
#NonNull
#Override
public ServiceViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View view = LayoutInflater.from(HomeActivity.this).inflate(R.layout.service_card, parent, false);
return new ServiceViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull ServiceViewHolder holder, int position, #NonNull ServiceClass model) {
holder.setServiceName(model.getServiceName());
holder.setServiceCaption(model.getServiceCaption());
}
};
mServiceList.setAdapter(FBRA);
}
public static class ServiceViewHolder extends RecyclerView.ViewHolder {
public ServiceViewHolder(View itemView) {
super(itemView);
View mView = itemView;
}
public void setServiceName(String serviceName) {
TextView sName = itemView.findViewById(R.id.serviceName);
sName.setText(serviceName);
}
public void setServiceCaption(String serviceCaption) {
TextView sCaption = itemView.findViewById(R.id.serviceCap);
sCaption.setText(serviceCaption);
}
}
}
In order to be able to display data from the Firebase realtime database you need to start listening for changes and for that you should add the following line of code in the onStart() method:
#Override
protected void onStart() {
super.onStart();
FBRA.startListening();
}
To stop listening foir changes you need add the following line of code in the onStop() method like this:
#Override
protected void onStop() {
super.onStop();
if(FBRA != null) {
FBRA.stopListening();
}
}
Please see my answer from this post where I have explained why you should remove the listener.
P.S. Please also don't forget to make the FBRA a global variable and remove FirebaseRecyclerAdapter<ServiceClass, ServiceViewHolder> from the declaration of the object.
This is more of an advice. If you want to continue using the old method to populate your
recyclerview ie The "populateViewHolder" method instead of the new "onBindViewHolder" method just use this;
implementation 'com.firebaseui:firebase-ui:1.0.1'
instead of upgraded firebase-ui versions

how to set a path param using retrofit

how to get ID position in call retrofit
GET https://api.themoviedb.org/3/movie/{movie_id}/credits?api_key=<>
i need to get position id send to server in loadCast function
and in MovieService that's retrofit call i need send postion id befor credits
i don't know how to do that if any one can help me thanks so much for that <3
//this my call retrofit server
public interface MovieService {
#GET("popular?" + Common.API_KEY + "&language=en-US")
Call<MoviesList> getPopular(#Query("api_key") String api_key);
#GET( ListMovieAdapter.SELECTED_MOVIE +"/credits?" + Common.API_KEY +
"&language=en-US")
Call<MovieCast> getCast(
#Query("api_key") String api_key);
----------------------------------------------------------------
package com.example.android.movie;
/**
* Created by yuyu on 12-Nov-18.
*/
public class MovieDetails extends YouTubeBaseActivity {
Result selectedMovie;
private ArrayList<Cast> cast;
private RecyclerView.LayoutManager mLayoutManager;
private RecyclerView mRecyclerView;
private CastMovieAdapter castMovieAdapter;
private TextView name;
private ImageView imageMovie;
private TextView date;
private TextView rating;
private ArrayList<Result> results;
MovieService mService;
private static final String YT_API_KEY = "###";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_details);
selectedMovie =
getIntent().getParcelableExtra(ListMovieAdapter.SELECTED_MOVIE);
mRecyclerView = (RecyclerView) findViewById(R.id.cast_recycler);
mLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
cast = new ArrayList<>();
castMovieAdapter = new CastMovieAdapter(cast, MovieDetails.this);
mRecyclerView.setAdapter(castMovieAdapter);
results = new ArrayList<>();
mService = Common.getMovieService();
loadTriler();
loadMovies();
loadCast();
}
this function to load movie
private void loadMovies() {
mService.getPopular(Common.API_KEY).enqueue(new Callback<MoviesList>()
{
#Override
public void onResponse(Call<MoviesList> call, Response<MoviesList>
response) {
results.clear();
results.addAll(response.body().getResults());
name = (TextView) findViewById(R.id.name_movie);
rating = (TextView) findViewById(R.id.rating);
date = (TextView) findViewById(R.id.date_det);
imageMovie = (ImageView) findViewById(R.id.imageView);
date.setText(selectedMovie.getReleaseDate());
name.setText(selectedMovie.getTitle());
rating.setText(String.valueOf(selectedMovie.getVoteAverage()));
final String image = Common.IMAGE_LOAD +
selectedMovie.getPosterPath();
Picasso.with(MovieDetails.this)
.load(image)
.into(imageMovie);
}
#Override
public void onFailure(Call<MoviesList> call, Throwable t) {
Log.d("===LoadMovies", "onResponse: " + t);
}
});
}
//i have proplem here in send ID postion
private void loadCast() {
mService.getCast(
ListMovieAdapter.SELECTED_MOVIE+Common.API_KEY).enqueue(new
Callback<MovieCast>() {
#Override
public void onResponse(Call<MovieCast> call, final
Response<MovieCast> response) {
cast.clear();
cast.addAll(response.body().getCast());
mRecyclerView.getAdapter().notifyDataSetChanged();
}
#Override
public void onFailure(Call<MovieCast> call, Throwable t) {
}
});
}
}
package com.example.android.movie.Adapter;
/**
* Created by yuyu on 11-Nov-18.
*/
public class ListMovieAdapter extends
RecyclerView.Adapter<ListMovieAdapter.MyViewHolder> {
private ArrayList<Result> mMovies;
private Context context;
public static final String SELECTED_MOVIE = "selected_movie";
private int lastPosition = -1;
public ListMovieAdapter(ArrayList<Result> mMovies, Context context) {
this.mMovies = mMovies;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.list_views, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
//Animation Scroll
Animation animation = AnimationUtils.loadAnimation(context,
(position > lastPosition) ? R.anim.up_from_bottom
: R.anim.down_from_top);
holder.itemView.startAnimation(animation);
lastPosition = position;
holder.nameMovie.setText(mMovies.get(position).getTitle());
final String image = Common.IMAGE_LOAD +
mMovies.get(position).getPosterPath();
Picasso.with(context)
.load(image)
.into(holder.imageMovie);
holder.rating.setText(String.valueOf(
mMovies.get(position).getVoteAverage()));
holder.dateMovie.setText(mMovies.get(position).getReleaseDate());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position) {
Intent intent = new Intent(context, MovieDetails.class);
Result result = mMovies.get(position);
intent.putExtra(SELECTED_MOVIE, result);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mMovies.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
ImageView imageMovie;
TextView nameMovie;
TextView rating;
TextView dateMovie;
ItemClickListener itemClickListener;
public MyViewHolder(View itemView) {
super(itemView);
this.imageMovie = (ImageView)
itemView.findViewById(R.id.image_movie);
this.nameMovie = (TextView) itemView.findViewById(R.id.name_movie);
this.rating = (TextView) itemView.findViewById(R.id.rating);
this.dateMovie = (TextView) itemView.findViewById(R.id.date);
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View v) {
itemClickListener.onClick(v, getAdapterPosition());
}
}
}
From the Retrofit documentation:
URL MANIPULATION A request URL can be updated dynamically using
replacement blocks and parameters on the method. A replacement block
is an alphanumeric string surrounded by { and }. A corresponding
parameter must be annotated with #Path using the same string.
#GET("group/{id}/users")
Call<List<User>> groupList(#Path("id") int groupId);
https://square.github.io/retrofit/

Cannot call method of RecyclerView adapter from an activity

I am trying to set the data for recycler view to display from an AsyncTask. I am calling the method setdataEntries from the postExecute of inner class AsyncTask. But the android studio is showing me error could not find the method.
Adapter class
public class EntryAdapter extends RecyclerView.Adapter<EntryAdapter.ViewHolder> {
List<UserTuple> entries;
final private itemClickListener mOnClickListener;
public interface itemClickListener{
void onItemClick(UserTuple utuple);
}
public EntryAdapter(itemClickListener clickhandler) {
mOnClickListener = clickhandler;
}
public void setdataEntries(List<UserTuple> Data) {
entries = Data;
notifyDataSetChanged();
}
#Override
public EntryAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.singleusertuple,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(EntryAdapter.ViewHolder holder, int position) {
holder.Username.setText(entries.get(position).getUsername());
holder.Password.setText(entries.get(position).getPassword());
}
#Override
public int getItemCount() {
return entries.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView Username;
private TextView Password;
private CardView card;
public ViewHolder(View itemView) {
super(itemView);
Username = itemView.findViewById(R.id.susername);
Password=itemView.findViewById(R.id.pass);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int adapterPosition = getAdapterPosition();
UserTuple ut=new UserTuple(entries.get(adapterPosition).getUsername(),entries.get(adapterPosition).getPassword());
mOnClickListener.onItemClick(ut);
}
}
}
Calling Activity
public class Usertuple extends AppCompatActivity implements EntryAdapter.itemClickListener {
private RecyclerView recyclerView ;
private RecyclerView.Adapter adapater;
private SnapHelper snapHelper;
private List<UserTuple> entries;
private ProgressBar mLoadingIndicator;
private Bundle extras;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logins);
extras = getIntent().getExtras();
//String site= extras.getString("sitename");
mLoadingIndicator = (ProgressBar) findViewById(R.id.pb_loading_indicator);
Log.i("Logins","Size of returned list "+entries.size());
recyclerView = findViewById(R.id.recycleview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
adapater = new EntryAdapter(this);
recyclerView.setAdapter(adapater);
snapHelper= new LinearSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
dataView();
}
public void dataView() {
String site= extras.getString("sitename");
recyclerView.setVisibility(View.VISIBLE);
new FetchDataTask().execute(site);
}
#Override
public void onItemClick(UserTuple utuple) {
}
private String key(){
SharedPreferences sharedPref = getSharedPreferences(
"User", this.MODE_PRIVATE);
final String passphrase = sharedPref.getString("userid", "none");
return passphrase;
}
public void showerror(){
recyclerView.setVisibility(View.GONE);
Toast.makeText(this,"Error in retrieving",Toast.LENGTH_SHORT).show();
}
public setdata(List<UserTuple> data){
adapater.setdataEntries(data);
}
public class FetchDataTask extends AsyncTask<String, Void, List<UserTuple>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mLoadingIndicator.setVisibility(View.VISIBLE);
}
#Override
protected List<UserTuple> doInBackground(String... params) {
/* If there's no zip code, there's nothing to look up. */
if (params.length == 0) {
return null;
}
String site = params[0];
try {
AppDatabase db = Room.databaseBuilder(getApplicationContext(),AppDatabase.class, "production")
.build();
entries =db.entryDao().getSpecific(site);
for(UserTuple ut : entries){
Log.i("password",ut.getPassword());
String st = new Decryption().decrypt(ut.getPassword(),key());
Log.i("After decryption",st);
ut.setPassword(st);
}
return entries;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(List<UserTuple> Data) {
mLoadingIndicator.setVisibility(View.INVISIBLE);
if (Data != null) {
adapater.setdataEntries(Data);
} else {
showerror();
}
}
}
}
I want the database calls to be a background task. I don't want the activity to freeze waiting for database calls. Any ideas? Thanks
Declare adapter like
private EntryAdapter adapter;
instead of
private RecyclerView.Adapter adapater;
because RecyclerView.Adapter class does not have any method named setdataEntries but only EntryAdapter class has this method so only the object of type EntryAdapter can call setdataEntries method.
Or you can use down-casting as
((EntryAdapter)adapater).setdataEntries(data);

RecyclerView for Android Chat - Something missing. Unable to reach to place where it selects who sent?

An Android newbie here. I am building a chat app. The sent and received messages are not shown in the UI. I am able to send to server, but not getting displayed. Please help.
I put breakpoints in the code where it should bind data to the Views and inflate the layout, but that code is not at all getting triggered.
Askquestion Activity
public class Askquestion extends AppCompatActivity implements View.OnClickListener{
private static final String TAG = "Chatapp";
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter ChatappChatAdapter;
private ArrayList<ChatappMsg> messages;
private ImageView img_send;
private EditText et_message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_askquestion);
int messageID = 111;
recyclerView = (RecyclerView) findViewById(R.id.recycler_chat);
ChatappChatAdapter = new ChatappChatAdapter(messageID, this,messages);
recyclerView.setAdapter(ChatappChatAdapter);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
messages = new ArrayList<>();
//fetchMessages();
img_send = (ImageView) findViewById(R.id.img_send);
et_message = (EditText) findViewById(R.id.et_message);
//ChatappChatAdapter = new ChatappChatAdapter(messageID, this,messages);
img_send.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view == img_send)
sendMessage();
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
private void sendMessage(){
final String messageBody = et_message.getText().toString().trim();
if(messageBody.equalsIgnoreCase(""))
return;
String messageBy = "Someone";
String messageAt = "sometime";
String messageType = "type";
int messageID = Integer.parseInt("111");
//LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setAdapter(ChatappChatAdapter);
ChatappChatAdapter.notifyDataSetChanged();
ScrollToBottom();
et_message.setText("");
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(APIUrl.BASEURL)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService apiService = retrofit.create(APIService.class);
final ChatappMsg ChatappMsg = new ChatappMsg(messageBody,messageAt,messageBy,messageType,messageID);
Call<ChatappMsg> call = apiService.TalktoChatapp(ChatappMsg);
Log.d(TAG, ""+ChatappMsg);
call.enqueue(new Callback<ChatappMsg>() {
#Override
public void onResponse(Call<ChatappMsg> call, Response<ChatappMsg> response) {
Toast.makeText(getApplicationContext(),"success", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<ChatappMsg> call, Throwable t) {
Toast.makeText(getApplicationContext(),"Failure", Toast.LENGTH_SHORT).show();
}
});
}
//method to scroll the recyclerview to bottom
private void ScrollToBottom() {
ChatappChatAdapter.notifyDataSetChanged();
if (ChatappChatAdapter.getItemCount() > 1)
recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView, null, ChatappChatAdapter.getItemCount() - 1);
}
}
ChatappChatAdapter.java
public class ChatappChatAdapter extends RecyclerView.Adapter<ChatappChatAdapter.ViewHolder> {
private static final String TAG = "Adapter";
private String messageBy;
private int messageID;
private Context context;
private int SELF = 111;
private ArrayList<ChatappMsg> messages;
public ChatappChatAdapter(int messageID, Context context, ArrayList<ChatappMsg> messages) {
this.messageID = messageID;
// this.messageBy = messageBy;
this.context = context;
this.messages = messages;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
// if else loop to identify if the message is sent message or received message
//Creating view
// View itemView;
//if view type is self
if (viewType == SELF) {
Log.i(TAG,"ViewType Defined as Self" );
//Inflating the layout self
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_sent_message_text, parent, false);
} else {
Log.i(TAG,"ViewType Defined as Not Self" );
//else inflating the layout others
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_received_message_text, parent, false);
}
Log.i(TAG,"Retuened" );
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ChatappChatAdapter.ViewHolder holder, int position) {
ChatappMsg msg = messages.get(position);
((ViewHolder) holder).messageBody.setText(msg.getMessageBody());
((ViewHolder) holder).messageAt.setText(msg.getMessageAt());
((ViewHolder) holder).messageBy.setText(msg.getMessageBy());
}
public int getItemViewType(int position){
ChatappMsg msg = messages.get(position);
if(msg.getMessageID() == messageID ) {
return SELF;
}
return position;
}
#Override
public int getItemCount() {
return 0;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView messageBody;
public TextView messageAt;
public TextView messageBy;
public ViewHolder(View itemView)
{
super(itemView);
messageBody = (TextView) itemView.findViewById(R.id.messageBody);
messageAt = (TextView) itemView.findViewById(R.id.messageAt);
messageBy = (TextView) itemView.findViewById(R.id.messageBy);
}
}
}
Chatapp Model.
public class ChatappMsg {
private String messageBody;
private String messageAt;
private String messageBy;
private String messageType;
private int messageID;
public String getMessageBody() {
return messageBody;
}
public void setMessageBody(String messageBody) {
this.messageBody = messageBody;
}
public String getMessageAt() {
return messageAt;
}
public void setMessageAt(String messageAt) {
this.messageAt = messageAt;
}
public String getMessageBy() {
return messageBy;
}
public void setMessageBy(String messageBy) {
this.messageBy = messageBy;
}
public String getMessageType() {
return messageType;
}
public void setMessageType(String messageType) {
this.messageType = messageType;
}
public int getMessageID() {
return messageID;
}
public void setMessageID(int messageID) {
this.messageID = messageID;
}
public ChatappMsg(String messageBody, String messageAt, String messageBy, String messageType, int messageID) {
this.messageBody = messageBody;
this.messageAt = messageAt;
this.messageBy = messageBy;
this.messageType = messageType;
this.messageID = messageID;
}
#Override
public String toString() {
return "ChatappMsg{" +
"messageBody='" + messageBody + '\'' +
", messageAt='" + messageAt + '\'' +
", messageBy='" + messageBy + '\'' +
", messageType='" + messageType + '\'' +
", messageID='" + messageID + '\'' +
'}';
}
}
Help me in understanding what am I missing here.
I believe it might be an issue with the viewType or the message ID. How to fix? What should be the solution?
Thank you.
You are returning 0 in getItemCount() method in adapter.
Can you change it to
#Override
public int getItemCount() {
return messages.size();
}
in your ChatappChatAdapter and try again

how can i get data from adapter and show in Activity in Android

In my application I want show countries in dialog. In my application has some editTexts in mainActivity, when click on Contry editText show countryDialog and sort countries in this dialog (I get this countries from server).
I want when click on county name, set this country on editText.
my adapter codes:
public class CountryAdapter extends RecyclerView.Adapter {
private List<CountryDatum> mData;
private Context context;
public CountryAdapter(List<CountryDatum> mData, Context context) {
this.mData = mData;
this.context = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh;
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_country, parent, false);
vh = new DataViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof DataViewHolder) {
((DataViewHolder) holder).countryListTxt.setText(mData.get(position).getName() + "");
((DataViewHolder) holder).countryListTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "" + mData.get(position).getId(), Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public int getItemCount() {
return mData.size();
}
public void add(List<CountryDatum> models) {
mData.addAll(models);
notifyDataSetChanged();
}
public void clear() {
mData.clear();
notifyDataSetChanged();
}
public class DataViewHolder extends RecyclerView.ViewHolder {
private TextView countryListTxt;
public DataViewHolder(View itemView) {
super(itemView);
countryListTxt = (TextView) itemView.findViewById(R.id.countryNameTxt);
}
}
}
Main Activity codes:
public class RegisterActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {
private String countryName = "";
#BindView(R.id.registerCountryEdtTxt)
EditText countryListEdt;
#BindView(R.id.registerDateBirthEdtTxt)
EditText birthDayEdt;
private CountryAdapter mAdapter;
private List<CountryDatum> models = new ArrayList<>();
private Context context;
private Dialog dialog;
private RecyclerView countryRecyler;
private ProgressBar countryProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//Initialize
ButterKnife.bind(this);
context = RegisterActivity.this;
mAdapter = new CountryAdapter(models, context);
}
#OnClick({R.id.registerCountryEdtTxt, R.id.registerCountryInptLay})
void selectCountry() {
getData();
}
#OnClick({R.id.registerDateBirthInptLay, R.id.registerDateBirthEdtTxt})
void selectBirthDay() {
Calendar now = Calendar.getInstance();
DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(
RegisterActivity.this,
now.get(Calendar.YEAR),
now.get(Calendar.MONTH),
now.get(Calendar.DAY_OF_MONTH)
);
datePickerDialog.setVersion(DatePickerDialog.Version.VERSION_1);
datePickerDialog.show(getFragmentManager(), "Datepickerdialog");
}
#Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
String date = "You picked the following date: " + dayOfMonth + "/" + (monthOfYear + 1) + "/" + year;
birthDayEdt.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
public void getData() {
dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_country);
countryRecyler = (RecyclerView) dialog.findViewById(R.id.countryRecyclerView);
countryProgress = (ProgressBar) dialog.findViewById(R.id.countryDialog_progress);
countryRecyler.setLayoutManager(new LinearLayoutManager(context));
countryRecyler.setHasFixedSize(true);
countryProgress.setVisibility(View.VISIBLE);
InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
Call<CountryResponse> call = api.getCountryList();
call.enqueue(new Callback<CountryResponse>() {
#Override
public void onResponse(Call<CountryResponse> call, Response<CountryResponse> response) {
try {
if (response.body() != null) {
models.clear();
models.addAll(response.body().getData());
countryProgress.setVisibility(View.GONE);
countryRecyler.setAdapter(mAdapter);
}
} catch (Exception e) {
}
}
#Override
public void onFailure(Call<CountryResponse> call, Throwable t) {
}
});
dialog.show();
}
}
How can I when click on country names (from adapter), set this name for registerCountryEdtTxt.setText (in mainActivity)? how can I it?
I am amateur, please help me <3
In adapter create on interface to transfer data
public class CountryAdapter extends RecyclerView.Adapter {
public interface onListClickedRowListner {
void onListSelected(int mposition);
}
}
and in adapter constructor
onListClickedRowListner listner;
public CountryAdapter(List<CountryDatum> mData, Context context,onListClickedRowListner listner) {
this.mData = mData;
this.context = context;
this.listner = listner;
}
and in onBindViewHolder
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof DataViewHolder) {
((DataViewHolder) holder).countryListTxt.setText(mData.get(position).getName() + "");
((DataViewHolder) holder).countryListTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "" + mData.get(position).getId(), Toast.LENGTH_SHORT).show();
listner.onListSelected(position);
}
});
}
}
and implements this listner in mainActivity
and onListSelected in this method you get position using that position get value from mData and assign to any view in your activity.
public class RegisterActivity extends AppCompatActivity implements
CountryAdapter.onListClickedRowListner {
.
.
.
#Override
public void onListSelected (int listposition){
Log.d("Tag",""+listposition);
}
}
and in you oncreate change like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//Initialize
ButterKnife.bind(this);
context = RegisterActivity.this;
mAdapter = new CountryAdapter(models, context,this);
}
Try this solution . In your activity class do this.
countryRecyler.setAdapter(mAdapter,registerCountryEdtTxt);
then in adapter class
private List<CountryDatum> mData;
private Context context;
private EditText mEditText;
public CountryAdapter(List<CountryDatum> mData, Context
context,EditText edittext) {
this.mData = mData;
this.context = context;
mEditText=edittext;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof DataViewHolder) {
((DataViewHolder) holder).countryListTxt.setText(mData.get(position).getName() + "");
((DataViewHolder) holder).countryListTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "" + mData.get(position).getId(), Toast.LENGTH_SHORT).show();
mEditText.setText(mData.get(position).getName())
}
});
}
}

Categories