Null pointer exception in android java sqlite [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
Now I trying to create a book app using sqlite and this is my first time to using it.
but there are a problem when i get the data from the cursor.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ar.team.company.app.ar_app_08, PID: 18302
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ar.team.company.app.ar_app_08/com.ar.team.company.app.ar_app_08.HomeActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor com.ar.team.company.app.ar_app_08.controller.ARDatabaseHelper.getBooks()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
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:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor com.ar.team.company.app.ar_app_08.controller.ARDatabaseHelper.getBooks()' on a null object reference
at com.ar.team.company.app.ar_app_08.HomeActivity.storeDataInArray(HomeActivity.java:58)
at com.ar.team.company.app.ar_app_08.HomeActivity.onCreate(HomeActivity.java:39)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
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:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
HomeActivity:
package com.ar.team.company.app.ar_app_08;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.ar.team.company.app.ar_app_08.adapters.BooksAdapter;
import com.ar.team.company.app.ar_app_08.controller.ARDatabaseHelper;
import com.ar.team.company.app.ar_app_08.databinding.ActivityHomeBinding;
import com.ar.team.company.app.ar_app_08.model.Book;
import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
#SuppressWarnings("FieldCanBeLocal")
public class HomeActivity extends AppCompatActivity {
// This For Control The XML-Main Views:
private ActivityHomeBinding binding;
private ARDatabaseHelper helper;
private BooksAdapter adapter;
private ArrayList<Book> books;
private ArrayList<String> id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityHomeBinding.inflate(getLayoutInflater()); // INFLATE THE LAYOUT.
View view = binding.getRoot(); // GET ROOT [BY DEF(CONSTRAINT LAYOUT)].
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
setContentView(view); // SET THE VIEW CONTENT TO THE (VIEW).
// Store the data:
storeDataInArray();
// Initialize:
helper = new ARDatabaseHelper(this);
books = new ArrayList<>();
id = new ArrayList<>();
adapter = new BooksAdapter(this, books, id, binding.parentHomeLayout);
// Developing the new activity fab:
binding.newBookFloatingActionButton.setOnClickListener(this::launchNewBookActivity);
// Developing the recycler view:
binding.booksRecyclerView.setAdapter(adapter);
binding.booksRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
private void launchNewBookActivity(View view) {
Intent newBookActivity = new Intent(this, NewBookActivity.class);
startActivity(newBookActivity);
}
private void storeDataInArray() {
Cursor cursor = helper.getBooks();
if (cursor.getCount() == 0) {
Snackbar.make(binding.parentHomeLayout, "No data.", Snackbar.LENGTH_LONG)
.setAction("Close", v -> Log.i("SnackBar_Click", "Closed")).show();
}else {
cursor.moveToFirst();
while (cursor.moveToNext()) {
String bookID = cursor.getString(0);
String bookTitle = cursor.getString(1);
String bookAuthor = cursor.getString(2);
int bookPages = Integer.parseInt(cursor.getString(3));
books.add(new Book(bookTitle, bookAuthor, bookPages));
id.add(bookID);
}
}
}
}
NewBookActivity:
package com.ar.team.company.app.ar_app_08;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.ar.team.company.app.ar_app_08.controller.ARDatabaseHelper;
import com.ar.team.company.app.ar_app_08.databinding.ActivityNewBookBinding;
import com.ar.team.company.app.ar_app_08.model.Book;
import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
import java.util.Objects;
#SuppressWarnings("FieldCanBeLocal")
public class NewBookActivity extends AppCompatActivity {
// This For Control The XML-Main Views:
private ActivityNewBookBinding binding;
private ARDatabaseHelper helper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityNewBookBinding.inflate(getLayoutInflater()); // INFLATE THE LAYOUT.
View view = binding.getRoot(); // GET ROOT [BY DEF(CONSTRAINT LAYOUT)].
setContentView(view); // SET THE VIEW CONTENT TO THE (VIEW).
// Initialize:
helper = new ARDatabaseHelper(this);
// Developing the new book button:
binding.newBookButton.setOnClickListener(this::createNewBook);
}
private void createNewBook(View view) {
String bookTitle = Objects.requireNonNull(binding.bookTitleEditText.getText()).toString();
String bookAuthor = Objects.requireNonNull(binding.bookAuthorEditText.getText()).toString();
int bookPages = Integer.parseInt(Objects.requireNonNull(binding.bookPagesEditText.getText()).toString());
Book book = new Book(bookTitle, bookAuthor, bookPages);
helper.newBook(book, binding.parentNewBookLayout);
}
}
BooksAdapter:
package com.ar.team.company.app.ar_app_08.adapters;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;
import com.ar.team.company.app.ar_app_08.R;
import com.ar.team.company.app.ar_app_08.model.Book;
import com.google.android.material.card.MaterialCardView;
import com.google.android.material.snackbar.Snackbar;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
public class BooksAdapter extends RecyclerView.Adapter<BooksAdapter.ViewHolder> {
private final Context context;
private final ArrayList<Book> books;
private final ArrayList<String> id;
private final ConstraintLayout layout;
public BooksAdapter(Context context, ArrayList<Book> books, ArrayList<String> id, ConstraintLayout layout) {
this.context = context;
this.books = books;
this.id = id;
this.layout = layout;
notifyDataSetChanged();
}
#NotNull
#Override
public ViewHolder onCreateViewHolder(#NonNull #NotNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.books_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull #NotNull BooksAdapter.ViewHolder holder, int position) {
holder.id.setText(id.get(position));
holder.title.setText(books.get(position).getBookTitle());
holder.author.setText(books.get(position).getBookAuthor());
holder.pages.setText(books.get(position).getBookPages());
holder.cardView.setOnClickListener(v -> {
Snackbar.make(layout, books.get(position).getBookTitle(), Snackbar.LENGTH_LONG)
.setAction("Close", v1 -> Log.i("SnackBar_Click", "Closed")).show();
});
}
#Override
public int getItemCount() {
return books.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private final MaterialCardView cardView;
private final TextView id, title, author, pages;
public ViewHolder(#NonNull #org.jetbrains.annotations.NotNull View itemView) {
super(itemView);
cardView = itemView.findViewById(R.id.cardView);
id = itemView.findViewById(R.id.book_id_text_view);
title = itemView.findViewById(R.id.book_title_text_view);
author = itemView.findViewById(R.id.book_author_text_view);
pages = itemView.findViewById(R.id.book_pages_text_view);
}
}
}
ARDatabaseHelper:
package com.ar.team.company.app.ar_app_08.controller;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.ar.team.company.app.ar_app_08.model.Book;
import com.ar.team.company.app.ar_app_08.utils.ARUtils;
import com.google.android.material.snackbar.Snackbar;
public class ARDatabaseHelper extends SQLiteOpenHelper {
private final Context context;
public ARDatabaseHelper(#Nullable Context context) {
super(context, ARUtils.DATABASE_FILE_NAME, null, ARUtils.DATABASE_VERSION);
this.context = context;
}
public Context getContext() {
return context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String tN = ARUtils.DATABASE_TABLE_NAME;
String id = ARUtils.COLUMN_ID;
String bT = ARUtils.COLUMN_TITLE;
String bA = ARUtils.COLUMN_AUTHOR;
String bP = ARUtils.COLUMN_PAGES;
String query = "CREATE TABLE " + tN +
"(" + id + " INTEGER PRIMARY KEY AUTOINCREMENT, " + bT + " TEXT, " + bA + " TEXT, " + bP + " TEXT )";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + ARUtils.DATABASE_TABLE_NAME);
onCreate(db);
}
public void newBook(Book book, ConstraintLayout layout) {
// Initialize database:
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
// Put the values:
values.put(ARUtils.COLUMN_TITLE, book.getBookTitle());
values.put(ARUtils.COLUMN_AUTHOR, book.getBookAuthor());
values.put(ARUtils.COLUMN_PAGES, book.getBookPages());
// Finishing:
long res = db.insert(ARUtils.DATABASE_TABLE_NAME, null, values);
if (res == -1) showSnackBar("Failed to create new book.", layout);
else showSnackBar("Successfully created new book.", layout);
}
public Cursor getBooks() {
// Initialize database:
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
if (db != null) {
cursor = db.rawQuery("SELECT * FROM " + ARUtils.DATABASE_TABLE_NAME, null);
}
return cursor;
}
public void showSnackBar(String mes, ConstraintLayout layout) {
Snackbar.make(layout, mes, Snackbar.LENGTH_LONG)
.setAction("Close", v -> Log.i("SnackBar_Click", "Closed")).show();
}
}

You are calling the storeDataInArray method before getting (initialising) the helper instance so helper is null.
So when the attempt is made to execute the line Cursor cursor = helper.getBooks(); you get the NPE because helper is null. The log is telling you this when it says :-
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor com.ar.team.company.app.ar_app_08.controller.ARDatabaseHelper.getBooks()' on a null object reference
at com.ar.team.company.app.ar_app_08.HomeActivity.storeDataInArray(HomeActivity.java:58)
Instead of :-
// Store the data:
storeDataInArray();
// Initialize:
helper = new ARDatabaseHelper(this);
use :-
// Initialize:
helper = new ARDatabaseHelper(this);
// Store the data:
storeDataInArray();

Related

SQLite Cursor initializing as -1 and causing error

hoping someone can help me figure this issue out. I'm trying to build an app in Android Studio for school and am running into an issue when trying to get it to load results from a database using a cursor. I keep getting the error message that the cursor is initialized at -1 and it can't access column 0. Any ideas what might be causing it? Code is below along with error message:
Main Activity:
package com.example.lab2;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.the_button);
EditText input = findViewById(R.id.edittext);
Switch urgent = findViewById(R.id.the_switch);
dbOpener dbOpener = new dbOpener(MainActivity.this);
Cursor cursor;
ListView thisList = (ListView) findViewById(R.id.listview);
AlertDialog.Builder alertDIalogBuilder = new AlertDialog.Builder(this);
ArrayList<toDoItem> arrayList = new ArrayList<toDoItem>();
class MyAdapter extends BaseAdapter {
private Context context;
private ArrayList<toDoItem> items;
public MyAdapter(Context context, ArrayList<toDoItem> items) {
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View mainView = LayoutInflater.from(context).inflate(R.layout.activity_main_todolayout, parent, false);
LayoutInflater inflater = getLayoutInflater();
if(mainView == null) {
mainView = inflater.inflate(R.layout.activity_main_todolayout, parent, false);
}
TextView itemView = mainView.findViewById(R.id.to_do_items);
itemView.setText((arrayList.get(position).getToDoName().toString()));
if(arrayList.get(position).geturgent() == true) {
mainView.setBackgroundColor(Color.RED);
itemView.setTextColor(Color.WHITE);
}
return mainView;}
};
MyAdapter adapter = new MyAdapter(this, arrayList);
thisList.setAdapter(adapter);
urgent.setChecked(false);
urgent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View V) {
urgent.setChecked(true);
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String holder = input.getText().toString();
arrayList.add (new toDoItem(holder, urgent.isChecked()));
input.getText().clear();
adapter.notifyDataSetChanged();
int urgentStatus = 0;
if(urgent.isChecked() == true) {
urgentStatus = 1;
} else {
urgentStatus = 0;
}
dbOpener.addItem(holder, urgentStatus);
urgent.setChecked(false);
}
});
thisList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
String title = getString(R.string.alert_dialogue_title);
String message = getString(R.string.alert_dialogue_message);
String pos_button = getString(R.string.pos_button);
String neg_button = getString(R.string.neg_button);
alertDIalogBuilder.setTitle(title);
alertDIalogBuilder.setMessage(message + " " + position);
alertDIalogBuilder.setPositiveButton(pos_button, (click, arg) -> {
arrayList.remove(position);
adapter.notifyDataSetChanged();
});
alertDIalogBuilder.setNegativeButton(neg_button, (click, arg) -> {
});
alertDIalogBuilder.create();
alertDIalogBuilder.show();
return false;
}
});
cursor = dbOpener.readData();
int nameColIndex = cursor.getColumnIndex("COL_ITEM_NAME");
int urgentColIndex = cursor.getColumnIndex("COL_URGENT");
int idColIndex = cursor.getColumnIndex("COL_ID");
for(int i = 0; i < cursor.getCount(); i++) {
String name = cursor.getString(nameColIndex);
int urgentHolder = cursor.getInt(urgentColIndex);
long id = cursor.getLong(idColIndex);
boolean converter = false;
if(urgentHolder == 1) {
converter = true;
} else {
converter = false;
}
arrayList.add(new toDoItem(name, converter));
}
}
}
Database Opener:
package com.example.lab2;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
public class dbOpener extends SQLiteOpenHelper {
protected final static String DATABASE_NAME = "toDoListDB";
protected final static int VERSION_NUM = 1;
public final static String TABLE_NAME = "TO_DO_ITEMS";
public final static String COL_ITEM_NAME = "ITEM";
public final static String COL_URGENT = "URGENT";
public final static String COL_ID = "_id";
private Context ctx;
String [] columns = {dbOpener.COL_ITEM_NAME, dbOpener.COL_ITEM_NAME, dbOpener.COL_URGENT};
public dbOpener(Context ctx) {super(ctx, DATABASE_NAME, null, VERSION_NUM);
this.ctx = ctx;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_ITEM_NAME
+ " TEXT," + COL_URGENT + " INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
void addItem(String itemName, int urgent) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cnt = new ContentValues();
cnt.put(COL_ITEM_NAME, itemName);
cnt.put(COL_URGENT, urgent);
long result = db.insert(TABLE_NAME, null, cnt);
if(result == -1) {
Toast.makeText(ctx, "Failure", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ctx, "Success", Toast.LENGTH_SHORT).show();
}
}
Cursor readData() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor results = db.rawQuery("SELECT * from " + TABLE_NAME, null);
return results;
}
}
Error message:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.lab2, PID: 15645
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lab2/com.example.lab2.MainActivity}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 3
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
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)
Caused by: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 3
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:468)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at com.example.lab2.MainActivity.onCreate(MainActivity.java:152)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
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/Process: Sending signal. PID: 15645 SIG: 9
Disconnected from the target VM, address: 'localhost:49568', transport: 'socket'
You've defined your schema with these constants:
public final static String TABLE_NAME = "TO_DO_ITEMS";
public final static String COL_ITEM_NAME = "ITEM";
public final static String COL_URGENT = "URGENT";
public final static String COL_ID = "_id";
But you're using the names of the constants here rather than their values:
int nameColIndex = cursor.getColumnIndex("COL_ITEM_NAME");
int urgentColIndex = cursor.getColumnIndex("COL_URGENT");
int idColIndex = cursor.getColumnIndex("COL_ID");
In other words, in MainActivity, do this:
int nameColIndex = cursor.getColumnIndex(dbOpener.COL_ITEM_NAME);
int urgentColIndex = cursor.getColumnIndex(dbOpener.COL_URGENT);
int idColIndex = cursor.getColumnIndex(dbOpener.COL_ID);
Also, classes start with capital letters. You should rename dbOpener to DbOpener.
In your cursor-reading for loop, you need to move the cursor in order to iterate over the result set. An easy fix there would be to change
for(int i = 0; i < cursor.getCount(); i++) {
to
while(cursor.moveToNext()) {
There are other issues in your code such as the one pointed out by Gavin Wright in his answer. Missing moveTo...() is the reason for the crash you've reported.

RecyclerView error : what makes widget null?

This is my error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.blogapp, PID: 20085
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.together.adapter.PetchingBunyangAdapter$2.onDataChange(PetchingBunyangAdapter.java:152)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##17.0.0:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##17.0.0:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##17.0.0:55)
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 know what meaning of null but in this case i can not under stand
i try to using recycler in my fragment
This is my adapater that can't find widget
package com.example.together.adapter;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
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.bumptech.glide.Glide;
import com.example.together.R;
import com.example.together.activities.petching.PetchingBunyangDetailInfo;
import com.example.together.common.Common;
import com.example.together.model.PetchingBunyang;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.List;
public class PetchingBunyangAdapter extends RecyclerView.Adapter<PetchingBunyangAdapter.MyViewHolder> {
private static final String TAG = "PetchingBunyangAdapter";
FirebaseUser firebaseUser;
DatabaseReference reference;
Context mContext;
List<PetchingBunyang> mPetchingBunyang;
public PetchingBunyangAdapter(Context mContext, List<PetchingBunyang> mPetchingBunyang) {
this.mContext = mContext;
this.mPetchingBunyang = mPetchingBunyang;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_petching_bunyang_pet_list, parent, false);
return new PetchingBunyangAdapter.MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder viewHolder, int position)
{
Common common = new Common();
final PetchingBunyang petchingBunyang = mPetchingBunyang.get(position);
petchingBunyang.getPetBunyangId();
Log.d(TAG, "AAAAAA"+mPetchingBunyang.get(0).getPetBunyangId());
Log.d(TAG, "TTTT "+petchingBunyang.getPetBunyangId());
Log.d(TAG, "onBindViewHolder: "+Log.d(TAG, "onBindViewHolder: "));
Log.d(TAG, "onBindViewHolder: 초코우유"+mPetchingBunyang.get(0).getPetBunyangId());
Log.d(TAG, "딸기우유: "+mPetchingBunyang.get(position).getPetBunyangId());
getPetInfo(mPetchingBunyang.get(position).getPetBunyangId(), viewHolder.img_pet, viewHolder.petName, viewHolder.petAge, viewHolder.petBreed, viewHolder.gender_m, viewHolder.gender_w);
viewHolder.itemView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(mContext, PetchingBunyangDetailInfo.class);
// 디테일 정보 전달....
intent.putExtra("petname", mPetchingBunyang.get(position).getPetName());
intent.putExtra("intro", mPetchingBunyang.get(position).getPetAge());
intent.putExtra("Thumbnail", mPetchingBunyang.get(position).getPetBreed());
// start the activity
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount()
{
return mPetchingBunyang.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder
{
public TextView petName, petBreed, petAge;
public ImageView gender_m, gender_w, bunyangpet_detail, img_pet;
public MyViewHolder(View itemView)
{
super(itemView);
//펫 프로필
petName = itemView.findViewById(R.id.petName);
petBreed = itemView.findViewById(R.id.petBreed);
petAge = itemView.findViewById(R.id.petAge);
img_pet = itemView.findViewById(R.id.img_pet);
//이미지들
img_pet = itemView.findViewById(R.id.img_pet);
gender_m = itemView.findViewById(R.id.gender_m);
gender_w = itemView.findViewById(R.id.gender_w);
//상세보기 넘어가는 icon
bunyangpet_detail = itemView.findViewById(R.id.bunyangpet_detail);
}
}
// 펫 정보 이름, 나이, 견종, 성별,
private void getPetInfo(String petbunyangid, final ImageView imageView, final TextView petAge, final TextView petName, final TextView petBreed, final ImageView gender_m, final ImageView gender_w)
{
Log.d(TAG, "펫분양: "+petbunyangid);
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("PetchingBunyang").child(petbunyangid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
PetchingBunyang petchingBunyang = dataSnapshot.getValue(PetchingBunyang.class);
Log.d(TAG, "펫정보 가져오는지 보자: "+petchingBunyang.getPetName());
Glide.with(mContext).load(petchingBunyang.getPetImg()).into(imageView);
petName.setText(petchingBunyang.getPetName());
petBreed.setText(petchingBunyang.getPetBreed());
petAge.setText(petchingBunyang.getPetAge());
//성별표시
if (petchingBunyang.getPetGender().equals("Female"))
{
gender_w.setVisibility(View.VISIBLE);
}else
{
gender_m.setVisibility(View.VISIBLE);
}
//
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
but i already get the widget as u see from here
From here i already added widget
public class MyViewHolder extends RecyclerView.ViewHolder{}
I don't understand what makes it null? eventhough it already exist
Try debugging these value , as one of the value might be coming null .
petchingBunyang.getPetName();
petchingBunyang.getPetBreed();
petchingBunyang.getPetAge()
and do check if Pet Age is String or not .

Android Sqlite can't get records from Listview

I am writing a program that saves to DB and then get infos from the DB using SQLiteOpenHelper.
Problem is I insert text from the edit text but I got nothing to show.
is the problem from the listview? cuz I extend from ArrayAdapter class not from enter code hereCursor adapter? or there is something wrong with my code. Please take a look at my code this is my main Acitvity
package com.perfectapps.fasaven.dbnews;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import DBHelper.DBContract;
import DBHelper.DBModel;
import newsAdapter.NewsMainMenuAdapter;
public class MainActivity extends AppCompatActivity {
Button submitNews;
ListView newsListView;
ArrayList<DBModel> dbmodel = new ArrayList<DBModel>();
EditText titleEditText;
TextView tvTitle;
TextView tvInfo;
EditText infoEditText;
DBContract dbContract;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvTitle =(TextView)findViewById(R.id.tvTitle);
tvInfo =(TextView)findViewById(R.id.tvInfo);
submitNews = (Button)findViewById(R.id.submit_news);
newsListView = (ListView)findViewById(R.id.lvNews);
titleEditText = (EditText)findViewById(R.id.etNews);
infoEditText = (EditText)findViewById(R.id.etNewsInfo);
dbContract = new DBContract(this,null,null,1);
NewsMainMenuAdapter customeAdapter = new NewsMainMenuAdapter(getApplicationContext(), R.layout.row_news_element,dbmodel);
newsListView.setAdapter(customeAdapter);
// printDataBase();
submitNews.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DBModel dbModel = new DBModel();
dbModel.setNewsInfos(infoEditText.getText().toString());
dbModel.setNewsTitle(titleEditText.getText().toString());
dbContract.addNews(dbModel);
Toast.makeText(getApplicationContext(),"saved to DB", Toast.LENGTH_LONG ).show();
titleEditText.setText("");
infoEditText.setText("");
// printDataBase();
}
});
}
public void printDataBase(){
DBModel dbModel = new DBModel();
String dbToStringTitle = dbContract.readNewsTitle();
tvTitle.setText(dbToStringTitle);
titleEditText.setText("");
String dbToStringInfo =dbContract.readNewsInfo();
tvInfo.setText(dbToStringInfo);
infoEditText.setText("");
}
}
This is my custom Adapter
package newsAdapter;
import android.support.annotation.LayoutRes;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import DBHelper.*;
import com.perfectapps.fasaven.dbnews.*;
import java.util.ArrayList;
/**
* Created by Salem on 22/12/2017.
*/
public class NewsMainMenuAdapter extends ArrayAdapter{
Context context;
ArrayList<DBModel> newsData;
int resource;
public NewsMainMenuAdapter(#NonNull Context context, #LayoutRes int resource, #NonNull ArrayList<DBModel> newsData) {
super(context, resource, newsData);
this.context =context;
this.newsData = newsData;
this.resource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.row_news_element,null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.tvInfo = (TextView)convertView.findViewById(R.id.tvInfo);
viewHolder.tvTitle = (TextView)convertView.findViewById(R.id.tvTitle);
viewHolder.tvTitle.setText(newsData.get(position).getNewsTitle());
viewHolder.tvInfo.setText(newsData.get(position).getNewsInfos());
//return super.getView(position, convertView, parent);
return convertView;
}
//#Nullable
// #Override
// public DBModel getItem(int position) {
// return super.getItem(position);
//}
class ViewHolder{
TextView tvTitle;
TextView tvInfo;
}
}
Here is my DB helper
package DBHelper;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Salem on 22/12/2017.
*/
public class DBContract extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static final String DB_NAME = "newsDB.db";
public static final String TABLE_NAME = "news";
public static final String COLUMN_ID = "_ID";
public static final String COLUMN_NEWS_TITLE = "newstitle";
public static final String COLUMN_NEWS_IMAGE = "newsimage";
public static final String COLUMN_NEWS_INFO= "newsinfo";
public DBContract(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DB_NAME, factory, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE "+ TABLE_NAME + " ("
+COLUMN_ID+ " INTEGER PRIMARY KEY AUTOINCREMENT , "
+COLUMN_NEWS_TITLE+ " TEXT ,"
+COLUMN_NEWS_INFO+ " TEXT );";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME );
onCreate(db);
}
public void addNews(DBModel dbModel){
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_NEWS_TITLE, dbModel.getNewsTitle());
contentValues.put(COLUMN_NEWS_INFO, dbModel.getNewsInfos());
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
sqLiteDatabase.close();
}
public String readNewsTitle(){
String readNews = "";
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT "+COLUMN_NEWS_TITLE+" FROM "+TABLE_NAME +" where 1";
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
if(cursor.getString(cursor.getColumnIndex(COLUMN_NEWS_TITLE))!=null);
{
readNews += cursor.getString(cursor.getColumnIndex(COLUMN_NEWS_TITLE));
readNews +="\n";
}
cursor.moveToNext();
}
sqLiteDatabase.close();
return readNews;
}
public String readNewsInfo(){
String readNewsInfo="";
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT "+COLUMN_NEWS_INFO+" FROM "+TABLE_NAME ;
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
if(cursor.getString(cursor.getColumnIndex(COLUMN_NEWS_INFO))!=null);
{
readNewsInfo += cursor.getString(cursor.getColumnIndex(COLUMN_NEWS_INFO));
readNewsInfo +="\n";
}
cursor.moveToNext();
}
sqLiteDatabase.close();
return readNewsInfo;
}
}
There is one 4th class that has setters and getters named DBModel
and got XML for main activity which has listview.. but it when I input from edit text it doesn't show there

Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a nullobjectreference

I am trying to fetch some data from my sqlite database-> displaying it in RecyclerView -> and on tapping an item I want to start a new activity.
But after displaying the list of items when i tap on one of them the following error pops up:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
My mainActivityClass:
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.Toast;
import com.example.blue2dew.trakin.Item.item;
import com.example.blue2dew.trakin.MovieAdapter;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mtoggle;
private NavigationView navigationView;
private Toolbar toolbar;
private Movie_det movie_det;
Context context;
private RecyclerView recyclerView;
private DatabaseHelper databaseHelper;
ArrayList<item> arrayList=new ArrayList<item>();
private Cursor cursor;
private MovieAdapter movieAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout=(DrawerLayout) findViewById(R.id.activity_main);
navigationView=(NavigationView)findViewById(R.id.navigation_view);
toolbar=(Toolbar)findViewById(R.id.nav_action);
setSupportActionBar(toolbar);
mtoggle=new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
recyclerView=(RecyclerView)findViewById(R.id.recycler_view);
mDrawerLayout.addDrawerListener(mtoggle);
mtoggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
item.setChecked(true);
mDrawerLayout.closeDrawers();
return false;
}
});
loadDatabase();
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
if(mtoggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
public void loadDatabase(){
databaseHelper=new DatabaseHelper(MainActivity.this);
try{
databaseHelper.checkAndCopyDatabase();
databaseHelper.openDatabase();
}catch(SQLiteException e){
e.printStackTrace();
}
try {
cursor = databaseHelper.QueryData("select * from movieDetails");
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
item itemv = new item();
itemv.setMovieName(cursor.getString(2));
itemv.setReleaseDate(cursor.getString(5));
itemv.setMovieImage(cursor.getBlob(1));
arrayList.add(itemv);
} while (cursor.moveToNext());
}
}
}catch (SQLiteException e){
e.printStackTrace();
}
LinearLayoutManager linearLayoutManager=new LinearLayoutManager(getApplicationContext());
movieAdapter=new MovieAdapter(MainActivity.this,context,arrayList);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(movieAdapter);
}
}
My Adapter class:
package com.example.blue2dew.trakin;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
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.example.blue2dew.trakin.Item.item;
import java.util.Collections;
import java.util.List;
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieViewHolder> {
Activity activity;
List<item> items= Collections.emptyList();
Context context;
public MovieAdapter(Activity activity,Context context, List<item> items){
this.activity=activity;
this.context=context;
this.items=items;
}
#Override
public MovieViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_list_item,parent,false);
MovieViewHolder movieViewHolder=new MovieViewHolder(view,context,items);
return movieViewHolder;
}
public void onBindViewHolder(MovieViewHolder holder,final int position) {
holder.movie_name.setText(items.get(position).getMovieName());
holder.release_date.setText(items.get(position).getReleaseDate());
holder.imageView.setImageBitmap(items.get(position).getMovieImage());
}
#Override
public int getItemCount() {
return items.size();
}
public class MovieViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView md_image;
TextView md_movie_name;
TextView md_length1;
TextView md_genre1;
TextView md_release_date1;
ImageView md_imdb_icon;
TextView md_rating1;
TextView md_director1;
TextView md_synopsis1;
TextView movie_name;
TextView release_date;
ImageView imageView;
List<item> items=Collections.emptyList();
Context context;
public MovieViewHolder(View itemView,Context context,List<item> items ) {
super(itemView);
this.context=context;
this.items=items;
itemView.setOnClickListener(this);
md_image = (ImageView) itemView.findViewById(R.id.md_image);
md_director1 = (TextView) itemView.findViewById(R.id.md_director1);
md_genre1 = (TextView) itemView.findViewById(R.id.md_genre1);
md_movie_name = (TextView) itemView.findViewById(R.id.md_movie_name);
md_length1 = (TextView) itemView.findViewById(R.id.md_length1);
md_release_date1 = (TextView) itemView.findViewById(R.id.md_release_date1);
md_rating1 = (TextView) itemView.findViewById(R.id.md_rating1);
md_synopsis1 = (TextView)itemView.findViewById(R.id.md_synopsis1);
md_imdb_icon = (ImageView) itemView.findViewById(R.id.md_imdb_icon);
movie_name=(TextView) itemView.findViewById(R.id.movie_name);
release_date=(TextView) itemView.findViewById(R.id.release_date);
imageView=(ImageView) itemView.findViewById(R.id.imageView);
}
#Override
public void onClick(View v) {
int position=getAdapterPosition();
item item=this.items.get(position);
Intent intent=new Intent (this.context,Main2Activity.class);
this.context.startActivity(intent);
}
}
}
My databaseHelper class:
package com.example.blue2dew.trakin;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class DatabaseHelper extends SQLiteOpenHelper {
private static String DB_Name="movie.db";
private static String DB_Path;
private SQLiteDatabase mydatabase;
private final Context mycontext;
public DatabaseHelper(Context context) {
super(context,DB_Name , null, 1);
if(Build.VERSION.SDK_INT>=15){
DB_Path=context.getApplicationInfo().dataDir+"/databases/";
}
else{
DB_Path= Environment.getDataDirectory()+"/data/"+context.getPackageName()+"/databases/";
}
this.mycontext=context;
}
#Override
public void onCreate(SQLiteDatabase db) {
//using existing database so creation not needed
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//the existing database need not be upgraded
}
public void checkAndCopyDatabase(){
boolean dbExist=checkDatabase();
if(dbExist){
Log.d("TAG","database already exists");
}
else {
this.getReadableDatabase();
}
try {
copyDatabase();
}
catch (IOException e){
e.printStackTrace();
Log.d("TAG","Error Copy Database");
}
}
public boolean checkDatabase(){
SQLiteDatabase checkDB=null;
try {
String mypath = DB_Path + DB_Name;
checkDB = SQLiteDatabase.openDatabase(mypath, null, SQLiteDatabase.OPEN_READWRITE);
}catch (SQLiteException e) {
e.printStackTrace();
}
if(checkDB!=null){
checkDB.close();
}
return checkDB!=null?true:false;
}
public void copyDatabase() throws IOException{
InputStream myInput=mycontext.getAssets().open(DB_Name);
String outfilename=DB_Path+DB_Name;
OutputStream myOutput=new FileOutputStream(outfilename);
byte[] buffer=new byte[1024];
int length;
while ((length=myInput.read(buffer))>0){
myOutput.write(buffer,0,length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDatabase(){
String myPath=DB_Path+DB_Name;
mydatabase=SQLiteDatabase.openDatabase(myPath,null, SQLiteDatabase.OPEN_READWRITE);
}
public synchronized void close(){
if(mydatabase!=null){
mydatabase.close();
}
super.close();
}
public Cursor QueryData(String query){
return mydatabase.rawQuery(query,null);
}
}
The error:
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.blue2dew.trakin, PID: 7430 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ComponentName.(ComponentName.java:128)
at android.content.Intent.(Intent.java:4521) at com.example.blue2dew.trakin.MovieAdapter$MovieViewHolder.onClick(MovieAdapter.java:127)
at android.view.View.performClick(View.java:5209)
at android.view.View$PerformClick.run(View.java:21179)
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:5437)
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 can either do this,
#Override
public void onClick(View v) {
int position=getAdapterPosition();
item item=this.items.get(position);
Intent intent=new Intent (v.getContext(),Main2Activity.class);
v.getContext().startActivity(intent);
}

search and retrieve the result in list-android

I am trying to search and retrieve the result in list view from sqlite database. When I try to search, the app closed.
Logcat
04-20 11:50:56.550 2297-2297/com.example.asus.myapplication3.app
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.asus.myapplication3.app, PID: 2297
java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase
com.example.asus.myapplication3.app.dbtry$DatabaseHelper.getReadableDatabase()'
on a null object reference
at com.example.asus.myapplication3.app.searchActivity$1.onClick(searchActivity.java:62)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Code
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.net.ContentHandler;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class ListAdapter extends ArrayAdapter {
List list= new ArrayList();
static class layoutHandler
{
TextView nameText;
}
public ListAdapter(Context context, int resource)
{
super(context, resource);
}
#Override
public void add (Object object){
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position)
{
return list.get(position);
}
#Override
// retern each row of data
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
layoutHandler layouthandler;
if (row==null){
LayoutInflater layoutInflater =(LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=layoutInflater.inflate(R.layout.result,parent,false);
// row=layoutInflater.inflate(R.layout.listrow,parent,false);
layouthandler=new layoutHandler();
layouthandler.nameText=(TextView)row.findViewById(R.id.nameText);
row.setTag(layouthandler);
}
else
{
layouthandler =(layoutHandler) row.getTag();
}
// return each abject from the list
dataProvider provider=(dataProvider)this.getItem(position);
//assaien each row of data
layouthandler.nameText.setText(provider.getName());
return row;
}
}
public class dataProvider {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public dataProvider(String name) {
this.name = name;
}
}
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class searchActivity extends Activity {
EditText rname;
TextView result;
Button search;
dbtry db;
ListView data;
ListAdapter listAdapter;
String search_name;
SQLiteDatabase sqLiteDatabase;
dbtry.DatabaseHelper dbhlper;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
search = (Button) findViewById(R.id.search);
rname = (EditText) findViewById(R.id.rname);
data = (ListView) findViewById(R.id.data);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// setContentView(R.layout.result);
search_name = rname.getText().toString();
//db = new dbtry(getBaseContext());
sqLiteDatabase= dbhlper.getReadableDatabase();
Log.e("the app search ","dbhlper");
db.open();
Cursor d = db.returndata(search_name, sqLiteDatabase);
Log.e("the app search ","yah!");
listAdapter = new ListAdapter(getApplicationContext(), R.layout.listrow);
data.setAdapter(listAdapter);
data.setVisibility(View.GONE);
if (d.moveToFirst()) {
do {
String result_search;
result_search = d.getString(0);
//adding data to adapter
dataProvider provider = new dataProvider(result_search);
listAdapter.add(provider);
Log.e("the app search ","good");
} while (d.moveToNext());
}
// startActivity( new Intent(searchActivity.this, resultActivity.class));
}
}); }}
package com.example.asus.myapplication3.app;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.sql.SQLException;
public class dbtry {
public static int _id;
public static final String ecapp_col_name = "name";
public static final String ecapp_col_discrption = "discrption";
public static final String ecapp_col_ingredant = "ingredant";
// public static final String ecapp_image = "image";
public static final String ecapp_col_Optional_ingredant = "Optional_ingredant";
public static final String TABLE_NAME1 = "recipe";
public static final String TABLE_NAME2 = "ingredant";
public static final String DATABASE_NAME="ecapp";
public static final int DATABASE_VERSION=1;
public static final String DATABASE_create1 = "create"+ TABLE_NAME1+ "("+_id +"int not null auto_increment,"+ecapp_col_name+" text UNIQUE,"+ecapp_col_discrption +"text+ );";
public static final String DATABASE_create2 = "create "+TABLE_NAME2+ "("+ ecapp_col_ingredant+"text ,"+ecapp_col_Optional_ingredant+"text ,"+_id+ "number );";
DatabaseHelper dbh;
Context con;
SQLiteDatabase db2;
public dbtry(Context con)
{
this.con = con;
dbh = new DatabaseHelper(con);
}
public static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper (Context con)
{
super(con,DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_create1);
db.execSQL(DATABASE_create2);
Log.d("db created ", "table2");
}
catch (Exception e) {
e.printStackTrace();
Log.e("db not created ", "bad");
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS ecapp");
onCreate(db);
}
}
public dbtry open()
{
db2= dbh.getWritableDatabase();
return this;
}
public void close()
{
dbh.close();
}
public void insertData(String name, String ingredant, String discrption) {
ContentValues content = new ContentValues();
content.put(ecapp_col_name, name);
Log.e("db created ", "good");
content.put(ecapp_col_ingredant, ingredant);
Log.e("db created ", "good");
content.put(ecapp_col_discrption, discrption);
Log.e("db created ", "good");
db2.insert("ecapp", null, content);
Log.e("db created ", "good");
}
//retrieve
public Cursor returndata(String sname, SQLiteDatabase sqldb)
{
sqldb = dbh.getReadableDatabase();
String selection, selectionArg;
Cursor query;
String[] projection = {ecapp_col_name};
String[] where = {ecapp_col_name};
query = sqldb.query(TABLE_NAME1, projection,sname,null, null, null, null);
// query = sqldb.query( "select"+ecapp_col_name+ "form" +TABLE_NAME1+"where "+ecapp_col_name+"="+sname+;)
Log.e( "get all data:", "query");
return query;
}
}
In your project's searchActivity, inside search.setOnClickListener before initializing sqLiteDatabase= dbhlper.getReadableDatabase(); add these line db = new dbtry(searchActivity.this); to avoid NullPointerException.
Also comment this line sqLiteDatabase= dbhlper.getReadableDatabase(); since you are already using SQLiteDatabase db2; inside open() method here as
public dbtry open()
{
db2= dbh.getWritableDatabase();
return this;
}
So no need for dbHelper & sqliteDatabase inside searchActivity class, just call db.open(). In case you want to read from database create another method read() similar to your open() method inside dbtry class
public dbtry read()
{
db2= dbh.getReadableDatabase();
return this;
}
Usage: db.read(); call this inside your searchActivity only after intializing db.
Happy coding..!!

Categories

Resources