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);
Related
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)
I have a simple adapter that uses 2 String based array lists. For some reason I am getting a NullPointerException even though I am sure the information is being passed by.
My adapter:
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.ViewHolder> {
private ArrayList<String> names = new ArrayList<>();
private ArrayList<String> details = new ArrayList<>();
private Context mContext;
public MovieAdapter(ArrayList<String> names, ArrayList<String> details, Context mContext) {
this.names = names;
this.details = details;
this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.detail_view, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.name.setText(names.get(position));
holder.detail.setText(details.get(position));
}
#Override
public int getItemCount() {
return names.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView name;
private TextView detail;
private ConstraintLayout cl;
public ViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
detail = itemView.findViewById(R.id.detial);
cl = itemView.findViewById(R.id.layout);
}
}
}
My REST call and recylerView initialization activity(added the REST call in case the problem is lying there):
// ArrayList<String> namesArray = new ArrayList<>(Arrays.asList("Rated:", "Released:", "Runtime:", "Genre:", , "Writer:", "Actors:", "Plot:", "Language:", "Country:"));
ArrayList<String> namesArray = new ArrayList<>();
namesArray.add("Rated:");
namesArray.add("Released:");
namesArray.add("Runtime:");
namesArray.add("Genre:");
namesArray.add("Director:");
namesArray.add("Writer:");
namesArray.add("Actors:");
namesArray.add("Plot");
namesArray.add("Language:");
namesArray.add("Country");
trazi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Call<Movie> call;
movieApi = ApiClient.getClient().create(MovieApi.class);
if (paramYear.getText().toString().matches("")) {
call = movieApi.getDetails(key, paramName.getText().toString(), null);
} else {
call = movieApi.getDetails(key, paramName.getText().toString(), Integer.parseInt(paramYear.getText().toString()));
}
call.enqueue(new Callback<Movie>() {
#Override
public void onResponse(Call<Movie> call, Response<Movie> response) {
Toast.makeText(getApplication().getApplicationContext(), " valja", Toast.LENGTH_LONG).show();
movie = response.body();
// ArrayList<String> details = new ArrayList<>(Arrays.asList(movie.getRated(), movie.getReleased(), movie.getRuntime(), movie.getGenre(), movie.getDirector(), movie.getWriter(), movie.getActors(), movie.getPlot(), movie.getLanguage(), movie.getCountry()));
ArrayList<String> details = new ArrayList<>();
details.add(movie.getRated());
details.add(movie.getReleased());
details.add(movie.getRuntime());
details.add(movie.getGenre());
details.add(movie.getDirector());
details.add(movie.getWriter());
details.add(movie.getActors());
details.add(movie.getPlot());
details.add(movie.getLanguage());
details.add(movie.getCountry());
Picasso.get().load(movie.getPoster()).fit().centerInside().into(image);
image.setVisibility(View.VISIBLE);
title.setText(movie.getTitle());
title.setVisibility(View.VISIBLE);
recyclerView = findViewById(R.id.layout);
movieAdapter = new MovieAdapter(namesArray, details, getApplication().getApplicationContext());
recyclerView.setAdapter(movieAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplication().getApplicationContext()));
}
So
Picasso.get().load(movie.getPoster()).fit().centerInside().into(image);
and
title.setText(movie.getTitle());
work perfectly so the information is passed to the adapter and I tried to initialize array lists on two different ways just in case. Still no success. Any ideas on where the problem is?
Edit:
My error log:
2020-05-24 17:20:22.600 27595-27595/com.example.cetvrtizadatak E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.cetvrtizadatak, PID: 27595
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference
at com.example.cetvrtizadatak.MainActivity$1$1.onResponse(MainActivity.java:115)
at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1.lambda$onResponse$0$DefaultCallAdapterFactory$ExecutorCallbackCall$1(DefaultCallAdapterFactory.java:81)
at retrofit2.-$$Lambda$DefaultCallAdapterFactory$ExecutorCallbackCall$1$3wC8FyV4pyjrzrYL5U0mlYiviZw.run(Unknown Source:6)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6702)
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:911)
Your NullPointerException is happening when you try to access a member of you recyclerView object, meaning that its value is probably null.
Looking at your code I can presume that the id you're passing is not of yout recyclerView but for an layout object.
Double check if in your layout xml file the id given to the recyclerView is the one you're referencing on you call to findViewById.
I have implemented a RecyclerView with a custom adapter that adds a my own custom objects made from the my class Item. Now I am trying to add a Spinner that will have a list of Strings where when you click on an object in the Spinner drop down menu, it will change the content of the RecyclerView. Basically where each choice in the Spinner will have its own list for the RecyclerView. But when I try to add content to the Spinner, the app crashes when I try to start it. This is the code I added to onCreate(Bundle savedInstanceState) that made the app crashed:
ArrayList<String> lists = new ArrayList<>();
lists.add("firstList");
lists.add("secondList");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, lists);
dropdown.setAdapter(adapter);
I thought it might be crashing because the ArrayAdpater somehow conflicts with my custom ItemAdapter, but I am not sure because I am new to using adapters. Does anyone know how I can resolve this?
If it will help I have my custom adapter here:
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ExampleViewHolder> {
private ArrayList<Item> mItemList;
private OnItemClickListener mListener;
private int selectedPosition=-1;
public interface OnItemClickListener{
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public static class ExampleViewHolder extends RecyclerView.ViewHolder{
public TextView mTextView1;
public TextView mTextView2;
public ExampleViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
mTextView1 = itemView.findViewById(R.id.text1);
mTextView2 = itemView.findViewById(R.id.text2);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(listener != null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
listener.onItemClick(position);
}
}
}
});
}
}
public ItemAdapter(ArrayList<Item> itemList) {
mItemList = itemList;
}
#NonNull
#Override
public ExampleViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.example_item, viewGroup, false);
ExampleViewHolder evh = new ExampleViewHolder(v, mListener);
return evh;
}
#Override
public void onBindViewHolder(#NonNull ExampleViewHolder exampleViewHolder, final int position) {
Item currentItem = mItemList.get(position);
exampleViewHolder.mTextView1.setText(currentItem.getText1());
exampleViewHolder.mTextView2.setText(currentItem.getText2());
if(selectedPosition==position)
exampleViewHolder.itemView.setBackgroundColor(Color.GREEN);
else
exampleViewHolder.itemView.setBackgroundColor(Color.parseColor("#ffffff"));
exampleViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity.positionOfChosenItem = position;
selectedPosition = position;
MainActivity.btnChange.setVisibility(View.VISIBLE);
MainActivity.btnDelete.setVisibility(View.VISIBLE);
MainActivity.changeAmountField.setVisibility(View.VISIBLE);
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return mItemList.size();
}
EDIT: I have made sure that the variables are set to the right value like setting dropdown to the Spinner in the layout.
dropdown = findViewById(R.id.spinner);
And have set contentView to the layout, that the Spinner lies in. setContentView(R.layout.activity_main);
EDIT: Here is the error as well:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.barxqrscanner2, PID: 20357
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.barxqrscanner2/com.example.barxqrscanner2.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2955)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3030)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference
at com.example.barxqrscanner2.MainActivity.buildDropDown(MainActivity.java:123)
at com.example.barxqrscanner2.MainActivity.onCreate(MainActivity.java:61)
at android.app.Activity.performCreate(Activity.java:7174)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2908)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3030)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Application terminated.
Your error (NullPointerException) is due to this line:
dropdown.setAdapter(adapter);
Your object dropdown seems to be null.
I think you forgot to instantiate this object, or you are calling setAdapter() before instantiating dropdown. But without the rest of the code, it is difficult to tell more precisely what's the real problem.
Best
I have two fragments and I am trying to update the recyclerView of the ReceiverFragment via interface. Both fragments have its own adapter (SenderAdapter and ReceiverAdapter).
I have to mention that I also have two SQLDatabase, where group.db is used to populate the SenderFragment and client.db is used to populate the ReceiverFragment.
But ReceiverFragment will only be populate if a CheckBox is ticked in the SenderAdapter.
All the communication between the fragments is ok. When I tick a CheckBox, The SenderAdapter sends a message to MainActivity and the MainActivity sends the same message to ReceiverFragment.
This is SenderFragment:
This would be the desired result.
When I use the message from interface to read the client.db, I get the nullException.
This is the ReceiverFragment:
public class ReceiverFragment extends Fragment {
View view;
private RecyclerView mClientList;
private RecyclerView.Adapter mClientListAdapter;
private RecyclerView.LayoutManager mClientListLayoutManager;
private String receivedFromSender;
ArrayList<ClientObject> clientList;
SQLiteDatabase clientListTable;
ClientRepository clientRepository;
private static String rootPath = Environment.getExternalStorageDirectory()+"/PassKeyBF/";
public ReceiverFragment() {
// Required empty public constructor
}
public String getMessageFromSender(String message){
if (message != null) {
receivedFromSender = message;
Log.i("debinf recfrag", "message from sender (function) is : " + receivedFromSender);
//Log.i("debinf recgfrag", "mContext in interface : " + mContext);
if (message != null) {
if (new File(rootPath + receivedFromSender, "client.db").isFile()) {
clientReading(message);
}
}
}
return null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_receiver, container, false);
// If I use mContext instead of getContext(), I get rid of the context error showed below.
//mContext = getContext();
clientList = new ArrayList<>();
initializeRecyclerView();
//clientReading("-LWBPaM7RA9UOcUVty79");
return view;
}
private void clientReading(String pathToClientTable) {
if (new File(rootPath + pathToClientTable, "client.db").isFile()) {
Log.i("debinf recgfrag", "mContext in clientReading" + mContext);
ClientDatabaseHelper clientDatabaseHelper = new ClientDatabaseHelper(mContext,"client.db", rootPath+pathToClientTable+"/");
clientListTable = clientDatabaseHelper.getReadableDatabase();
clientRepository = new ClientRepository(clientListTable);
clientList = clientRepository.SearchAllClients();
Log.i("debinf recfrag", "clientList in clientReading is " + clientList.get(0).getName());
mClientListAdapter = new ReceiverAdapter(mContext,clientList);
mClientList.setAdapter(mClientListAdapter);
//mClientListAdapter.notifyDataSetChanged();
}
}
private void initializeRecyclerView() {
mClientList = (RecyclerView) view.findViewById(R.id.clientList);
mClientList.setNestedScrollingEnabled(false);
mClientList.setHasFixedSize(false);
mClientListLayoutManager = new LinearLayoutManager(mContext,LinearLayout.VERTICAL,false);
mClientList.setLayoutManager(mClientListLayoutManager);
mClientListAdapter = new ReceiverAdapter(mContext,clientList);
mClientList.setAdapter(mClientListAdapter);
}
}
This is the ReceiverAdapter
public class ReceiverAdapter extends RecyclerView.Adapter<ReceiverAdapter.ReceiverViewHolder> {
ArrayList<ClientObject> clientList;
Context mContext;
private ReceiverAdapter adapter;
public ReceiverAdapter(Context mContext, ArrayList<ClientObject> clientList) {
this.clientList = clientList;
this.mContext = mContext;
}
#NonNull
#Override
public ReceiverViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_callcenter_client, null, false);
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
layoutView.setLayoutParams(lp);
ReceiverViewHolder rcv = new ReceiverViewHolder(layoutView);
return rcv;
}
#Override
public void onBindViewHolder(#NonNull ReceiverViewHolder holder, int position) {
holder.mName.setText(clientList.get(position).getName());
holder.mPhone.setText(clientList.get(position).getPhone());
}
#Override
public int getItemCount() {
return clientList.size();
}
public class ReceiverViewHolder extends RecyclerView.ViewHolder {
public TextView mName, mPhone;
//public LinearLayout mLayout;
public ReceiverViewHolder(#NonNull View itemView) {
super(itemView);
mName = (TextView) itemView.findViewById(R.id.client_name);
mPhone = (TextView) itemView.findViewById(R.id.client_phone);
//mLayout = (LinearLayout) itemView.findViewById(R.id.layoutItemClient);
}
}
}
EDIT
I changed the ReceiverFragment so that it could be more understandable.
That's the FATAL ERROR I get when I use the getContext(). I simply cannot make a connection with my SQLDatabase.
2019-01-31 15:41:45.118 22318-22318/com.example.aliton.passkeybetweenfrags E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.aliton.passkeybetweenfrags, PID: 22318
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getDatabasePath(java.lang.String)' on a null object reference
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:352)
at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:322)
at com.example.aliton.passkeybetweenfrags.ReceiverFragment.clientReading(ReceiverFragment.java:104)
at com.example.aliton.passkeybetweenfrags.ReceiverFragment.getMessageFromSender(ReceiverFragment.java:53)
at com.example.aliton.passkeybetweenfrags.MainActivity.getMessage(MainActivity.java:64)
at com.example.aliton.passkeybetweenfrags.SenderAdapter$1.onCheckedChanged(SenderAdapter.java:54)
at android.widget.CompoundButton.setChecked(CompoundButton.java:171)
at android.widget.CompoundButton.toggle(CompoundButton.java:127)
at android.widget.CompoundButton.performClick(CompoundButton.java:132)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
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)
Now, when I suppress getContext() and make it static in mContext. I can make a connection with SQLDatabase, but I get this FATAL error because the ReceiverAdapter:
2019-01-31 15:35:05.541 21936-21936/com.example.aliton.passkeybetweenfrags E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.aliton.passkeybetweenfrags, PID: 21936
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference
at com.example.aliton.passkeybetweenfrags.ReceiverFragment.clientReading(ReceiverFragment.java:110)
at com.example.aliton.passkeybetweenfrags.ReceiverFragment.getMessageFromSender(ReceiverFragment.java:53)
at com.example.aliton.passkeybetweenfrags.MainActivity.getMessage(MainActivity.java:64)
at com.example.aliton.passkeybetweenfrags.SenderAdapter$1.onCheckedChanged(SenderAdapter.java:54)
at android.widget.CompoundButton.setChecked(CompoundButton.java:171)
at android.widget.CompoundButton.toggle(CompoundButton.java:127)
at android.widget.CompoundButton.performClick(CompoundButton.java:132)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
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)
I can either get an error while reading the SQLDatabase (client.db) or while updating the ReceiverAdapter.
This is the link for the Main folder of the app:
https://1drv.ms/u/s!AjteqjTsJm9qgn6kODT9OJmMcY4e
This is the link to the SQLDatabase (group.db and client.db)
https://1drv.ms/u/s!AjteqjTsJm9qgn_L52cz3lDWOOWe
I finally found an answer.
The whole problem happened in the MainActivity. I was communicating from the MainActivity to the ReceiverFragment like this :
ReceiverFragment receiverFragment = new ReceiverFragment();
And sending the message like this:
#Override
public void getMessage(String message) {
receiverFragment.getMessageFromSender(message);
}
The message was been passed from MainActivity to ReceiverFragment normally, But I was getting a NullPointerException for the recyclerView of the ReceiverFragment.
The problem was solved by using the following way to deliver the message to the ReceiverFragment (answer found in this link https://www.journaldev.com/14207/android-passing-data-between-fragments):
#Override
public void getMessage(String message) {
String tag = "android:switcher:" + R.id.tabs_pager + ":" + 1;
ReceiverFragment rf = (ReceiverFragment) getSupportFragmentManager().findFragmentByTag(tag);
rf.getMessageFromSender(message);
}
The links for the code and the SQLDatabase (group.db and client.db) are still available for download.
For those who are starting in Android like me and interested in the code, please do not forget to change the delivering function in the MainActivity.
Thank you all and good luck!
b = BitmapFactory.decodeResource(this.getApplicationContext().getResources(),R.drawable.elon);
Im trying to create a photo effects app, the thing when I create bitmap using this and this returns a null pointer exception.
What I have done created one simple activity, that has recycler view(Horizontal) at bottom and a image view in above of recyclerview.
The recycler view has only buttons for each effect that has to change, a button is added. when a click a button from recycler view, a method in main class is called and has to run, my MainActivity.java is:
public class MainActivity extends AppCompatActivity {
static {
System.loadLibrary("NativeImageProcessor");
}
Toolbar tl;
ImageView mainImage;
RecyclerView rec;
ArrayList<String> list = new ArrayList<String>();
com.zomato.photofilters.imageprocessors.Filter myFilter;
Drawable b;
Bitmap input;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tl = (Toolbar)findViewById(R.id.toolbar);
tl.setTitle("Image Effects");
setSupportActionBar(tl);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int height = dm.heightPixels;
int width = dm.widthPixels;
mainImage = (ImageView)findViewById(R.id.mainImage);
mainImage.setMinimumHeight((int) (0.6 * height));
rec= (RecyclerView)findViewById(R.id.rec);
rec.setLayoutManager(new
LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
list.add("Keep original");
list.add("Star Lit Filter");
list.add("Blue Mess Filter");
list.add("Awe Stuck Vibe Filter");
list.add("Lime Stutter Filter");
list.add("Night Whispher Filter");
HorizontalAdapter ha=new HorizontalAdapter(list);
rec.setAdapter(ha);
}
public void imageOutput(int filterNum){
try{
input = BitmapFactory.decodeResource(getApplicationContext().getResources(),R.mipmap.ic_launcher_round);
}catch (Exception e){
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_SHORT).show();
}
switch (filterNum){
case 0:
mainImage.setImageBitmap(input);
break;
case 1:
myFilter = SampleFilters.getStarLitFilter();
mainImage.setImageBitmap(myFilter.processFilter(input));
break;
case 2:
myFilter = SampleFilters.getBlueMessFilter();
mainImage.setImageBitmap(myFilter.processFilter(input));
break;
case 3:
myFilter = SampleFilters.getAweStruckVibeFilter();
mainImage.setImageBitmap(myFilter.processFilter(input));
break;
case 4:
myFilter = SampleFilters.getLimeStutterFilter();
mainImage.setImageBitmap(myFilter.processFilter(input));
break;
case 5:
myFilter = SampleFilters.getNightWhisperFilter();
mainImage.setImageBitmap(myFilter.processFilter(input));
break;
}
}
}
Here is my HorizontalAdapter.java class:
public class HorizontalAdapter extends
RecyclerView.Adapter<HorizontalAdapter.myViewHolder> {
ArrayList<String> list;
MainActivity ma = new MainActivity();
HorizontalAdapter(ArrayList list){
this.list = list;
}
#Override
public myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false);
return new myViewHolder(v);
}
#Override
public void onBindViewHolder(myViewHolder holder, final int position) {
holder.filterButton.setText(list.get(position));
holder.filterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("exe","1");
ma.imageOutput(position);
Log.i("exe","0");
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class myViewHolder extends RecyclerView.ViewHolder{
Button filterButton;
public myViewHolder(View itemView) {
super(itemView);
filterButton = (Button)itemView.findViewById(R.id.filterButton);
}
}
}
Here ImageOutput method is called from horizontal recycler adapter passing position of the button as parameter.
and error i'm getting is in bitmap that is in try catch block, showing error as null object reference and crashing, My error program in monitor is:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ag.testphotofilterwithbuttons, PID: 2528
java.lang.NullPointerException: Attempt to invoke virtual method
'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:107)
at com.example.ag.testphotofilterwithbuttons.MainActivity.imageOutput(MainActivity.java:69)
at com.example.ag.testphotofilterwithbuttons.HorizontalAdapter$1.onClick(HorizontalAdapter.java:38)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
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)
use instead ContextCompat
ContextCompat.getDrawable(context, R.drawable.elon);
MainActivity ma = new MainActivity();
NEVER create an instance of an activity yourself.
Since MainActivity is the one that is using HorizontalAdapter, add a constructor parameter to HorizontalAdapter that takes a MainActivity:
MainActivity ma;
HorizontalAdapter(MainActivity ma, ArrayList list){
this.list = list;
this.ma = ma;
}
MainActivity can pass in this:
HorizontalAdapter ha=new HorizontalAdapter(this, list);
rec.setAdapter(ha);