My App works perfectly at loading all the events and activities. However, when I try to load an Activity containing RecyclerView to show some stored strings. It crashes and finish.
I don´t know if the syntax is wrong or maybe the logic of the code itself.
I am calling the activity from a listener
Object parceable to the new activity:
final public FrasesProvisional frases = new FrasesProvisional();
Method starting the activity:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.config:
lanzarConfiguracion(null);
break;
case R.id.about:
lanzarAbout(null);
break;
case R.id.mismotivaciones:
abrirMotivaciones(null);
break;
}
return true;
}
private void abrirMotivaciones(View view) {
Intent i = new Intent(this, MotivacionesUser.class);
startActivity(i);
}
Activity content:
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
/**
* Created by Pablo on 14/01/2017.
*/
public class MotivacionesUser extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutMmanager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.motivacionesrecycler);
FrasesProvisional frases = getIntent().getParcelableExtra("frases");
mRecyclerView = (RecyclerView) findViewById(R.id.motivaciones_recycler);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
//Init LayoutManager
mLayoutMmanager = new LinearLayoutManager(this); //Podemos elegir entre LinearM, GridM o ScrappableM en relación al estilo que queramos
mRecyclerView.setLayoutManager(mLayoutMmanager); //Set the Layout to the RrecyclerView
mAdapter = new RecyclerAdaptador(frases.getArrayList()); //Especificamos el adaptador a usar y lo agenciamos al Recycler
mRecyclerView.setAdapter(mAdapter);
}
}
RecyclerView code:
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Pablo on 14/01/2017.
*/
public class RecyclerAdaptador extends RecyclerView.Adapter < RecyclerAdaptador.ViewHolder > {
private ArrayList < String > frases;
public static class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView mTextView;
public ViewHolder(View v) {
super(v); //Inicializa el textview
mTextView = (TextView) v.findViewById(R.id.text_recycler);
}
}
public RecyclerAdaptador(ArrayList < String > frases) {
this.frases = frases;
}
#Override
public RecyclerAdaptador.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//Create a new view
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.frase_recycler, parent, false);
ViewHolder vh = new ViewHolder(view);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
//Get element of the data set at the position x and replace the content of the rextView with it
holder.mTextView.setText(frases.get(position));
}
#Override
public int getItemCount() {
return frases.size();
}
}
Thanks in advance!
Looking at your code, you create the activity through the following snippet:
Intent i = new Intent(this, MotivacionesUser.class);
startActivity(i);
However in the activity you try to read out extra data in FrasesProvisional frases = getIntent().getParcelableExtra("frases");.
Since you never attached that data to the intent that would return null.
You then use it without checking if it was null at new RecyclerAdaptador(frases.getArrayList());, causing a NullPointerException and crashing your class.
Add a class variable
Context context;
public RecyclerAdaptador(Context context,ArrayList<String> frases) {
this.context=context
this.frases = frases;
}
from activity
mAdapter = new RecyclerAdaptador(this,frases.getArrayList());
Related
Actually, I am adding objects in ArrayList from a RecyclerAdapter and I have written a function for getting the arraylist in adapter.And I am getting the arraylist from that function in MainActivity.But whenever I am trying to pass that arraylist from MainActivity to a Fragment it is giving NullPointer(Null value).
Help me.
package com.example.codingmounrtain.addtocartbadgecount.adapter;
import android.content.Context;
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 com.example.codingmounrtain.addtocartbadgecount.activity.MainActivity;
import com.example.codingmounrtain.addtocartbadgecount.ModelClasses.Movie;
import com.example.codingmounrtain.addtocartbadgecount.R;
import com.example.codingmounrtain.addtocartbadgecount.interfaces.AddorRemoveCallbacks;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
ArrayList<Movie> cartmovies = new ArrayList<>();
public interface Listener {
void onSelectMovie(int position);
}
Context context;
private final ArrayList<Movie> movies;
private final Listener listener;
public RecyclerAdapter(Context context, ArrayList<Movie> movies,Listener listener) {
this.context = context;
this.movies = movies;
this.listener = listener;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.productName.setText(movies.get(position).getTitle());
Picasso.with(context).load(movies.get(position).getPhoto()).centerCrop().resize(400,400).into(holder.productImage);
holder.productImage.setImageResource(movies.get(position).getPhoto());
holder.productImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onSelectMovie(position);
}
});
holder.addRemoveBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!movies.get(position).isAddedTocart())
{
Log.v("tej","tej");
movies.get(position).setAddedTocart(true);
Log.v("t","t");
holder.addRemoveBt.setText("Remove");
Movie movie = movies.get(position);
cartmovies.add(movie);
Log.v("t","t");
if(context instanceof MainActivity)
{
((AddorRemoveCallbacks)context).onAddProduct();
}
}
else
{
movies.get(position).setAddedTocart(false);
Movie movie = movies.get(position);
cartmovies.remove(movie);
holder.addRemoveBt.setText("Add");
((AddorRemoveCallbacks)context).onRemoveProduct();
}
}
});
}
public ArrayList<Movie> getArrayList(){
return cartmovies;
}
#Override
public int getItemCount() {
return movies.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
ImageView productImage;
TextView productName;
Button addRemoveBt;
public MyViewHolder(View itemView) {
super(itemView);
productImage=(ImageView) itemView.findViewById(R.id.productImageView);
productName=(TextView) itemView.findViewById(R.id.productNameTv);
addRemoveBt=(Button)itemView.findViewById(R.id.addButton);
}
}
}
MainActivity.java
package com.example.codingmounrtain.addtocartbadgecount.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.example.codingmounrtain.addtocartbadgecount.Converter;
import com.example.codingmounrtain.addtocartbadgecount.ModelClasses.Movie;
import com.example.codingmounrtain.addtocartbadgecount.R;
import com.example.codingmounrtain.addtocartbadgecount.adapter.RecyclerAdapter;
import com.example.codingmounrtain.addtocartbadgecount.fragment.CartFragment;
import com.example.codingmounrtain.addtocartbadgecount.fragment.SearchFragment;
import com.example.codingmounrtain.addtocartbadgecount.interfaces.AddorRemoveCallbacks;
import java.util.ArrayList;
import java.util.Iterator;
public class MainActivity extends AppCompatActivity implements AddorRemoveCallbacks,RecyclerAdapter.Listener{
ArrayList<Movie> cartmovies = new ArrayList<>();
ArrayList<Movie> movies = new ArrayList<>();
RecyclerView mRecyclerView;
RecyclerAdapter mAdapter;
private static int cart_count=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("MovieShop");
getSupportActionBar().show();
movies.add(new Movie("Stree","A town is held in the grip of terror by tales of a mysterious woman who calls men by their name and then abducts them, leaving their clothes behind.","Rajkummar Rao","Shraddha Kapoor","Amar Kaushik",4.0f,R.drawable.stree));
movies.add(new Movie("Nun","When a young nun at a cloistered abbey in Romania takes her own life, a priest with a haunted past and a novitiate on the threshold of her final vows are sent by the Vatican to investigate. ","Demián Bichir","Taissa Farmiga","Corin Hardy",2.5f,R.drawable.nun));
movies.add(new Movie("Savita Damodar Paranjpe","The lives of a married couple are turned upside down when hard truths come to light.","Subodh Bhave","Trupti Madhukar Toradmal","Swapna Waghmare Joshi",3.5f,R.drawable.savita));
movies.add(new Movie("TC GN"," A recently retired professional is cheated of a large sum of money through a digital fraud. ","Sachin Khedekar","Iravati Harshe","Girish Jayant Joshi",3.0f,R.drawable.tcgn));
movies.add(new Movie("MI","Ethan Hunt and the IMF team join forces with CIA assassin August Walker to prevent a disaster of epic proportions.","Tom Cruise","Rebecca Ferguson","Christopher McQuarrie",4.0f,R.drawable.mi));
movies.add(new Movie("Searching","After David Kim (John Cho)'s 16-year-old daughter goes missing, a local investigation is opened and a detective is assigned to the case. ","John Cho","Debra Messing","Aneesh Chaganty",2.5f,R.drawable.searching));
movies.add(new Movie("SURYA"," Indian Telugu-language action film written and directed by Vakkantham Vamsi in his directorial debut. ","Allu Arjun","Anu Emmanuel","Vakkantham Vamsi",3.5f,R.drawable.surya));
movies.add(new Movie("TC GN"," A recently retired professional is cheated of a large sum of money through a digital fraud. ","Sachin Khedekar","Iravati Harshe","Girish Jayant Joshi",3.0f,R.drawable.tcgn));
mRecyclerView = findViewById(R.id.recyclerview);
mRecyclerView.setHasFixedSize(true);
GridLayoutManager mLayoutManager = new GridLayoutManager(this,2);
mRecyclerView.setLayoutManager(mLayoutManager);
// specify an adapter (see also next example)
mAdapter = new RecyclerAdapter(this, movies,this);
mRecyclerView.setAdapter(mAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem menuItem = menu.findItem(R.id.cart_action);
menuItem.setIcon(Converter.convertLayoutToImage(MainActivity.this,cart_count,R.drawable.ic_shopping_cart_white_24dp));
MenuItem menuItem2 = menu.findItem(R.id.search_action);
menuItem2.setIcon(R.drawable.ic_search_black_24dp);
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();
cartmovies = mAdapter.getArrayList();
Movie movie = null;
Iterator<Movie> iter = cartmovies.iterator();
while ( iter .hasNext() == true )
{
movie = iter.next();
Log.v("tejjjj",movie.getTitle());
}
// cartmovies.get(0).getTitle();
if(id==R.id.cart_action){
Bundle bundle = new Bundle();
bundle.putSerializable("catmovies",cartmovies);
Fragment fragment = new CartFragment();
fragment.setArguments(bundle);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.contentLayout, fragment)
.addToBackStack("MainActivity")
.commit();
}
if(id==R.id.search_action){
Bundle bundle = new Bundle();
// bundle.putString("query", editSearch.getText().toString());
bundle.putSerializable("movies",movies);
Fragment fragment = new SearchFragment();
fragment.setArguments(bundle);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.contentLayout, fragment)
.addToBackStack("MainActivity")
.commit();
// search(searchStr, movies);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onAddProduct() {
cart_count++;
Log.v("stej",""+cart_count);
invalidateOptionsMenu();
Snackbar.make((CoordinatorLayout)findViewById(R.id.parentlayout), "Movie added to cart !!", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
#Override
public void onRemoveProduct() {
cart_count--;
Log.v("tej",""+cart_count);
invalidateOptionsMenu();
Snackbar.make((CoordinatorLayout)findViewById(R.id.parentlayout), "Movie removed from cart !!", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
#Override
public void onSelectMovie(int position) {
Movie movie = movies.get(position);
// Toast.makeText(this, "selected movie: " + movie.getTitle(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, DetailActivity.class);
intent.putExtra("title",movie.getTitle());
intent.putExtra("director",movie.getDirector());
intent.putExtra("actors",movie.getActors());
intent.putExtra("actresses",movie.getActresses());
intent.putExtra("info",movie.getDescription());
intent.putExtra("photo",movie.getPhoto());
intent.putExtra("rating",movie.getRating());
startActivity(intent);
}
}
CartFragment.java
package com.example.codingmounrtain.addtocartbadgecount.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
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.LinearLayout;
import com.example.codingmounrtain.addtocartbadgecount.ModelClasses.Movie;
import com.example.codingmounrtain.addtocartbadgecount.R;
import com.example.codingmounrtain.addtocartbadgecount.activity.DetailActivity;
import com.example.codingmounrtain.addtocartbadgecount.adapter.MovieListAdapter;
import com.example.codingmounrtain.addtocartbadgecount.adapter.RecyclerAdapter;
import java.util.ArrayList;
import java.util.Iterator;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
public class CartFragment extends Fragment implements View.OnClickListener, MovieListAdapter.Listener {
#BindView(R.id.recyclerView)
RecyclerView recyclerView;
Unbinder unbinder;
MovieListAdapter adapter;
RecyclerAdapter madapter;
ArrayList<Movie> movies = new ArrayList<>();
ArrayList<Movie> movies1 = new ArrayList<>();
public CartFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.fragment_cart, null);
unbinder = ButterKnife.bind(this, layout);
adapter = new MovieListAdapter(getActivity(),movies,this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 1));
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Movie Cart");
// movies1 =(ArrayList<Movie>) savedInstanceState.getParcelable("movies");
// buttonSearch.setOnClickListener(this);
return layout;
}
#Override
public void onResume() {
super.onResume();
getList();
}
#Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
void getList(){
Bundle bundle = getArguments();
movies1 =(ArrayList<Movie>) bundle.getSerializable("cartmovies");
Iterator<Movie> iter = movies1.iterator();
Movie movie = null;
while(iter.hasNext() == true){
movie = iter.next();
movies.add(movie);
adapter.notifyDataSetChanged();
}
}
#Override
public void onClick(View view) {
}
#Override
public void onSelectMovie(int position) {
Movie movie = movies.get(position);
Intent intent = new Intent(getActivity(),DetailActivity.class);
intent.putExtra("title",movie.getTitle());
intent.putExtra("director",movie.getDirector());
intent.putExtra("actors",movie.getActors());
intent.putExtra("actresses",movie.getActresses());
intent.putExtra("info",movie.getDescription());
intent.putExtra("photo",movie.getPhoto());
intent.putExtra("rating",movie.getRating());
startActivity(intent);
}
}
Write a get method inside your adapter then call it from your activity or fragment.
public ArrayList<Object> getArrayList() {
return yourArrayList;
}
Inside your activity you can get this like, yourAdapterObject.getArrayList();
Try to pass it via bundle.
First create a model class which will be passed. It should implement Serializable
public class MyModel implements Serializable {
private ArrayList<Data> datas;
public MyModel(ArrayList<Data> datas) {
this.datas = datas
}
}
Then put your data to the bundle
Bundle bundle = new Bundle();
bundle.putSerializable();
Finally put that bundle instance to your fragment
myFragment.setArguments(bundle);
You can pass your array list to fragment by setting arguments for that fragment. But for that, the type of object your array list contains should extend Serializable. Then make a getInstance() method in your fragment that returns an instance of your fragment and wherever you are opening your fragment call that getInstance() method and pass your Array list.
getSupportFragmentManager().beginTransaction()
.add(containerId, YourFragment.getInstance(yourArrayList), tag)
.commitAllowingStateLoss();
The sample code snippet for getInstance() method in your fragment is:
public static YourFragment getInstance( ArrayList<Object> yourArrayList) {
Bundle bundle = new Bundle();
bundle.putParcelableArrayList(Constants.YOUR_LIST,yourArrayList);
YourFragment yourFragment = new YourFragment();
yourFragment.setArguments(bundle);
return yourFragment;
}
Now, you can get your arraylist by calling getArguments() wherever need in your fragment. Also, make sure to check for null Arguments. The sample code for this is:
if (getArguments()!=null && getArguments().containsKey(Constants.YOUR_LIST) && getArguments().getParcelableArrayList(Constants.YOUR_LIST) != null){
ArrayList<Object> yourlist = getArguments().getParcelableArrayList(Constants.YOUR_LIST);
}
Now, by making this list global you can access it anywhere in the fragment. Hope, it helps.
We have been working on implementing a RecyclerView in our project for a while now, and although the backend seems to work just fine, as soon as I call the recyclerView.setAdapter it causes the program to crash. I have spent several hours poring over this program, and nothing yet, although I have suspicions that the answer lies in the adapter. Can anyone shed some light on this?
Create and set adapter:
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView = findViewById(R.id.navRV);
mRecyclerView.setHasFixedSize(false);
mRecyclerView.setLayoutManager(mLayoutManager);
Date todaysDate = new Date(System.currentTimeMillis());
AnnouncementList.add("Test Announcement 1", "This is some random text in the body" +
". It really needs to show up correctly!!", todaysDate);
mAdapter = new TwitterAdapter(mContext);
mRecyclerView.setAdapter(mAdapter);
And this is the adapter:
package com.company.application;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
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.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* Twitter Adapter:
* This adapter is the interface between the data and the view
*/
public class TwitterAdapter extends RecyclerView.Adapter<TwitterAdapter.ViewHolder> {
//Use this as the tag for logging in this activity
final private String LOGTAG = "TWITTER_ADAPTER";
private Context mContext;
public TwitterAdapter(Context mContext) {
this.mContext = mContext;
}
#NonNull
#Override
public TwitterAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.list_layout, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull TwitterAdapter.ViewHolder holder, int position) {
//Set the text and the title
holder.textViewBody.setText((String)AnnouncementList.getList().get(position).getBody());
holder.textViewTitle.setText((String)AnnouncementList.getList().get(position).getTitle());
//If we have an image, insert it so we can draw it
if(AnnouncementList.getList().get(position).getImage() != null)
holder.imageView.setImageDrawable((Drawable)AnnouncementList.getList().get(position).getImage());
else
holder.imageView.setImageDrawable(null);
}
#Override
public int getItemCount() {
Log.d(LOGTAG, "getItemCount returns " + AnnouncementList.size());
return AnnouncementList.size();
}
/**
* Holds the view so that the RecyclerView can process it
*/
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
public RelativeLayout mRelativeLayout;
ImageView imageView;
TextView textViewTitle, textViewBody, textViewDate;
public ViewHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
textViewTitle = itemView.findViewById(R.id.textViewTitle);
textViewBody = itemView.findViewById(R.id.textViewBody);
// textViewDate = itemView.findViewById(R.id.textViewDate);
}
}
}
You need to pass the the arraylist to adapter like this
mAdapter = new TwitterAdapter(mContext, AnnouncementList);
Then in the adapter change the constructor like this
private Context mContext;
private ArrayList<ModelClass> mAnnouncementList = new ArrayList();
public TwitterAdapter(Context mContext,ArrayList<ModelClass> mAnnouncementList) {
this.mContext = mContext;
this.mAnnouncementList= mAnnouncementList;
}
and then access variables like this
holder.textViewBody.setText(mAnnouncementList.getList().get(position).getBody());
holder.textViewTitle.setText(mAnnouncementList.getList().get(position).getTitle());
dont forget to return the size like below
#Override
public int getItemCount() {
Log.d(LOGTAG, "getItemCount returns " + mAnnouncementList.size());
return mAnnouncementList.size();
}
I have one big problem ( for me )
I have some items from api in RecycleViewHolder.class in that class i tell where is xml file of that items.. Now my problem is because i have preference settings in mainactivity and when i define background color to black of whole app my text will be in the same color "black" and i can not see anything in app because of colour. Now i need your help how to change colour of textview in mainactivity,when i try to make findviewbyid in MainActivity and call method setTextColor I get nullpointexception because it is already connected to xml in RecycleViewHolder Class.
This is RecyclceViewHolder class that contains textview of price that i wanna to change colour from mainactivity.
package com.example.domo.cryptotrace;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;
import android.view.View;
/**
* Created by Antun on 31.1.2018..
*/
public class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView name, symbol, rank, percentChange1h, percentChange24h, percentChange7d;
public TextView price;
public RecyclerViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
name = itemView.findViewById(R.id.name);
symbol= itemView.findViewById(R.id.symbol);
rank = itemView.findViewById(R.id.
rank);
price=itemView.findViewById(R.id.price);
percentChange1h=itemView.findViewById(R.id.percent_change_1h);
percentChange24h=itemView.findViewById(R.id.percent_change_24h);
percentChange7d=itemView.findViewById(R.id.percent_change_7d);
}
#Override
public void onClick(View view) {
}
}
This is mainactivity (in this class i wanna change
RecyclerViewHolder --> itemView--> price color)
package com.example.domo.cryptotrace;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.View;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Button;
import com.crashlytics.android.Crashlytics;
import java.util.List;
import io.fabric.sdk.android.Fabric;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
public Button register;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
final Fabric fabric = new Fabric.Builder(this)
.kits(new Crashlytics())
.debuggable(true)
.build();
Fabric.with(fabric);
setContentView(R.layout.activity_main);
getUserList();
register=findViewById(R.id.register);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, LoginSys.class);
startActivity(intent);
}
});
}
#Override
protected void onResume() {
super.onResume();
getPreference();
}
//Ovo je klasa koju smo sami gore kreirali kako bi mogli odrediti boje od pozadine kroz Settings
//Tu još možeš i mjenjati text boju od texViewa sa metodom ||myTextView.setTextColor(0xAARRGGBB);||
//Ili ovako ||ContextCompat.getColor(context, R.color.your_color);||
private void getPreference() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
if (preferences.contains("color")) {
if (preferences.getString("color", "0").equals("1")) {
getWindow().getDecorView().setBackgroundColor(Color.WHITE);
} else if (preferences.getString("color", "0").equals("2")) {
getWindow().getDecorView().setBackgroundColor(Color.BLACK);
} else if (preferences.getString("color","0").equals("3")){
getWindow().getDecorView().setBackgroundColor(Color.RED);
}else{
getWindow().getDecorView().setBackgroundColor(Color.MAGENTA);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.your_item_id) {
//A ovo je metoda za pozivanje i startanje preferences activity-a
Intent intent = new Intent(MainActivity.this, PreferencesScreenActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
private void getUserList() {
try {
APIService service = ApiClient.getRetrofit().create(APIService.class);
Call<List<User>> call = service.getUserData();
call.enqueue(new Callback<List<User>>() {
#Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
//Log.d("onResponse", response.message());
List<User> userList = response.body();
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
RecyclerView recyclerView = findViewById(R.id.recycler);
recyclerView.setLayoutManager(layoutManager);
RecyclerViewAdapter recyclerViewAdapter =
new RecyclerViewAdapter(userList);
recyclerView.setAdapter(recyclerViewAdapter);
}
#Override
public void onFailure(Call<List<User>> call, Throwable t) {
}
});
}catch (Exception e) {}
}
}
So one more time,
I need code to change color of textview item of price from RecyclerViewHolder class.
Thank for all help, every good point of answer will be credited with thanks!
use color as a recyclerview constructor:
int color;
RecyclerViewAdapter recyclerViewAdapter =
new RecyclerViewAdapter(this, userList, color);
//////////////////////////////////////////////////////////////////////////
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder>{
private Context context;
public static List<UserList> userList;
private int color;
public UserAdapter(Context context, List<UserList> userList, int color){
super();
//Getting all the superheroes
this.color = color;
this.userList = userList;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_layout, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.colorText.setText(mColorText.setText);
//here you will change the text color from mainactivity
// this change color
holder.colorText.setTextColor(ContextCompat.getColor(context,color));
}
#Override
public int getItemCount() {
return 0;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView colorText;
public ViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
}
}
I didn't really get into your code but I think you could create another TextView in your .xml file with an id like "priceColored" or something.
When you will want to change the price's color, you simply do:
price = itemView.findViewById(R.id.priceColored);
The TextView with the id priceColored will have the color you want to use. If you need to figure out how to create a textview of a certain color in android, you can find it very easily online.
Hope it helps,
In RecyclerViewHolder class make one public method with color arguments and that method used in mainactivity with that class object and call that public method and pass your color code.
Make below method in RecyclerViewHolder.
public void changeColor(int color){
price.setTextColor(color)
}
and call this method in mainActivity
RecyclerViewHolderobject.changeColor(Color.BLACK)
I've been trying to implement a recycler view inside a fragment which displays parsed data using the retrofit library. Whenever I run the project the lists don't show and the monitor says "E/RecyclerView: No adapter attached; skipping layout". Here is my code:
MainActivity:
package com.example.ahmed.newsapp
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.design.widget.TabLayout;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int ACTIVITY_NUM = 0;
// TODO - insert your themoviedb.org API KEY here
private final static String API_KEY = "<API KEY CENSORED>";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the view pager that will allow the user to swipe between fragments
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
// Create an adapter that knows which fragment should be shown
FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager
());
// Set the adapter onto the view pager
viewPager.setAdapter(adapter);
TabLayout ob=(TabLayout) findViewById(R.id.sliding_tabs);
ob.setupWithViewPager(viewPager);
}
}
FragmentAdapter:
package com.example.ahmed.newsapp;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
* Created by ahmed on 3/22/2017.
*/
public class FragmentAdapter extends FragmentPagerAdapter {
private String tabs[]=new String[]{"Home","Family Members","Colors"};
public FragmentAdapter(FragmentManager fm){
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position){
case 0:
return new HomeActivity();
case 1:
return new HomeActivity();
/* case 2:
return new ColorFragment();*/
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabs[position];
}
#Override
public int getCount() {
return 2;
}
}
NewsAdapter:
package com.example.ahmed.newsapp;
/**
* Created by ahmed on 27-08-17.
*/
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.LinearLayout;
import android.widget.TextView;
import java.util.List;
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
private List<News> news;
private int rowLayout;
private Context context;
public static class NewsViewHolder extends RecyclerView.ViewHolder {
LinearLayout moviesLayout;
TextView movieTitle;
TextView data;
TextView movieDescription;
TextView rating;
public NewsViewHolder(View v) {
super(v);
moviesLayout = (LinearLayout) v.findViewById(R.id.movies_layout);
movieTitle = (TextView) v.findViewById(R.id.title);
data = (TextView) v.findViewById(R.id.subtitle);
movieDescription = (TextView) v.findViewById(R.id.description);
rating = (TextView) v.findViewById(R.id.rating);
}
}
public NewsAdapter(List<News> news, Context context) {
this.news = news;
// this.rowLayout = rowLayout;
this.context = context;
}
#Override
public NewsViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_news, parent, false);
return new NewsViewHolder(view);
}
#Override
public void onBindViewHolder(NewsViewHolder holder, final int position) {
holder.movieTitle.setText(news.get(position).getTitle());
holder.data.setText(news.get(position).getReleaseDate());
holder.movieDescription.setText(news.get(position).getOverview());
holder.rating.setText(news.get(position).getVoteAverage().toString());
}
#Override
public int getItemCount() {
return news.size();
}
}
HomeActivity:
package com.example.ahmed.newsapp;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.content.ContentValues.TAG;
public class HomeActivity extends Fragment {
RecyclerView recyclerView;
private final static String API_KEY = "<API KEY CENSORED>";
NewsAdapter adapter;
List<News> news,dummy;
View rootview;
public HomeActivity() {
// Required empty public constructor
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.activity_home, container, false);
if (API_KEY.isEmpty()) {
Toast.makeText(getContext(), "Please obtain your API KEY first from themoviedb.org", Toast.LENGTH_LONG).show();
return rootview;
}
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
recyclerView = (RecyclerView) rootview.findViewById(R.id.home_page_recycler_view);
adapter= new NewsAdapter(dummy,getContext());
Call<NewsResponse> call = apiService.getTopRatedMovies(API_KEY);
call.enqueue(new Callback<NewsResponse>() {
#Override
public void onResponse(Call<NewsResponse> call, Response<NewsResponse> response) {
news = response.body().getResults();
adapter.notifyDataSetChanged();
adapter=new NewsAdapter(news,getContext());
recyclerView.setAdapter(adapter);
// adapter.setData(news);
Log.d(TAG, "Number of movies received: " + news.size());
}
#Override
public void onFailure(Call<NewsResponse> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
return rootview;
}
}
i think the problem is in your FragmentAdapter class
just remove return null; statement from your FragmentAdapter like below code
#Override
public Fragment getItem(int position) {
Fragment fragment=null;
switch(position){
case 0:
fragment= new HomeActivity();
case 1:
fragment= new HomeActivity();
/* case 2:
return new ColorFragment();*/
}
return fragment;
}
change this
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
recyclerView = (RecyclerView) rootview.findViewById(R.id.home_page_recycler_view);
adapter= new NewsAdapter(dummy,getContext());
You don't need to recreate your adapter when you receive response.
It may looks like:
recyclerView = (RecyclerView) rootview.findViewById(R.id.home_page_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new NewsAdapter(null, getActivity());
recyclerView.setAdapter(adapter);
Call<NewsResponse> call = apiService.getTopRatedMovies(API_KEY);
call.enqueue(new Callback<NewsResponse>() {
#Override
public void onResponse(Call<NewsResponse> call, Response<NewsResponse> response) {
news = response.body().getResults();
adapter.setData(news);
Log.d(TAG, "Number of movies received: " + news.size());
}
...
And in NewsAdapter:
...
public void setData(Collection<News> newData) {
news.clear();
news.addAll(newData);
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return news == null ? 0 : news.size();
}
...
I am trying to write different functionalities for my FloatingActionButton depending on the fragment that the mainActivity is currently hosting. Yet for for reason in my onClick() method, getSupportFragmentManager().findFragmentById() returns null.
I haven't seen any examples of this question implemented with a viewpager and I am curious if there is a different approach I have to take.
MainActivity
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
public class MainActivity extends FragmentActivity {
private Adapter mAdapter;
private ViewPager mViewPager;
private static FloatingActionButton bButton;
private static String UID;
private Intent intent;
public static String getUID(){
return UID;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new Adapter(getSupportFragmentManager());
mViewPager = (ViewPager)findViewById(R.id.vPager);
mViewPager.setAdapter(mAdapter);
intent = getIntent();
UID = intent.getStringExtra("uid");
bButton = (FloatingActionButton)findViewById(R.id.bButton);
bButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragContainer);
if(fragment == null){
Log.e("TAG","FRAGMENT IS NULL!!");
}
else{
Log.e("TAG","FRAGMENT IS NOT NULL!!");
}
}
});
}
}
NewsFeedFragment
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.mycompany.neighbors.R;
import com.mycompany.neighbors.SinglePost;
import java.util.ArrayList;
/**
* Created by joshua on 5/25/2016.
*/
public class NewsFeedFragment extends ListFragment implements AdapterView.OnItemClickListener{
private ListView lv;
private TextView tvUserName;
private TextView tvStatus;
private ArrayList<SinglePost> posts = new ArrayList<>();
private static final String POSTS_PATH = "MY_PATH";
private Firebase postsRef;
// private static final String FRAGMENT_POST = "post";
public void postFragment(){
Log.d("TAG", "Doing something else");
PostFragment postFragment = new PostFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.fragContainer,postFragment)
.addToBackStack(null)
.commit();
}
#Override
public void onViewCreated(View v, Bundle s){
lv = getListView();
lv.setOnItemClickListener(this);
}
#Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_post_feed_item,parent,false);//changed
tvUserName = (TextView)v.findViewById(R.id.tvUN);
tvStatus = (TextView)v.findViewById(R.id.tvStatus);
postsRef = new Firebase(POSTS_PATH);
postsRef.addChildEventListener(new com.firebase.client.ChildEventListener() {
#Override
public void onChildAdded(com.firebase.client.DataSnapshot dataSnapshot, String s) {
SinglePost post = dataSnapshot.getValue(SinglePost.class);
post.setKey(dataSnapshot.getKey());
posts.add(0, post);
if(posts.size() > 0) {
PostAdapter adapter = new PostAdapter(posts);
setListAdapter(adapter);
}else{
Toast toast = Toast.makeText(getActivity(),"No data", Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public void onChildChanged(com.firebase.client.DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(com.firebase.client.DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(com.firebase.client.DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
return v;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id){
SinglePost p = ((PostAdapter) getListAdapter()).getItem(position);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
private class PostAdapter extends ArrayAdapter<SinglePost>{
public PostAdapter(ArrayList<SinglePost> singlePost){
super(getActivity(),android.R.layout.simple_list_item_1,singlePost);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
convertView = getActivity().getLayoutInflater().inflate(R.layout.fragment_post_feed_item,null);
}
SinglePost p = getItem(position);
TextView tvUserName = (TextView)convertView.findViewById(R.id.tvUN);
tvUserName.setText(p.getUserName());
TextView tvStatus = (TextView)convertView.findViewById(R.id.tvStatus);
tvStatus.setText(p.getStatus());
return convertView;
}
}
}
I have 2 other fragments but i'll post one as an example. Here is my adapter for the viewpager.
Adapter
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.mycompany.neighbors.Fragments.MapFragment;
import com.mycompany.neighbors.Fragments.NewsFeedFragment;
import com.mycompany.neighbors.Fragments.ProfileFragment;
/**
* Created by joshua on 5/25/2016.
*/
public class Adapter extends FragmentPagerAdapter {
private String Fragment[] = {"Posts" , "Map" , "Profile"};
public Adapter(FragmentManager fm){
super (fm);
}
#Override
public Fragment getItem(int position) {
switch(position){
case 0:
return new NewsFeedFragment();
case 1:
return new MapFragment();
case 2:
return new ProfileFragment();
default:
return null;
}
}
#Override
public int getCount(){return Fragment.length;}
#Override
public CharSequence getPageTitle(int position) {
return Fragment[position];
}
}
Please check below link, It has very good explanation for your problem:
http://tamsler.blogspot.in/2011/11/android-viewpager-and-fragments-part-ii.html
Or you can try below code snippet:
1.Where you add fragment in view pager or view pager adapter:
MyFragment myFragment = MyFragment.newInstance();
mPageReferenceMap.put(index, "Some Tag");
getSupportFragmentManager().beginTransaction().add(myFragment,"Some Tag").commit();
2.To get the tag for the currently visible page, you then call:
int index = mViewPager.getCurrentItem();
String tag = mPageReferenceMap.get(index);
3.and then get the fragment page:
Fragment myFragment = getSupportFragmentManager().findFragmentByTag(tag);