null pointer exception at db insert - android

package com.omkarsoft.ImagePortofolio;
import java.util.ArrayList;
import com.omkarsoft.ImagePortofolio.dataBaseHelper;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class sqlQueries {
dataBaseHelper database;
SQLiteDatabase db ;
UrlList urllist ;
public sqlQueries( dataBaseHelper dbh , SQLiteDatabase db )
{
database = dbh;
this.db = db;
}
public sqlQueries() {
System.out.println("no are sqlqueries constructor");
}
public void insertIntoCompanyTable( String companyname ) {
db = database.getWritableDatabase(); // this works fine here
ContentValues values = new ContentValues();
values.put(dataBaseHelper.COMPANY_NAME, companyname);
System.out.println(values);
db.insert(dataBaseHelper.COMPANY_LIST, null, values);
}
public int getCompanyID( String companyName)
{
int id = 0 ;
Cursor c = null;
try {
db = database.getReadableDatabase(); // this works fine here
String query = "SELECT company_id FROM company_list WHERE company_name = '"+ companyName +"'";
c = db.rawQuery(query,null);
} catch (Exception e) {
System.out.println("In getCompanyID : " +e);
}
if (c != null ) {
if (c.moveToFirst()) {
id = c.getInt(c.getColumnIndex("company_id"));
}
}
return id;
}
public int getCompanies( String comp) {
int id = 0;
Cursor c = null;
ArrayList<String> names = new ArrayList<String>();
try {
db = database.getReadableDatabase(); // this works fine here
String query = "SELECT * FROM company_list ";
c = db.rawQuery(query, null);
} catch (Exception e) {
System.out.println(e);
}
if (c != null) {
if (c.getCount() == 0)
id = 1;
else {
if (c.moveToFirst()) {
do {
String name = c.getString(c.getColumnIndex("company_name"));
names.add(name);
} while (c.moveToNext());
}
if( names.contains(comp))
id = 0;
else
id = 1 ;
}
}
return id;
}
public void insertIntoImageTable( int companyid , String productname , String productdesc , byte[] bmp )
{
try
{
db = database.getWritableDatabase(); // blows here i get a NPE
ContentValues values = new ContentValues();
values.put(dataBaseHelper.COMPANY_ID, companyid);
values.put(dataBaseHelper.PRODUCT_NAME, productname);
values.put(dataBaseHelper.PRODUCT_DESCRIPTION, productdesc);
values.put(dataBaseHelper.PRODUCT_IMAGE, bmp);
System.out.println(values);
db.insertOrThrow(dataBaseHelper.IMAGE_DATA, null, values);
System.out.println(values);
}
catch( Exception e)
{
e.printStackTrace();
}
}
}

You need to open the DB for writing first like e.g.
SQLiteDatabase db = tdHelper.getWritableDatabase();
and tdHelper being an instance of
private static class TweetDBOpenHelper extends SQLiteOpenHelper

Just try to logcat every parameter you put in db.insert with String.valueOf(); You'll then see which parameter is null.

Related

Model object is not matching with the database result

After the record iteration, the list key value is mismatching/wrongly shown ! what could be the reason.
Correct data in the database like this is saved (which is correct)
Problem: You can see in this screenshot link, record is a mismatch with columns, e.g the key dayName has wrong value showing , key MenuIcon value is shown on dayName key
the sql lite DAO
/*
* Get the all the exercises by ID asecending order
*/
public LinkedList<ExerciseDetails> getAllExerciseInfo() {
LinkedList<ExerciseDetails> listCompanies = new LinkedList<ExerciseDetails>();
Cursor cursor = mDatabase.query(DBHelper.TABLE_EXERCISE_DETAILS, mAllColumns,
"",
new String[]{}, "order_id", null, "order_id ASC");
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
ExerciseDetails company = cursorToExerciseDetails(cursor);
listCompanies.add(company);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
}
return listCompanies;
}
Full code of DAO for insertion,create table, list object . Please let me know any code you want to see, i will post
public class ExercisesDAO {
public static final String TAG = "ExercisesDAO";
// Database fields
private SQLiteDatabase mDatabase;
private DBHelper mDbHelper;
private Context mContext;
private String[] mAllColumns = {DBHelper.COLUMN_EX_DETAILS_ID,
DBHelper.COLUMN_ROUTINE_ID,
DBHelper.COLUMN_DAY_ID,
DBHelper.COLUMN_EXERCISE_ID,
DBHelper.COLUMN_REPS,
DBHelper.COLUMN_SETS,
DBHelper.COLUMN_TIME_PERSET,
DBHelper.COLUMN_CALORIE_BURN,
DBHelper.COLUMN_RESTTIME_PERSET,
DBHelper.COLUMN_RESTTIME_POST_SET,
DBHelper.COLUMN_ORDER_ID,
DBHelper.COLUMN_EXERCISE_NAME,
DBHelper.COLUMN_TIPS,
DBHelper.COLUMN_YOUTUBE_URL,
DBHelper.COLUMN_WARNINGS,
DBHelper.COLUMN_DISPLAY_ID,
DBHelper.COLUMN_VISIBILITY,
DBHelper.COLUMN_FOR_DATE,
DBHelper.COLUMN_GIF,
DBHelper.COLUMN_DAYNAME
};
public ExercisesDAO(Context context) {
this.mContext = context;
mDbHelper = new DBHelper(context);
// open the database
try {
open();
} catch (SQLException e) {
Log.e(TAG, "SQLException on openning database " + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException {
mDatabase = mDbHelper.getWritableDatabase();
}
public void close() {
mDbHelper.close();
}
public ExerciseDetails createExerciseDetail(String routineId,String dayId,
String exerciseId, String reps,String sets, String timePerset,
String calorieBurn, String resttimePerset, String resttimeAfterex,String order,
String menuName, String tips, String youtubeUrl, String warnings, String displayId,
String visibility, String forDate, String menuIcon, String dayName) {
ExerciseDetails newCompany = null;
try {
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_ROUTINE_ID, routineId);
values.put(DBHelper.COLUMN_DAY_ID, dayId);
values.put(DBHelper.COLUMN_EXERCISE_ID, exerciseId);
values.put(DBHelper.COLUMN_REPS, reps);
values.put(DBHelper.COLUMN_SETS, sets);
values.put(DBHelper.COLUMN_TIME_PERSET, timePerset);
values.put(DBHelper.COLUMN_CALORIE_BURN, calorieBurn);
values.put(DBHelper.COLUMN_RESTTIME_PERSET, resttimePerset);
values.put(DBHelper.COLUMN_RESTTIME_POST_SET, resttimeAfterex);
values.put(DBHelper.COLUMN_ORDER_ID, order);
values.put(DBHelper.COLUMN_EXERCISE_NAME, menuName);
values.put(DBHelper.COLUMN_TIPS, tips);
values.put(DBHelper.COLUMN_YOUTUBE_URL, youtubeUrl);
values.put(DBHelper.COLUMN_WARNINGS, warnings);
values.put(DBHelper.COLUMN_DISPLAY_ID, displayId);
values.put(DBHelper.COLUMN_VISIBILITY, visibility);
values.put(DBHelper.COLUMN_FOR_DATE, forDate);
values.put(DBHelper.COLUMN_GIF, menuIcon);
values.put(DBHelper.COLUMN_DAYNAME, dayName);
long insertId = mDatabase
.insert(DBHelper.TABLE_EXERCISE_DETAILS, null, values);
Cursor cursor = mDatabase.query(DBHelper.TABLE_EXERCISE_DETAILS, mAllColumns,
DBHelper.COLUMN_EX_DETAILS_ID + " = " + insertId, null, null,
null, null);
cursor.moveToFirst();
newCompany = cursorToExerciseDetails(cursor);
cursor.close();
} catch (Exception e) {
Log.e("exception", "exception in CreateFollowing class - " + e);
}
return newCompany;
}
public void executeSqlOnExerciseDetail(String sql) {
mDatabase.execSQL(sql);
}
public Long getTotalCountExerciseDetail() {
return DatabaseUtils.queryNumEntries(mDatabase, DBHelper.TABLE_EXERCISE_DETAILS);
}
/*
* Get the all the exercises by ID asecending order
*/
public LinkedList<ExerciseDetails> getAllExerciseInfo() {
LinkedList<ExerciseDetails> listCompanies = new LinkedList<ExerciseDetails>();
Cursor cursor = mDatabase.query(DBHelper.TABLE_EXERCISE_DETAILS, mAllColumns,
"",
new String[]{}, "order_id", null, "order_id ASC");
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
ExerciseDetails company = cursorToExerciseDetails(cursor);
listCompanies.add(company);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
}
return listCompanies;
}
/*
* Check whether the exercise data present or not in the db before executing statement
*/
public boolean CheckIfRecordExists(String rid, String did) {
String Query = "Select * from " + DBHelper.TABLE_EXERCISE_DETAILS + " where " + DBHelper.COLUMN_ROUTINE_ID + " = " + rid + " AND " + DBHelper.COLUMN_DAY_ID + " = " + did;
Cursor cursor = mDatabase.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
protected ExerciseDetails cursorToExerciseDetails(Cursor cursor) {
try{
ExerciseDetails exerciseDetails = new ExerciseDetails();
exerciseDetails.setExDetailsId(cursor.getLong(0));
exerciseDetails.setRoutineId(cursor.getString(1));
exerciseDetails.setDayId(cursor.getString(2));
exerciseDetails.setExerciseId(cursor.getString(3));
exerciseDetails.setReps(cursor.getString(4));
exerciseDetails.setSets(cursor.getString(5));
exerciseDetails.setTimePerset(cursor.getString(6));
exerciseDetails.setCalorieBurn(cursor.getString(7));
exerciseDetails.setResttimePerset(cursor.getString(8));
exerciseDetails.setOrder(cursor.getString(9));
exerciseDetails.setMenuName(cursor.getString(10));
exerciseDetails.setTips(cursor.getString(11));
exerciseDetails.setYoutubeUrl(cursor.getString(12));
exerciseDetails.setWarnings(cursor.getString(13));
exerciseDetails.setDisplayId(cursor.getString(14));
exerciseDetails.setVisibility(cursor.getString(15));
exerciseDetails.setForDate(cursor.getString(16));
exerciseDetails.setMenuIcon(cursor.getString(17));
exerciseDetails.setDayName(cursor.getString(18));
return exerciseDetails;
} catch (Exception e){
System.out.println("error------------"+e);
return null;
}
}
}
FUll json value which i inserted Into sqllite
https://pastebin.com/DmAkPkXg
In cursorToExerciseDetails() instead of explicitly setting the index of a column:
exerciseDetails.setExDetailsId(cursor.getLong(0));
exerciseDetails.setRoutineId(cursor.getString(1));
....................................................
use getColumnIndex() with he name of the column to return the index:
exerciseDetails.setExDetailsId(cursor.getLong(cursor.getColumnIndex(DBHelper.COLUMN_EX_DETAILS_ID)));
exerciseDetails.setRoutineId(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_ROUTINE_ID))));
....................................................

Set message sending start datetime

I have chat application in which I am sending message to numbers which are being sent successfully. Now I want that I should set start date time of message sending. for this purpose I have stored datetime in sqlite database. that is my code:
while (true) {
cursor = databaseHelperClass.getMessageNotSent();
if (cursor != null && cursor.moveToFirst()) {
do {
Id = cursor.getInt(cursor.getColumnIndex("ID"));
jobMessageNotSent = cursor.getString(cursor.getColumnIndex("Message"));
startDatetime = cursor.getString(cursor.getColumnIndex("StartDatetime"));
isComplete = cursor.getInt(cursor.getColumnIndex("isComplete"));
} while (cursor.moveToNext());
new SendJobMessages().execute(Id);
}
and this is my asyncTask code:
private class SendJobMessages extends AsyncTask<Integer , Integer, Integer> {
private String jobNumbers = null;
#Override
protected Integer doInBackground(Integer... jobMessageIds) {
totalNumbers = jobMessageIds.length;
jobNumbersArray = new ArrayList<String>();
databaseHelperClass = new DatabaseHelperClass(getApplicationContext());
cursor = databaseHelperClass.getMessagesNumber(Id);
if (cursor != null && cursor.moveToFirst()) {
do {
JobMessagesId = cursor.getInt(cursor.getColumnIndex("ID"));
laterJobsNumbers = cursor.getString(cursor.getColumnIndex("Numbers"));
JobId = cursor.getInt(cursor.getColumnIndex("JobId"));
jobNumbersArray.add(laterJobsNumbers);
} while (cursor.moveToNext());
// sendJobsMessages();
for (int i = 0; i < jobNumbersArray.size(); i++) {
jobNumbers = jobNumbersArray.get(i);
if (countMessagePerDay() >= Integer.parseInt(MaxNoOfMessagePerDay)) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
try {
sendSMSLater(String.valueOf(jobNumbers));
} catch (ParseException e) {
e.printStackTrace();
}
this.publishProgress(1);
}
}
}
return jobMessageIds.length;
}
}
and this is my sqlite query:
public Cursor getJMessagesNotSent() {
db = this.getReadableDatabase();
String query = "select * from Jobs where iscomplete = 0 and datetime('now') > startdatetime";
Cursor cursor = db.rawQuery(query, null);
return cursor;
}
and for numbers:
public Cursor getJobsNumber(int jobId) {
db = this.getReadableDatabase();
String query = "SELECT * From JobMessages where issent = 0 and JobId = " + jobId + "";
Cursor cursor = db.rawQuery(query, null);
return cursor;
}

StreamCorruptedException aftet de-serialized

i'm trying to de-serialization a class from a sqlite db, this is how i serialize it:
protected String serializeRule(){
String ruleSerialized = "";
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream so = new ObjectOutputStream(bo);
so.writeObject(this);
so.flush();
ruleSerialized = bo.toString();
} catch (Exception e) {
ruleSerialized ="";
}
return ruleSerialized;
}
store into a sqlite database:
public void writeRule(){
String ruleSerialized = serializeRule();
if (ruleSerialized != null && !ruleSerialized.isEmpty() ){
DatabaseHelper mDbHelper = new DatabaseHelper(context);
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(RuleContract.RuleEntry.COLUMN_NAME, ruleSerialized);
id = db.insert(RuleContract.RuleEntry.TABLE_NAME, null, values);
}
}
de-serialized it:
public static ArrayList<RuleBase> getRules(Context context){
ArrayList<RuleBase> ret = new ArrayList<RuleBase>();
DatabaseHelper mDbHelper = new DatabaseHelper(context);
SQLiteDatabase db = mDbHelper.getWritableDatabase();
String[] projection = {
RuleContract.RuleEntry._ID,
RuleContract.RuleEntry.COLUMN_NAME
};
Cursor c = db.query(
RuleContract.RuleEntry.TABLE_NAME, // The table to query
projection, // The columns to return
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // The sort order
);
if(c.moveToFirst()){
do{
String column1 = c.getString(0);
String column2 = c.getString(1);
RuleBase r = getRule(column2);
ret.add(r);
}while(c.moveToNext());
}
c.close();
db.close();
return ret;
}
public static RuleBase getRule(String rules){
RuleBase obj = null;
try {
byte b[] = rules.getBytes();
ByteArrayInputStream bi = new ByteArrayInputStream(b);
ObjectInputStream si = new ObjectInputStream(bi);
obj = (RuleBase) si.readObject();
} catch (Exception e) {}
return obj;
}
when i open a new ObjectInputStream(bi) i always have StreamCorruptedException some problem with sqlite or other?

Favorites list, check if item is already recorded in SQLite

I`m new in android coding...
I created some Activities and Sqlite...
I added a button in to my activity to store some data in to database, but every time we click on the button it added the same data to the database...
How can I check if the data is already exist in the data base??!!!
I created a listView for showing some data and when we click on each item it directed us in to a new activity, in the new activity I created a new button to store data in database, so I want to see how can I find out data is already exist so the button can be off and if not exist the button should be on...
here is my code:
database:
public class PhraseDataBaseAdapter {
private Context context;
private SQLiteOpenHelper sqLiteOpenHelper;
public PhraseDataBaseAdapter(Context context){
this.context = context;
sqLiteOpenHelper = new SQLiteOpenHelper(context, "database.db", null, 1) {
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table tb1_phrases (id integer primary key, eng text, per text)";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
};
}
public long savePhrase(Phrases phrases){
String eng = phrases.getEng();
String per = phrases.getPer();
long id = -1;
SQLiteDatabase database = null;
try{
ContentValues values = new ContentValues();
values.put("eng", eng);
values.put("per", per);
database = sqLiteOpenHelper.getWritableDatabase();
id = database.insert("tb1_phrases", null, values);
}catch (Exception ex){
Log.d("Database", "Exception: " + ex.getMessage());
}finally {
if (database!=null && database.isOpen()){
database.close();
}
}
return id;
}
public Phrases readPhrase(long id){
Phrases phrases = null;
String[] columns = new String[]{"id", "eng", "per"};
String selection = "id=?";
String[] selectionArgs = new String[]{String.valueOf(id)};
String groupBy = null;
String having = null;
String orderBy = null;
String limit = null;
SQLiteDatabase database = null;
try{
database = sqLiteOpenHelper.getWritableDatabase();
Cursor cursor = database.query("tb1_phrases", columns, selection, selectionArgs, groupBy, having, orderBy, limit);
if (cursor !=null && cursor.moveToFirst()){
int idIndex = 0;
int engIndex = 1;
int perIndex = 2;
long phraseId = cursor.getLong(idIndex);
String phraseEng = cursor.getString(engIndex);
String phrasePer = cursor.getString(perIndex);
phrases = new Phrases();
phrases.setId(phraseId);
phrases.setEng(phraseEng);
phrases.setPer(phrasePer);
}
}catch (Exception ex){
Log.d("Database", "Exception: " + ex.getMessage());
}finally {
if (database!=null && database.isOpen()){
database.close();
}
}
return phrases;
}
public int updatePhrase(Phrases phrases){
int noOfDataUpdatedRecords = 0;
String whereClause = "id=?";
String[] whereArgs = new String[]{String.valueOf(phrases.getId())};
SQLiteDatabase database = null;
try{
ContentValues values = new ContentValues();
values.put("eng", phrases.getEng());
values.put("per", phrases.getPer());
database = sqLiteOpenHelper.getWritableDatabase();
noOfDataUpdatedRecords = database.update("tb1_phrases", values, whereClause, whereArgs);
}catch (Exception ex){
Log.d("Database", "Exeption: " + ex.getMessage());
} finally {
if(database!=null && database.isOpen()){
database.close();
}
}
return noOfDataUpdatedRecords;
}
public int deletePhrase(long id){
int noOfDeletedRecords = 0;
String whereClause = "id=&";
String[] whereArgs = new String[]{String.valueOf(id)};
SQLiteDatabase database = null;
try{
database = sqLiteOpenHelper.getWritableDatabase();
noOfDeletedRecords = database.delete("tb1_phrases", whereClause, whereArgs);
}catch (Exception ex){
Log.d("Database", "Exception: " + ex.getMessage());
} finally {
if(database!=null && database.isOpen()){
database.close();
}
}
return noOfDeletedRecords;
}
public ArrayList<Phrases> readAllPhrases(){
ArrayList<Phrases> phrasesArrayList = null;
String[] columns = new String[]{"id", "eng", "per"};
String selection = null;
String[] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
String limit = null;
SQLiteDatabase database = null;
try{
database = sqLiteOpenHelper.getWritableDatabase();
Cursor cursor = database.query("tb1_phrases", columns, selection, selectionArgs, groupBy, having, orderBy, limit);
if (cursor !=null && cursor.moveToFirst()){
phrasesArrayList = new ArrayList<>();
int idIndex = 0;
int engIndex = 1;
int perIndex = 2;
do {
long phraseId = cursor.getLong(idIndex);
String phraseEng = cursor.getString(engIndex);
String phrasePer = cursor.getString(perIndex);
Phrases phrases = new Phrases();
phrases.setId(phraseId);
phrases.setEng(phraseEng);
phrases.setPer(phrasePer);
phrasesArrayList.add(phrases);
}while (cursor.moveToNext());
}
}catch (Exception ex){
Log.d("Database", "Exception: " + ex.getMessage());
}finally {
if (database!=null && database.isOpen()){
database.close();
}
}
return phrasesArrayList;
}
the favorite button:
favorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PhraseDataBaseAdapter dataBaseAdapter = new PhraseDataBaseAdapter(getApplicationContext());
Phrases phrases = new Phrases();
phrases.setEng(mainAdviceEnglish);
phrases.setPer(mainAdvicePersian);
dataBaseAdapter.savePhrase(phrases);
}
});
Thanks...
For your requirement i have a great solution without using SQLite.
You should use this class for storing your words and also it have feature to check those word has stored or not.
import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class WordListPref {
public static final String PREFS_NAME = "XYZ";
public static final String WORD_LIST = "WordList";
public void storeWords(Context context, List favorites) {
// used for store arrayList in json format
SharedPreferences settings;
SharedPreferences.Editor editor;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(WORD_LIST, jsonFavorites);
editor.commit();
}
public ArrayList<String> loadWords(Context context) {
// used for retrieving arraylist from json formatted string
SharedPreferences settings;
List favorites;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
if (settings.contains(WORD_LIST)) {
String jsonFavorites = settings.getString(WORD_LIST, null);
Gson gson = new Gson();
String[] favoriteItems = gson.fromJson(jsonFavorites, String[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList(favorites);
} else
return new ArrayList<>();
return (ArrayList) favorites;
}
public void addWord(Context context, String beanSampleList) {
List favorites = loadWords(context);
if (favorites == null)
favorites = new ArrayList();
favorites.add(beanSampleList);
storeWords(context, favorites);
}
public void removeUsers(Context context, String beanSampleList) {
ArrayList<String> favorites = loadWords(context);
if (favorites != null) {
for (int i = 0; i < favorites.size(); i++) {
String bean = favorites.get(i);
if (bean == beanSampleList) {
favorites.remove(i);
storeWords(context, favorites);
}
}
}
}
public boolean isWordExist(String bean, Context context) {
ArrayList<String> data = loadWords(context);
if (data != null) {
for (int i = 0; i < data.size(); i++) {
String beanSampleList = data.get(i);
if (bean == beanSampleList) {
return true;
}
}
}
return false;
}
public void flushWordPref(Context context) {
SharedPreferences settings;
SharedPreferences.Editor editor;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
editor.clear();
editor.commit();
}
}
For storing Word use Method
addWord("")
For Checking word exits
isWordExist()
This class would be solve your problem you will never use sqlite for same kind of stuffs.
Best of luck and dont forgot to VOTE :)

fetch data from a dbHandler.java file but not able to show it in listview?

I did some changes in my code and it runs but I didn't get appropriate output. I create a method.
public void fetchData() {
dbHandler = new CourseDbHandler(this,null,null,1);
List<CreateCourse> course_data = dbHandler.getdata();
String[] data = new String[course_data.size()];
int i=0;
for(CreateCourse co : course_data)
{
data[i] = co.getCourseSelected();
i++;
}
courseList = (ListView) findViewById(R.id.CourselistView);
courseAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
courseList.setAdapter(courseAdapter);
courseAdapter.notifyDataSetChanged();
}
in this method i used dbHandler.getdata method, which is as follows
public List<CreateCourse> getdata() throws NullPointerException {
String dbString = "";
String course;
String sec;
List<CreateCourse> list = new ArrayList<>();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_COURSE +";";
Cursor c = db.rawQuery(query,null);
c.moveToFirst();
if(c.equals(null)){
System.out.println("NO DATA");
return null;
}
else {
do {
course = c.getString(1);
sec = c.getString(2);
dbString = course+" "+sec;
CreateCourse co = new CreateCourse();
co.setCourseSelected(dbString);
list.add(new CreateCourse(c.getString(1), c.getString(2)));
}while (c.moveToNext());
}
db.close();
return list;
}
These are the getter and setter method
public void setCourseSelected(String courSelected) {
courseSelected = courSelected;
}
public String getCourseSelected() {
System.out.println(courseSelected);
return courseSelected;
}
It gives an error unfortunately app has stopped.
Create a class with your data:
public class Course {
public String id;
public String course;
public String sec;
public Course (String id, String course, String sec) {
this.id = id;
this.course = course;
this.sec = sec;
}
Then modify your method to return List of your data:
public List<Course> getdata() throws NullPointerException {
List<Course> list = new ArrayList<>();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_COURSE +";";
Cursor c = db.rawQuery(query,null);
c.moveToFirst();
if(c.equals(null)){
System.out.println("NO DATA");
return null;
}
else {
do {
list.add(new Course(c.getString(0), c.getString(1), c.getString(2)));
}while (c.moveToNext());
}
db.close();
return list;
}
Then you can use this List with ArrayAdapter to show your data in ListView.
I changed all the code and solve my problem in above code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_course);
dbHandler = new CourseDbHandler(this, null, null, 1);
Cursor c = dbHandler.getData();
c.moveToFirst();
// System.out.println("Select");
if(c.equals(null)){
System.out.println("NO DATA");
}
else {
if(c.moveToFirst()) {
do {
dbString=null;
course = c.getString(1);
sec = c.getString(2);
dbString = course + " " + sec;
courseItem.add(dbString);
} while (c.moveToNext());
}
}
courseList = (ListView) findViewById(R.id.CourselistView);
courseAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, courseItem);
courseList.setAdapter(courseAdapter);
courseAdapter.notifyDataSetChanged();
}
Thank you for your help..

Categories

Resources