Null pointer exception in Android prompt user input dialog box [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
This is my activity ,where I need to Add Category to the database,I used Android prompt user input dialog box to add that catgeory.I refer this link for the dialog box. http://www.mkyong.com/android/android-prompt-user-input-dialog-example/
But now it's giving null pointer exception when I pressing ADD(OK) button in dialog box.
public class budget extends Activity {
int selected_id;
ListView rldlist = null;
DBhelper helper;
String budget;
TextView menubtn;
Context context = this;
EditText txr;
Button btn1;
SQLiteDatabase db;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.budget);
helper = new DBhelper(this);
txr = (EditText) findViewById(R.id.add);
btn1 = (Button) findViewById(R.id.button);
menubtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.addcategory, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("ADD",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ContentValues value = new ContentValues();
value.put(DBhelper.Name, txr.getText().toString());
db = helper.getWritableDatabase();
if (helper.checkIdExist(txr.getText().toString())) {
db.insert(DBhelper.TABLE1, null, value);
db.close();
} else {
Toast.makeText(getApplicationContext(), "Duplicate Category Name!", Toast.LENGTH_LONG).show();
}
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
This is my DB class..
public class DBhelper extends SQLiteOpenHelper{
static final String DATABASE = "wedding9.db";
static final int VERSION = 9;
static final String TABLE1 = "Category";
static final String TABLE2 = "Budget";
static final String TABLE3 = "Expenses";
static final String C_ID = "_id";
static final String Name = "name";
static final String B_ID = "_id";
static final String Description = "description";
static final String Amount = "amount";
public static final String ID1="_id";
public static final String DATE_T1="date1";
public static final String CATEGORY="category";
public static final String DETAIL="detail";
public static final String AMOUNT1="amount1";
public static final String STATUS="status";
public static final String EX_YEAR="exyear";
public static final String EX_MONTH="exmonth";
public DBhelper(Context context){
super(context, DATABASE, null, VERSION);
}
public void onCreate(SQLiteDatabase db){
db.execSQL("CREATE TABLE " + TABLE1+ "(" +C_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT," +Name+ " text unique not null)");
db.execSQL("CREATE TABLE " + TABLE2+ "(" +B_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT," +Description+ " text,"
+Amount+ " text, FOREIGN KEY ("+Description+") REFERENCES "+TABLE1+"("+Name+"));");
db.execSQL("CREATE TABLE " + TABLE3 + " ( "
+ ID1 + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ DATE_T1 + " text, "
+ CATEGORY + " text, "
+ DETAIL + " text, "
+ STATUS + " text, "
+ EX_YEAR + " text, "
+ EX_MONTH + " text, "
+ AMOUNT1 + " text, FOREIGN KEY ("+CATEGORY+") REFERENCES "+TABLE1+"("+Name+"));");
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table " + TABLE1);
onCreate(db);
}
public ArrayList<category> getCategories(){
ArrayList<category> arrayList = new ArrayList<category>();
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.query(DBhelper.TABLE1, null, null, null, null, null, null);
while (c.moveToNext()) {
category cat = new category(c.getInt(0),c.getString(1));
arrayList.add(cat);
}
return arrayList;
}
public boolean checkIdExist(String name) {
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.query(DBhelper.TABLE1, null, null, null, null, null, null);
while (c.moveToNext()) {
if(c.getString(1).equals(name))
return false;
}
return true;
}
}
10-25 13:56:21.179 16248-16248/com.example.username.weddingplanning
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.username.weddingplanning.budget$1$2.onClick(budget.java:83)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:185)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)

Here:
Context context = this;
Initializing context before creating Activity which probably causing issue.
Initialize context in onCreate method :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.budget);
context=this;//<<<<
....
}
If add EditText is inside addcategory layout then initialize it using promptsView as in onClick method:
View promptsView = li.inflate(R.layout.addcategory, null);
txr = (EditText)promptsView. findViewById(R.id.add);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);

Related

Unfortunately Myapp has stopped after entering login details

I am developing an application and after I enter the login details the app crashes.I think the error is due to the problem of database linking and fetching and tried few solutions posted online, but nothing worked.
What can i do to solve this?
06-21 13:21:04.590 1913-1913/in.co.arrow E/AndroidRuntime: FATAL EXCEPTION: main
Process: in.co.arrow, PID: 1913
java.lang.IllegalStateException: Couldn't read row 0, col 4 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetString(Native Method)
at android.database.CursorWindow.getString(CursorWindow.java:438)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at in.co.arrow.sql.SqliteHelper.Authenticate(SqliteHelper.java:140)
at in.co.arrow.LoginActivity$1.onClick(LoginActivity.java:55)
at android.view.View.performClick(View.java:6367)
at android.view.View$PerformClick.run(View.java:25032)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6753)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:482)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
here are my SqliteHelper and LoginActivity classes
package in.co.arrow;
public class LoginActivity extends AppCompatActivity {
EditText editTextEmail;
EditText editTextPassword;
TextInputLayout textInputLayoutEmail;
TextInputLayout textInputLayoutPassword;
Button buttonLogin;
SqliteHelper sqliteHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sqliteHelper = new SqliteHelper(this);
initCreateAccountTextView();
initViews();
buttonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (validate()) {
String Email = editTextEmail.getText().toString();
String Password = editTextPassword.getText().toString();
User currentUser = sqliteHelper.Authenticate(new User(null,null,null,null,null,Email,Password,null,null,null,null,null,null));
if (currentUser != null) {
Snackbar.make(buttonLogin, "Successfully Logged in!", Snackbar.LENGTH_LONG).show();
/* Intent intent=new Intent(LoginActivity.this,HomeScreenActivity.class);
startActivity(intent);
finish(); */
} else {
Snackbar.make(buttonLogin, "Failed to log in , please try again", Snackbar.LENGTH_LONG).show();
}
}
}
});
}
private void initCreateAccountTextView() {
TextView textViewCreateAccount = (TextView) findViewById(R.id.textViewCreateAccount);
textViewCreateAccount.setText(fromHtml("<font color='#ffffff'>I don't have account yet. </font><font color='#0c0099'>create one</font>"));
textViewCreateAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
}
});
}
private void initViews() {
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
textInputLayoutEmail = (TextInputLayout) findViewById(R.id.textInputLayoutEmail);
textInputLayoutPassword = (TextInputLayout) findViewById(R.id.textInputLayoutPassword);
buttonLogin = (Button) findViewById(R.id.buttonLogin);
}
#SuppressWarnings("deprecation")
public static Spanned fromHtml(String html) {
Spanned result;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
result = Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY);
} else {
result = Html.fromHtml(html);
}
return result;
}
public boolean validate() {
boolean valid = false;
String Email = editTextEmail.getText().toString();
String Password = editTextPassword.getText().toString();
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
valid = false;
textInputLayoutEmail.setError("Please enter valid email!");
} else {
valid = true;
textInputLayoutEmail.setError(null);
}
if (Password.isEmpty()) {
valid = false;
textInputLayoutPassword.setError("Please enter valid password!");
} else {
if (Password.length() > 5) {
valid = true;
textInputLayoutPassword.setError(null);
} else {
valid = false;
textInputLayoutPassword.setError("Password is to short!");
}
}
return valid;
}
}
SqliteHelper.java
package in.co.arrow.sql;
public class SqliteHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "arrow";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_USERS = "users";
public static final String KEY_ID = "id";
public static final String KEY_USER_NAME = "username";
public static final String KEY_FIRST_NAME="firstname";
public static final String KEY_LAST_NAME="lastname";
public static final String KEY_MOBILE_NO="mobileno";
public static final String KEY_EMAIL = "email";
public static final String KEY_PASSWORD = "password";
public static final String KEY_FATHERS_NAME="fathersname";
public static final String KEY_GENDER="gender";
public static final String KEY_INST_NAME="instname";
public static final String KEY_DOB="dob";
public static final String KEY_BRANCH="branch";
public static final String KEY_YOP="yop";
public static final String SQL_TABLE_USERS = " CREATE TABLE " + TABLE_USERS
+ " ( "
+ KEY_ID + " INTEGER PRIMARY KEY, "
+ KEY_USER_NAME + " TEXT, "
+ KEY_FIRST_NAME + " TEXT,"
+ KEY_LAST_NAME + " TEXT,"
+ KEY_MOBILE_NO + " TEXT,"
+ KEY_EMAIL + " TEXT, "
+ KEY_PASSWORD + " TEXT, "
+ KEY_FATHERS_NAME + " TEXT,"
+ KEY_GENDER + " TEXT,"
+ KEY_INST_NAME + " TEXT,"
+ KEY_DOB + " TEXT,"
+ KEY_BRANCH + " TEXT,"
+ KEY_YOP + " TEXT "
+ " ) ";
public SqliteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(SQL_TABLE_USERS);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL(" DROP TABLE IF EXISTS " + TABLE_USERS);
}
public void addUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_USER_NAME, user.userName);
values.put(KEY_FIRST_NAME, user.firstname);
values.put(KEY_LAST_NAME, user.lastname);
values.put(KEY_GENDER, user.gender);
values.put(KEY_FATHERS_NAME, user.fathersname);
values.put(KEY_MOBILE_NO, user.mobileno);
values.put(KEY_EMAIL, user.email);
values.put(KEY_PASSWORD, user.password);
values.put(KEY_DOB, user.dob);
values.put(KEY_INST_NAME,user.instname);
values.put(KEY_BRANCH, user.branch);
values.put(KEY_YOP, user.yop);
long todo_id = db.insert(TABLE_USERS, null, values);
}
public User Authenticate(User user) {
SQLiteDatabase db = this.getReadableDatabase();
#SuppressLint("Recycle") Cursor cursor = db.query(TABLE_USERS,
new String[]{KEY_ID, KEY_USER_NAME, KEY_EMAIL, KEY_PASSWORD},
KEY_EMAIL + "=?",
new String[]{user.email},
null, null, null);
if (cursor != null && cursor.moveToFirst()&& cursor.getCount()>0) {
User user1;
user1 = new User(cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3),cursor.getString(4), cursor.getString(5), cursor.getString(6),cursor.getString(7),cursor.getString(8),cursor.getString(9),cursor.getString(10),cursor.getString(11),cursor.getString(12));
if (user.password.equalsIgnoreCase(user1.password)) {
return user1;
}
}
return null;
}
public boolean isEmailExists(String email) {
SQLiteDatabase db = this.getReadableDatabase();
#SuppressLint("Recycle") Cursor cursor = db.query(TABLE_USERS,// Selecting Table
new String[]{KEY_ID, KEY_USER_NAME, KEY_EMAIL, KEY_PASSWORD},
KEY_EMAIL + "=?",
new String[]{email},
null, null, null);
if (cursor != null && cursor.moveToFirst()&& cursor.getCount()>0) {
return true;
}
return false;
}
}
Your cursor has only 4 columns:
new String[]{KEY_ID, KEY_USER_NAME, KEY_EMAIL, KEY_PASSWORD}
but you are trying to read 13 columns out of it. It fails on the first non-existing one at index 4.
You can add all the columns you're reading to your projection.
Your isssue is that you have only specified 4 columns to be extracted into the cursor, yet you are trying to get data from 13 columns.
You could change :-
Cursor cursor = db.query(TABLE_USERS,
new String[]{KEY_ID, KEY_USER_NAME, KEY_EMAIL, KEY_PASSWORD},
KEY_EMAIL + "=?",
new String[]{user.email},
null, null, null);
to either :-
Cursor cursor = db.query(TABLE_USERS,
null, // <<<< gets all columns from the table
KEY_EMAIL + "=?",
new String[]{user.email},
null, null, null);
or :-
Cursor cursor = db.query(TABLE_USERS,
new String[]{KEY_ID, KEY_USER_NAME, KEY_EMAIL, KEY_PASSWORD, KEY_FIRST_NAME, KEY_LAST_NAME, KEY_GENDER, KEY_FATHERS_NAME, KEY_MOBILE_NO, KEY_DOB, KEY_INST_NAME, KEY_BRANCH, KEY_YOP},
KEY_EMAIL + "=?",
new String[]{user.email},
null, null, null);
The above two assuming that you want data from all columns.
or you could reduce the number of columns from which you retrieve data but that would depend upon what constructors are available for a User object.

SQLIte database not able to delete entries

I have a SQLdatabase and I want to delete entries that are displayed in a list view using a button that is next to each entry on the list view. But currently it is not letting me delete.
This problem is located in the selectionargs variable as shown below. If I put a number e.g. 1, into the selectionargs manually it will work, but I have been trying to do it through the a variable that represents each entry. This does not result in an error but just goes straight to the toast message cannot delete. ac.ID refers to the adapter class and the ID of the list item entries.
Bookmark class:
public class Bookmark extends AppCompatActivity {
myAdapter myAdapter;
DBManager db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bookmark);
db = new DBManager(this);
onLoadAttraction();
// onLoadTransport();
}
public void onLoadAttraction() {
ArrayList<Adapter> listData = new ArrayList<Adapter>();
listData.clear();
Cursor cursor = db.Query("BookmarkAttraction",null, null, null, DBManager.ColId);
if (cursor.moveToFirst()) {
do {
listData.add(new Adapter(
cursor.getString(cursor.getColumnIndex(DBManager.ColType))
, cursor.getString(cursor.getColumnIndex(DBManager.ColName))
, cursor.getString(cursor.getColumnIndex(DBManager.ColLocation))
, cursor.getString(cursor.getColumnIndex(DBManager.ColOpening))
, cursor.getString(cursor.getColumnIndex(DBManager.ColClosing))
, cursor.getString(cursor.getColumnIndex(DBManager.ColNearbyStop))
,null,null,null, null, null));
} while (cursor.moveToNext());
}
myAdapter = new myAdapter(listData);
ListView ls = (ListView) findViewById(R.id.listView);
ls.setAdapter(myAdapter);
}
public void onLoadTransport(){
ArrayList<Adapter> listData = new ArrayList<Adapter>();
listData.clear();
Cursor cursor = db.Query("BookmarkTransport",null, null, null, DBManager.ColId);
if (cursor.moveToFirst()) {
do {
listData.add(new Adapter(
cursor.getString(cursor.getColumnIndex(DBManager.ColType))
, cursor.getString(cursor.getColumnIndex(DBManager.ColName))
, cursor.getString(cursor.getColumnIndex(DBManager.ColLocation))
, null
, null
, null
,cursor.getString(cursor.getColumnIndex(DBManager.ColTime))
,cursor.getString(cursor.getColumnIndex(DBManager.ColNextStop))
, cursor.getString(cursor.getColumnIndex(DBManager.ColPhoneNumber))
,null,null));
} while (cursor.moveToNext());
}
myAdapter = new myAdapter(listData);
ListView ls = (ListView) findViewById(R.id.listView);
ls.setAdapter(myAdapter);
}
class myAdapter extends BaseAdapter {
public ArrayList<Adapter> listItem;
Adapter ac;
public myAdapter(ArrayList<Adapter> listItem) {
this.listItem = listItem;
}
#Override
public int getCount() {
return listItem.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
LayoutInflater myInflator = getLayoutInflater();
final View myView = myInflator.inflate(R.layout.list_bookmark, null);
ac = listItem.get(position);
TextView Type = (TextView) myView.findViewById(R.id.BMType);
Type.setText(ac.Type);
TextView Name = (TextView) myView.findViewById(R.id.BMName);
Name.setText(ac.Name);
TextView Location = (TextView) myView.findViewById(R.id.BMLocation);
Location.setText(ac.Location);
TextView Opening = (TextView) myView.findViewById(R.id.BMOpen);
Opening.setText(ac.Opening);
TextView Closing = (TextView) myView.findViewById(R.id.BMClose);
Closing.setText(ac.Closing);
TextView NearbyStop1 = (TextView) myView.findViewById(R.id.BMNearbyStop);
NearbyStop1.setText(ac.NearbyStop);
Button buttonDelete = (Button)myView.findViewById(R.id.buttonDelete);
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String[] selectionArgs = {ac.ID};
int count = db.Delete("BookmarkAttraction","ID=? ",selectionArgs);
if (count > 0) {
onLoadAttraction();
Toast.makeText(getApplicationContext(),"Data deleted", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(),"Cannnot delete", Toast.LENGTH_LONG).show();
}
}
});
return myView;
}
}
}
DBManager class:
public class DBManager {
private SQLiteDatabase sqlDB;
static final String ColId = "ID";
static final String DBName = "InternalDB";
static final String TableName = "BookmarkAttraction";
static final String TableName2 = "BookmarkTransport";
static final String TableName3 = "Itinerary";
static final String ColItineraryName = "ItineraryName";
static final String ColDate = "Date";
static final String ColType = "Type";
static final String ColName = "Name";
static final String ColLocation = "Location";
static final String ColOpening = "OpeningTime";
static final String ColClosing = "ClosingTime";
static final String ColNearbyStop = "NerbyStop1";
static final String ColTime = "Time";
static final String ColNextStop = "NextStop";
static final String ColPhoneNumber = "PhoneNumber";
static final int DBVersion = 1;
static final String CreateTable = "CREATE TABLE IF NOT EXISTS " + TableName + "(ID INTEGER PRIMARY KEY AUTOINCREMENT," + ColType+ " TEXT," +
ColName+ " TEXT," + ColLocation+ " TEXT," + ColOpening+ " TEXT," +ColClosing+ " TEXT," + ColNearbyStop+ " TEXT);";
static final String CreateTabe2 = "CREATE TABLE IF NOT EXISTS " +TableName2 + "(ID INTEGER PRIMARY KEY AUTOINCREMENT,"
+ ColType + " TEXT,"
+ ColName + " TEXT,"
+ ColLocation + " TEXT,"
+ ColTime+ " TEXT,"
+ ColNextStop + " TEXT,"
+ ColPhoneNumber + " TEXT);";
static final String CreateTable3 = "CREATE TABLE IF NOT EXISTS " + TableName3 + "(ID INTEGER PRIMARY KEY AUTOINCREMENT," + ColItineraryName + " TEXT,"
+ ColDate + " TEXT," + ColName + " TEXT," + ColLocation + " TEXT," + ColTime + " TEXT);";
static class DBHelper extends SQLiteOpenHelper{
Context context;
DBHelper(Context context){
super(context, DBName, null, DBVersion);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
Toast.makeText(context,DBName,Toast.LENGTH_LONG).show();
db.execSQL(CreateTable);
Toast.makeText(context,"Table is created ", Toast.LENGTH_LONG).show();
db.execSQL(CreateTabe2);
Toast.makeText(context,"Transport table created", Toast.LENGTH_LONG).show();
db.execSQL(CreateTable3);
Toast.makeText(context,"Itin table created", Toast.LENGTH_LONG).show();
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS" + TableName);
db.execSQL("DROP TABLE IF EXISTS" + TableName2);
db.execSQL("DROP TABLE IF EXISTS" + TableName3);
onCreate(db);
}
}
public DBManager(Context context){
DBHelper db = new DBHelper(context);
sqlDB = db.getWritableDatabase();
}
public long Insert(String tablename,ContentValues values){
long ID = sqlDB.insert(tablename,"",values);
return ID;
}
public Cursor Query(String tablename, String [] projection, String selection, String [] selectionArgs, String sortOrder){
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(tablename);
Cursor cursor = qb.query(sqlDB,projection, selection, selectionArgs,null,null,sortOrder);
return cursor;
}
public int Delete(String tablename,String selection, String[] selectionArgs){
int count = sqlDB.delete(tablename,selection,selectionArgs);
return count;
}
}
Adapter class:
public class Adapter {
public String ID;
public String Type;
public String Name;
public String Location;
public String Opening;
public String Closing;
public String NearbyStop;
public String Time;
public String NextStop;
public String PhoneNumber;
public String Latitude;
public String Longitude;
public Adapter(String type, String name, String location, String opening, String closing,
String nearbyStop, String time, String nextStop, String phoneNumber, String Latitude,
String Longitude) {
this.Type = type;
this.Name = name;
this.Location = location;
this.Opening = opening;
this.Closing = closing;
this.NearbyStop = nearbyStop;
this.Time = time;
this.NextStop = nextStop;
this.PhoneNumber = phoneNumber;
this.Latitude = Latitude;
this.Longitude = Longitude;
}
}
The code for the delete button is in my bookmark class with the DBManager holding the actual delete code. If anyone can help with this it would be greatly appreciated.
Remove the ac field of your myAdapter class, and use it as a method variable inside the getView method.
Then use the ListView.setOnItemClickListener method to add an on click listener with positional awareness. (do this only once after you set the adapter) This way you can do listItem.get(position) to get the item in that position.

Check if data was written in SQLite Database

I want to save the Score from a Quiz in a SQLite Database and change an image in another activity if the Score is 5. There is no error shown, but even if I score 5 the image won't change... How can I log the content of my database to check if the score was added or how can I find the mistake?
DB Helper:
public class DbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 7;
private static final String DATABASE_NAME = "CE";
public static final String SCORE_TABLE = "score";
public static final String COLUMN_ID = "ID";
public static final String COLUMN_SCORE = "SCORE";
public static final String COLUMN_MARKERID = "MARKERID";
private SQLiteDatabase dbase;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
dbase= db;
String create_query = "CREATE TABLE IF NOT EXITS " + SCORE_TABLE + " ( "
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_SCORE + " INTEGER, "
+ COLUMN_MARKERID + " TEXT) ";
db.execSQL(create_query);
}
public void addScore (DbHelper dbh, Integer score, String markerID) {
dbase = dbh.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_SCORE, score);
cv.put(COLUMN_MARKERID, markerID);
dbase.insert(SCORE_TABLE, null, cv);
}
public Cursor getScore(DbHelper dbh) {
dbase = dbh.getReadableDatabase();
String columns[] = {COLUMN_SCORE, COLUMN_MARKERID};
Cursor cursor = dbase.query(SCORE_TABLE, columns, null, null, null, null, null);
return cursor;
}
Write the Score into the Database after completing the Quiz:
public class ResultActivity extends Activity {
String markerID;
int score;
TextView t=(TextView)findViewById(R.id.textResult);
Button saveButton = (Button) findViewById(R.id.saveButton);
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_layout);
Bundle b = getIntent().getExtras();
score = b.getInt("score");
markerID = b.getString("markerID");
}
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DbHelper dbh = new DbHelper(context);
dbh.addScore(dbh,score,markerID);
Intent intent = new Intent(ResultActivity.this, Discover.class);
intent.putExtra("MarkerID", markerID);
startActivity(intent);
}
});
}
Discover class -> Check if score is 5 and change image if:
DbHelper dbh = new DbHelper(context);
Cursor cursor = dbh.getScore(dbh);
cursor.moveToFirst();
if (cursor.moveToFirst()) {
do {
if (Integer.parseInt(cursor.getString(0))== 5 && InfoUeberschrift.toString().equals(cursor.getString(1))){
ImageDone.setImageResource(R.drawable.markerdone);
}
}
while(cursor.moveToNext());
}
cursor.close();
}
The SQLiteDatabase insert function returns a long value, so if an error has occurred it returns -1.
'the row ID of the newly inserted row, or -1 if an error occurred'
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
This can be used to see if the insert is happening correctly.
Or you can wrap in try and catch and print message like so
try {
//code
} catch(SQLiteException ex) {
Log.v("Insert into database exception caught", ex.getMessage());
return -1;
}
}
When I have issues using Java and SQLite i normally do it directly with the SQLite desktop version using Shell, as I find it easier to test out table design.
Hope this helps

How to retrieve database values based on user clicks

I have made a database film app, which allows the user to search for a film. The results will then display in a ScrollView. Once the search results are returned, I want the user to be able to click on a film, which will lead to a new activity with the full details of the film. How would I go about doing this?
The clicks will all lead to one activity, but I need different details to display depending on the film clicked. I have 20 films in my database in total.
Search function on MainActivity:
public void search(View v){
EditText search = (EditText)findViewById(R.id.edtSearch);
String searchresult = "%" + search.getText().toString() + "%";
db = new DbHelper(this).getReadableDatabase();
String[] tblColumns = {"*"};
String where = "film LIKE ? OR actor LIKE ? OR actor2 LIKE ? OR director LIKE ?";
String[] args = {searchresult, searchresult, searchresult, searchresult};
Cursor results = db.query("FILMTABLE", tblColumns, where, args, null, null, null);
film(results);
}
public void film (Cursor c){
c.moveToFirst();
int titleint = c.getColumnIndex("film");
int id= c.getColumnIndex("id");
String title = c.getString(titleint);
int filmID = c.getInt(id);
TextView txt = new TextView(getApplicationContext());
txt.setId(filmID);
txt.setText(title);
txt.setTextColor(Color.BLACK);
txt.setTextSize(15);
txt.setClickable(true);
txt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity4.class);
startActivity(intent);
}
});
ScrollView scrollView = (ScrollView)findViewById(R.id.scrolLView);
scrollView.addView(txt);
}
DatabaseHelper:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbHelper extends SQLiteOpenHelper {
private static final String ID = "id";
private static final String FILM = "film";
private static final String ACTOR = "actor";
private static final String ACTOR2 = "actor2";
private static final String DIRECTOR = "director";
private static final String DESCRIPTION = "description";
private static final String TABLE_NAME = "FILMTABLE";
private static final String DATABASE_NAME = "filmdatabase3";
private static final int DATABASE_VERSION = 1;
private static final boolean FAVOURITE = false;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
FILM + " TEXT NOT NULL, " +
ACTOR + " TEXT NOT NULL, " +
ACTOR2 + " TEXT NOT NULL, " +
DIRECTOR + " TEXT NOT NULL, " +
FAVOURITE + " BOOLEAN, " +
DESCRIPTION + " TEXT NOT NULL);"
);
Cursor countRows = db.rawQuery("SELECT count(*) FROM FILMTABLE", null);
countRows.moveToFirst();
int NumRows = countRows.getInt(0);
countRows.close();
if (NumRows == 0) {
ContentValues values = new ContentValues();
values.put("film", "Gone Girl");
values.put("actor", "Ben Affleck");
values.put("actor2", "Rosamund Pike");
values.put("director", "David Fincher");
values.put("description", "description");
db.insert("FILMTABLE", null, values);
values.clear();
values.put("film", "The Hobbit");
values.put("actor", "Martin Freeman");
values.put("actor2", "Elijah Wood");
values.put("director", "Peter Jackson");
values.put("description", "description");
db.insert("FILMTABLE", null, values);
values.clear();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
onCreate(db);
}
}
When you start the detail activity, put the id of the film to the Intent you are creating.
Intent intent = new Intent(getApplicationContext(), MainActivity4.class);
intent.putExtra("FILM_ID_KEY", getSelectedFilmId());
startActivity(intent);
Or make your film POJO parcelable and again put that in your intent via putExtra method.
After that, in your MainActivity4 get these values in onCreate with getIntent method.

How to display database fields in seperate textViews

I have created a database film app where a user can search for films, the search results then display in a scroll view. The user can then click on a film result which will lead to another activity which will display the full film details (film, actors, directors). How would I retrieve the database fields and display these in separate textViews?
MainActivity:
public void search(View v){
EditText search = (EditText)findViewById(R.id.edtSearch);
String searchresult = "%" + search.getText().toString() + "%";
db = new DbHelper(this).getReadableDatabase();
String[] tblColumns = {"*"};
String where = "film LIKE ? OR actor LIKE ? OR actor2 LIKE ? OR director LIKE ?";
String[] args = {searchresult, searchresult, searchresult, searchresult};
Cursor results = db.query("FILMTABLE", tblColumns, where, args, null, null, null);
film(results);
}
public void film (Cursor c){
c.moveToFirst();
int titleint = c.getColumnIndex("film");
int id= c.getColumnIndex("id");
String title = c.getString(titleint);
int filmID = c.getInt(id);
TextView txt = new TextView(getApplicationContext());
txt.setId(filmID);
txt.setText(title);
txt.setTextColor(Color.BLACK);
txt.setTextSize(15);
txt.setClickable(true);
txt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity4.class);
intent.putExtra("FILM_ID_KEY", String.valueOf(v.getId()));
startActivity(intent);
}
});
ScrollView scrollView = (ScrollView)findViewById(R.id.scrolLView);
scrollView.addView(txt);
}
MainActivity4:
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
public class MainActivity4 extends ActionBarActivity {
String filmId;
protected SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
Intent intent = getIntent();
filmId = intent.getStringExtra(MainActivity.FILM_ID_KEY);
}
}
DbHelper:
public class DbHelper extends SQLiteOpenHelper {
private static final String ID = "id";
private static final String FILM = "film";
private static final String ACTOR = "actor";
private static final String ACTOR2 = "actor2";
private static final String DIRECTOR = "director";
private static final String DESCRIPTION = "description";
private static final String TABLE_NAME = "FILMTABLE";
private static final String DATABASE_NAME = "filmdatabase3";
private static final int DATABASE_VERSION = 1;
private static final boolean FAVOURITE = false;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
FILM + " TEXT NOT NULL, " +
ACTOR + " TEXT NOT NULL, " +
ACTOR2 + " TEXT NOT NULL, " +
DIRECTOR + " TEXT NOT NULL, " +
FAVOURITE + " BOOLEAN, " +
DESCRIPTION + " TEXT NOT NULL);"
);
Cursor countRows = db.rawQuery("SELECT count(*) FROM FILMTABLE", null);
countRows.moveToFirst();
int NumRows = countRows.getInt(0);
countRows.close();
if (NumRows == 0) {
ContentValues values = new ContentValues();
values.put("film", "Wolf of Wall Street");
values.put("actor", "Leonardo Dicaprio");
values.put("actor2", "Jonah Hill");
values.put("director", "Martin Scorses");
values.put("description", "Description");
db.insert("FILMTABLE", null, values);
values.clear();
values.put("film", "Captain Philips");
values.put("actor", "Tom Hanks");
values.put("actor2", "Catherine Keener");
values.put("director", "Paul Greengrass");
values.put("description", "Description");
db.insert("FILMTABLE", null, values);
values.clear();
}
}
The answer to this question lies in the use of ListViews (https://developer.android.com/reference/android/widget/ListView.html). Basically you should create an ArrayAdapter which takes in a List of FilmObjects you retrieve from the database. In this adapter you will define how you want this data shown for each row. When you attach the adapter to the listview Android will take care of the visualization of the each row.
This tutorial will definitely help:http://developer.android.com/guide/topics/ui/layout/listview.html
I would advice to get rid of the seperate Strings that make up a movie but instead make a class that contains all these fields. This allows for much easier data handling.

Categories