So I have two Adapter class for RecyclerView. I want the ImageView inside one Adapter class to display the other Adapter class
I already tried to use intent on MainActivity
// listener for image
cardViewHolder.photo.setOnClickListener(new CustomOnItemClick(
i, new CustomOnItemClick.OnItemClickCallback() {
#Override
public void onItemClicked(View view, int position) {
Intent detail = new Intent(context,DetailAdapter.class);
context.startActivity(detail);
}
}
));
here is the link for what the application supposed to be
https://ibb.co/gmnnghw
https://giphy.com/gifs/Y3NK0lHfAcN1dGbCZX
CardViewDeviceAdapter
package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
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 android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import java.util.ArrayList;
public class CardViewDeviceAdapter extends RecyclerView.Adapter<CardViewDeviceAdapter.CardViewHolder> {
private Context context;
private ArrayList<Device> deviceArrayList;
private ArrayList<Device> getDeviceArrayList() {
return deviceArrayList;
}
public void setDeviceArrayList(ArrayList<Device> deviceArrayList) {
this.deviceArrayList = deviceArrayList;
}
public CardViewDeviceAdapter(Context context) {
this.context = context;
}
#Override
public CardViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_device, viewGroup, false);
return new CardViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CardViewHolder cardViewHolder, int i) {
Device d = getDeviceArrayList().get(i);
Glide.with(context)
.load(d.getPhoto())
.apply(new RequestOptions().override(350, 550))
.into(cardViewHolder.photo);
cardViewHolder.title.setText(d.getTitle());
cardViewHolder.detail.setText(d.getDetail());
// listener untuk button favorite
cardViewHolder.favorite.setOnClickListener(new CustomOnItemClick(
i, new CustomOnItemClick.OnItemClickCallback() {
#Override
public void onItemClicked(View view, int position) {
Toast.makeText(context, "Favorite device"+getDeviceArrayList()
.get(position)
.getTitle()
, Toast.LENGTH_SHORT).show();
}
}
));
// listener untuk button share
cardViewHolder.share.setOnClickListener(new CustomOnItemClick(
i, new CustomOnItemClick.OnItemClickCallback() {
#Override
public void onItemClicked(View view, int position) {
Toast.makeText(context, "Share device"+getDeviceArrayList()
.get(position)
.getTitle()
, Toast.LENGTH_SHORT).show();
}
}
));
// listener untuk image
cardViewHolder.photo.setOnClickListener(new CustomOnItemClick(
i, new CustomOnItemClick.OnItemClickCallback() {
#Override
public void onItemClicked(View view, int position) {
Intent detail = new Intent(context, DetailAdapter.class);
context.startActivity(detail);
}
}
));
}
#Override
public int getItemCount() {
return getDeviceArrayList().size();
}
public class CardViewHolder extends RecyclerView.ViewHolder {
ImageView photo;
TextView title, detail;
Button favorite, share;
public CardViewHolder(View itemView) {
super(itemView);
photo = itemView.findViewById(R.id.pc_photo);
title = itemView.findViewById(R.id.pc_name);
detail = itemView.findViewById(R.id.pc_details);
favorite = itemView.findViewById(R.id.pc_favourite);
share = itemView.findViewById(R.id.pc_share);
}
}
}
DetailAdapter
package com.example.myapplication;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
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 android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import java.util.ArrayList;
public class DetailAdapter extends RecyclerView.Adapter<DetailAdapter.DetailHolder> {
private Context context;
private ArrayList<Device> deviceArrayList;
private ArrayList<Device> getDeviceArrayList() {
return deviceArrayList;
}
#NonNull
#Override
public DetailAdapter.DetailHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.detail_adapter, viewGroup, false);
return new DetailAdapter.DetailHolder(view);
}
#Override
public void onBindViewHolder(#NonNull DetailAdapter.DetailHolder detailHolder, int i) {
Device d = getDeviceArrayList().get(i);
Glide.with(context)
.load(d.getPhoto())
.apply(new RequestOptions().override(350, 550))
.into(detailHolder.photo);
detailHolder.title.setText(d.getTitle());
detailHolder.detail.setText(d.getDetail());
detailHolder.summary.setText(d.getSummary());
detailHolder.origin.setText(d.getOrigin());
detailHolder.market_value.setText(d.getMarket_value());
detailHolder.consumer.setText(d.getConsumer());
}
#Override
public int getItemCount() {
return getDeviceArrayList().size();
}
public class DetailHolder extends RecyclerView.ViewHolder {
ImageView photo;
TextView title, detail, summary, origin, market_value, consumer;
public DetailHolder(View view) {
super(view);
photo = view.findViewById(R.id.photo_detail);
title = view.findViewById(R.id.title_title);
detail = view.findViewById(R.id.detail_title);
summary = view.findViewById(R.id.detail_detail);
origin = view.findViewById(R.id.origin_year);
market_value = view.findViewById(R.id.market_value);
consumer = view.findViewById(R.id.konsumer);
}
}
}
Right now it asks for explicit activity on AndroidManifest.xml ,
but I can't assign DetailAdapter to AndroidManifest.xml
Logcat
2019-05-29 17:38:59.097 8897-8897/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 8897
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.myapplication/com.example.myapplication.DetailAdapter}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2012)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1675)
at android.app.Activity.startActivityForResult(Activity.java:4586)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
at android.app.Activity.startActivityForResult(Activity.java:4544)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:754)
at android.app.Activity.startActivity(Activity.java:4905)
at android.app.Activity.startActivity(Activity.java:4873)
at com.example.myapplication.CardViewDeviceAdapter$3.onItemClicked(CardViewDeviceAdapter.java:89)
at com.example.myapplication.CustomOnItemClick.onClick(CustomOnItemClick.java:16)
at android.view.View.performClick(View.java:6608)
at android.view.View.performClickInternal(View.java:6585)
at android.view.View.access$3100(View.java:782)
at android.view.View$PerformClick.run(View.java:25945)
at android.os.Handler.handleCallback(Handler.java:874)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:198)
at android.app.ActivityThread.main(ActivityThread.java:6729)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
App crashses when tapping on Image
You've got all the concept of RecyclerView wrong. Check out how to use RecyclerView from
Simple RecyclerView Example.
What you're trying to do is launch RecyclerView like an Activity. Your RecyclerView is not an activity, it is a view.
In the gif you've attached to shown what you want to accomplish, it's a completely different thing. After clicking the item in RecyclerView, a new activity is launched with SharedElement transition. Your DetailAdapter should be AppCompatActivity.
To correct your error, make your DetailAdapter extend AppCompatActivity, after doing that, while launching the DetailAdapter with Intent, pass the data like title, detail through Intent.
Related
I've been working on a Android Project (A Basic College Information App), I have three main activities, the user goes in like, Goal/Course Select activity-> CollegeList activity-> College Details Activity. Now When I press back on College Details Activity it crashes with this Error:
Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
Below are the files/code which I think might be responsible for this.....
CollegeListActivity.java file
package com.anurag.college_information.activities;
import static com.anurag.college_information.activities.CareerGoalActivity.GOAL;
import static com.anurag.college_information.activities.CareerGoalActivity.SHARED_PREFS;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.anurag.college_information.R;
import com.anurag.college_information.adapters.RecyclerAdapter;
import com.anurag.college_information.models.ModelClass;
import java.util.ArrayList;
import java.util.List;
public class CollegeListActivity extends AppCompatActivity {
private RecyclerAdapter.RecyclerViewClickListener listener;
//ListView collegeList;
TextView collegeListTitle;
Button courseChange;
RecyclerView recyclerView;
LinearLayoutManager LayoutManager;
RecyclerAdapter recyclerAdapter;
List<ModelClass> cList;
String courseName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_college_list);
collegeListTitle = findViewById(R.id.college_list_title);
courseChange = findViewById(R.id.btn_change_course);
//collegeListTitle.setText(goal + "Colleges");
collegeListTitle.setText(getIntent().getStringExtra("Title") + " Colleges");
initData();
initRecyclerView();
//collegeList = findViewById(R.id.lv_college_list);
courseChange.setTransformationMethod(null);
courseChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
Intent i = new Intent(CollegeListActivity.this, CareerGoalActivity.class);
startActivity(i);
//finish();
}
});
}
private void initData() {
cList = new ArrayList<>();
courseName = getIntent().getStringExtra("Title");
switch (courseName) {
case "BE/BTech":
cList.add(new ModelClass("https://images.static-collegedunia.com/public/college_data/images/campusimage/1479294300b-5.jpg", "A.P. Shah College of Engineering", "Thane", "8.0"));
break;
case "Pharmacy":
cList.add(new ModelClass("https://images.static-collegedunia.com/public/college_data/images/campusimage/14382400753.jpg", "Bombay College Of Pharmacy", "Mumbai", "9.0"));
break;
}
}
private void initRecyclerView() {
setOnClickListener();
recyclerView = findViewById(R.id.recycler_view);
LayoutManager = new LinearLayoutManager(this);
LayoutManager.setOrientation(RecyclerView.VERTICAL);
recyclerView.setLayoutManager(LayoutManager);
recyclerAdapter = new RecyclerAdapter(cList, listener);
recyclerView.setAdapter(recyclerAdapter);
}
private void setOnClickListener() {
listener = new RecyclerAdapter.RecyclerViewClickListener() {
#Override
public void onClick(View v, int position) {
Intent i = new Intent(CollegeListActivity.this, CollegeDetailsActivity.class);
startActivity(i);
}
};
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
RecyclerAdapter.java
package com.anurag.college_information.adapters;
import android.content.Context;
import android.content.Intent;
import android.telecom.Call;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.anurag.college_information.activities.CollegeDetailsActivity;
import com.anurag.college_information.models.ModelClass;
import com.anurag.college_information.R;
import com.squareup.picasso.Picasso;
import java.util.List;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private List<ModelClass> collegeList ;
private RecyclerViewClickListener listener;
List<String> imageUrl, collegeName, collegeLocation, collegeRating;
public RecyclerAdapter(List<ModelClass> collegeList, RecyclerViewClickListener listener){
this.collegeList=collegeList;
this.listener = listener;
}
#NonNull
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.college_list_single_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerAdapter.ViewHolder holder, int position) {
String imageLink = collegeList.get(position).getImageLink();
//int img = collegeList.get(position).getCollegeImage();
String cName = collegeList.get(position).getCollegeName();
String cRating = collegeList.get(position).getCollegeRating();
String cLocation = collegeList.get(position).getLocation();
Picasso.get().load(imageLink).into(holder.imageView);
//holder.setData(img, cName, cRating);
holder.setData(imageLink, cName, cLocation ,cRating);
}
#Override
public int getItemCount() {
return collegeList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView imageView;
private TextView collegeName, collegeRating, collegeLocation;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.college_image);
collegeName = itemView.findViewById(R.id.college_name);
collegeRating = itemView.findViewById(R.id.college_rating);
collegeLocation = itemView.findViewById(R.id.college_location);
itemView.setOnClickListener(this);
}
public void setData(String imageLink, String cName, String cLocation, String cRating) {
//imageView.setImageResource(img);
Picasso.get().load(imageLink).error(R.drawable.error).into(imageView);
collegeName.setText(cName);
collegeRating.setText(cRating);
collegeLocation.setText(cLocation);
}
#Override
public void onClick(View v) {
listener.onClick(v, getAdapterPosition());
Intent i = new Intent(v.getContext(), CollegeDetailsActivity.class);
i.putExtra("collegeImage", collegeList.get(getAdapterPosition()).getImageLink());
i.putExtra("collegeName", collegeList.get(getAdapterPosition()).getCollegeName());
i.putExtra("collegeRating", collegeList.get(getAdapterPosition()).getCollegeRating());
i.putExtra("collegeLocation", collegeList.get(getAdapterPosition()).getLocation());
v.getContext().startActivity(i);
}
}
public interface RecyclerViewClickListener{
void onClick(View v, int position);
}
}
CollegeDetailsActivity.java
package com.anurag.college_information.activities;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.anurag.college_information.R;
import com.squareup.picasso.Picasso;
public class CollegeDetailsActivity extends AppCompatActivity {
Button btnApply;
ImageView dCollegeImage;
TextView dCollegeName, dCollegeRating, dCollegeLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_college_details);
dCollegeImage = findViewById(R.id.details_college_image);
dCollegeName = findViewById(R.id.details_college_name);
dCollegeRating = findViewById(R.id.details_college_rating);
dCollegeLocation = findViewById(R.id.details_college_location);
btnApply = findViewById(R.id.btn_apply);
Intent i = getIntent();
String cn = i.getStringExtra("collegeName");
String cr = i.getStringExtra("collegeRating");
String ci = i.getStringExtra("collegeImage");
String cl = i.getStringExtra("collegeLocation");
Picasso.get().load(ci).error(R.drawable.error).into(dCollegeImage);
dCollegeName.setText(cn);
dCollegeRating.setText(cr);
dCollegeLocation.setText(cl);
btnApply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "The institute will be notified, of your application", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "The college will contact you, Thank you", Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onBackPressed() {
Intent i = new Intent(CollegeDetailsActivity.this, CollegeListActivity.class);
startActivity(i);
}
}
This is the Error Screenshot:
I'm pretty new to android I've just worked on just 4 to 5 projects,
Any Assistance will be appreciated, Thank You
The commented Out code, is just a normal listview I implemented just In Case, I have to remove the recycler view.
This will probably go away if you don't override onBackPressed in CollegeDetailsActivity. Instead of going back to an activity that had a valid "Title" string extra, the code you posted will go to a new activity where "Title" isn't defined, then get a NullPointerException since courseName will be null in initData (which the error message tells you results in an error on line 81 in that method). Using a null string in a switch results in that type of error
Just remove your onBackPressed entirely in CollegeDetailsActivity.
I would like to change the fragment when listview item clicked under Bottom navigation activity
But I have not idea how to write the OnClickListener
Anyone can provide some hints or tell me what wrong in this program?
Here is the program
And thank you for spend the time to view my program
Thank you very much
package com.example.campus.ui.campus;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.c.MainActivity;
import com.example.c.R;
import com.example.c.database.campus.CampusData;
import com.example.c.ui.campusInformation.CampusInformationActivity;
import com.example.c.ui.campusInformation.CampusInformationFragment;
import java.util.ArrayList;
import java.util.List;
public class CampusListLayoutAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
private List<CampusData> campusList = new ArrayList<CampusData>();
private int resourceViewID;
private Context context;
private Context mContext;
static class ViewHolder{
LinearLayout llCampusCard;
TextView tvCampusName;
TextView tvCampusAddress;
ImageView ivCampusImage;
}
public CampusListLayoutAdapter(Context c, List<CampusData> campusList){
context = c;
layoutInflater = LayoutInflater.from(c);
this.campusList = campusList;
}
#Override
public int getCount() {
return campusList.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
mContext = viewGroup.getContext();
ViewHolder holder = new ViewHolder();
view = layoutInflater.inflate(R.layout.listview_campus, null);
if(view != null){
holder.tvCampusName = view.findViewById(R.id.tvCampusName);
holder.tvCampusAddress = view.findViewById(R.id.tvCampusAddress);
holder.ivCampusImage = view.findViewById(R.id.ivCampusImage);
holder.tvCampusName.setText(campusList.get(i).name);
holder.tvCampusAddress.setText(campusList.get(i).address);
String image = campusList.get(i).image;
resourceViewID = context.getResources().getIdentifier(image, "drawable", context.getPackageName());
holder.ivCampusImage.setImageResource(resourceViewID);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}else {
return null;
}
}
}
First of all, create an interface in your adapter class.
public interface Callbacks {
void onItemClick(YourObject object, int position); // arguments as per the requirement
}
change your constructor of adapter as
Callbacks callback;
public CampusListLayoutAdapter(Context c, List<CampusData> campusList, Callbacks callback){
.....
this.callback = callback;
}
Now in your onClick() use..
callback.onItemClick(yourClickedItem, position)
then pass an anonymous or simply implement interface in your activity.
adapter = new CampusListLayoutAdapter(context, list, new CampusListLayoutAdapter.Callbacks() {
#Override
public void onItemClick(Alert_bean alert, int position) {
// do what you want here in activity like changing fragment or view updates
}
});
I am making a practice app for my self creating friends profile my self in my app and having their avatar as imageview and name,nickname as text view it accepts object but it never shows anything on recyclerview
Please Help!
My main activity.java
package rex.MyFriends;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.OnItemTouchListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class MainActivity extends AppCompatActivity {
FloatingActionButton btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView view = findViewById(R.id.elementsview);
btn = (FloatingActionButton) findViewById(R.id.newfbtn);
view.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
view.setAdapter(new Friendsadapter(this));
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getBaseContext(),FriendsAdder.class));
}
});
}
}
my FriendAdder activity
package rex.MyFriends;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class FriendsAdder extends AppCompatActivity {
TextView name,nickname;
Button add ,selectimage;
ImageView image;
String imgpath;
private static final int SELECT_IMAGE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.friendsadder);
name = findViewById(R.id.name);
nickname = findViewById(R.id.nickname);
add = findViewById(R.id.add);
selectimage = findViewById(R.id.selimg);
image = findViewById(R.id.disimg);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(name.toString().isEmpty() || nickname.toString().isEmpty() || image.getDrawable()==null){
Toast.makeText(getBaseContext(),"please fill every thing!",Toast.LENGTH_SHORT).show();
}
else{
FriendList.addFriend(name.toString(),nickname.toString(),imgpath);
finish();
Toast.makeText(getBaseContext(),"Friend Added!",Toast.LENGTH_SHORT).show();
}
}
});
selectimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Your Friends Avatar!"), SELECT_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==SELECT_IMAGE && resultCode== Activity.RESULT_OK){
imgpath= data.getData().getPath();
Toast.makeText(getBaseContext(),imgpath,Toast.LENGTH_LONG).show();
image.setImageURI(data.getData());
}
}
}
my adapter class
package rex.MyFriends;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.io.File;
public class Friendsadapter extends RecyclerView.Adapter<Friendsadapter.FriendsHolder> {
Context context;
public Friendsadapter(Context context) {
this.context = context;
}
#NonNull
#Override
public FriendsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.friendrow,null,false);
return new FriendsHolder(view);
}
#Override
public void onBindViewHolder(#NonNull FriendsHolder holder, int position) {
FriendList.Friend friend = (FriendList.Friend) FriendList.friendlist.get(position);
holder.nickname.setText(friend.nickname);
holder.name.setText(friend.name);
File imgFile = new File(friend.imgpath);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
holder.image.setImageBitmap(myBitmap);
}
}
#Override
public int getItemCount() {
return FriendList.friendlist.size();
}
public class FriendsHolder extends RecyclerView.ViewHolder {
TextView name,nickname;
ImageView image;
public FriendsHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
nickname = itemView.findViewById(R.id.nickname);
image = itemView.findViewById(R.id.imageView2);
}
}
}
A helper Class I made with static Array list of Friend object acting as A runtime temporary database to add and remove Friend used in adapter class to display
package rex.MyFriends;
import java.util.ArrayList;
public class FriendList {
public static ArrayList<Friend> friendlist = new ArrayList<>();
public static class Friend {
String name;
String nickname;
String imgpath ;
public Friend(String name, String nickname, String imgpath) {
this.name = name;
this.nickname = nickname;
this.imgpath = imgpath;
}
}
public static void addFriend(String name, String nickname, String imgpath){
Friend friend = new Friend(name,nickname,imgpath);
friendlist.add(friend);
}
public int getSize(){
return friendlist.size();
}
public Friend getFriend(int position){
return friendlist.get(position);
}
}
Where the RecyclerView is handled adapterName.notifyDataSetChanged (); you need to run.
In your case, the data is collected statically. The place where the data is processed is a different Activity.
After switching to the new screen and adding data, you will need to update your adapter in onResume if you want the relevant data to appear when you come back. Recyclerview will appear blank since there is no data in its initial state.
#Override
public void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
I am using adapter to show images. In Adapter, How to get context when using Picasso?
I tried different solutions but I couldn't solve. What should I do when using picasso in Adapter? Context is a big problem for developers I see on the internet.
package gc.x;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
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.TextView;
import com.squareup.picasso.Picasso;
import gc.ovidos_challenge.R;
import gc.ovidos_challenge.models.Image;
import java.net.URL;
import java.util.List;
public class ImagesAdapter extends RecyclerView.Adapter<ImagesAdapter.MyViewHolder> {
private List<Image> imagesList;
private Context context;
public ImagesAdapter(Context context) {
this.context = context;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public ImageView imageview;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.textview);
imageview = (ImageView) view.findViewById(R.id.imageurl);
}
}
public ImagesAdapter(List<Image> imagesList) {
this.imagesList = imagesList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_image, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Image image = imagesList.get(position);
holder.title.setText(image.title);
Picasso.with(this.context).load(image.url).into(holder.imageview);
// holder.imageview.setImageBitmap(image.getBitmapFromURL());
}
#Override
public int getItemCount() {
return imagesList.size();
}
}
you have created two constructors one for context and one for your data. use one constructor to initialize both of them
like this
public ImagesAdapter(Context context,List<Image> imagesList) {
this.context = context;
this.imagesList=imagesList;
}
I am creating simple contacts app in android. MainActivity consist of listview displaying image and name. I am using a model for setting and getting data and ArrayList to pass the data to next activity. When I click on single listview item. It should display next activity displaying contact details.
MainActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
String[] name={
"Adam",
"John",
"Jasmine"
};
int[] image={
R.drawable.img1,
R.drawable.img2,
R.drawable.img3
};
String[] mobile_no={
"03349875429",
"03458294792",
"03318245801",
};
String[] email={
"adam123#yahoo.com",
"john123#gmail.com",
"jasmine456#hotmail.com"
};
String[] url={
"https://www.google.com.pk/",
"https://www.google.com.pk/",
"https://www.google.com.pk/"
};
ContactModel contact;
ArrayList<ContactModel> contact_list=new ArrayList<ContactModel>();
ListView ls;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ls=(ListView)findViewById(R.id.listView);
for(int i=0;i<name.length;i++){
contact=new ContactModel();
contact.setImage(image[i]);
contact.setName(name[i]);
contact.setMobile_no(mobile_no[i]);
contact.setEmail(email[i]);
contact.setUrl(url[i]);
contact_list.add(contact);
}
CustomBaseAdapter adapter=new CustomBaseAdapter(this,contact_list);
ls.setAdapter(adapter);
ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ContactModel contacts=contact_list.get(i);
Intent intent=new Intent(getApplicationContext(),ContactDetails.class);
intent.putExtra("contacts",contacts);
startActivity(intent);
}
});
}
}
CustomeBaseAdapter.java
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomBaseAdapter extends BaseAdapter {
Activity activity;
ArrayList<ContactModel> contact;
LayoutInflater inflator;
TextView name;
ImageView image;
public CustomBaseAdapter(Activity activity, ArrayList<ContactModel> contact) {
this.activity=activity;
this.contact=contact;
inflator=activity.getLayoutInflater();
}
#Override
public int getCount() {
return contact.size();
}
#Override
public Object getItem(int i) {
return contact.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v=view;
if(view==null){
v=inflator.inflate(R.layout.contact_list_,null);
}
name=(TextView)v.findViewById(R.id.name_textView);
image=(ImageView)v.findViewById(R.id.imageView);
ContactModel c=(ContactModel) getItem(i);
name.setText(c.getName());
image.setImageResource(c.getImage());
return v;
}
}
ContactDetails.java
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class ContactDetails extends AppCompatActivity {
ImageView imageView;
TextView nameView;
TextView mobileView;
TextView emailtextview;
TextView urlView;
ImageView callButton;
ImageView messageButton;
ImageView emailButton;
ImageView websiteButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_details);
Intent intent=getIntent();
final ContactModel contacts=(ContactModel)intent.getSerializableExtra("contacts");
imageView=(ImageView)findViewById(R.id.imageView);
nameView=(TextView)findViewById(R.id.name_view);
mobileView=(TextView)findViewById(R.id.number_view);
emailtextview=(TextView)findViewById(R.id.email_textview);
urlView=(TextView)findViewById(R.id.url_textview);
//Buttons
callButton=(ImageView)findViewById(R.id.callButton);
messageButton=(ImageView)findViewById(R.id.message_view);
emailButton=(ImageView)findViewById(R.id.email_imageview);
websiteButton=(ImageView)findViewById(R.id.url_imageview);
imageView.setImageResource(contacts.getImage());
nameView.setText(contacts.getName());
mobileView.setText(contacts.getMobile_no());
emailtextview.setText(contacts.getEmail());
urlView.setText(contacts.getUrl());
}
}
ContactModel simply consist of setter and getter methods. Call Button etc functionality is not implemented yet. No error is displayed but when I run the project it displays 1 error: Error:java.lang.NullPointerException (no error message)
logcat:
09-25 05:09:54.006 1745-1775/system_process E/BluetoothAdapter: Bluetooth binder is null
09-25 05:11:00.001 1745-1773/system_process I/ProcessStatsService: Prepared write state in 0ms
09-25 05:16:38.974 98-98/? D/Genyd: Received Set Clipboard
09-25 05:16:38.974 98-98/? D/Genymotion: Received Set Clipboard
you can do this to resolve your problem:
ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//ContactModel contacts=new ContactModel();//here you did mistake
Intent intent=new Intent(getApplicationContext(),ContactDetails.class);
intent.putExtra("contacts",(Serializable) adapterView.getSelectedItem());
startActivity(intent);
}
});
In ls.setOnItemClickListener, you're passing ContactModel contacts=new ContactModel(); which is technically a blank object of ContactModel.
Now, when you're trying to set data in ContactDetails.java from that blank object that you got from Intent like this,
imageView.setImageResource(contacts.getImage());
nameView.setText(contacts.getName());
the contact object has no image or name (or other attributes for that matter) that has been previously set on it. Hence, you're getting a null pointer exception.
So, change it like below and your problem should get away.
ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ContactModel contacts= contact_list.get(i);
Intent intent=new Intent(getApplicationContext(),ContactDetails.class);
Bundle bundle = new Bundle();
bundle.putSerializable("contacts",contacts);
intent.putExtras(bundle);
startActivity(intent);
}
});
And in ContactDetails.java, get the object like this.
Intent intent=getIntent();
Bundle bundle = intent.getExtras();
final ContactModel contacts=(ContactModel)bundle.getSerializable("contacts");