SmsAdapter.java
package com.s4starb4boy.smstopdf.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.TextView;
import com.s4starb4boy.smstopdf.R;
import com.s4starb4boy.smstopdf.model.SMS;
import java.util.List;
public class SmsAdapter extends RecyclerView.Adapter<SmsAdapter.SmsViewHolder> {
private static final String TAG = SmsAdapter.class.getSimpleName() ;
private List<SMS> smsList;
private LayoutInflater mInflater;
public SmsAdapter(Context context, List<SMS> smsList) {
this.smsList = smsList;
this.mInflater = LayoutInflater.from(context);
}
#Override
public SmsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.i(TAG, "onCreateViewHolder");
View view = mInflater.inflate(R.layout.sms_list, parent, false);
SmsViewHolder holder = new SmsViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(SmsViewHolder holder, int position) {
Log.i(TAG, "onBindViewHolder" + position);
SMS currentObj = smsList.get(position);
holder.setData(currentObj, position);
}
#Override
public int getItemCount() {
return smsList.size();
}
class SmsViewHolder extends RecyclerView.ViewHolder{
TextView tvPhoneNo;
TextView tvsmsBody;
int position;
SMS current;
public SmsViewHolder(View itemView) {
super(itemView);
tvPhoneNo = (TextView) itemView.findViewById(R.id.tvPhoneNo);
tvsmsBody = (TextView) itemView.findViewById(R.id.tvMessageBody);
}
public void setData(SMS current, int position) {
this.tvPhoneNo.setText(current.getPhoneNo());
this.tvsmsBody.setText(current.getSmsBody());
this.current =current;
this.position = position;
}
}
}
SMS.java
public class SMS extends AppCompatActivity{
private String phoneNo;
private String smsBody;
public SMS(String phoneNo, String smsBody) {
this.phoneNo = phoneNo;
this.smsBody = smsBody;
}
public SMS() {
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public String getSmsBody() {
return smsBody;
}
public void setSmsBody(String smsBody) {
this.smsBody = smsBody;
}
public static ArrayList<String> getSMS(){
ArrayList<String> sms = new ArrayList<String>();
Uri uriSMSURI = Uri.parse("content://sms/inbox");
Cursor cur = getContentResolver().query(uriSMSURI, null, null, null, null);
while (cur != null && cur.moveToNext()) {
String address = cur.getString(cur.getColumnIndex("address"));
String body = cur.getString(cur.getColumnIndexOrThrow("body"));
sms.add("Number: " + address + " .Message: " + body);
}
if (cur != null) {
cur.close();
}
return sms;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final int READ_SMS_PERMISSIONS_REQUEST = 1;
private static final int READ_CONTACTS_PERMISSIONS_REQUEST = 1;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpToolbar();
setUpRecyclerView();
}
private void setUpRecyclerView() {
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
SmsAdapter adapter = new SmsAdapter(this, SMS.getSMS());
recyclerView.setAdapter(adapter);
LinearLayoutManager mLinearLayoutManagerVertical = new LinearLayoutManager(this);
mLinearLayoutManagerVertical.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(mLinearLayoutManagerVertical);
recyclerView.setItemAnimator(new DefaultItemAnimator());
}
private void setUpToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Navigation Drawer Demo");
toolbar.inflateMenu(R.menu.menu_main);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
String msg = "";
switch (item.getItemId()) {
case R.id.settings:
msg = "Settings";
break;
case R.id.edit:
msg = "Edit";
break;
case R.id.search:
msg = "Search";
break;
case R.id.exit:
msg = "Exit";
break;
case R.id.delete:
msg = "Delete";
break;
}
Toast.makeText(MainActivity.this, msg + " Clicked", Toast.LENGTH_SHORT).show();
return true;
}
});
}
}
Above are all code I want to fetch sms and display them in card view using recycler view. I am repeating here that I am absolutely beginner so please keep this point in your mind while giving me solution I may unable to get your professional hint rather ask me in detail plz.
Try to pass current context object to the SMS class
SmsAdapter adapter = new SmsAdapter(this, SMS.getSMS(this.getApplicationContext()));
and change getSMS to:
public static ArrayList<String> getSMS(Context context){
.....
Cursor cur = context.getContentResolver().query(uriSMSURI, null, null, null, null);
.....
Unfortunately I don't have any Android IDE to test this but it should work.
getContentResolver>>>nonstatic member can not be referenced
This means, you are trying to access non-static member from static context, in case getContentResolver() is non-static method, which you are trying to invoke from static method i.e. getSMS ()
You can do either :
Remove static from getSMS OR add static to getContentResolver
Create an instance of this class to call getContentResolver
Related
I want the onclicklistener method to open the activity which is related to the object:entidad1, entidad2 or entidad3.
The OnRecipe method on the MainActivity.java which i want it to make that if the entidad1 appears it takes me to x activity, and if entidad2 appears to y activity and so, any idea of how to do it, because now it takes me all the time to the activity of the entidad1. I guess it must be related with using priority to decide which to open instead of the position.
That's my Adapter:
package com.test.platos_4;
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.RatingBar;
import android.widget.TextView;
import java.util.List;
public class Adaptador2 extends RecyclerView.Adapter<Adaptador2.ViewHolder>
{
private List<Entidad2> listItems;
private OnRecipeListener mOnRecipeListener;
public Adaptador2(List<Entidad2> listItems, OnRecipeListener onRecipeListener) {
this.listItems = listItems;
this.mOnRecipeListener = onRecipeListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.elemento_lista2, parent, false);
return new ViewHolder(view, mOnRecipeListener);
}
#Override
public void onBindViewHolder(ViewHolder viewholder, int position) {
int resource = listItems.get(position).getImgFoto();
String title = listItems.get(position).getTitulo();
String time = listItems.get(position).getTiempo();
int barra = listItems.get(position).getRating();
//int fondo = listItems.get(position).getColorfondo();
viewholder.setData(resource, title, time, barra);
// por si necesito color de fondo viewholder.setData(resource, title, time, barra, fondo);
}
#Override
public int getItemCount() {
return listItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView imgFoto;
private TextView titulo;
private TextView tiempo;
private RatingBar ratingBar;
//private ImageView colorfondo;
OnRecipeListener onRecipeListener;
public ViewHolder(View itemView, OnRecipeListener onRecipeListener) {
super(itemView);
imgFoto = itemView.findViewById(R.id.imgFoto);
titulo = itemView.findViewById(R.id.tvTitulo);
tiempo = itemView.findViewById(R.id.tvTiempo);
ratingBar = itemView.findViewById(R.id.ratingBarVerd);
//colorfondo = itemView.findViewById(R.id.colorfondo);
this.onRecipeListener = onRecipeListener;
itemView.setOnClickListener(this);
}
//por si necesito color de fondo private void setData(int resource, String title, String time, int barra, int fondo){
private void setData(int resource, String title, String time, int barra){
imgFoto.setImageResource(resource);
titulo.setText(title);
tiempo.setText(time);
ratingBar.setRating(barra);
//colorfondo.setImageResource(fondo);
}
#Override
public void onClick(View v) {
onRecipeListener.OnRecipe(getAdapterPosition());
}
}
public interface OnRecipeListener{
void OnRecipe(int priority);
}
}
And that is the MainActivity.java:
public class Comida extends AppCompatActivity implements Adaptador2.OnRecipeListener {
private RecyclerView recyclerView1;
List<Entidad2> listItems;
Adaptador2 adaptor;
private Entidad2 entidad1,entidad2,entidad3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_comida);
recyclerView1 = findViewById(R.id.lv_1);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView1.setLayoutManager(layoutManager);
listItems = new ArrayList<>();
entidad1 = new Entidad2(R.drawable.calabacines_3, "Solomillo a la plancha", " 10 min.", 4, 20);
entidad2 = new Entidad2(R.drawable.patatas_deluxe_especiadas_70523_300_150, "Entrecot", " 15 min.", 2, 50);
entidad3 = new Entidad2(R.drawable.tomate, "Hamburguesa", " 2 min.", 5, 100);
listItems.add(entidad1);
listItems.add(entidad2);
listItems.add(entidad3);
adaptor = new Adaptador2(listItems, this);
recyclerView1.setAdapter(adaptor);
adaptor.notifyDataSetChanged();
pickEntidad();
}
#Override
public void OnRecipe(int priority) {
if (priority == 20) {
Intent in = new Intent(this, Solomillo.class);
startActivity(in);
}
if (priority == 50) {
Intent in = new Intent(this, Entrecot.class);
startActivity(in);
}
if (priority == 100) {
Intent in = new Intent(this, Hamburguesa.class);
startActivity(in);
}
}
private void pickEntidad(){
final int random = new Random().nextInt(101);
int priority1 = entidad1.getPriority();
int priority2 = entidad2.getPriority();
int priority3 = entidad3.getPriority();
listItems.clear();
if(random < priority1){
listItems.add(entidad1);
}else if(random < priority2){
listItems.add(entidad2);
}else if (random <= priority3){
listItems.add(entidad3);
}
adaptor.notifyDataSetChanged();
}
}
And the Entidad.java:
public class Entidad2 {
private int imgFoto;
private String titulo;
private String tiempo;
private int ratingBar;
private int priority;
private int d;
public Entidad2(int imgFoto, String titulo, String tiempo, int ratingBar, int priority) {
this.imgFoto = imgFoto;
this.titulo = titulo;
this.tiempo = tiempo;
this.ratingBar = ratingBar;
this.priority = priority;
}
public int getImgFoto() {
return imgFoto;
}
public String getTitulo() {
return titulo;
}
public String getTiempo() {
return tiempo;
}
public int getRating() { return ratingBar; }
public int getPriority() {
return priority;
}
}
Please help me to solve the problem and if you need more information just tell me i will post it.
You are trying to differentiate your items by Priority but you are passing item position from your adapter to your activity. You need to pass clicked item's Priority instead of its position. I have changed your Adaptor2 class
package com.test.platos_4;
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.RatingBar;
import android.widget.TextView;
import java.util.List;
public class Adaptador2 extends RecyclerView.Adapter<Adaptador2.ViewHolder>
{
private List<Entidad2> listItems;
private OnRecipeListener mOnRecipeListener;
public Adaptador2(List<Entidad2> listItems, OnRecipeListener onRecipeListener) {
this.listItems = listItems;
this.mOnRecipeListener = onRecipeListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.elemento_lista2, parent, false);
return new ViewHolder(view, mOnRecipeListener);
}
#Override
public void onBindViewHolder(ViewHolder viewholder, int position) {
Entidad2 entidad = listItems.get(position);
int resource = entidad.getImgFoto();
String title = entidad.getTitulo();
String time = entidad.getTiempo();
int barra = entidad.getRating();
final int priority = entidad.getPriority();
//int fondo = listItems.get(position).getColorfondo();
viewholder.setData(resource, title, time, barra);
//You can pass the clicked item's priority back to your activity like this
viewholder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mOnRecipeListener.OnRecipe(priority);
}
});
// por si necesito color de fondo viewholder.setData(resource, title, time, barra, fondo);
}
#Override
public int getItemCount() {
return listItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView imgFoto;
private TextView titulo;
private TextView tiempo;
private RatingBar ratingBar;
//private ImageView colorfondo;
OnRecipeListener onRecipeListener;
public ViewHolder(View itemView, OnRecipeListener onRecipeListener) {
super(itemView);
imgFoto = itemView.findViewById(R.id.imgFoto);
titulo = itemView.findViewById(R.id.tvTitulo);
tiempo = itemView.findViewById(R.id.tvTiempo);
ratingBar = itemView.findViewById(R.id.ratingBarVerd);
//colorfondo = itemView.findViewById(R.id.colorfondo);
//This is useless
//this.onRecipeListener = onRecipeListener;
}
//por si necesito color de fondo private void setData(int resource, String title, String time, int barra, int fondo){
private void setData(int resource, String title, String time, int barra){
imgFoto.setImageResource(resource);
titulo.setText(title);
tiempo.setText(time);
ratingBar.setRating(barra);
//colorfondo.setImageResource(fondo);
}
#Override
public void onClick(View v) {
}
}
public interface OnRecipeListener{
void OnRecipe(int priority);
}
}
I am making a news app using Firebase. I have a problem when I try to transfer an object to another activity.
An exception:
"java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fx.fibi/com.example.fx.fibi.DetailActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.fx.fibi.News.getTitle()' on a null object reference.
Here is my code:
MainActivity:
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycle_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setAdapter(firebaseRecyclerAdapter);
}
Query query = FirebaseDatabase.getInstance().getReference().child("Global");
FirebaseRecyclerOptions<News> options = new FirebaseRecyclerOptions.Builder<News>()
.setQuery(query, News.class).build();
final FirebaseRecyclerAdapter<News,NewsViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<News,
NewsViewHolder>(options) {
#NonNull
#Override
public NewsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.news_row, parent, false);
return new NewsViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull NewsViewHolder holder, int position, #NonNull News model) {
holder.setTitle(model.getTitle());
holder.setDesc(model.getDesc());
holder.setImage(getApplicationContext(), model.getImage());
holder.setOnClickListener(new NewsViewHolder.ClickListener() {
#Override
public void onItemClick(View view, int position) {
Toast.makeText(MainActivity.this, "Item clicked at " + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("news", position);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
#Override
public void onItemLongClick(View view, int position) {
}
});
}
};
#Override
protected void onStart() {
super.onStart();
firebaseRecyclerAdapter.startListening();
}
}
DetailActivity (this class gets NullPointerException at "title.setText(news.getTitle());"
public class DetailActivity extends AppCompatActivity {
TextView title, desc;
ImageView imageView;
News news;
String titleString, descString, image;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
initCollapsingToolbar();
imageView = findViewById(R.id.thumbnail_image_header);
title = findViewById(R.id.detail_title);
Intent intentThatStartedThisActivity = getIntent();
if (intentThatStartedThisActivity.hasExtra("news")) {
news = getIntent().getParcelableExtra("news");
title.setText(news.getTitle());
desc.setText(news.getDesc());
Picasso.with(mContext).load(image).into(imageView);
}
}
private void initCollapsingToolbar() {
final CollapsingToolbarLayout collapsingToolbarLayout =
(CollapsingToolbarLayout)findViewById(R.id.collapsing_toolbar);
collapsingToolbarLayout.setTitle(" ");
AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
appBarLayout.setExpanded(true);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
collapsingToolbarLayout.setTitle(getString(R.string.app_name));
isShow = true;
} else if (isShow) {
collapsingToolbarLayout.setTitle(" ");
isShow = false;
}
}
});
}
}
Model:
public class News implements Parcelable {
private String title;
private String desc;
private String image;
public News(String title, String desc, String image) {
this.title = title;
this.desc = desc;
this.image = image;
}
public News (Parcel in) {
String[] data = new String[3];
in.readStringArray(data);
title = data[0];
desc = data[1];
image = data[2];
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public News() {
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] {title, desc, image});
}
public static final Parcelable.Creator<News> CREATOR = new Parcelable.Creator<News>() {
#Override
public News createFromParcel(Parcel source) {
return new News(source);
}
#Override
public News[] newArray(int size) {
return new News[size];
}
};
}
Sorry if my question seems to be foolish, this is my first full app.
Thanks!
I added an object list List <News> newsList and changed method onItem click to:
if (position != RecyclerView.NO_POSITION) {
News clickedDataItem = newsList.get(position);
Toast.makeText(MainActivity.this, "Item clicked at " + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("news", clickedDataItem);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
But now i get "java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference"
You can implement java Serializable interface instead of implementing Parcelable in your model class as shown below
public class News implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String title;
private String desc;
private String image;
public News(String title, String desc, String image) {
this.title = title;
this.desc = desc;
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public News() {
//empty contructor neeeded
}
#Overide
public String toString(){
return super.toString();
}
}
Then you can pass the object the intent like this
News news = new News("title", "desc", "image");
Intent intent = new Intent(StartActivity.this, TargetActivity.class);
intent.putExtra("news", news);
startActivity(intent);
In order to get the object from the intent, you need to cast New class into the Intent results as shown below.
News news = (News)getIntent().getSerializableExtra("news");
In your onBindViewHolder, you put wrong data.
intent.putExtra("news", position); // position is int
which position is an int, put the News object at the position instead.
You can set the value to the intent ....
Intent i = new Intent(FirstScreen.this, SecondScreen.class);
String strName = "value";
i.putExtra("STRING_I_NEED", strName);
startActivity(i);
You can retrive the value in second activity..........
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("STRING_I_NEED");
}
} else {
newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
news = getIntent().getIntExtra("news");
Long post, thanks for taking the time to look through this
I have been struggling with this issue for a while now. I have an SQLiteDatabase which stores a shoe's brand name, name of shoe, and a byte image of the shoe. I was able to load all of the information to a recyclerview via a content provider. But it seems when I try and load the information to the details of each item in the recycler view, the details activity is filled with the wrong information, it returns a completely different entry other than the one I selected.
The solutions I've seen in many youtube videos have contained me creating ArrayLists to store the information, but I find that very hard to do using my SQLiteDatabase information.
Here are the classes I have...
My Closet.java class(with my getter methods)
package com.example.android.myshoecloset;
import android.database.Cursor;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by man on 12/21/2017.
*/
public class Closet
{
private static final String TAG = Closet.class.getSimpleName();
//Brand name
private final String brandName;
//Shoe Name
private final String shoeName;
//Image of the shoe
private final String shoeImage;
public Closet(String brandName, String shoeName, String shoeImage)
{
this.brandName = brandName;
this.shoeName = shoeName;
this.shoeImage = shoeImage;
}
public Closet(Cursor cursor)
{
this.brandName = null;
this.shoeName = null;
this.shoeImage = null;
}
public String getShoeImageName()
{
return shoeImage;
}
public String getBrandName()
{
return brandName;
}
public String getShoeName()
{
return shoeName;
}
}
My Adapter Class(CustomAdapter.java)
package com.example.android.myshoecloset.data;
/*Assume appropriate imports*/
/**
* Created by man on 11/23/2017.
*/
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.TaskHolder> {
private Cursor mCursor;
private Context mContext;
public static String shoeName;
public static String brandName;
public static byte[] byteArray;
public CustomAdapter(Context mContext) {
this.mContext = mContext;
}
public CustomAdapter()
{
mContext = null;
}
/* ViewHolder for each task item */
public class TaskHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView shoeBrandName;
public TextView shoeName;
public ImageView shoeImage;
public LinearLayout linearLayout;
public TaskHolder(final View itemView) {
super(itemView);
itemView.setOnClickListener(this);
shoeBrandName = (TextView) itemView.findViewById(R.id.textBrandName);
shoeImage = (ImageView) itemView.findViewById(R.id.shoeImage);
shoeName = (TextView) itemView.findViewById(R.id.textShoeName);
linearLayout = (LinearLayout) itemView.findViewById(R.id.linear_closet);
}
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), ShoeDetailActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(i);
}
}
#Override
public TaskHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View itemView = inflater
.inflate(R.layout.text_row_item, parent, false);
return new TaskHolder(itemView);
}
#Override
public void onBindViewHolder(TaskHolder holder, int position) {
int idIndex = mCursor.getColumnIndex(DatabaseContract.ShoeColumns._ID);
int imgValue = mCursor.getColumnIndex(DatabaseContract.ShoeColumns.SHOE_IMAGE);
int shoeBrandName = mCursor.getColumnIndex(DatabaseContract.ShoeColumns.SHOE_BRAND);
int shoeName = mCursor.getColumnIndex(DatabaseContract.ShoeColumns.SHOE_NAME);
mCursor.moveToPosition(position);
final int id = mCursor.getInt(idIndex);
byte[] shoeImg = mCursor.getBlob(imgValue);
String brandNameStr = mCursor.getString(shoeBrandName);
String shoeNameStr = mCursor.getString(shoeName);
Bitmap bmp = BitmapFactory.decodeByteArray(shoeImg, 0, shoeImg.length);
holder.itemView.setTag(id);
holder.shoeImage.setImageBitmap(Bitmap.createScaledBitmap(bmp, 100, 100, false));
holder.shoeBrandName.setText(brandNameStr);
holder.shoeName.setText(shoeNameStr);
holder.getAdapterPosition();
CustomAdapter.shoeName = shoeNameStr;
CustomAdapter.brandName = brandNameStr;
CustomAdapter.byteArray = mCursor.getBlob(imgValue);
}
#Override
public int getItemCount() {
return (mCursor != null) ? mCursor.getCount() : 0;
}
public void swapCursor(Cursor cursor) {
if (mCursor != null) {
mCursor.close();
}
mCursor = cursor;
notifyDataSetChanged();
}
}
My ClosetFragment, which loads the information on a Loader and to the fragments recyclerview.
package com.example.android.myshoecloset;
/*Assume appropriate imports*/
public class ClosetFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = "ClosetFragment";
protected RecyclerView mRecyclerView;
protected CustomAdapter mAdapter;
private static final int CUSTOM_LOADER_ID = 0;
#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_closet, container, false);
rootView.setTag(TAG);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
mAdapter = new CustomAdapter(getActivity().getApplicationContext());
mRecyclerView.setAdapter(mAdapter);
getActivity().getSupportLoaderManager().initLoader(CUSTOM_LOADER_ID, null, this);
return rootView;
}
#Override
public void onResume()
{
super.onResume();
getActivity().getSupportLoaderManager().restartLoader(CUSTOM_LOADER_ID, null, this); }
#Override
public Loader<Cursor> onCreateLoader(int id, final Bundle loaderArgs) {
return new AsyncTaskLoader<Cursor>(getActivity().getApplicationContext()) {
Cursor mTaskData = null;
#Override
protected void onStartLoading()
{
if(mTaskData != null)
{
deliverResult(mTaskData);
}
else
{
forceLoad();
}
}
public Cursor loadInBackground()
{
try
{
return getActivity().getApplicationContext().getContentResolver().query(DatabaseContract.CONTENT_URI,
null,
null,
null,
null);
} catch(Exception e)
{
Log.e("", "Failed to asynchronously load data.");
e.printStackTrace();
return null;
}
}
public void deliverResult(Cursor data)
{
mTaskData = data;
super.deliverResult(data);
}
};
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data)
{
mAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader)
{
mAdapter.swapCursor(null);
}
}
Finally here is my DetailsActivity(when the recyclerview item is clicked this is where the click will take you)
package com.example.android.myshoecloset;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.android.myshoecloset.data.CustomAdapter;
public class ShoeDetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shoe_detail);
ImageView imgShoe = (ImageView) findViewById(R.id.shoeImgDetails);
TextView brandShoe = (TextView) findViewById(R.id.shoeBrandDetails);
TextView nameShoe = (TextView) findViewById(R.id.shoeNameDetails);
byte[] b = getIntent().getByteArrayExtra("ImageBit");
Bitmap bmp = BitmapFactory.decodeByteArray(b, 0, b.length);
imgShoe.setImageBitmap(bmp);
brandShoe.setText(getIntent().getStringExtra("ShoeName"));
nameShoe.setText(getIntent().getStringExtra("BrandName"));
}
}
Thanks!
As far as I can tell, the relevant pieces of your code are the onClick method in your view holder:
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), ShoeDetailActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(i);
}
And the onCreate method in your details activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
byte[] b = getIntent().getByteArrayExtra("ImageBit");
...
brandShoe.setText(getIntent().getStringExtra("ShoeName"));
nameShoe.setText(getIntent().getStringExtra("BrandName"));
}
In the details activity, you're trying to pull information out of the intent extras... but you've never provided that information in the first place. Making this information available to your view holder will require re-thinking how you've implemented the view holder itself.
I believe you should be able to use the viewholder's "adapter position" to get the necessary info out of your cursor at click time. Maybe something like this:
#Override
public void onClick(View v) {
int position = getAdapterPosition();
mCursor.moveToPosition(position);
Intent i = new Intent(v.getContext(), ShoeDetailActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
int imgValue = mCursor.getColumnIndex(DatabaseContract.ShoeColumns.SHOE_IMAGE);
int shoeBrandName = mCursor.getColumnIndex(DatabaseContract.ShoeColumns.SHOE_BRAND);
int shoeName = mCursor.getColumnIndex(DatabaseContract.ShoeColumns.SHOE_NAME);
i.putExtra("ImageBit", mCursor.getBlob(imgValue));
i.putExtra("ShoeName", mCursor.getString(shoeBrandName));
i.putExtra("BrandName", mCursor.getString(shoeName));
v.getContext().startActivity(i);
}
(Note that "ShoeName" and "BrandName" appear to be swapped, but they're also swapped in your details activity so I left them that way.)
If this getAdapterPosition() + mCursor method doesn't work for you, you can always pass the necessary information to the view holder at bind time, and update the onClick() method when binding.
Let me know if this works for you. If it doesn't, we can try to figure it out from here.
I'm trying to visualize a toast inside a fragment by pressing an item of a recycling but I can not see it
Note: There is no error in the log attached to my class
This is my fragment
public class FotoFragment extends Fragment
{
private Cursor cursor;
private int columnIndex;
private static final String TAG = "RecyclerViewExample";
private List<DataPictures> mediaList = new ArrayList<>();
private RecyclerView mRecyclerView;
private MediaRVAdapter adapter;
String type = "";
public FotoFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
type = "images";
new MediaAsyncTask().execute(type);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blank, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
return view;
}
public class MediaAsyncTask extends AsyncTask<String, Void, Integer> {
#Override
protected Integer doInBackground(String... params) {
Integer result = 0;
String type = params[0];
try {
mediaList = new ArrayList<>();
if (type.equalsIgnoreCase("images")) {
result = 1;
}
} catch (Exception e) {
e.printStackTrace();
result = 0;
}
return result;
}
#Override
protected void onPostExecute(Integer result) {
if (result == 1) {
adapter = new MediaRVAdapter(getActivity(), mediaList);
mRecyclerView.setAdapter(adapter);
mRecyclerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Click pressed",Toast.LENGTH_SHORT).show();
}
});
} else {
Log.e(TAG, "Failed to show list");
}
}
}
}
This is my adapter
public class MediaRVAdapter extends RecyclerView.Adapter<MediaListRowHolder> {
private List<DataPictures> itemList;
private Context mContext;
public MediaRVAdapter(Context context, List<DataPictures> itemList) {
this.itemList = itemList;
this.mContext = context;
}
#Override
public MediaListRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);
MediaListRowHolder mh = new MediaListRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(MediaListRowHolder mediaListRowHolder, int i) {
try{
DataPictures item = itemList.get(i);
Uri uri = Uri.fromFile(new File(item.getFilePath()));
if(item.getFileType().equalsIgnoreCase("video")) {
Bitmap bmThumbnail = ThumbnailUtils.
extractThumbnail(ThumbnailUtils.createVideoThumbnail(item.getFilePath(),
MediaStore.Video.Thumbnails.FULL_SCREEN_KIND), 90, 60);
if(bmThumbnail != null) {
mediaListRowHolder.thumbnail.setImageBitmap(bmThumbnail);
}
} else if (item.getFileType().equalsIgnoreCase("audio")) {
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
mmr.setDataSource(item.getFilePath());
try{
if (mmr != null) {
byte[] art = mmr.getEmbeddedPicture();
Bitmap bmp = BitmapFactory.decodeByteArray(art,0,art.length);
if(bmp != null) {
bmp= ThumbnailUtils.extractThumbnail(bmp,90,60);
mediaListRowHolder.thumbnail.setImageBitmap(bmp);
}
}
}catch (Exception e){
e.printStackTrace();
}
}else {
Picasso.with(mContext).load(uri)
.error(R.drawable.logo_slogan)
.placeholder(R.drawable.logo_slogan)
.centerCrop()
.resize(90, 60)
.into(mediaListRowHolder.thumbnail);
}
}catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return (null != itemList ? itemList.size() : 0);
}
}
Adapter class adapter
public class MediaListRowHolder extends RecyclerView.ViewHolder {
protected ImageView thumbnail;
protected TextView title;
public MediaListRowHolder(View view) {
super(view);
this.thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
this.title = (TextView) view.findViewById(R.id.title);
}
}
solution:
public class MediaListRowHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected ImageView thumbnail;
protected TextView title;
public MediaListRowHolder(View view) {
super(view);
this.thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
this.title = (TextView) view.findViewById(R.id.title);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "position = " + getPosition(), Toast.LENGTH_SHORT).show();
}
}
I think you can do this, such as the following code:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
/**
* Author:Administrator on 2016/9/2 0002 20:37
* Contact:289168296#qq.com
*/
public abstract class OnItemSelectedListener implements RecyclerView.OnItemTouchListener{
private final GestureDetector mGestureDetector;
public OnItemSelectedListener(Context context){
mGestureDetector = new GestureDetector(context,
new GestureDetector.SimpleOnGestureListener(){
#Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
public abstract void onItemSelected(RecyclerView.ViewHolder holder, int position);
#Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
if (mGestureDetector.onTouchEvent(e)) {
View touchedView = rv.findChildViewUnder(e.getX(), e.getY());
onItemSelected(rv.findContainingViewHolder(touchedView),
rv.getChildAdapterPosition(touchedView));
}
return false;
}
#Override public void onTouchEvent(RecyclerView rv, MotionEvent e) {
throw new UnsupportedOperationException("Not implemented");
}
#Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
throw new UnsupportedOperationException("Not implemented");
}
}
And then to the RecycleView registration event, the event can be handled:
private RecyclerView grid;
grid.setAdapter(new PhotoAdapter(this, relevantPhotos));
grid.addOnItemTouchListener(new OnItemSelectedListener(MainActivity.this) {
#Override public void onItemSelected(RecyclerView.ViewHolder holder, int position) {
if (!(holder instanceof PhotoViewHolder)) {
return;
}
PhotoItemBinding binding = ((PhotoViewHolder) holder).getBinding();
final Intent intent = getDetailActivityStartIntent(MainActivity.this, relevantPhotos, position, binding);
final ActivityOptions activityOptions = getActivityOptions(binding);
MainActivity.this.startActivityForResult(intent, IntentUtil.REQUEST_CODE,
activityOptions.toBundle());
}
});
PhotoAdapter.java:
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.bumptech.glide.Glide;
import com.googlesamples.unsplash.R;
import com.googlesamples.unsplash.data.model.Photo;
import com.googlesamples.unsplash.databinding.PhotoItemBinding;
import com.googlesamples.unsplash.ui.ImageSize;
import java.util.ArrayList;
public class PhotoAdapter extends RecyclerView.Adapter<PhotoViewHolder> {
private final ArrayList<Photo> photos;
private final int requestedPhotoWidth;
private final LayoutInflater layoutInflater;
public PhotoAdapter(#NonNull Context context, #NonNull ArrayList<Photo> photos) {
this.photos = photos;
requestedPhotoWidth = context.getResources().getDisplayMetrics().widthPixels;
layoutInflater = LayoutInflater.from(context);
}
#Override
public PhotoViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
return new PhotoViewHolder((PhotoItemBinding) DataBindingUtil.inflate(layoutInflater,
R.layout.photo_item, parent, false));
}
#Override
public void onBindViewHolder(final PhotoViewHolder holder, final int position) {
PhotoItemBinding binding = holder.getBinding();
Photo data = photos.get(position);
binding.setData(data);
binding.executePendingBindings();
Glide.with(layoutInflater.getContext())
.load(holder.getBinding().getData().getPhotoUrl(requestedPhotoWidth))
.placeholder(R.color.placeholder)
.override(ImageSize.NORMAL[0], ImageSize.NORMAL[1])
.into(holder.getBinding().photo);
}
#Override
public int getItemCount() {
return photos.size();
}
#Override
public long getItemId(int position) {
return photos.get(position).id;
}
}
I have created a Recyclerview, with itemobjects, Adapter, viewholder and activity.
The Recyclerview works fine.
My problem is when an item is clicked from Recyclerview, I want to direct the user to TicketDetails activity.
I have the code to get the clicked item and its position in the view holder, but when I try to create a new intent to new activity like this inside view holder
startActivity(new Intent(getActivity(), TicketDetails.class));
I am unable to resolve getActivity()
ViewHolder
public class TicketsRecyclerViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener{
public ImageView priority;
public TextView sts_open;
public TextView sts_overdue;
public TextView tkt_from;
public TextView tkt_subject;
public TextView tkt_assignedto;
public TextView tkt_created_date;
public TextView txt_ticket_id;
private SparseBooleanArray selectedItems = new SparseBooleanArray();
public TicketsRecyclerViewHolders(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
priority = (ImageView) itemView.findViewById(R.id.priority_status_icon);
sts_open= (TextView) itemView.findViewById(R.id.tv_Tk_opn_status);
sts_overdue = (TextView) itemView.findViewById(R.id.tv_Tk_overdue);
tkt_from = (TextView) itemView.findViewById(R.id.tv_Tk_from);
tkt_subject = (TextView) itemView.findViewById(R.id.tv_Tk_subject);
tkt_assignedto = (TextView) itemView.findViewById(R.id.tv_Tk_Assignedto);
tkt_created_date = (TextView) itemView.findViewById(R.id.tv_Tk_Created_date);
txt_ticket_id = (TextView) itemView.findViewById(R.id.tv_Tk_TicketID);
}
#Override
public void onClick(View view) {
int position = getAdapterPosition();
String ticket_id = txt_ticket_id.getText().toString();
Log.d("ZD-clicked : ", "Position => "+String.valueOf(position)+", Ticket Id => "+ticket_id);
startActivity(new Intent(getActivity(), TicketDetails.class));
// if (selectedItems.get(getAdapterPosition(), false)) {
// selectedItems.delete(getAdapterPosition());
// view.setSelected(false);
// }
// else {
// selectedItems.put(getAdapterPosition(), true);
// view.setSelected(true);
// }
}
}
Adapter
public class TicketsRecyclerViewAdapter extends RecyclerView.Adapter<TicketsRecyclerViewHolders>{
public List<TicketsItemObject> TicketsItemList;
private Context context;
public TicketsRecyclerViewAdapter(Context context, List<TicketsItemObject> itemList) {
this.TicketsItemList = itemList;
this.context = context;
}
#Override
public TicketsRecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_tickets_row, null);
TicketsRecyclerViewHolders rcv = new TicketsRecyclerViewHolders(layoutView);
return rcv;
}
#Override
public void onBindViewHolder(TicketsRecyclerViewHolders holder, int position) {
holder.priority.setImageResource(TicketsItemList.get(position).getStatus_priority());
holder.sts_open.setText(TicketsItemList.get(position).getStatus_open());
holder.sts_overdue.setText(TicketsItemList.get(position).getStatus_overdue());
holder.tkt_from.setText(TicketsItemList.get(position).getTicket_from());
holder.tkt_subject.setText(TicketsItemList.get(position).getTicket_subject());
holder.tkt_assignedto.setText(TicketsItemList.get(position).getTicket_assignedto());
holder.tkt_created_date.setText(TicketsItemList.get(position).getTicket_created_date());
holder.txt_ticket_id.setText(TicketsItemList.get(position).getTicket_id());
}
#Override
public int getItemCount() {
return this.TicketsItemList.size();
}
}
Item Object
public class TicketsItemObject {
private int status_priority;
private String status_open;
private String status_overdue;
private String ticket_from;
private String ticket_subject;
private String ticket_assignedto;
private String ticket_created_date;
private String ticket_id;
public TicketsItemObject(int status_priority, String status_open, String status_overdue, String ticket_from, String ticket_subject, String ticket_assignedto, String ticket_created_date, String ticket_id) {
this.status_priority = status_priority;
this.status_open = status_open;
this.status_overdue = status_overdue;
this.ticket_from = ticket_from;
this.ticket_subject = ticket_subject;
this.ticket_assignedto = ticket_assignedto;
this.ticket_created_date = ticket_created_date;
this.ticket_id =ticket_id;
}
public int getStatus_priority() {
return status_priority;
}
public String getStatus_open() {
return status_open;
}
public String getStatus_overdue() {
return status_overdue;
}
public String getTicket_from() {
return ticket_from;
}
public String getTicket_subject() {
return ticket_subject;
}
public String getTicket_assignedto() {
return ticket_assignedto;
}
public String getTicket_created_date(){return ticket_created_date;}
public String getTicket_id(){return ticket_id;}
}
Activity
public class Dashboard extends AppCompatActivity {
private Toolbar toolbar;
public DrawerLayout drawerLayout;
public ListView drawerList;
private navigationDrawerFragment drawerFragment;
private CompanyProfileAdapter mAdapter;
ApplicationEnvironmentURL applicationEnvironment;
ProgressDialog pDialog;
Context context;
String BASEURL;
String FilteredData;
String allAgents;
List<TicketsItemObject> items = new ArrayList<TicketsItemObject>();
private RecyclerView recyclerView;
private LinearLayoutManager layoutManager;
private TicketsRecyclerViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Dashboard");
setContentView(R.layout.activity_dashboard);
applicationEnvironment = new ApplicationEnvironmentURL(this.context);
context = this.getApplicationContext();
toolbar = (Toolbar) findViewById(R.id.app_bar_dashboard);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (navigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setup(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
SharedPreferences prefs = getSharedPreferences("zupportdesk", MODE_PRIVATE);
String islogged = prefs.getString("islogged", "Not defined");
String userid = prefs.getString("userid", "Not defined");
String profileToken = prefs.getString("profileToken", "Not defined");
String companyId = prefs.getString("companyId", "Not defined");
String companyName = prefs.getString("companyName", "Not defined");
String ProfileId = prefs.getString("ProfileId", "Not defined");
Log.d("islogged : ", islogged);
Log.d("userid : ", userid);
Log.d("profileToken : ", profileToken);
Log.d("companyId : ", companyId);
Log.d("companyName : ", companyName);
Log.d("ProfileId : ", ProfileId);
recyclerView = (RecyclerView)findViewById(R.id.recycler_view_tickets);
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(this));
layoutManager = new LinearLayoutManager(Dashboard.this);
recyclerView.setLayoutManager(layoutManager);
getTickets(ProfileId, companyId, profileToken);
View newTicket = findViewById(R.id.newtic);
newTicket.setOnClickListener(onClickListener);
}
/* Multiple Button on click event handle */
private View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(final View v) {
switch(v.getId()){
case R.id.newtic:
// Create a login URl, before starting anything
if(isNetworkAvailable()){
Intent intentTicket = new Intent(Dashboard.this, NewTicket.class);
startActivity(intentTicket);
} else {showErrorMessage("Please check your internet connection.", "No Connectivity!"); }
break;
}
}
};
private void getTickets(String profileId, String companyId, String profileToken){
if(isNetworkAvailable()) {
try {
setFilteredDataURL(companyId);
FilteredData = new getFilteredData().execute(profileToken).get();
Log.d("Full Filtered Data", FilteredData);
setTicketsURL(profileId, companyId);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
new getNewTickets().execute(profileToken);
}else{ showErrorMessage("Please check your internet connection.", "No Connectivity!"); }
}
................
.............
..More...........
getActivity() only works in fragments. A view will have activity Context. So get Context from the view.
Change
startActivity(new Intent(getActivity(), TicketDetails.class));
to
Context context = view.getContext();
context.startActivity(new Intent(context, TicketDetails.class));
You can try
holder.itemView.context as Activity
Interface approach
You can also solve this problem using interface
1) Create an interface
public interface ItemclickListerner{
public void startActivity(int index);
}
2) Implement the interface in the Activity
public class YourActivity extends AppcompatActivity implements ItemclickListerner{
protected void onCreate(Bundle bundle)
.......
#override
public void startActivity(int index)
{
Intent i = new Intent(YourActivity.this, SecondActivity.class)
startActivity(i);
}
}
3) Use the ItemclickListerner in the holder
public class TicketsRecyclerViewHolders extends .... {
private ItemclickListerner listener;
// Typecast the listener
public TicketsRecyclerViewHolders(Context context)
{
listener = (ItemclickListerner)context;
}
// Call the listener method
#Override
public void onBindViewHolder(TicketsRecyclerViewHolders holder, int position{
listener.startActivity(position)
}
}
You can use an interface to pass the itemclick from Adapter to your activity or fragment. Inside the callback you can call the Intent.
See this thread for more info. See #Jacob Tabaks answer.
EDIT:
See #AkshayBhat's answer for an alternative method.
You have context in your constructor.So you can use context to go to an Activity from adapter.
Intent goTicket = new Intent(context, MyDetailActivity.class);
goTicket.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Pass fragment to the Adaptar constructor.
Check if fragment is currently added to its activity and then launch particular activity:
if (fragment.isAdded())
fragment.startActivity(intent)