NullPointerException - attempt to invoke virtual method `notifyDataSetChanged()` [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Before you mark this duplicate, I did view solution to other similar question but it isn't working. I am getting this error only the first time I run my app.
I am not sure why is this happening. I am calling MainActivity.adapter.notifyDataSetChanged in the Main2Activity (Edit Text Activity). The app crashes when after installing during pressing the back button in the EditText actitvity i.e. Main2Activity.java.
MainActivity:
public class MainActivity extends AppCompatActivity {
ListView notesListView;
static ArrayList<String> notesArrayList;
static ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notesListView = (ListView) findViewById(R.id.notesListView);
notesArrayList = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, notesArrayList);
notesListView.setAdapter(adapter);
Main2Activity.myDb = new DatabaseOperations(this);
if (Main2Activity.myDb != null) {
notesArrayList.clear();
Cursor result = Main2Activity.myDb.getData();
if (result.getCount() == 0) {
Log.i("Error", "error");
return;
}
while (result.moveToNext()) {
notesArrayList.add(result.getString(result.getColumnIndex("text")));
}
}
//notesArrayList.add("Akhilesh Chobey");
notesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
intent.putExtra("notePosition", i);
startActivity(intent);
}
});
notesListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.add_button) {
notesArrayList.add("");
}
Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
intent.putExtra("notePosition", notesArrayList.size() - 1);
startActivity(intent);
return true;
}
}
Main2Activity (EditText Activity):
public class Main2Activity extends AppCompatActivity implements TextWatcher {
static DatabaseOperations myDb;
EditText editNote;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
editNote = (EditText) findViewById(R.id.noteEditText);
myDb = new DatabaseOperations(Main2Activity.this);
Intent intent = getIntent();
position = intent.getIntExtra("notePosition", -1);
if(position != -1){
editNote.setText(MainActivity.notesArrayList.get(position));
}
editNote.addTextChangedListener(this);
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (myDb != null) {
}
}
#Override
public void afterTextChanged(Editable editable) {
}
#Override
public void onBackPressed(){
myDb.insertData(editNote.getText().toString());
MainActivity.notesArrayList.set(position, editNote.getText().toString());
MainActivity.adapter.notifyDataSetChanged();
this.finish();
}
}
Log:
07-02 18:45:40.402 17500-17500/com.akhileshchobey.mynotes
E/MessageQueue-JNI: java.lang.NullPointerException: Attempt to invoke
virtual method 'void
android.widget.ArrayAdapter.notifyDataSetChanged()' on a null object
reference at
com.akhileshchobey.mynotes.Main2Activity.onBackPressed(Main2Activity.java:70)
at android.app.Activity.onKeyUp(Activity.java:2495) at
android.view.KeyEvent.dispatch(KeyEvent.java:2695) at
android.app.Activity.dispatchKeyEvent(Activity.java:2746) at
android.support.v7.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:533)
at
android.support.v7.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:53)
at
android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.dispatchKeyEvent(AppCompatDelegateImplBase.java:254)
at
com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:2221)
at
android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:3918)
at
android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3880)
at
android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3449)
at
android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3502)
at
android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3468)
at
android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3578)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3476)
at
android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3635)
at
android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3449)
at
android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3502)
at
android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3468)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3476)
at
android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3449)
at
android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3502)
at
android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3468)
at
android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3611)
at
android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:3772)
at
android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:2244)
at
android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:1885)
at
android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:1876)
at
android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:2221)
at
android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:141)
at android.os.MessageQueue.nativePollOnce(Native Method) at
android.os.MessageQueue.next(MessageQueue.java:143) at
android.os.Looper.loop(Looper.java:122) at
android.app.ActivityThread.main(ActivityThread.java:5264) at
java.lang.reflect.Method.invoke(Native Method) at
java.lang.reflect.Method.invoke(Method.java:372) at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:900)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695)

ArrayAdapter.notifyDataSetChanged() is been called BUT ArrayAdapter instance is pointing to a null reference (is not initialized or wrongly initialized...)
in your case it looks like the 2nd option is the cause...
you have this in the code:
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, notesArrayList);
but you need to check the parameters in the constructor
the instance: this
the resourcesin layout: android.R.layout.simple_list_item_1 or the list: notesArrayList
at least one of those is breaking the correct initialization of the adapter, which means, after that line adapter still is null
the consecuence is: calling adapter.notifyDataSetChanged() will throw a NPE

Related

I want to add sub tasks on clicking the task but I get the following error when ever I click the task

The error that I get when clicking on a task inorder to add the subtasks:
2020-04-23 14:52:48.749 12289-12289/com.example.justdoit E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.justdoit,
PID: 12289 java.lang.RuntimeException: Unable to start activity ComponentInfo {
com.example.justdoit/com.example.justdoit.ItemActivity
}
: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.floatingactionbutton.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.floatingactionbutton.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at com.example.justdoit.ItemActivity.onCreate(ItemActivity.java:61) at android.app.Activity.performCreate(Activity.java:7009) at android.app.Activity.performCreate(Activity.java:7000) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
ItemActivity Class:
public class ItemActivity extends AppCompatActivity {
Toolbar item_toolbar;
RecyclerView rv_item;
FloatingActionButton fab_item;
long todoId=-1;
ItemActivity activity;
DBHandler dbHandler;
ItemTouchHelper touchHelper;
ItemAdapter adapter;
ArrayList<ToDoItem>list;
#Override protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item);
item_toolbar=findViewById(R.id.item_toolbar);
rv_item=findViewById(R.id.rv_item);
fab_item=findViewById(R.id.fab_item);
setSupportActionBar(item_toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle(getIntent().getStringExtra(INTENT_TODO_NAME));
todoId=getIntent().getLongExtra(INTENT_TODO_ID, -1);
activity=this;
dbHandler=new DBHandler(activity);
rv_item.setLayoutManager(new LinearLayoutManager(activity));
fab_item.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
AlertDialog.Builder dialog=new AlertDialog.Builder(activity);
dialog.setTitle("Add ToDo item");
View view=getLayoutInflater().inflate(R.layout.dialog_dashboard, null);
final EditText toDoName=view.findViewById(R.id.ev_todo);
dialog.setView(view);
dialog.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override public void onClick(DialogInterface dialog, int i) {
if (toDoName.getText().toString().length() > 0) {
ToDoItem item=new ToDoItem();
item.setItemName(toDoName.getText().toString());
item.setToDoId(todoId);
item.setCompleted(false);
dbHandler.addToDoItem(item);
refreshList();
}
}
}
);
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override public void onClick(DialogInterface dialogInterface, int i) {}
}
);
dialog.show();
}
}
);
touchHelper=new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN, 0) {
#Override public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder p1, #NonNull RecyclerView.ViewHolder p2) {
int sourcePosition=p1.getAdapterPosition();
int targetPosition=p2.getAdapterPosition();
Collections.swap(list, sourcePosition, targetPosition);
adapter.notifyItemMoved(sourcePosition, targetPosition);
return true;
}
#Override public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int i) {}
}
);
touchHelper.attachToRecyclerView(rv_item);
}
#Override public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==android.R.id.home) {
finish();
return true;
}
else return super.onOptionsItemSelected(item);
}
#Override protected void onResume() {
refreshList();
super.onResume();
}
void refreshList() {
list=dbHandler.getToDoItems(todoId);
adapter=new ItemAdapter(activity);
rv_item.setAdapter(adapter);
}
void updateItem(final ToDoItem item) {
AlertDialog.Builder dialog=new AlertDialog.Builder(activity);
dialog.setTitle("Update ToDo Item");
View view=getLayoutInflater().inflate(R.layout.dialog_dashboard, null);
final EditText toDoName=view.findViewById(R.id.ev_todo);
toDoName.setText(item.getItemName());
dialog.setView(view);
dialog.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override public void onClick(DialogInterface dialogInterface, int i) {
if (toDoName.getText().toString().length() > 0) {
item.setItemName(toDoName.getText().toString());
item.setToDoId(todoId);
item.setCompleted(false);
dbHandler.updateToDoItem(item);
refreshList();
}
}
}
);
dialog.show();
}
class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder> {
ItemActivity activity;
ItemAdapter(ItemActivity activity) {
this.activity=activity;
}
#NonNull #Override public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
return new ViewHolder(LayoutInflater.from(activity).inflate(R.layout.rv_child_item, viewGroup, false));
}
#Override public void onBindViewHolder(#NonNull final ViewHolder holder, final int i) {
holder.itemName.setText(list.get(i).getItemName());
holder.itemName.setChecked(list.get(i).isCompleted());
holder.itemName.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
list.get(i).setCompleted(!list.get(i).isCompleted());
activity.dbHandler.updateToDoItem(list.get(i));
}
}
);
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
AlertDialog.Builder dialog=new AlertDialog.Builder(activity);
dialog.setTitle("Are you sure");
dialog.setMessage("Do you want to delete this item?");
dialog.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
#Override public void onClick(DialogInterface dialogInterface, int pos) {
activity.dbHandler.deleteToDoItem(list.get(i).getId());
activity.refreshList();
}
}
);
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override public void onClick(DialogInterface dialogInterface, int i) {}
}
);
dialog.show();
}
}
);
holder.edit.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
activity.updateItem(list.get(i));
}
}
);
holder.move.setOnTouchListener(new View.OnTouchListener() {
#Override public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getActionMasked()==MotionEvent.ACTION_DOWN) {
activity.touchHelper.startDrag(holder);
}
return false;
}
}
);
}
#Override public int getItemCount() {
return list.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
CheckBox itemName;
ImageView edit;
ImageView delete;
ImageView move;
ViewHolder(View v) {
super(v);
itemName=v.findViewById(R.id.cb_item);
edit=v.findViewById(R.id.iv_edit);
delete=v.findViewById(R.id.iv_delete);
move=v.findViewById(R.id.iv_move);
}
}
}
}
When I click on the task to add sub tasks, the app stops working and shuts down immediately showing the following error that I've attached.
I want to add sub tasks by clicking on the main task, but I'm not able to do it. How can I do that?
I've declared the FloatingActionButton as fab_item and have written:
fab_item = findViewById(R.id.fab_item);
before the onClick under the onCreate.
Declare this as your Class property:
FloatingActionButton fab_item = findViewById(R.id.fab_item);
Instead of initializing your fab_item in the onCreate(), try to initialize it in the class definition.

Android: Always receiving null object in extras passed in the intent

I am creating a recycler view in my app and fetching data from firestore for the same. In the process, I am passing some arguments to the intent which is called when an item in the recycler view is clicked.
RecyclerView recyclerView = findViewById(R.id.my_recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new LearningModuleAdapter.OnItemClickListener() {
#Override
public void onItemClick(DocumentSnapshot documentSnapshot, int position) {
LearningModule learningModule = documentSnapshot.toObject(LearningModule.class);
String id=documentSnapshot.getId();
String path = documentSnapshot.getReference().getPath();
String title = (String) documentSnapshot.get("title");
System.out.println("what did i get from document snapshot? id: "+id+" path:"+path+" title:"+title);
Intent intent = new Intent(learn.this,learn_content.class);
intent.putExtra("title",title);
startActivity(intent);
}
});
The output from the print statements in above code is as follows :
what did i get from document snapshot? id: EsHW9FGjVe8A3pG4 path:LearningModules/EsHW9FGjVe8A3pG4 title:Front Load vs Top Load
The onClick method of the called activity looks like this :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_learn_view_pager);
viewPager = findViewById(R.id.pager);
progressBar = findViewById(R.id.progressBarViewPager);
Bundle extras;
extras = getIntent().getExtras();
System.out.println("captured form the first " + extras.getString("title"));
However, this piece of code throws an error NullPointerException for the print statement.
Where am I going wrong ?
Additional code:
Adapter
public class LearningModuleAdapter extends FirestoreRecyclerAdapter<LearningModule, LearningModuleAdapter.LearningModuleViewHolder> {
private OnItemClickListener listener;
public LearningModuleAdapter(#NonNull FirestoreRecyclerOptions<LearningModule> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull final LearningModuleViewHolder holder, final int position, #NonNull LearningModule model) {
holder.title.setText(model.getTitle());
// holder.img.setImageResource(model.getImg());
}
#NonNull
#Override
public LearningModuleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType){
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false);
return new LearningModuleViewHolder(v);
}
public class LearningModuleViewHolder extends RecyclerView.ViewHolder {
public View view;
public TextView title;
public ImageView img;
public LearningModuleViewHolder(View v) {
super(v);
view = v;
img = itemView.findViewById(R.id.list_image);
title = itemView.findViewById(R.id.list_text_title);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("The click was captured");
int position = getAdapterPosition();
if(position!=RecyclerView.NO_POSITION && null!=listener){
listener.onItemClick(getSnapshots().getSnapshot(position),position);
}
Intent intent = new Intent(view.getContext(), learn_content.class);
view.getContext().startActivity(intent);
}
});
}
}
public interface OnItemClickListener{
void onItemClick(DocumentSnapshot documentSnapshot,int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
this.listener = listener;
}
}
Error Stacktrace
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gigforce.app/com.gigforce.app.learn_content}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at com.gigforce.app.learn_content.onCreate(learn_content.java:45)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7356)
You are calling startActivity twice that cause the problem.
Option - 1: Try removing inside itemView.setOnClickListener like below :
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("The click was captured");
int position = getAdapterPosition();
if(position!=RecyclerView.NO_POSITION && null!=listener){
listener.onItemClick(getSnapshots().getSnapshot(position),position);
}
//Intent intent = new Intent(view.getContext(), learn_content.class);
//view.getContext().startActivity(intent);
}
});
Option - 2: Try to start activity inside itemView.setOnClickListener and remove OnItemClickListener related code like below :
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("The click was captured");
int position = getAdapterPosition();
/*if(position!=RecyclerView.NO_POSITION && null!=listener){
listener.onItemClick(getSnapshots().getSnapshot(position),position);
}*/
Intent intent = new Intent(view.getContext(), learn_content.class);
DocumentSnapshot documentSnapshot = getSnapshots().getSnapshot(position);
String title = (String) documentSnapshot.get("title");
intent.putExtra("title",title);
view.getContext().startActivity(intent);
}
});
Try this out :
Intent i = getIntent()
if (i == null)
Log.d("***DEBUG****", "Intent was null");
else
Log.d("**** DEBUG ***", "Intent OK");
String title= i.getStringExtra("title"); //Exception points to this line
Log.d("*** DEBUG", rec + " " + title);
Also from itemview click you are not passing title see below
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("The click was captured");
int position = getAdapterPosition();
if(position!=RecyclerView.NO_POSITION && null!=listener){
listener.onItemClick(getSnapshots().getSnapshot(position),position);
}
Intent intent = new Intent(view.getContext(),
learn_content.class);
intent.putExtra("title",title); //This one
view.getContext().startActivity(intent);
}
});
My alternative solution: Instead of putting click listener on LearningModuleViewHolder class put in onCreateViewHolder, so now view will not be null.i will try to add a code here :
#NonNull
#Override
public LearningModuleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType){
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false);
LearningModuleViewHolder holder = new LearningModuleViewHolder(v);
v.setOnClickListener(v -> {
System.out.println("The click was captured");
Intent intent = new Intent(parent.getContext(), learn_content.class);
parent.getContext().startActivity(intent);
});
return holder;
}

Object not being deleted from ListView

I am creating a simple tasklist app in Android Studios.
I have two activities as following (removed imports and package specifications):
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
EditText taskAdd;
Button add;
public ListView tasks;
public Integer pos = 0;
public ArrayList<String> taskArray;
public ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
taskAdd = findViewById(R.id.taskAdd);
add = findViewById(R.id.add);
tasks = findViewById(R.id.tasks);
taskArray = FileHelper.readData(this);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, taskArray);
tasks.setAdapter(adapter);
add.setOnClickListener(this);
tasks.setOnItemClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.add:
String entered = taskAdd.getText().toString();
if (entered != "" || entered != null || entered != "null") {
adapter.add(entered);
taskAdd.setText("");
FileHelper.writeData(taskArray, this);
Toast.makeText(this, "Task Added!", Toast.LENGTH_SHORT).show();
}
break;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pos = position;
Intent intent = new Intent(MainActivity.this, Pop.class);
startActivity(intent);
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
processExtraData();
}
private void processExtraData(){
Bundle extras = getIntent().getExtras();
if (extras != null) {
int value = extras.getInt("Value");
if (value == 1) {
taskArray.remove(pos);
adapter.notifyDataSetChanged();
Toast.makeText(this, "Task Removed!", Toast.LENGTH_SHORT).show();
}
}
}
}
Pop.java (a popup)
public class Pop extends Activity implements View.OnClickListener {
Button deleteButton;
Button finishedButton;
Button timerButton;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.popwindow);
deleteButton = findViewById(R.id.deleteButton);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int)(width*0.5),(int)(height*0.5));
deleteButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent i = new Intent(this, MainActivity.class);
i.putExtra("Value", 1);
startActivity(i);
}
}
After I click deleteButton in Pop.java, processExtraData in MainActivity.java is supposed to run. The Toast does appear, but the selected object in the ListView is not deleted. No errors are thrown either. In addition, using Log.d to check the size of taskArray confirmed that this is not just a graphical issue. Why is this the case, and how should I go about fixing it?
Thank you for replying in advance.
The issue is that you are using an object reference instead of a primitive data type, and so when you are calling taskArray.remove(pos), it is looking for pos the object rather than its denoted integer value.
Instead of:
taskArray.remove(pos);
try:
taskArray.remove(pos.intValue());

How can i combine search listview and ListView.OnItemClickListener

I have a search listview, and i'm trying to combine the search listview with onItemClickListener using switch case like this. So that a user can search an item and click it to do another activity.
Here is sample screen shot
Here is my code
public class MainActivity extends AppCompatActivity {
String[] items;
ArrayAdapter<String> adapter;
ArrayList<String> listItems;
ListView listView;
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.txtSearch);
listView = findViewById(R.id.listName);
initList();
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if(charSequence.toString().equals("")){
initList();
}else{
searchItem(charSequence.toString());
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
listView.setOnItemClickListener(listener);
}
ListView.OnItemClickListener listener = new ListView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
switch (listView.getSelectedItemPosition()){
case 0:
changeActivity();
break;
case 1:
changeActivity();
break;
case 2:
changeActivity();
break;
case 3:
changeActivity();
break;
}
}
};
public void changeActivity(){
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
intent.putExtra("Key", "Value");
startActivity(intent);
}
public void searchItem(String textSeache){
for (String item:items){
if(!item.contains(textSeache)){
listItems.remove(item);
}
}
adapter.notifyDataSetChanged();
}
public void initList(){
items = new String[]{"California, USA", "Toronto, CANADA", "Beijing, CHINA", "Taipei, TAIWAN"};
listItems = new ArrayList<>(Arrays.asList(items));
adapter = new ArrayAdapter<String>(this,R.layout.list_item, R.id.txtItem, listItems);
listView.setAdapter(adapter);
}
}
Can anyone please help me?
You can directly use the code in Your onItemClickListener as,
String selected = listitems.get(position) ;//or (String)parent.getItemAtPosition(position);
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
intent.putExtra("Key", selected);
startActivity(intent);
I think, switch cases are not needed, since you just want to move to next activity.
And also check your list_item.xml layout since the textview may not be clickable or not be focused.
Add this code snippet of code below listview.setAdapter(adapter) and remove listview.setOnItemClickListener(listener);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ((TextView)view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
and to pass data to next activity you `changeActivity(); should look like this:
public void changeActivity(){
Intent intent = new Intent(currentActivity.this,NextActivity.class);
intent.putString("key","value");
startActivity(intent);
}`

Error On Null Pointer But Still Unsolved on Android Studio

i am a newbie for Android Programming.
Here i have some problem when i want to make an activity (call Category_Setting) that showing list view, but when i switch from main activity to Category_Setting the error report in Android Studio gimme some error like this
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ever_ncn.cashflow/com.example.ever_ncn.cashflow.CategorySetting}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
I have googling for it, asking some friend, but still i even don't know what is my error for.
Please somebody answer my question with simple understanding words.
Thank You..
NB. here is my code for MainActivity.java
public class MainActivity extends Activity implements OnItemSelectedListener {
private static Button BtnINewTrans;
private static Button BtnIViewCash;
private static Button BtnIAddCateg;
Spinner my_Spinner;
DatabaseHelper dbHelper = new DatabaseHelper(this);
//ArrayAdapter<String> adapterCategory;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
my_Spinner = (Spinner)findViewById(R.id.spnCategSelect);
my_Spinner.setOnItemSelectedListener(this);
select_spinner_Category();
onButtonClickButtonListener();
}
/*ArrayList<String> my_array = new ArrayList<String>();
my_array = getTableValues();*/
/*ArrayAdapter my_Adapter = new ArrayAdapter(this, R.layout.spinner_row, my_array);
My_spinner.setAdapter(my_Adapter);*/
public void select_spinner_Category () {
my_Spinner = (Spinner)findViewById(R.id.spnCategSelect);
DatabaseHelper dbH = new DatabaseHelper(getApplicationContext());
List<String> listCategory = dbH.getAllCategory();
ArrayAdapter<String> adapterCategory = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, listCategory);
adapterCategory
.setDropDownViewResource(android.R.layout.simple_spinner_item);
my_Spinner.setAdapter(adapterCategory);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id){
String label = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "You selected "+label,
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
/*ArrayList<String> arrayCategory;
arrayCategory = dbHelper.getAllCategory();
selectCategory = (Spinner) findViewById(R.id.spnCategSelect);
ArrayAdapter adapterCategory = new ArrayAdapter(this, android.R.layout.simple_spinner_item, arrayCategory);
// adapterCategory = new ArrayList<String>(this, android.R.layout.simple_spinner_item, R.id.spnCategSelect, AllCategoryList);
adapterCategory.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selectCategory.setAdapter(adapterCategory);
selectCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), parent.getItemAtPosition(position) + " selected", Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void onButtonClickButtonListener(){
BtnINewTrans = (Button)findViewById(R.id.btnNewTrans);
BtnINewTrans.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentNewTrans = new Intent ("com.example.ever_ncn.cashflow.NewTransaction");
startActivity(intentNewTrans);
}
}
);
BtnIViewCash = (Button)findViewById(R.id.btnViewCashflow);
BtnIViewCash.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentViewCash = new Intent ("com.example.ever_ncn.cashflow.ViewCashflow");
startActivity(intentViewCash);
}
}
);
BtnIAddCateg = (Button)findViewById(R.id.btnAddCateg);
BtnIAddCateg.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentAddCateg = new Intent ("com.example.ever_ncn.cashflow.CategorySetting");
startActivity(intentAddCateg);
}
}
);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this is Category_Setting.java (where i get this error)
public class CategorySetting extends Activity {
private SQLiteDatabase db;
private CursorAdapter currAdapter;
private static Button BtnIAddCateg;
private static Button BtnICancelCateg;
private static final String TAG = CategorySetting.class.getSimpleName();
DatabaseHelper dBHelper = new DatabaseHelper (this);
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onButtonClickButtonListener();
//reload();
}
public void reload(){
listView = (ListView) findViewById(R.id.listViewCateg);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "clicked on item: " + position);
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_category_setting, menu);
return true;
}
public void onButtonClickButtonListener(){
BtnIAddCateg = (Button)findViewById(R.id.btnAddNewCateg);
BtnIAddCateg.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentAddCateg = new Intent ("com.example.ever_ncn.cashflow.AddCategory");
startActivity(intentAddCateg);
}
}
);
BtnICancelCateg = (Button)findViewById(R.id.btnCancelCateg);
BtnICancelCateg.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
}
);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
In this method in Category_Setting.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onButtonClickButtonListener();
//reload();
}
you forgot to load the layout. You should add some code like you used in the MainActivity:
setContentView(R.layout.activity_main);
Right now, the layout is not loaded at all, so
BtnINewTrans = (Button)findViewById(R.id.btnNewTrans);
will return null.

Categories