Android : App Crashed When Intent called inside the Recycler View - android

i created a recycler view which display images and text from Sqlite in listview, To pass the Selected Item name to the New Activity i used Intent to pass data, But When My Intent was Called My App Was Crashed and it Shows Attempt to invoke virtual method 'void android.content.Context.startActivity(android.content.Intent)' on a null object reference
recyclerview
ArrayList<byte[]> list_image;
private LayoutInflater mInflater;
private Context context;
private ArrayList<String> list_name;
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
holder.listname.setText(String.valueOf(list_name.get(position)));
Bitmap bmp = BitmapFactory.decodeByteArray(list_image.get(position), 0, list_image.get(position).length);
ImageView image = holder.imgname;
image.setImageBitmap(bmp);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(),AddItems.class);
intent.putExtra("listname", String.valueOf(list_name.get(position)));
context.startActivity(intent);
}
});
}
Additems
lisname = findViewById(R.id.listname_dis);
Intent intent = getIntent();
String dataTransmited=intent.getStringExtra("listname");
lisname.setText(dataTransmited);
}
logcat :
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.content.Context.startActivity(android.content.Intent)' on a null object reference
at com.Karthi.check.CustomAdapter$1.onClick(CustomAdapter.java:76)

In Your Custom Adapter initlize private Activity activity;
Then
public CustomAdapter(Activity activity,....){
this.activity = activity;
......
.....
....
}
use activity.startActivity(intent); in your OnClickListerner
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(),AddItems.class);
intent.putExtra("listname", String.valueOf(list_name.get(position)));
activity.startActivity(intent);
}
Also i ur main activity add
CustomAdapter ca = new CustomAdapter(MainActivity.this,this,......)

since your "context" is null Try this:
view.getContext().startActivity(intent)
instead of this:
context.startActivity(intent)

Related

Button not launching to new activity

I have been trying to make a ListView which will have image, textviews and buttons.
I am trying to get the buttons to start a new activity by using the code
but when I use
Intent intent = new Intent(MyListAdapter.this, Login.class);
I get the error Cannot Resolve constructor intent error.
And in the very next line
startActivity(intent);
I get the error cannot resolve method startactivity
I wanted to ask how can I get it to launch the activity I want? I have put the full code below
Any help would be appreciated.
Thank You
public class MyListAdapter extends ArrayAdapter<Hero> {
//the list values in the List of type hero
List<Hero> heroList;
//activity context
Context context;
//the layout resource file for the list items
int resource;
//constructor initializing the values
public MyListAdapter(Context context, int resource, List<Hero> heroList) {
super(context, resource, heroList);
this.context = context;
this.resource = resource;
this.heroList = heroList;
}
//this will return the ListView Item as a View
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//we need to get the view of the xml for our list item
//And for this we need a layoutinflater
LayoutInflater layoutInflater = LayoutInflater.from(context);
//getting the view
View view = layoutInflater.inflate(resource, null, false);
//getting the view elements of the list from the view
ImageView imageView = view.findViewById(R.id.imageView);
TextView textViewName = view.findViewById(R.id.textViewName);
TextView textViewTeam = view.findViewById(R.id.textViewTeam);
Button test = view.findViewById(R.id.buttonDelete);
//getting the hero of the specified position
Hero hero = heroList.get(position);
//adding values to the list item
imageView.setImageDrawable(context.getResources().getDrawable(hero.getImage()));
textViewName.setText(hero.getName());
textViewTeam.setText(hero.getTeam());
//adding a click listener to the button to remove item from the list
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MyListAdapter.this, Login.class);
startActivity(intent);
}
});
return view;
}
Intent takes first argument as Context. Since Adapter is not child class of Context you can not directly use this. You have to use context which is passed as a Argument. Modify your code as follows.
tx.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context, Login.class);
context.startActivity(intent);
}
});
Because the params you put inside Intent's constructor is not correct. Use Context instead.
Intent intent = new Intent(yourContext, Login.class);
yourContext.startActivity(intent);
Try to startActivity with Context. Where we can get context in Adapter? Check below:
final Context mContext = test.getContext();
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, Login.class);
mContext.startActivity(intent);
}
});

How to start activty on recycler view item click?

I am feteching data from server using JSON and showing that data in recycler view. But the problem is I may need to add some new data to the server.
Using volley, request will be send to server and recycler view list will be updated. So the problem is I want to open new activity on each recycler view item click. But my recycler view list will increase if I added some new data to the server. So, I can't change layout/start activity based on itemclick postion.
Is there any better way to implement this?
Just like whatsapp, I want to open new activity/fragment on itemclick of recycler view.
This what I tried to do but this is not proper way. Coz I don't know how many item will be present inside recyclerview. Here is my code:
private final Context context;
public MyViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
}
#Override
public void onClick(View v) {
final Intent intent;
switch (getAdapterPostion()){
case 0:
intent = new Intent(context, FirstActivity.class);
break;
case 1:
intent = new Intent(context, SecondActivity.class);
break;
...
default:
intent = new Intent(context, DefaultActivity.class);
break;
}
context.startActivity(intent);
}
a proper approach is using an interface in your adapter class:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private List<Item> items;
private final OnItemClickListener listener;
public interface OnItemClickListener {
void onItemClick(Item item);
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
public void bind (final Item item, final OnItemClickListener listener) {
yourclickableView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(item);
}
});
}
}
public MyAdapter(List<Item> items, OnItemClickListener listener) {
...
this.listener = listener;
items = items;
}
and finally:
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.bind(items.get(position), listener);
...
}
and whenever using your adapter class:
myAdapter = new MyAdapter (itemsList, new MyAdapter.OnItemClickListener(){
#Override
public void onItemClick(Item item) {
//bluh bluh...
}
});
If you trying to replicate the functionality of WhatsApp pay attention that when you click on an item on a list the app will not open a new Activity, it will open the same Activity sending different data to load the data for that specific user.
...
Intent intent = new Intent(context, Chat.class);
intent.putExtra("EXTRA_USER_ID", userId);
startActivity(intent);
...
On the Chat.class
...
Intent intent = getIntent();
String userId = intent.getStringExtra("EXTRA_USER_ID");
...
Using this user id you can load data for this specific user.

how to include different intent in recyclerview

I plan to include a CardView in my project. i have already included RecyclerView and card view in my project. the problem is, i want to call for different activity for each card. i have implement different intent for each card. but it require me to initialize the data. this is my original code:
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private Context context;
private String[] titles = {"Add new Research",
"View Your Research"};
private String[] details = {"Add your research files here",
"View all of your posted research"};
private int[] images = { R.drawable.add,
R.drawable.view};
class ViewHolder extends RecyclerView.ViewHolder{
public int currentItem;
public ImageView itemImage;
public TextView itemTitle;
public TextView itemDetail;
public ViewHolder(View itemView) {
super(itemView);
itemImage = (ImageView)itemView.findViewById(R.id.item_image);
itemTitle = (TextView)itemView.findViewById(R.id.item_title);
itemDetail =
(TextView)itemView.findViewById(R.id.item_detail);
itemView.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
int position = getAdapterPosition();
Intent intent = new Intent(context, Choose.class);
if(position==0){
intent = new Intent(context, AddFiles.class);
}else if(position==1){
intent = new Intent(context, ViewFiles.class);
}
context.startActivity(intent);
}
});
}
}
when i click on the card view, it stated that my program are not responding.
even if i initialize intent as
Intent intent = null;
if(position==0){
intent = new Intent(context, AddFiles.class);
}else if(position==1){
intent = new Intent(context, ViewFiles.class);
}
context.startActivity(intent);
there still an error, what should i do? or is there better way to do it.
this is my logcat error.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.mcormpelo, PID: 3645
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ComponentName.<init>(ComponentName.java:128)
at android.content.Intent.<init>(Intent.java:4449)
at com.example.user.mcormpelo.RecyclerAdapter$ViewHolder$1.onClick(RecyclerAdapter.java:46)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
You did not initialize the context
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private Context context;
public RecyclerAdapter(Context context) {
this.context = context;
}
Pass the Activity reference from the caller activity.
sample usage
RecyclerAdapter rcAdapter = new RecyclerAdapter(MainActivity.this);

Can show the toast but cant startActivity

I am using an adapter class to populate my listview, but each item in my listview has two textviews to whom I wanna setOnClick listener. So I set it in adapter class and it works fine when I try to show the toast.
But the problem is I cant startActivity within OnClickListener. The app crashes. Please help or suggest an alternate way to achieve the same.
The activity is already mentioned in Manifest.
This Is My Code:-
public class Adapter_NearMe_TyreWorx extends ArrayAdapter<List_NearMe> implements View.OnClickListener {
ArrayList<List_NearMe> arraylist;
private Context context;
private List<List`enter code here`_NearMe> list;
public Adapter_NearMe_TyreWorx(Context context, int resource, List<List_NearMe> objects) {
super(context, resource, objects);
this.context = context;
this.List = objects;
arraylist = new ArrayList<List_NearMe>();
arraylist.addAll(List);
}
TextView Btn_Call;
String Fac_landmark;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.canvas_two, parent, false);
List_NearMe list= list.get(position);
String Fac_name=list.getName();
Fac_landmark=list.getLandmark();
String Fac_gMap=list.getgMap();
String Fac_contact=list.getContact();
TextView distance=(TextView)view.findViewById(R.id.fac_distance);
TextView Fac_Name=(TextView)view.findViewById(R.id.fac_name);
TextView Fac_Address=(TextView)view.findViewById(R.id.fac_address);
Btn_Call=(TextView)view.findViewById(R.id.btn_call);
TextView Btn_Go=(TextView)view.findViewById(R.id.btn_go);
Btn_Go.setOnClickListener(this);
return view;
}
public void onClick(View v) {
Toast.makeText(getContext(),"Toast text",LENGTH.SHORT).show(); //working toast code
Intent intent = new Intent(getContext(), SampleActivity.class);
getContext().startActivity(intent);
}
}
You have to add a Intent flag to pass a Intent from a Non - Activity class Intent.FLAG_ACTIVITY_NEW_TASK adding this flag in intent will work fine try to pass your Intent like this :
Intent intent = new Intent(getContext(), SampleActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(intent);
Or
Intent intent = new Intent(getContext(), SampleActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(intent);
replace getContext() with context.
Intent intent = new Intent(context, SampleActivity.class);
context.startActivity(intent);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
context.startActivity(new Intent(context.getApplicationContext(), SampleActivity.class));
}
});
call the method on the context which you are setting in the constructor of the adapter.
as startActivity() can only be started from the method which in the context of the application, as your adapter is not there you would have to reference the context which you have provided at the constructor of your adapter class

Listview not loading properly

I am trying to save a link from webview. From my webview class, I am saving the page url as below.
public void AddUrl(String page_url){
SaveUrlActivity urlactivity = new SaveUrlActivity();
urlactivity.saveurl(page_url);
}
My SaveUrlActivity class is as below:
public class SaveUrlActivity extends Activity {
public String url;
public ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_savedurl);
lv = (ListView) findViewById(R.id.list);
saveurl(url);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent in = new Intent(SaveUrlActivity.this, DisPlayWebPageActivity.class);
in.putExtra("page_url", url);
startActivity(in);
}
});
}
public void saveurl(String url1){
url = url1;
final List<RowItem> ri = new ArrayList<RowItem>();
RowItem item = new RowItem(url);
ri.add(item);
SavedUrlAdapter adapter = new SavedUrlAdapter(SaveUrlActivity.this, ri);
lv.setAdapter(adapter);
}
}
Whenever I run my program, I am getting the following error.
FATAL EXCEPTION: main
Process: com.example.smarthelp, PID: 16284
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.example.smarthelp.SaveUrlActivity.saveurl(SaveUrlActivity.java:46)
at com.example.smarthelp.DisPlayWebPageActivity.AddUrl(DisPlayWebPageActivity.java:76)
at com.example.smarthelp.DisPlayWebPageActivity.onOptionsItemSelected(DisPlayWebPageActivity.java:66)
Can anyone help me figure out where I am making the mistake?
You're using reference to ListView lv before it has been initialized, and you can't do that without first starting the SaveUrlActivity, only after it's setContentView(R.layout.activity_savedurl); you can initialize the lv.
public void saveurl(String url1){
url = url1;
final List<RowItem> ri = new ArrayList<RowItem>();
RowItem item = new RowItem(url);
ri.add(item);
SavedUrlAdapter adapter = new SavedUrlAdapter(SaveUrlActivity.this, ri);
lv.setAdapter(adapter);
}
It would be easier if you make a static var in your SaveUrlActivity class and assign a value to it before you start the Activity, and the make call to the saveurl() from inside of that class when you have all your views initialized.
Something like:
public void AddUrl(String page_url){
SaveUrlActivity.page_url = page_url;
Intent i = new Intent(this, SaveUrlActivity.class);
startActivity(i);
}
And in your SaveUrlActivity.java:
public class SaveUrlActivity extends Activity {
public String url;
public ListView lv;
static page_url;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_savedurl);
lv = (ListView) findViewById(R.id.list);
saveurl();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent in = new Intent(SaveUrlActivity.this, DisPlayWebPageActivity.class);
in.putExtra("page_url", url);
startActivity(in);
}
});
}
public void saveurl(){
url = page_url;
final List<RowItem> ri = new ArrayList<RowItem>();
RowItem item = new RowItem(url);
ri.add(item);
SavedUrlAdapter adapter = new SavedUrlAdapter(SaveUrlActivity.this, ri);
lv.setAdapter(adapter);
}
}
It's accurate if you're planning to start this activity, if you need to update data in already started one, you better use the Handler
A couple of things to look at:
Make sure that the activity_savedurl layout file actually contains a view with the list ID. If it does not, then lv will be null.
You pass url to saveurl(), but you never assigned it a value.

Categories

Resources