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..!!
Related
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();
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
when I click delete it doesn't delete or edit the row I created
so my MainActivity is
package com.frolicfreak.bhushan.memo;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import static com.frolicfreak.bhushan.memo.DatabaseHelper.Table_Name;
import static com.frolicfreak.bhushan.memo.DatabaseHelper.col1;
import static com.frolicfreak.bhushan.memo.DatabaseHelper.col2;
public class MainActivity extends AppCompatActivity implements
View.OnClickListener{
FloatingActionButton fab;
DatabaseHelper mydb;
ListView listView;
ArrayAdapter<String> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb =new DatabaseHelper(this);
fab= (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(this);
ListView listView = (ListView)findViewById(R.id.list);
registerForContextMenu(listView);
}
#Override
public void onResume() {
super.onResume();
ArrayList<String> theList =new ArrayList<>();
Cursor data= mydb.getAllData();
listView = (ListView)findViewById(R.id.list);
listView.setAdapter(null);
if (data.getCount()==0){
Toast.makeText(MainActivity.this,"data not inserted",Toast.LENGTH_LONG).show();
}
else
{
while(data.moveToNext()){
theList.add(data.getString(1));
ListAdapter listAdapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,theList);
listView.setAdapter(listAdapter);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId()==R.id.list) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId()) {
case R.id.edit:
// int count= mydb.updaterow(getString(col2),EditText.)
return true;
case R.id.delete:
int count=mydb.deleterow(getString(item.getItemId()));
onResume();
return true;
default:
return super.onContextItemSelected(item);
}
}
#Override
public void onClick(View v) {
Intent intent= new Intent(this,Main2Activity.class);
startActivity(intent);
}
}
My DataBasehelper class
package com.frolicfreak.bhushan.memo;
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.EditText;
import java.util.ArrayList;
/**
* Created by BHUSHAN on 24-08-2017.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String Database_Name = "Memo.db";
public static final String Table_Name = "Memo";
public static final String col1 = "ID";
public static final String col2 = "data";
//DatabaseHelper mydb;
public DatabaseHelper(Context context) {
super(context, Database_Name, null, 1);
//mydb=new DatabaseHelper(context);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + Table_Name + "(ID integer primary key autoincrement, data text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + Table_Name);
onCreate(db);
}
public boolean insertData(String data, String Data) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(col2, Data);
long result = db.insert(Table_Name, null, contentValues);
if (result==-1)
return false;
else
return true;
}
public ArrayList<String> getList(){
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor= db.query(Table_Name,new String[]{col1},new String(col2),null,null,null,null);
while (cursor.moveToNext()){
int index= cursor.getColumnIndex(col1);
taskList.add(cursor.getString(index));
}
cursor.close();
db.close();
return taskList;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM " + Table_Name, null);
return res;
}
public int deleterow(String col1) {
String whereClause = "ID = ?";
String[] whereArgs = {String.valueOf(col1)};
SQLiteDatabase db = this.getWritableDatabase();
int count = db.delete(Table_Name, whereClause, whereArgs);
db.close();
return count;
}
/* public int updaterow(String oldname, String newdata){
SQLiteDatabase db= mydb.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(DatabaseHelper.col2,newdata);
String[] whereargs={oldname};
int count = db.update(Table_Name,cv, DatabaseHelper.col2+"=?" , whereargs);
return count;
}*/
}
my Main2Activity class where I edit and insert data
package com.frolicfreak.bhushan.memo;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Main2Activity extends AppCompatActivity {
DatabaseHelper db;
EditText Data;
FloatingActionButton add;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
db = new DatabaseHelper(this);
Data = (EditText)findViewById(R.id.edit);
add =(FloatingActionButton)findViewById(R.id.add);
AddData();
}
public void AddData(){
add.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted =
db.insertData(Data.getText().toString(),
Data.getText().toString() );
if (isInserted==true)
Toast.makeText(Main2Activity.this,"data
inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(Main2Activity.this,"data not
inserted",Toast.LENGTH_LONG).show();
}
}
);
}
}
please help me I'm new to programming so I'm trying to learn here
thankyou in advance
and I actually need help with editing and saving the data too I wrote the code but I saved it in the comments
Your delete function is working fine according to the code. Check the return is greater than 0 or not.
But you won't be able to see the changes in the ListView because you have to populate the list again.
Set an CursorAdapter since you're using a database to link to the listview and use CursorAdapter.notifyDataSetChanged()
Or create a method that will recreate the listview when a delete occurs.
ArrayList<String> COUNTRIES = new ArrayList<>();
public void refreshView() {
MyDatabase database = new MyDatabase(ViewList.this);
Cursor cursor = database.fetchAllData();
COUNTRIES.clear();
while (cursor.moveToNext()) {
String temp = cursor.getString(cursor.getColumnIndex(database.COL1));
COUNTRIES.add(temp);
}
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, COUNTRIES);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(arrayAdapter);
}
When deleting, you are calling this
int count=mydb.deleterow(getString(item.getItemId()));
onResume();
You are not passing the id of selected item, but you are passing menu item's string fetched by getString(...) method, which is weird. There are so much unused code in your class.
I advice you to work on BaseAdapter and ListView.
It's not a good programming pattern to call onResume() method. You should extract it to different method and call it in onResume().
Anyway, in this case notifyDataSetChanged() is a solution what you are looking for.
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);
}
I am currently working on a small application which allows a persons details to be stored in a database and then retrieved into an EditText field. Currently i am able to store a persons name into the database. But i am having trouble retrieving this data.
Any help anyone can give would be greatly appreciated!
Thanks!
DatabaseHelper.java:
package my.example.com.mymedicare;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, "user.db", null, 4);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE Users (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , FullName VARCHAR, Email VARCHAR, Number INTEGER, Age INTEGER, Nurse VARCHAR)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS Users");
// Create tables again
onCreate(db);
}
}
SQLHelper.java:
package my.example.com.mymedicare;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class SQLHelper {
Context mContext;
DatabaseHelper dbHelper;
public SQLHelper(Context mContext) {
dbHelper = new DatabaseHelper(mContext);
this.mContext = mContext;
}
public boolean insert(String FullName, int i){
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("FullName", FullName);
db.close();
return true;
}
}
Register.java:
package my.example.com.mymedicare;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Register extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
};
public void btnCreate(View view) {
SQLHelper sqlHelper = new SQLHelper(this);
EditText addName = (EditText) findViewById(R.id.nameText);
sqlHelper.insert(addName.getText().toString(), 0);
Toast.makeText(this, "Your Account Details Have Been Saved", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Register.this, MainMenu.class));
}}
Modify.java:
package my.example.com.mymedicare;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
public class Modify extends AppCompatActivity {
static SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modify);
EditText getName=(EditText)findViewById(R.id.nameText);
}
}
Follow this step.
put this method in SQLHelper.java file.
public ArrayList<String> fetch_Edittext() {
ArrayList<String> arr_ = new ArrayList<String>();
String selectQuery = "Select * FROM " + TABLE_SCANITEMS + " ORDER BY id";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
arr_.add(cursor.getString(0));
} while (cursor.moveToNext());
}
db.close();
return arr_;
}
put this class in your modify java class
private class GetEdittext extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// dialog start
Log.e("Currency", "3");
}
#Override
protected Void doInBackground(Void... arg0) {
ArrayList<String> arr_ = new ArrayList<String>();
arr_ = db.fetch_Edittext();
return null;
}
#Override
protected void onPostExecute(Void resul) {
super.onPostExecute(resul);
// dialog dismiss
//hear set your edit text
}
}
then call this class at on create method like.
new GetEdittext().execute();