EditText field gets an incorrect output - java

So, I have this testing app where I am trying to have two fragments communicate via MainActivity. After some research, I have managed to pass data from MainFragment to FragmentTwo. However, whenever I pass in string value from the MainFragment, I get a message saying
"android.support.v7.widget.AppCompatEditText{cce883f VFED .....
app:id/editText}"
I couldn't find what the problem was for this case. Please help.
BTW I know how to use intents and that they are much more flexible(sometimes) than fragments are but this is just so that I know how far I can go with Fragments.
Here's my MainActivity
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, MainFragment.OnHeadlineSelectedListener {
private String dataReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void sendInformations(String message) {
FragmentTwo fragmentTwo = new FragmentTwo();
Bundle args = new Bundle();
args.putString(fragmentTwo.DATA_RECEIVE, message);
fragmentTwo.setArguments(args);
getFragmentManager().beginTransaction()
.replace(R.id.container, fragmentTwo)
.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentManager fragmentManager = getFragmentManager();
int id = item.getItemId();
if (id == R.id.frag_one) {
fragmentManager.beginTransaction().replace(R.id.container, new FragmentOne()).commit();
} else if (id == R.id.frag_two) {
fragmentManager.beginTransaction().replace(R.id.container, new FragmentTwo()).commit();
} else if (id == R.id.frag_three) {
fragmentManager.beginTransaction().replace(R.id.container, new FragmentThree()).commit();
} else if (id == R.id.frag_four) {
fragmentManager.beginTransaction().replace(R.id.container, new FragmentFour()).commit();
} else if (id == R.id.main_frag) {
fragmentManager.beginTransaction().replace(R.id.container, new MainFragment()).commit();
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
MainFragment class
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class MainFragment extends Fragment {
OnHeadlineSelectedListener mCallback;
Button sendData;
public interface OnHeadlineSelectedListener {
public void sendInformations(String message);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main_fragment, container, false);
final EditText userInput = (EditText) rootView.findViewById(R.id.editText);
sendData = (Button) rootView.findViewById(R.id.button);
sendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.button) {
mCallback.sendInformations(userInput.toString());
}
}
});
return rootView;
}
}
FragmentTwo class
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FragmentTwo extends Fragment {
final static String DATA_RECEIVE = "data_receive";
TextView textView;
String input;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_two, container, false);
textView = (TextView) rootView.findViewById(R.id.data_receiver2);
savedInstanceState = getArguments();
if(savedInstanceState != null) {
input = savedInstanceState.getString(DATA_RECEIVE);
}
textView.setText(input);
return rootView;
}
}
Oh, and the message I get is when I run the app, type into the textfield, and press the button, I get the weird message. I would appreciate if anyone can tell me what is causing the weird output..
If this is a bug, which I had noticed in some cases that were relevant, is it because I deprecated the v7.Fragment & v7.FragmentManager?

You are basically passing the EditText as a string in place of the EditText value.
In your MainFragment change mCallback.sendInformations(userInput.toString()); to mCallback.sendInformations(userInput.getText().toString());
sendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.button) {
mCallback.sendInformations(userInput.getText().toString());
}
}
});

Related

it doesn't show the items in the recyclerviewer

This is what I got when I make it.
The first thing this is the database and I don't know what exactly happen, but it is not work with me it doesn't show any data in the app.
And this is the code with every thing with it
package com.ta3am.ta3ami.ta3ami;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
import com.ta3am.ta3ami.ta3ami.Common.Common;
import com.ta3am.ta3ami.ta3ami.Interface.ItemClickListener;
import com.ta3am.ta3ami.ta3ami.Model.Category;
import com.ta3am.ta3ami.ta3ami.ViewHolder.MenuViewHolder;
public class Home extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DatabaseReference ref;
TextView txtFullName;
RecyclerView recycler_menu;
RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Menu");
setSupportActionBar(toolbar);
//Init Firebase
ref = FirebaseDatabase.getInstance().getReference("Category");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//Set Name for user
View headerView = navigationView.getHeaderView(0);
txtFullName = (TextView)headerView.findViewById(R.id.txtFullName);
txtFullName.setText(Common.currentUser.getName());
//Load menu
recycler_menu =(RecyclerView)findViewById(R.id.recycler_menu);
recycler_menu.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recycler_menu.setLayoutManager(layoutManager);
loadMenu();
}
private void loadMenu() {
FirebaseRecyclerAdapter<Category,MenuViewHolder> adapter=new FirebaseRecyclerAdapter <Category, MenuViewHolder>(Category.class, R.layout.menu_item, MenuViewHolder.class, ref) {
#Override
protected void populateViewHolder(MenuViewHolder viewHolder, Category model, int position) {
viewHolder.txtMenuName.setText(model.getName());
Picasso.with(getBaseContext()).load(model.getImage()).into(viewHolder.imageView);
final Category clickItem =model;
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Toast.makeText(Home.this, ""+clickItem.getName(), Toast.LENGTH_SHORT).show();
}
});
}
};
recycler_menu.setAdapter(adapter);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_menu) {
// Handle the camera action
} else if (id == R.id.nav_cart) {
} else if (id == R.id.nav_orders) {
} else if (id == R.id.nav_log_out) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
And the other thing about the other code is ViewHolder and so on
package com.ta3am.ta3ami.ta3ami.ViewHolder;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.ta3am.ta3ami.ta3ami.Interface.ItemClickListener;
import com.ta3am.ta3ami.ta3ami.R;
public class MenuViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView txtMenuName;
public ImageView imageView;
private ItemClickListener itemClickListener;
public MenuViewHolder(View itemView) {
super(itemView);
txtMenuName =(TextView)itemView.findViewById(R.id.menu_name);
imageView =(ImageView)itemView.findViewById(R.id.menu_image);
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View view){
itemClickListener.onClick(view,getAdapterPosition(),false);
}
}
And as I say there is noting here every thing seem to me good and work harmfully, but I don't know what is the wrong with the data
package com.ta3am.ta3ami.ta3ami.Model;
import android.net.Uri;
import android.widget.ImageView;
public class Category {
private String Name;
private String Image;
public Category() {
}
public Category(String name, String image) {
Name = name;
Image = image;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
}
You have not set the layout manager to the adapter. Kindly set a Layout Manager as per your requirement.
Like, adapter.setLayoutManager(new LinearLayoutManager(context)); and it shall work fine then.
You have to update the syntax of the FirebaseRecyclerAdapter
Update loadMenu() method.
private void loadMenu() {
Query query = ref.limitToLast(10); // you can set data limit for how much data you want in list
FirebaseRecyclerOptions dataoptions = new FirebaseRecyclerOptions.Builder<Category>().setQuery(query, Category.class).build();
adapter=new FirebaseRecyclerAdapter <Category, MenuViewHolder>(dataoptions) {
#Override
protected void onBindViewHolder(MenuViewHolder viewHolder, Category model, int position) {
viewHolder.txtMenuName.setText(model.getName());
Picasso.with(getBaseContext()).load(model.getImage()).into(viewHolder.imageView);
final Category clickItem =model;
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Toast.makeText(Home.this, ""+clickItem.getName(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public MenuViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.menu_item, parent, false);
return new MenuViewHolder(view);
}
};
recycler_menu.setAdapter(adapter);
}
After that you need to register adapter listener in OnStart() method of the your activity.
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}

How to open a details activity when an item is clicked in Firebase RecyclerView Cardview

I want to Implement Onclick Item in recyclerView To open new activity I can pass data from one to another activity but in the code cannot figure out where to Implement on click onclicklistener if anyone is free to help me edit and give intent to Details.class
as I am getting data from firebase its first time to work on firebase any help would be appreciated.
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import com.dekhou.provissionstore.model.Movie;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private FloatingActionButton fab;
ScaleAnimation shrinkAnim;
private RecyclerView mRecyclerView;
private StaggeredGridLayoutManager mLayoutManager;
private TextView tvNoMovies,tvNoMovies1;
private Context context;
//Getting reference to Firebase Database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabaseReference = database.getReference();
private static final String userId = "01";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//Initializing our Recyclerview
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
tvNoMovies = (TextView) findViewById(R.id.tv_no_movies);
//tvNoMovies1 = (TextView) findViewById(R.id.addresstxt);
//scale animation to shrink floating actionbar
shrinkAnim = new ScaleAnimation(1.15f, 0f, 1.15f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
if (mRecyclerView != null) {
//to enable optimization of recyclerview
mRecyclerView.setHasFixedSize(true);
}
//using staggered grid pattern in recyclerview
mLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(mLayoutManager);
//Say Hello to our new FirebaseUI android Element, i.e., FirebaseRecyclerAdapter
FirebaseRecyclerAdapter<Movie,MovieViewHolder> adapter = new FirebaseRecyclerAdapter<Movie, MovieViewHolder>(
Movie.class,
R.layout.movie_board_item,
MovieViewHolder.class,
//referencing the node where we want the database to store the data from our Object
mDatabaseReference.child("users").child(userId).child("shops").getRef()
) {
#Override
protected void populateViewHolder(MovieViewHolder viewHolder, final Movie model, final int position) {
if(tvNoMovies.getVisibility()== View.VISIBLE){
tvNoMovies.setVisibility(View.GONE);
}
viewHolder.tvMovieName.setText(model.getMovieName());
viewHolder.address.setText(model.getAddress());
viewHolder.phone.setText(model.getPhone());
viewHolder.lit.setText(model.getLit());
viewHolder.lon.setText(model.getLon());
Picasso.with(MainActivity.this).load(model.getMoviePoster()).into(viewHolder.ivMoviePoster);
// all your stuff
}
};
mRecyclerView.setAdapter(adapter);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.frame_container, new AddMovieFragment())
.addToBackStack(null)
.commit();
//animation being used to make floating actionbar disappear
shrinkAnim.setDuration(400);
fab.setAnimation(shrinkAnim);
shrinkAnim.start();
shrinkAnim.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
//changing floating actionbar visibility to gone on animation end
fab.setVisibility(View.GONE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.menu_map) {
Intent intent = new Intent(this, MapsActivity.class);
this.startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_slideshow) {
Intent cinemaIntent = new Intent(this, MapsActivity.class);
startActivity(cinemaIntent);
} else if (id == R.id.nav_manage) {
Intent cinemaIntent = new Intent(this, Get_Data.class);
startActivity(cinemaIntent);
} else if (id == R.id.nav_share) {
try {
//try to open page in facebook native app.
String uri = "fb://page/" + "293069792077"; //Cutsom URL
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);
}catch (ActivityNotFoundException ex){
//facebook native app isn't available, use browser.
String uri = "http://touch.facebook.com/pages/x/" + "293069792077"; //Normal URL
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(i);
}
} else if (id == R.id.nav_send) {
Intent cinemaIntent = new Intent(this, About_Us.class);
startActivity(cinemaIntent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//ViewHolder for our Firebase UI
public static class MovieViewHolder extends RecyclerView.ViewHolder{
TextView tvMovieName,address,phone,lit,lon;
ImageView ivMoviePoster;
public MovieViewHolder(View v) {
super(v);
tvMovieName = (TextView) v.findViewById(R.id.tv_name);
address = (TextView) v.findViewById(R.id.address1);
phone = (TextView) v.findViewById(R.id.tv_phone);
lit = (TextView) v.findViewById(R.id.geo);
lon = (TextView) v.findViewById(R.id.geo2);
ivMoviePoster = (ImageView) v.findViewById(R.id.iv_movie_poster);
}
}
}
Add onClickListener to the itemView for your ViewHolder in populateViewHolder and start the Activity. like the below example.
#Override
protected void populateViewHolder(MovieViewHolder viewHolder, final Movie model, final int position) {
if(tvNoMovies.getVisibility()== View.VISIBLE){
tvNoMovies.setVisibility(View.GONE);
}
viewHolder.tvMovieName.setText(model.getMovieName());
viewHolder.address.setText(model.getAddress());
viewHolder.phone.setText(model.getPhone());
viewHolder.lit.setText(model.getLit());
viewHolder.lon.setText(model.getLon());
Picasso.with(MainActivity.this).load(model.getMoviePoster()).into(viewHolder.ivMoviePoster);
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
//intent.putExtra("model", model);
intent.putExtra("latitude", model.getLit());
intent.putExtra("longitude", model.getLon());
startActivity(intent);
}
});
// all your stuff
}
try this add onClickListener in your populateViewHolderlike this
#Override
protected void populateViewHolder(MovieViewHolder viewHolder, final Movie model, final int position) {
if(tvNoMovies.getVisibility()== View.VISIBLE){
tvNoMovies.setVisibility(View.GONE);
}
viewHolder.tvMovieName.setText(model.getMovieName());
viewHolder.address.setText(model.getAddress());
viewHolder.phone.setText(model.getPhone());
viewHolder.lit.setText(model.getLit());
viewHolder.lon.setText(model.getLon());
Picasso.with(MainActivity.this).load(model.getMoviePoster()).into(viewHolder.ivMoviePoster);
viewHolder.tvMovieName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
startActivity(intent);
}
});
}

Force class with Java import

While building my app I noticed that my app force closes when I import any Java util in my MainActivity(.java).
The original one is this one:
package com.ivancristina.navigazione;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_formule) {
LinearLayout mainLayout = (LinearLayout) findViewById(R.id. main_container);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.content_formule, null);
mainLayout.removeAllViews();
mainLayout.addView(layout);
} else if (id == R.id.nav_esempi) {
LinearLayout mainLayout = (LinearLayout) findViewById(R.id. main_container);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.content_esempi, null);
mainLayout.removeAllViews();
mainLayout.addView(layout);
} else if (id == R.id.nav_home) {
LinearLayout mainLayout = (LinearLayout) findViewById(R.id. main_container);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.content_main, null);
mainLayout.removeAllViews();
mainLayout.addView(layout);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
while the that one with java is this one:
package com.ivancristina.navigazione;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import java.util.*;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private ImageView logo;
private Button github;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initialize();
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
private void initialize() {
logo = (ImageView) findViewById(R.id.logo);
github = (Button) findViewById(R.id.github);
logo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View _v) {
showMessage("OnClick");
}
});
github.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View _v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.github.com/ivancristina")));
}
});
}
// created automatically
private void showMessage(String _s) {
Toast.makeText(getApplicationContext(), _s, Toast.LENGTH_SHORT).show();
}
private int getRandom(int _minValue ,int _maxValue){
Random random = new Random();
return random.nextInt(_maxValue - _minValue + 1) + _minValue;
}
public ArrayList<Double> getCheckedItemPositionsToArray(ListView _list) {
ArrayList<Double> _result = new ArrayList<Double>();
SparseBooleanArray _arr = _list.getCheckedItemPositions();
for (int _iIdx = 0; _iIdx < _arr.size(); _iIdx++) {
if (_arr.valueAt(_iIdx))
_result.add((double)_arr.keyAt(_iIdx));
}
return _result;
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_formule) {
LinearLayout mainLayout = (LinearLayout) findViewById(R.id. main_container);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.content_formule, null);
mainLayout.removeAllViews();
mainLayout.addView(layout);
} else if (id == R.id.nav_esempi) {
LinearLayout mainLayout = (LinearLayout) findViewById(R.id. main_container);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.content_esempi, null);
mainLayout.removeAllViews();
mainLayout.addView(layout);
} else if (id == R.id.nav_home) {
LinearLayout mainLayout = (LinearLayout) findViewById(R.id. main_container);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.content_main, null);
mainLayout.removeAllViews();
mainLayout.addView(layout);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
I'm sure I made something wrong with some activity, anyway if anyone would like to get a look to the rest of the project, here there are my
content_main and content_formule, which as I said work fine without Java, but in this way are useless.
(Posted on behalf of the OP).
The mistake was mine.
I put initialize(); right after super.onCreate(savedInstanceState);. Moving it right before
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
solved my problem.

Android studio - Button onclick in a fragment ERROR [duplicate]

This question already has answers here:
Start an activity from a fragment
(7 answers)
Closed 6 years ago.
SecondFragment.java
package com.hci.acer.heroesunite;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class SecondFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.trivia, container, false);
Button button = (Button) view.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i;
i = new Intent(SecondFragment.this, jrizal_trivia.class);
startActivity(i);
}
});
return view;
}
}
jrizal_trivia.java
package com.hci.acer.heroesunite;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class jrizal_trivia extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jrizal_trivia);
}
}
MainActivity.java
package com.hci.acer.heroesunite;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
android.app.FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_home) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
,new FirstFragment())
.commit();
} else if (id == R.id.nav_dyk) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
,new SecondFragment())
.commit();
} else if (id == R.id.nav_about) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
,new ThirdFragment())
.commit();
} else if (id == R.id.nav_hero1) {
startActivity(new Intent(this, jose_rizal.class));
} else if (id == R.id.nav_hero2) {
startActivity(new Intent(this, andres_bonifacio.class));
} else if (id == R.id.nav_hero3) {
startActivity(new Intent(this, emilio_aguinaldo.class));
} else if (id == R.id.nav_hero4) {
startActivity(new Intent(this, apolinario_mabini.class));
} else if (id == R.id.nav_hero5) {
} else if (id == R.id.nav_hero6) {
startActivity(new Intent(this, juan_luna.class));
} else if (id == R.id.nav_hero7) {
} else if (id == R.id.nav_hero8) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
And this is the error
Error:(28, 31) error: no suitable constructor found for
Intent(,Class) constructor
Intent.Intent(String,Uri) is not applicable (argument mismatch;
cannot be converted to String) constructor
Intent.Intent(Context,Class) is not applicable (argument mismatch;
cannot be converted to Context)
under (SecondFragment.this, jrizal_trivia.class);
error says. "Cannot resolve constructor'intent(com.hci.acer.heroesunite.SecondFragment,java.lang.Class)'
Help anyone ? i want to call another activity in my button here in SecondFragment. Thanks
i = new Intent(SecondFragment.this, jrizal_trivia.class);
the first param need a Context, so you can get Context from fragment by getActivity()/getContext().
so should be like this:
i = new Intent(getActivity(), jrizal_trivia.class);

RecyclerView error: No adapter attached; skipping layout

When I try to add RecyclerView in the sample application, I get an error E/RecyclerView: No adapter attached; skipping layout.
Because of this, the data which is successfully retrieved from my server does not appear on the screen (empty)
This in my code
MainActivity
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import page.DefaultFragment;
import page.HomeFragment;
import page.ProfileFragment;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = MainActivity.class.getSimpleName();
private final static String API_KEY = "7e8f60e325cd06e164799af1e317d7a7";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_test);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
Fragment fragment = null;
fragment = new DefaultFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.root, fragment);
fragmentTransaction.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment = null;
String title = getString(R.string.app_name);
if (id == R.id.nav_camera) {
fragment = new HomeFragment();
title = "Home";
} else if (id == R.id.nav_gallery) {
fragment = new ProfileFragment();
title = "Profile";
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.root, fragment);
fragmentTransaction.commit();
getSupportActionBar().setTitle(title);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void showToast(String output){
Toast.makeText(this.getBaseContext(), output, Toast.LENGTH_SHORT).show();
}
}
My Fragment code
package page;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
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.Toast;
import com.transvision.bertho.transvisiondashboardapp.R;
import java.util.List;
import adapter.ChannelAdapter;
import model.Channel;
import model.ChannelResponse;
import rest.ApiClient;
import rest.ApiInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class HomeFragment extends Fragment {
private RecyclerView recyclerView;
private static final String TAG = HomeFragment.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.movies_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
getChannelData();
// Inflate the layout for this fragment
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
public void getChannelData() {
ApiInterface apiService = ApiClient.getChannel().create(ApiInterface.class);
Call<ChannelResponse> call = apiService.getItems();
call.enqueue(new Callback<ChannelResponse>() {
#Override
public void onResponse(Call<ChannelResponse> call, Response<ChannelResponse> response) {
int statusCode = response.code();
List<Channel> channel = response.body().getItems();
recyclerView.setAdapter(new ChannelAdapter(channel, R.layout.list_channel, getActivity()));
}
#Override
public void onFailure(Call<ChannelResponse> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
showToast("CONNECTION ERROR");
}
});
}
public void showToast(String output){
Toast.makeText(getActivity(), output, Toast.LENGTH_SHORT).show();
}
}
My adapter
package adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.transvision.bertho.transvisiondashboardapp.R;
import java.util.List;
import model.Channel;
public class ChannelAdapter extends RecyclerView.Adapter<ChannelAdapter.ChannelViewHolder> {
private List<Channel> channels;
private int rowLayout;
private Context context;
public static class ChannelViewHolder extends RecyclerView.ViewHolder {
LinearLayout moviesLayout;
TextView movieTitle;
TextView data;
TextView movieDescription;
TextView rating;
TextView name;
TextView code;
TextView description;
TextView number;
TextView definition;
TextView paket;
ImageView logo;
public ChannelViewHolder(View v) {
super(v);
moviesLayout = (LinearLayout) v.findViewById(R.id.movies_layout);
name = (TextView) v.findViewById(R.id.title);
definition = (TextView) v.findViewById(R.id.subtitle);
description = (TextView) v.findViewById(R.id.description);
// rating = (TextView) v.findViewById(R.id.rating);
}
}
public ChannelAdapter(List<Channel> channels, int rowLayout, Context context) {
this.channels = channels;
this.rowLayout = rowLayout;
this.context = context;
}
#Override
public ChannelAdapter.ChannelViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new ChannelViewHolder(view);
}
#Override
public void onBindViewHolder(ChannelViewHolder holder, final int position) {
holder.name.setText(channels.get(position).getName());
holder.definition.setText(channels.get(position).getDefinition());
holder.description.setText(channels.get(position).getDescription());
// holder.rating.setText(channels.get(position).getVoteAverage().toString());
}
#Override
public int getItemCount() {
return channels.size();
}
}
Is there anything wrong in my code? Or wrong in code placement?
Thanks
Getting data from internet is an async task and may takes too long, here you don't bind any adapter to the recyclerView until you get a response and this is not the usual right way, If you don't get any response for some reasons (e.g no internet connection), then recyclerView.setAdapter won't run, So I suggest you to create an empty adapter first, Then whenever you get response just update the adapter :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.movies_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
//Pass empty list to (predefined) adapter
adapter = new ChannelAdapter (new ArrayList<>(), rowLayout, getActivity());
//Bind it to recyclerView
recyclerView.setAdapter(adapter);
getChannelData();
// Inflate the layout for this fragment
return rootView;
}
Add some method to your adapter in case you want add Channel :
public void addChannel(Channel channel) {
channels.add(channel);
notifyDatasetChanged();//even better notifyItemInserted();
}
Now in your response listener add the response body that you got to the adapter:
#Override
public void onResponse(Call<ChannelResponse> call, Response<ChannelResponse> response) {
//Use a loop to add channels you got
adapter.addChannel(responsebodyItems);
}

Categories