I have made a content provider for my project, and also another project for content resolver.
but suddenly content resolver app is stop running.
this is the content provider app:
package com.example.connectly.database;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import static android.content.Context.MODE_PRIVATE;
public class SeekersContactsProvider extends ContentProvider {
SQLiteDatabase seekerSQLiteDatabase;
private static final String AUTHORITY = "com.example.connectly";
private static final String BASE_PATH = "seekers";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);
private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
private static final int SEEKER = 0;
// private static final String SEEKER_EMAIL = "email";
private static final int SEEKER_EMAIL = 1;
private static final String SEEKER_TABLE_NAME = "seeker";
Cursor cursor;
public static final String[] ALL_COLUMNS =
{"email", "password", "firstname", "lastname","phone","age","dob","gender"};
static {
uriMatcher.addURI(AUTHORITY, BASE_PATH, SEEKER);
// uriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", EMAIL);
uriMatcher.addURI(AUTHORITY, BASE_PATH + "/" + SEEKER_TABLE_NAME, SEEKER_EMAIL);
}
#Override
public boolean onCreate() {
seekerSQLiteDatabase = getContext().openOrCreateDatabase("Users", MODE_PRIVATE, null);
seekerSQLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS seeker (email VARCHAR, password VARCHAR, firstname VARCHAR, lastname VARCHAR, phone VARCHAR, age VARCHAR, dob VARCHAR, gender VARCHAR)");
return true;
}
#Nullable
#Override
public Cursor query(#NonNull Uri uri, #Nullable String[] projection, #Nullable String selection, #Nullable String[] selectionArgs, #Nullable String sortOrder) {
switch (uriMatcher.match(uri)) {
case SEEKER:
cursor = seekerSQLiteDatabase.query(SEEKER_TABLE_NAME, ALL_COLUMNS,selection
, null, null, null, "firstname" + " ASC");
break;
default:
throw new IllegalArgumentException("This is an Unknown URI " + uri);
}
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
#Nullable
#Override
public String getType(#NonNull Uri uri) {
switch (uriMatcher.match(uri)) {
case SEEKER:
return "com.example.connectly/seeker";
default:
throw new IllegalArgumentException("This is an Unknown URI " + uri);
}
}
#Nullable
#Override
public Uri insert(#NonNull Uri uri, #Nullable ContentValues contentValues) {
long id = seekerSQLiteDatabase.insert(SEEKER_TABLE_NAME, null, contentValues);
if (id > 0) {
Uri _uri = ContentUris.withAppendedId(CONTENT_URI, id);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}
throw new SQLException("Insertion Failed for URI :" + uri);
}
#Override
public int delete(#NonNull Uri uri, #Nullable String selection, #Nullable String[] selectionArgs) {
int delCount = 0;
switch (uriMatcher.match(uri)) {
case SEEKER:
delCount = seekerSQLiteDatabase.delete(SEEKER_TABLE_NAME, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("This is an Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return delCount;
}
#Override
public int update(#NonNull Uri uri, #Nullable ContentValues values, #Nullable String selection, #Nullable String[] selectionArgs) {
int updCount = 0;
switch (uriMatcher.match(uri)) {
case SEEKER:
updCount = seekerSQLiteDatabase.update(SEEKER_TABLE_NAME, values, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("This is an Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return updCount;
}
}
this is the content resolver code, but when I run the app and click on the load data button, it suddenly stops:
p
ackage com.example.App2ContentProvider;
import androidx.appcompat.app.AppCompatActivity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Button loadBtn;
Uri CONTENT_URI = Uri.parse("content://com.example.connectly/seekers");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadBtn = findViewById(R.id.load);
loadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// inserting complete table details in this text field
TextView resultView = (TextView) findViewById(R.id.textView);
// creating a cursor object of the
// content URI
Cursor cursor = getContentResolver().query(Uri.parse("content://com.example.connectly/seekers"), null, null, null, null);
// iteration of the cursor
// to print whole table
if (cursor.moveToFirst()) {
StringBuilder strBuild = new StringBuilder();
while (!cursor.isAfterLast()) {
strBuild.append("\n" + cursor.getString(
cursor.getColumnIndex("firstname")) + "-" + cursor.getString(cursor.getColumnIndex("lastname")) + cursor.getString(cursor.getColumnIndex("email")) + cursor.getString(cursor.getColumnIndex("phone")) +
cursor.getString(cursor.getColumnIndex("age")) + cursor.getString(cursor.getColumnIndex("dob")) +
cursor.getString(cursor.getColumnIndex("gender")) );
cursor.moveToNext();
}
resultView.setText(strBuild);
} else {
resultView.setText("No Records Found");
}
}
});
}
}
and this is the error shown:
FATAL EXCEPTION: main
Process: com.example.contentprovider_p2, PID: 9084
java.lang.NullPointerException: Attempt to invoke interface method 'boolean android.database.Cursor.moveToFirst()' on a null object reference
at com.example.App2ContentProvider.MainActivity$1.onClick(MainActivity.java:35)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
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)
Related
I am trying to write a program CFM.java to insert data into product table using content provider using android studio.
But the app crashes after clicking on the add button to add record to the database.
I can't solve the issue.
Any help is sincerely appreciated.
MyContentProvider.java
`
package com.example.cfm;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import java.util.HashMap;
import android.text.TextUtils;
public class MyContentProvider extends ContentProvider {
public MyContentProvider() {}
static final String PROVIDER_NAME = "com.example.cfm.MyContentProvider";
static final String URL = "content://" + PROVIDER_NAME + "/food_products";
static final Uri CONTENT_URI = Uri.parse(URL);
static final String _ID = "_id";
static final String NAME = "name";
static final String COSTPERITEM = "cost";
static final String NOOFITEMS = "itemsno";
private static HashMap<String, String> PRODUCT_PROJECTION_MAP;
static final int PRODUCTS = 1;
static final int PRODUCTS_ID = 2;
static final UriMatcher uriMatcher;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "products", PRODUCTS);
uriMatcher.addURI(PROVIDER_NAME, "products/#",PRODUCTS_ID);
}
private SQLiteDatabase db;
static final String DATABASE_NAME = "ProductDetails";
static final String PRODUCT_TABLE_NAME = "food_products";
static final int DATABASE_VERSION = 1;
static final String CREATE_TABLE = " CREATE TABLE " + PRODUCT_TABLE_NAME+
" (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ " name TEXT NOT NULL," +
"cost DECIMAL(6,2) NOT NULL,"+
"itemsno INTEGER NOT NULL)";
private static class DatabaseHelper extends SQLiteOpenHelper{
DatabaseHelper (Context context){
super(context, DATABASE_NAME ,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(CREATE_TABLE);
}
public void onUpgrade(SQLiteDatabase db,int previousversion,int newversion)
{
db.execSQL("DROP TABLE IF EXISTS " + PRODUCT_TABLE_NAME);
onCreate(db);
}
}
#Override
public boolean onCreate() {
Context context = getContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
db = dbHelper.getWritableDatabase();
if (db != null) {
return true;
}
return false;
}
#Override
public Uri insert(Uri uri, ContentValues values) throws SQLException {
long rowID = db.insert("PRODUCT_TABLE_NAME", "", values);
if (rowID > 0) {
Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}
throw new SQLException("RECORD NOT ADDED INTO" + uri);
}
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(PRODUCT_TABLE_NAME);
switch (uriMatcher.match(uri)) {
case PRODUCTS:
qb.setProjectionMap(PRODUCT_PROJECTION_MAP);
break;
case PRODUCTS_ID:
qb.appendWhere( _ID + "=" + uri.getPathSegments().get(1));
break;
default:
}
if (sortOrder == null || sortOrder =="") {
sortOrder = NAME;
}
Cursor c = qb.query(db, projection, selection, selectionArgs, null,
null, sortOrder);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs)
{
int count = 0;
switch (uriMatcher.match(uri)){
case PRODUCTS:
count = db.delete(PRODUCT_TABLE_NAME,_ID + " id = ?"+ (!TextUtils.isEmpty(selection)? "AND(" + selection + ')' : ""), selectionArgs);
break;
default:
throw new IllegalArgumentException("UNKOWN URI " + uri );
}
getContext().getContentResolver().notifyChange(uri,null);
return count;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)) {
case PRODUCTS:
count = db.update(PRODUCT_TABLE_NAME, values, selection, selectionArgs);
break;
case PRODUCTS_ID:
count = db.update(PRODUCT_TABLE_NAME,values,_ID+"="+uri.getPathSegments().get(1) +
(!TextUtils.isEmpty(selection) ?"AND (" + selection + ')':
""), selectionArgs);
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
#Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
case PRODUCTS:
return "vnd.android.cursor.dir/vnd.example.food_products";
case PRODUCTS_ID:
return "und.android.cursor.item/vnd.example.students";
default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
}
}
MainActivity.java
package com.example.cfm;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button add;
EditText Name;
EditText Cost;
EditText No;
TextView seeProduct;
TextView seeCost;
TextView seeNo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add = findViewById(R.id.btnAdd);
Name = findViewById(R.id.editText1);
No = findViewById(R.id.editText2);
Cost = findViewById(R.id.editText3);
seeProduct = findViewById(R.id.product);
seeCost = findViewById(R.id.cost);
seeNo = findViewById(R.id.no);
}
public void onClickAddName(View view) {
ContentValues values = new ContentValues();
values.put(MyContentProvider.NAME, (Name).getText().toString());
values.put(MyContentProvider.NOOFITEMS, (No).getText().toString());
values.put(MyContentProvider.COSTPERITEM, (Cost).getText().toString());
Uri uri = getContentResolver().insert(MyContentProvider.CONTENT_URI, values);
//Name.setText("");
assert uri != null;
Toast.makeText(getBaseContext(),uri.toString(), Toast.LENGTH_LONG).show();
}
}
Stack Trace on Clicking the ADD button
Caused by: android.database.SQLException: RECORD NOT ADDED INTOcontent://com.example.cfm.MyContentProvider/food_products
at com.example.cfm.MyContentProvider.insert(MyContentProvider.java:76)
at android.content.ContentProvider.insert(ContentProvider.java:1673)
at android.content.ContentProvider$Transport.insert(ContentProvider.java:336)
at android.content.ContentResolver.insert(ContentResolver.java:2149)
at android.content.ContentResolver.insert(ContentResolver.java:2111)
at com.example.cfm.MainActivity.onClickAddName(MainActivity.java:39)
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28296)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
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)
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
The logcat is here:
list view activity --> clicked item(admin_parents_item) ---> option selected EDIT (current activity)
When I click on my button to update/edit the database it crashes. Something is missing. How to fix this error?
03-08 06:44:57.163 11022-11022/edu.angelo.parentsportal E/AndroidRuntime: FATAL EXCEPTION: main
Process: edu.angelo.parentsportal, PID: 11022
java.lang.NullPointerException: Attempt to invoke virtual method 'void edu.angelo.parentsportal.DatabaseHelper.updateData(int, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)' on a null object reference
at edu.angelo.parentsportal.Admin_Parents_Item_Edit$1.onClick(Admin_Parents_Item_Edit.java:63)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
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:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
admin_parent__item_edit.java (my current activity)
package edu.angelo.parentsportal;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Admin_Parents_Item_Edit extends AppCompatActivity {
Button btn_update;
EditText ed_Name;
EditText ed_Surname;
EditText ed_Email;
EditText ed_Phone_Number;
EditText ed_Password;
String s_Id;
String s_Name;
String s_Surname;
String s_Email;
String s_Phone_Number;
String s_Password;
Integer getId;
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin__parents__item__edit);
ed_Name = findViewById(R.id.ed_name_update);
ed_Surname = findViewById(R.id.ed_surname_update);
ed_Email = findViewById(R.id.ed_email_update);
ed_Phone_Number = findViewById(R.id.ed_PhoneNumber_update);
ed_Password = findViewById(R.id.ed_password_update);
Intent intent = getIntent();
s_Id = intent.getStringExtra("ID");
s_Name = intent.getStringExtra("Name");
s_Surname = intent.getStringExtra("Surname");
s_Email = intent.getStringExtra("Email Address");
s_Phone_Number = intent.getStringExtra("Phone number");
s_Password = intent.getStringExtra("Password");
getId = Integer.parseInt(s_Id);
ed_Name.setText(s_Name);
ed_Surname.setText(s_Surname);
ed_Email.setText(s_Email);
ed_Phone_Number.setText(s_Phone_Number);
ed_Password.setText(s_Password);
btn_update = findViewById(R.id.btn_admin_parent_update);
btn_update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
databaseHelper.updateData(getId,
ed_Name.getText().toString(),
ed_Surname.getText().toString(),
ed_Email.getText().toString(),
ed_Phone_Number.getText().toString(),
ed_Password.getText().toString());
finish();
}
});
}
}
Admin_parent_Item (my previous activity)
package edu.angelo.parentsportal;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
public class Admin_Parents_Item extends AppCompatActivity {
TextView tv_Id;
TextView tv_Name;
TextView tv_Surname;
TextView tv_Email;
TextView tv_Phone_Number;
TextView tv_Password;
String s_Id;
String s_Name;
String s_Surname;
String s_Email;
String s_Phone_Number;
String s_Password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin__parents__item);
tv_Id = findViewById(R.id.tv_id_info);
tv_Name = findViewById(R.id.tv_name_info);
tv_Surname = findViewById(R.id.tv_surname_info);
tv_Email = findViewById(R.id.tv_email_info);
tv_Phone_Number = findViewById(R.id.tv_PhoneNumber_info);
tv_Password = findViewById(R.id.tv_password_info);
Intent intent = getIntent();
if (intent != null) {
s_Id = intent.getStringExtra("ID");
s_Name = intent.getStringExtra("Name");
s_Surname = intent.getStringExtra("Surname");
s_Email = intent.getStringExtra("Email Address");
s_Phone_Number = intent.getStringExtra("Phone Number");
s_Password = intent.getStringExtra("Password");
}
tv_Id.setText(s_Id);
tv_Name.setText(s_Name);
tv_Surname.setText(s_Surname);
tv_Email.setText(s_Email);
tv_Phone_Number.setText(s_Phone_Number);
tv_Password.setText(s_Password);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.admin__parents_item, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case R.id.admin_parent_item_action_edit: {
Intent intent = new Intent(this, Admin_Parents_Item_Edit.class);
intent.putExtra("ID", s_Id);
intent.putExtra("Name", s_Name);
intent.putExtra("Surname", s_Surname);
intent.putExtra("Email Address", s_Email);
intent.putExtra("Phone number", s_Phone_Number);
intent.putExtra("Password", s_Password);
startActivity(intent);
finish();
break;
}
}
return super.onOptionsItemSelected(item);
}
}
DatabaseHelper.java
package edu.angelo.parentsportal;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Parents_Portal.db";
public static final String TABLE_NAME = "Parents_Table";
public static final String COL_0 = "ID";
public static final String COL_1 = "NAME";
public static final String COL_2 = "SURNAME";
public static final String COL_3 = "EMAIL_ADDRESS";
public static final String COL_4 = "PHONE_NUMBER";
public static final String COL_5 = "PASSWORD";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +"(ID INTEGER PRIMARY KEY
AUTOINCREMENT, NAME TEXT, SURNAME TEXT, EMAIL_ADDRESS TEXT, PHONE_NUMBER TEXT,
PASSWORD 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 name, String surname, String email_address,
String phone_number, String password) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1, name);
contentValues.put(COL_2, surname);
contentValues.put(COL_3, email_address);
contentValues.put(COL_4, phone_number);
contentValues.put(COL_5, password);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) {
return false;
}
else {
return true;
}
}
public Cursor getAllData() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor result = db.rawQuery("select * from " + TABLE_NAME, null);
return result;
}
public ArrayList<ParentModel> getAllParentsData() {
ArrayList<ParentModel> list = new ArrayList<>();
String sql = "select * from " + TABLE_NAME;
SQLiteDatabase mydb = this.getWritableDatabase();
Cursor cursor = mydb.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
ParentModel parentModel = new ParentModel();
parentModel.setID(cursor.getString(0));
parentModel.setName(cursor.getString(1));
parentModel.setSurname(cursor.getString(2));
parentModel.setEmail(cursor.getString(3));
parentModel.setPhone_number(cursor.getString(4));
parentModel.setPassword(cursor.getString(5));
list.add(parentModel);
}
while (cursor.moveToNext())
;
}
return list;
}
public void updateData(int id, String name, String surname, String email,
String phone_number, String password) {
ContentValues contentValues = new ContentValues();
String sql = "select * from " + TABLE_NAME;
SQLiteDatabase mydb = this.getWritableDatabase();
Cursor cursor = mydb.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
contentValues.put(COL_1, name);
contentValues.put(COL_2, surname);
contentValues.put(COL_3, email);
contentValues.put(COL_4, phone_number);
contentValues.put(COL_5, password);
}
while (cursor.moveToNext());
}
mydb.update(TABLE_NAME, contentValues, COL_0 + "=" + id, null);
mydb.close();
}
}
Your databaseHelper is null. Initialize it in onCreate() like below.
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin__parents__item__edit);
databaseHelper = new DatabaseHelper (this); // Add this line
.........................
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to practise on the loader and content provider i have a database of students that contains (name , degree) in the activity_main.xml i have a recyclerview and 2 editText one for name other for degree my target is that when a user click on the button the name will appear in the recyclerview
here's my logcat
FATAL EXCEPTION: main
Process: com.example.abdelmagied.myapplication, PID: 16160
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.abdelmagied.myapplication.recyclerview.swapcursor(android.database.Cursor)' on a null object reference
at com.example.abdelmagied.myapplication.MainActivity.onLoadFinished(MainActivity.java:97)
at com.example.abdelmagied.myapplication.MainActivity.onLoadFinished(MainActivity.java:17)
at android.support.v4.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:476)
at android.support.v4.app.LoaderManagerImpl$LoaderInfo.onLoadComplete(LoaderManager.java:444)
at android.support.v4.content.Loader.deliverResult(Loader.java:126)
at android.support.v4.content.CursorLoader.deliverResult(CursorLoader.java:105)
at android.support.v4.content.CursorLoader.deliverResult(CursorLoader.java:37)
at android.support.v4.content.AsyncTaskLoader.dispatchOnLoadComplete(AsyncTaskLoader.java:255)
at android.support.v4.content.AsyncTaskLoader$LoadTask.onPostExecute(AsyncTaskLoader.java:80)
at android.support.v4.content.ModernAsyncTask.finish(ModernAsyncTask.java:485)
at android.support.v4.content.ModernAsyncTask$InternalHandler.handleMessage(ModernAsyncTask.java:502)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
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)
this is my mainactivity class
package com.example.abdelmagied.myapplication;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor>{
public static final String[] MAIN_STUDENT_PROJECTION = {
studentContract.StudentEntry._ID ,
studentContract.StudentEntry.COLUMN_NAME ,
studentContract.StudentEntry.COLUMN_DEGREE ,
};
public static final int INDEX_COLUMN_ID = 0;
public static final int INDEX_COLUMN_NAME = 1;
public static final int INDEX_COLUMN_DEGREE = 2;
private recyclerview recyclerAdapter;
private int mposition = RecyclerView.NO_POSITION;
public static final int ID_STUDNET_LOADER = 99;
// details of the recyclerview
RecyclerView recycler;
RecyclerView.Adapter myadapter;
RecyclerView.LayoutManager mymanager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// adjust the recyclerview
recycler = (RecyclerView) findViewById(R.id.recyclerid);
myadapter = new recyclerview(this);
mymanager = new LinearLayoutManager(this);
recycler.setAdapter(myadapter);
recycler.setLayoutManager(mymanager);
getSupportLoaderManager().initLoader(ID_STUDNET_LOADER , null , this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
switch(id)
{
case ID_STUDNET_LOADER :
Uri Query = studentContract.StudentEntry.CONTENT_URI;
return new CursorLoader(this ,
Query ,
MAIN_STUDENT_PROJECTION ,
null ,
null ,
null
);
default:
throw new RuntimeException("Loader is not implemented : " + id);
}
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
recyclerAdapter.swapcursor(data);
if(mposition == RecyclerView.NO_POSITION) mposition = 0;
recycler.smoothScrollToPosition(mposition);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
recyclerAdapter.swapcursor(null);
}
public void addtodatabase(View view) {
EditText name = (EditText) findViewById(R.id.name);
EditText degree=(EditText) findViewById(R.id.degree);
// make a contentvalues and put name , degree , salary on it...
ContentValues values = new ContentValues();
values.put(studentContract.StudentEntry.COLUMN_NAME , name.getText().toString());
values.put(studentContract.StudentEntry.COLUMN_DEGREE , degree.getText().toString());
getContentResolver().insert(studentContract.StudentEntry.CONTENT_URI , values);
}
}
here's the recyclerview adapter
package com.example.abdelmagied.myapplication;
import android.content.Context;
import android.database.Cursor;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by AbdELMagied on 8/4/2017.
*/
public class recyclerview extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context context;
private Cursor mycursor;
public recyclerview(Context context) {
this.context = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recyclerrow , parent , false);
return new viewholder(view);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
mycursor.move(position);
viewholder myholder = (viewholder) holder;
myholder.mytxt.setText(mycursor.getString(MainActivity.INDEX_COLUMN_NAME));
}
void swapcursor(Cursor mycurso)
{
this.mycursor = mycurso;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
if(mycursor == null) return 0;
return mycursor.getCount();
}
public class viewholder extends RecyclerView.ViewHolder
{
public TextView mytxt;
public viewholder(View itemView) {
super(itemView);
mytxt = (TextView) itemView.findViewById(R.id.textView);
}
}
}
here's my content provider
package com.example.abdelmagied.myapplication;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.text.TextUtils;
/**
* Created by AbdELMagied on 8/4/2017.
*/
public class studentprovider extends ContentProvider {
databaseopenhelper mydatabase;
static final int STUDENT = 100;
static final int STUDENT_WITH_ID = 101;
private UriMatcher urimatcher = matcher();
private UriMatcher matcher() {
UriMatcher mymatcher = new UriMatcher(UriMatcher.NO_MATCH);
mymatcher.addURI(studentContract.authority, "student", STUDENT);
mymatcher.addURI(studentContract.authority, "student/#", STUDENT_WITH_ID);
return mymatcher;
}
#Override
public boolean onCreate() {
mydatabase = new databaseopenhelper(getContext());
return true;
}
#Nullable
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Cursor returncursor;
switch (urimatcher.match(uri)) {
case STUDENT:
returncursor = mydatabase.getReadableDatabase().query(
studentContract.StudentEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
break;
case STUDENT_WITH_ID:
String where = "_id = " + uri.getLastPathSegment() + (!TextUtils.isEmpty(selection)? " AND " + selection : "");
returncursor = mydatabase.getReadableDatabase().query(
studentContract.StudentEntry.TABLE_NAME,
projection,
where,
selectionArgs,
null,
null,
sortOrder
);
break;
default:
throw new UnsupportedOperationException("not found uri " + uri);
}
returncursor.setNotificationUri(getContext().getContentResolver() , uri);
return returncursor;
}
#Nullable
#Override
public String getType(Uri uri) {
return null;
}
#Nullable
#Override
public Uri insert(Uri uri, ContentValues values) {
long rowid = mydatabase.getWritableDatabase().insert(studentContract.StudentEntry.TABLE_NAME, null , values);
if(rowid > 0)
{
Uri _uri = ContentUris.withAppendedId(studentContract.StudentEntry.CONTENT_URI, rowid);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}
throw new SQLException("Faild to add a record " + uri);
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
if(selection == "") selection= "1";
int numberofdeleted = 0;
switch (urimatcher.match(uri))
{
case STUDENT:
String where = "_id = " + uri.getLastPathSegment() + (!TextUtils.isEmpty(selection)? "AND " + selection : "");
numberofdeleted = mydatabase.getWritableDatabase().delete("students" , where , selectionArgs);
break;
default:
throw new UnsupportedOperationException("uri not found " + uri);
}
if(numberofdeleted != 0)
{
getContext().getContentResolver().notifyChange(uri , null);
}
return numberofdeleted;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
}
here's the database class
package com.example.abdelmagied.myapplication;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by AbdELMagied on 8/4/2017.
*/
public class databaseopenhelper extends SQLiteOpenHelper {
public databaseopenhelper(Context context) {
super(context, "student.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
final String SQL_CREATE_STUDENT_TABLE =
"CREATE TABLE " + studentContract.StudentEntry.TABLE_NAME + " (" +
studentContract.StudentEntry._ID + " INTEGER PRIMARY KEY , " +
studentContract.StudentEntry.COLUMN_NAME + " TEXT , " +
studentContract.StudentEntry.COLUMN_DEGREE + " TEXT ); " ;
db.execSQL(SQL_CREATE_STUDENT_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop database if exists student");
onCreate(db);
}
}
here's studentcontract class
package com.example.abdelmagied.myapplication;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.text.TextUtils;
/**
* Created by AbdELMagied on 8/4/2017.
*/
public class studentprovider extends ContentProvider {
databaseopenhelper mydatabase;
static final int STUDENT = 100;
static final int STUDENT_WITH_ID = 101;
private UriMatcher urimatcher = matcher();
private UriMatcher matcher() {
UriMatcher mymatcher = new UriMatcher(UriMatcher.NO_MATCH);
mymatcher.addURI(studentContract.authority, "student", STUDENT);
mymatcher.addURI(studentContract.authority, "student/#", STUDENT_WITH_ID);
return mymatcher;
}
#Override
public boolean onCreate() {
mydatabase = new databaseopenhelper(getContext());
return true;
}
#Nullable
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Cursor returncursor;
switch (urimatcher.match(uri)) {
case STUDENT:
returncursor = mydatabase.getReadableDatabase().query(
studentContract.StudentEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
break;
case STUDENT_WITH_ID:
String where = "_id = " + uri.getLastPathSegment() + (!TextUtils.isEmpty(selection)? " AND " + selection : "");
returncursor = mydatabase.getReadableDatabase().query(
studentContract.StudentEntry.TABLE_NAME,
projection,
where,
selectionArgs,
null,
null,
sortOrder
);
break;
default:
throw new UnsupportedOperationException("not found uri " + uri);
}
returncursor.setNotificationUri(getContext().getContentResolver() , uri);
return returncursor;
}
#Nullable
#Override
public String getType(Uri uri) {
return null;
}
#Nullable
#Override
public Uri insert(Uri uri, ContentValues values) {
long rowid = mydatabase.getWritableDatabase().insert(studentContract.StudentEntry.TABLE_NAME, null , values);
if(rowid > 0)
{
Uri _uri = ContentUris.withAppendedId(studentContract.StudentEntry.CONTENT_URI, rowid);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}
throw new SQLException("Faild to add a record " + uri);
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
if(selection == "") selection= "1";
int numberofdeleted = 0;
switch (urimatcher.match(uri))
{
case STUDENT:
String where = "_id = " + uri.getLastPathSegment() + (!TextUtils.isEmpty(selection)? "AND " + selection : "");
numberofdeleted = mydatabase.getWritableDatabase().delete("students" , where , selectionArgs);
break;
default:
throw new UnsupportedOperationException("uri not found " + uri);
}
if(numberofdeleted != 0)
{
getContext().getContentResolver().notifyChange(uri , null);
}
return numberofdeleted;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
}
recyclerAdapter is never instantiated. onCreate would be an ideal place to instantiate this object of type recyclerview.
So after editing a method in my MainAcivity, I'm getting a RuntimeException.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tim.timapp
/com.example.tim.timapp.MainActivity}: java.lang.IllegalStateException:
Activity has been destroyed
I honestly have no idea where this is coming from. Searching online suggests that it's a big with the ChildFragmentManager, but doesn't give me a fix that works for me.
Any idea what I can do to fix this exception?
PS. If you need any more code or info, let me know. My mind is quite flustered by this error, so I might overlooked some stuff here.
Full log:
03-30 21:19:47.910 24785-24785/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.tim.timapp, PID: 24785
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tim.timapp/com.example.tim.timapp.MainActivity}: java.lang.IllegalStateException: Activity has been destroyed
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
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)
Caused by: java.lang.IllegalStateException: Activity has been destroyed
at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1433)
at android.app.BackStackRecord.commitInternal(BackStackRecord.java:687)
at android.app.BackStackRecord.commit(BackStackRecord.java:663)
at com.example.tim.timapp.MainActivity.DrawVariableFragments(MainActivity.java:271)
at com.example.fragments.Settings.GeneralSettingsFragment.onCreateView(GeneralSettingsFragment.java:57)
at android.app.Fragment.performCreateView(Fragment.java:2220)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:973)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1148)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1130)
at android.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:1953)
at android.app.FragmentController.dispatchActivityCreated(FragmentController.java:152)
at android.app.Activity.performCreateCommon(Activity.java:6232)
at android.app.Activity.performCreate(Activity.java:6239)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
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)
MainActivity (Sorry about the mess, it's a WIP):
Sorry about this, but I went over the 30.000 characters limit with the entire file.
http://pastebin.com/XZ9k995G
DBHandler (Was giving me grief earlier, so might have something to do with it):
package com.example.tim.timapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.util.Log;
import java.util.ArrayList;
public class DBHandler extends SQLiteOpenHelper {
private static String tag = "TEST DBHandler";
private static DBHandler sInstance;
// Database Stuff
private static final int DATABASE_VERSION = 6;
private static final String DATABASE_NAME = "LinkDatabase.db";
// Table Stuff
private static final String TABLE_LinkTable = "LinkTable";
private static final String TABLE_SettingsTable = "SettingsTable";
// LinkTable Stuff
private static final String LT_COLUMN_ID = "_id";
private static final String LT_COLUMN_NAME = "name";
private static final String LT_COLUMN_TAG = "tag";
// SettingsTable Stuff
private static final String ST_COLUMN_ID = "_id";
private static final String ST_COLUMN_NAME = "name";
private static final String ST_COLUMN_IP = "ip";
private static final String ST_COLUMN_PORT = "port";
private static final String ST_COLUMN_USERNAME = "username";
private static final String ST_COLUMN_PASS = "pass";
// Table Create Statements
// LinkTable Create Statement
private static final String CREATE_TABLE_LINKS =
"CREATE TABLE " + TABLE_LinkTable + "(" +
LT_COLUMN_ID + " INTEGER PRIMARY KEY, " +
LT_COLUMN_NAME + " TEXT, " +
LT_COLUMN_TAG + " TEXT" + ");";
// SettingsTable Create Statement
private static final String CREATE_TABLE_SETTINGS =
"CREATE TABLE " + TABLE_SettingsTable + "(" +
ST_COLUMN_ID + " INTEGER PRIMARY KEY, " +
ST_COLUMN_NAME + " TEXT, " +
ST_COLUMN_IP + " TEXT, " +
ST_COLUMN_PORT + " TEXT, " +
ST_COLUMN_USERNAME + " TEXT, " +
ST_COLUMN_PASS + " TEXT" + ");";
// TODO: 28-Mar-16 DON"T FORGET TO UPDATE
// Don't forget to update this when adding a new table.
private static final ArrayList<String> createTablesArray = new ArrayList<String>() {{add(CREATE_TABLE_LINKS); add(CREATE_TABLE_SETTINGS);}};
private static final ArrayList<String> tableNamesArray = new ArrayList<String>() {{add(TABLE_LinkTable); add(TABLE_SettingsTable);}};
public ArrayList<String> tagArray;
public static synchronized DBHandler getInstance(Context context) {
if (sInstance == null) {
Log.d(tag, "sInstance == null");
sInstance = new DBHandler(context.getApplicationContext());
}
return sInstance;
}
private DBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
for (String s : createTablesArray) {
db.execSQL(s);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
for (String s : tableNamesArray) {
db.execSQL("DROP TABLE IF EXISTS " + s);
}
onCreate(db);
}
public ArrayList<String> returnArray(String base, String column) {
SQLiteDatabase db;
db = getWritableDatabase();
String TABLENAME;
if (base.equalsIgnoreCase("StuffManager")) {
TABLENAME = TABLE_LinkTable;
} else if (base.equalsIgnoreCase("GeneralSettings")) {
TABLENAME = TABLE_SettingsTable;
} else {
Log.e(tag, "String Base not recognised");
return null;
}
String query = "SELECT * FROM " + TABLENAME + " WHERE 1";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
ArrayList<String> tempArray = new ArrayList<>();
int i = 0;
while(!c.isAfterLast()){
if(c.getString(c.getColumnIndex(column)) != null){
tempArray.add(i, c.getString(c.getColumnIndex(column)));
} else {
Log.e(tag, "String Column not recognised");
return null;
}
c.moveToNext();
i++;
}
c.close();
if (db != null && db.isOpen()) {
db.close();
}
return tempArray;
}
// *** --------- ***
//
// All methods for the SETTINGS_TABLES
//
// *** --------- ***
public void addSettings(String name, String ip, String port, String username, String pass) {
ContentValues values = new ContentValues();
values.put(ST_COLUMN_NAME, name);
values.put(ST_COLUMN_IP, ip);
values.put(ST_COLUMN_PORT, port);
values.put(ST_COLUMN_USERNAME, username);
values.put(ST_COLUMN_PASS, pass);
SQLiteDatabase db;
db = getWritableDatabase();
db.insert(TABLE_SettingsTable, null, values);
db.close();
}
public void updateSettings(int id, String name, String ip, String port, String username, String pass) {
ContentValues values = new ContentValues();
values.put(ST_COLUMN_NAME, name);
values.put(ST_COLUMN_IP, ip);
values.put(ST_COLUMN_PORT, port);
values.put(ST_COLUMN_USERNAME, username);
values.put(ST_COLUMN_PASS, pass);
SQLiteDatabase db;
db = getWritableDatabase();
db.update(TABLE_SettingsTable, values, "_id=" + id, null);
db.close();
}
public void deleteSettings(String name) {
SQLiteDatabase db;
db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_SettingsTable + " WHERE " + ST_COLUMN_NAME + "=\"" + name + "\";");
db.close();
}
public void deleteAllSettings() {
SQLiteDatabase db;
db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_SettingsTable + " WHERE 1");
db.close();
}
public float settingsTableSize() {
SQLiteDatabase db;
db = getReadableDatabase();
float amount = DatabaseUtils.queryNumEntries(db, TABLE_SettingsTable);
db.close();
return amount;
}
public ArrayList<String> settingsNameArrayMethod() {
SQLiteDatabase db;
db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_SettingsTable + " WHERE 1";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
int i = 0;
ArrayList<String> nameArray = new ArrayList<>();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("name")) != null) {
nameArray.add(i, c.getString(c.getColumnIndex("name")));
}
c.moveToNext();
i++;
}
c.close();
db.close();
return nameArray;
}
// *** --------- ***
//
// All methods for the LINK_TABLES
//
// *** --------- ***
public void addStuffLink(String name, String tag) {
ContentValues values = new ContentValues();
values.put(LT_COLUMN_NAME, name);
values.put(LT_COLUMN_TAG, tag);
SQLiteDatabase db;
db = getWritableDatabase();
db.insert(TABLE_LinkTable, null, values);
db.close();
}
public Bundle updateStuffLink(int id, String name, String tag) {
ContentValues values = new ContentValues();
values.put(LT_COLUMN_NAME, name);
values.put(LT_COLUMN_TAG, tag);
SQLiteDatabase db;
db = getWritableDatabase();
db.update(TABLE_LinkTable, values, "_id=" + id, null);
db.close();
ArrayList<String> nameArray = stuffLinksNameArrayMethod();
ArrayList<String> tagArray = tagArrayMethod();
Bundle bundle = new Bundle();
bundle.putStringArrayList("nameArray", nameArray);
bundle.putStringArrayList("tagArray", tagArray);
return bundle;
}
public void deleteStuffLink(String name) {
SQLiteDatabase db;
db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_LinkTable + " WHERE " + LT_COLUMN_NAME + "=\"" + name + "\";");
db.close();
}
public void deleteAllStuffLinks() {
SQLiteDatabase db;
db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_LinkTable + " WHERE 1");
db.close();
}
public ArrayList<String> stuffLinksNameArrayMethod(){
SQLiteDatabase db;
db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_LinkTable + " WHERE 1";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
int i = 0;
ArrayList<String> nameArray = new ArrayList<>();
tagArray = new ArrayList<>();
while(!c.isAfterLast()){
if(c.getString(c.getColumnIndex("name")) != null){
nameArray.add(i, c.getString(c.getColumnIndex("name")));
tagArray.add(i, c.getString(c.getColumnIndex("tag")));
}
c.moveToNext();
i++;
}
c.close();
db.close();
return nameArray;
}
public ArrayList<String> tagArrayMethod() {
stuffLinksNameArrayMethod();
return tagArray;
}
public float stuffTableSize(){
SQLiteDatabase db;
db = getReadableDatabase();
float amount = DatabaseUtils.queryNumEntries(db, TABLE_LinkTable);
db.close();
return amount;
}
}
GeneralSettingsFragment
package com.example.fragments.Settings;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.example.fragments.MainFragments.DialogFragments.GeneralSettingsInitialInputDialog;
import com.example.fragments.MainFragments.VariableFragments.GeneralSettingsEmptyFragment;
import com.example.fragments.MainFragments.VariableFragments.GeneralSettingsVariableFragment;
import com.example.fragments.MainFragments.VariableFragments.StuffManagerVariableFragment;
import com.example.tim.timapp.DBHandler;
import com.example.tim.timapp.MainActivity;
import com.example.tim.timapp.R;
import java.util.ArrayList;
public class GeneralSettingsFragment extends Fragment {
DBHandler dbHandler;
MainActivity ma = new MainActivity();
private static Menu optionsMenu;
public static boolean hideDeleteAllButton = false;
LinearLayout linearLayout;
View rootView;
#Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_generalsettings, container, false);
linearLayout = (LinearLayout) rootView.findViewById(R.id.FragmentContainerGeneralSettings);
if (linearLayout == null) {
Log.e("GMF", "Layout is null");
} else if (linearLayout.getChildCount() == 0) {
GeneralSettingsInitialInputDialog GSIID = new GeneralSettingsInitialInputDialog();
GSIID.show(getFragmentManager(), "dialog");
hideDeleteAllButton = true;
} else {
hideDeleteAllButton = false;
}
ma.DrawVariableFragments("GeneralSettings", "draw");
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.stuffmanager_actionbuttons, menu);
optionsMenu = menu;
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
optionsMenu.findItem(R.id.removeAllButton).setVisible(!hideDeleteAllButton);
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addButton:
GeneralSettingsInitialInputDialog GSIID = new GeneralSettingsInitialInputDialog();
GSIID.show(getFragmentManager(), "dialog");
return true;
case R.id.removeAllButton:
dbHandler = DBHandler.getInstance(getActivity());
final ArrayList<String> nameArray = dbHandler.settingsNameArrayMethod();
final FragmentManager fm = getFragmentManager();
AlertDialog.Builder removeAllDialog = new AlertDialog.Builder(getActivity())
.setTitle("Delete all?")
.setMessage("Are you sure you want to delete all your devices? This is irreversible.")
.setIcon(R.drawable.ic_delete_black)
.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dbHandler.deleteAllSettings();
for (String name : nameArray){
fm.beginTransaction().remove(fm.findFragmentByTag(name)).commit();
}
fm.executePendingTransactions();
// TODO: 30-Mar-16 Add "No devices created" screen like stuffmanager
hideDeleteAllButton = true;
getActivity().invalidateOptionsMenu();
}
})
.setNegativeButton("Cancel", null);
removeAllDialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
MainActivity ma = new MainActivity();
This isn't valid in Android. You can't create an instance of an Activity like this because it isn't actually attached to the Android processes. This instance of MainActivity isn't going to step through any of the lifecycle methods, which is why you're seeing the error that the activity has been stopped. It was never actually started.
Instead, remove this reference to MainActivity, as it's bad practice to keep references like this around in your fragment. Any time you need an instance of MainActivity inside a fragment, use the following example:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// ...
MainActivity ma = (MainActivity) getActivity();
ma.DrawVariableFragments("GeneralSettings", "draw");
// ...
}
I am building an app that populates a ListView with a single random record from a SQLite DB every time I click on a "next" button for a guessing-style game. Currently I am able to pull a random record from the DB when the app opens, however, I do not know if I need a new class and I do not know where to put the code for the "next" button, nor do I know what the code should be. I'm basically trying to get the app to refresh the ListView with a new single random record from the DB every time someone clicks on a button that says "next". I already have the xml layout done and the app opens and displays the first random record perfectly. Thank you for any help! :)
MainActivity class:
package com.example.derek.guessinggame;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.Menu;
import android.view.MenuInflater;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager fragmentManager = getSupportFragmentManager();
if (fragmentManager.findFragmentById(android.R.id.content) == null) {
GuessListFragment guessListFragment = new GuessListFragment();
fragmentManager.beginTransaction().add(android.R.id.content, guessListFragment).commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
ContentProvider class:
package com.example.derek.guessinggame;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.util.Log;
public class GuessProvider extends ContentProvider {
private GuessDatabase mOpenHelper;
private static final String TAG = GuessProvider.class.getSimpleName();
private static final UriMatcher sUriMatcher = buildUriMatcher();
private static final int GUESS = 100;
private static final int GUESS_ID = 101;
private Uri uri;
private String selection;
private String[] selectionArgs;
private static UriMatcher buildUriMatcher() {
final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
final String authority = GuessContract.CONTENT_AUTHORITY;
matcher.addURI(authority, "guess", GUESS);
matcher.addURI(authority, "guess/*", GUESS_ID);
return matcher;
}
#Override
public boolean onCreate() {
mOpenHelper = new GuessDatabase(getContext());
return true;
}
private void deleteDatabase() {
mOpenHelper.close();
GuessDatabase.deleteDatabase(getContext());
mOpenHelper = new GuessDatabase(getContext());
}
#Override
public String getType(Uri uri) {
final int match = sUriMatcher.match(uri);
switch (match) {
case GUESS:
return GuessContract.Guess.CONTENT_TYPE;
case GUESS_ID:
return GuessContract.Guess.CONTENT_ITEM_TYPE;
default:
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
}
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
final int match = sUriMatcher.match(uri);
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(GuessDatabase.Tables.GUESS);
switch (match) {
case GUESS:
// do nothing
break;
case GUESS_ID:
String id = GuessContract.Guess.getGuessId(uri);
queryBuilder.appendWhere(BaseColumns._ID + "=" + id);
break;
default:
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
return cursor;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
Log.v(TAG, "insert(uri=" + uri + ", values=" + values.toString());
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
switch (match) {
case GUESS:
long recordId = db.insertOrThrow(GuessDatabase.Tables.GUESS, null, values);
return GuessContract.Guess.buildGuessUri(String.valueOf(recordId));
default:
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Log.v(TAG, "update(uri=" + uri + ", values=" + values.toString());
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
String selectionCriteria = selection;
switch (match) {
case GUESS:
// do nothing
break;
case GUESS_ID:
String id = GuessContract.Guess.getGuessId(uri);
selectionCriteria = BaseColumns._ID + "=" + id
+ (!TextUtils.isEmpty(selection) ? " AND (" + selection + ")" : "");
break;
default:
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
return db.update(GuessDatabase.Tables.GUESS, values, selectionCriteria, selectionArgs);
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
Log.v(TAG, "delete(uri=" + uri);
if (uri.equals(GuessContract.BASE_CONTENT_URI)) {
deleteDatabase();
return 0;
}
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
switch (match) {
case GUESS_ID:
String id = GuessContract.Guess.getGuessId(uri);
String selectionCriteria = BaseColumns._ID + "=" + id
+ (!TextUtils.isEmpty(selection) ? " AND (" + selection + ")" : "");
return db.delete(GuessDatabase.Tables.GUESS, selectionCriteria, selectionArgs);
default:
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
}
}
ListLoader class:
package com.example.derek.guessinggame;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.support.v4.content.AsyncTaskLoader;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class GuessListLoader extends AsyncTaskLoader<List<Guess>> {
private static final String LOG_TAG = GuessListLoader.class.getSimpleName();
private List<Guess> mGuess;
private ContentResolver mContentResolver;
private Cursor mCursor;
public GuessListLoader(Context context, Uri uri, ContentResolver contentResolver) {
super(context);
mContentResolver = contentResolver;
}
#Override
public List<Guess> loadInBackground() {
String[] projection = {BaseColumns._ID,
GuessContract.GuessColumns.GUESS_TITLE,
GuessContract.GuessColumns.GUESS_ANSWER,
GuessContract.GuessColumns.GUESS_HINT1,
GuessContract.GuessColumns.GUESS_HINT2,
GuessContract.GuessColumns.GUESS_HINT3,
GuessContract.GuessColumns.GUESS_HINT4,
GuessContract.GuessColumns.GUESS_HINT5};
List<Guess> entries = new ArrayList<Guess>();
mCursor = mContentResolver.query(GuessContract.URI_TABLE, projection, null, null, " random()");
if (mCursor != null) {
if (mCursor.moveToFirst()) {
do {
int _id = mCursor.getInt(mCursor.getColumnIndex(BaseColumns._ID));
String title = mCursor.getString(mCursor.getColumnIndex(GuessContract.GuessColumns.GUESS_TITLE));
String answer = mCursor.getString(mCursor.getColumnIndex(GuessContract.GuessColumns.GUESS_ANSWER));
String hint1 = mCursor.getString(mCursor.getColumnIndex(GuessContract.GuessColumns.GUESS_HINT1));
String hint2 = mCursor.getString(mCursor.getColumnIndex(GuessContract.GuessColumns.GUESS_HINT2));
String hint3 = mCursor.getString(mCursor.getColumnIndex(GuessContract.GuessColumns.GUESS_HINT3));
String hint4 = mCursor.getString(mCursor.getColumnIndex(GuessContract.GuessColumns.GUESS_HINT4));
String hint5 = mCursor.getString(mCursor.getColumnIndex(GuessContract.GuessColumns.GUESS_HINT5));
Guess guess = new Guess(_id, title, answer, hint1, hint2, hint3, hint4, hint5);
entries.add(guess);
} while (mCursor.isLast());
}
}
return entries;
}
#Override
public void deliverResult(List<Guess> guess) {
if (isReset()) {
if (guess != null) {
mCursor.close();
}
}
List<Guess> oldGuessList = mGuess;
if (mGuess == null || mGuess.size() == 0) {
Log.d(LOG_TAG, "++++++++ No data returned");
}
mGuess = guess;
if (isStarted()) {
super.deliverResult(guess);
}
if (oldGuessList != null && oldGuessList != guess) {
mCursor.close();
}
}
#Override
protected void onStartLoading() {
if (mGuess != null) {
deliverResult(mGuess);
}
if (takeContentChanged() || mGuess == null) {
forceLoad();
}
}
#Override
protected void onStopLoading() {
cancelLoad();
}
#Override
protected void onReset() {
onStopLoading();
if (mCursor != null) {
mCursor.close();
}
mGuess = null;
}
#Override
public void onCanceled(List<Guess> guess) {
super.onCanceled(guess);
if (mCursor != null) {
mCursor.close();
}
}
#Override
public void forceLoad() {
super.forceLoad();
}
}
ListFragment class:
package com.example.derek.guessinggame;
import android.content.ContentResolver;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import java.util.List;
public class GuessListFragment extends ListFragment
implements LoaderManager.LoaderCallbacks<List<Guess>> {
private static final String LOG_TAG = GuessListFragment.class.getSimpleName();
private GuessCustomAdapter mAdapter;
private static final int LOADER_ID = 1;
private ContentResolver mContentResolver;
private List<Guess> mGuess;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
mContentResolver = getActivity().getContentResolver();
mAdapter = new GuessCustomAdapter(getActivity(), getChildFragmentManager());
setEmptyText("No entries");
setListAdapter(mAdapter);
setListShown(false);
getLoaderManager().initLoader(LOADER_ID, null, this);
}
#Override
public Loader<List<Guess>> onCreateLoader(int id, Bundle args) {
mContentResolver = getActivity().getContentResolver();
return new GuessListLoader(getActivity(), GuessContract.URI_TABLE, mContentResolver);
}
#Override
public void onLoadFinished(Loader<List<Guess>> loader, List<Guess> guess) {
mAdapter.setData(guess);
mGuess = guess;
if(isResumed()) {
setListShown(true);
} else {
setListShownNoAnimation(true);
}
}
#Override
public void onLoaderReset(Loader<List<Guess>> loader) {
mAdapter.setData(null);
}
}
SQLiteOpenHelper class:
package com.example.derek.guessinggame;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
public class GuessDatabase extends SQLiteOpenHelper {
private static final String TAG = GuessDatabase.class.getSimpleName();
private static final String DATABASE_NAME = "guess.db";
private static final int DATABASE_VERSION = 2;
private final Context mContext;
interface Tables {
String GUESS = "guess";
}
public GuessDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + Tables.GUESS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ GuessContract.GuessColumns.GUESS_TITLE + " TEXT NOT NULL,"
+ GuessContract.GuessColumns.GUESS_ANSWER + " TEXT NOT NULL,"
+ GuessContract.GuessColumns.GUESS_HINT1 + " TEXT NOT NULL,"
+ GuessContract.GuessColumns.GUESS_HINT2 + " TEXT NOT NULL,"
+ GuessContract.GuessColumns.GUESS_HINT3 + " TEXT NOT NULL,"
+ GuessContract.GuessColumns.GUESS_HINT4 + " TEXT NOT NULL,"
+ GuessContract.GuessColumns.GUESS_HINT5 + " TEXT NOT NULL)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
int version = oldVersion;
if (version == 1) {
version = 2;
}
if (version != DATABASE_VERSION) {
db.execSQL("DROP TABLE IF EXISTS " + Tables.GUESS);
onCreate(db);
}
}
public static void deleteDatabase(Context context) {
context.deleteDatabase(DATABASE_NAME);
}
}
ArrayAdapter class:
package com.example.derek.guessinggame;
import android.content.Context;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class GuessCustomAdapter extends ArrayAdapter<Guess> {
private LayoutInflater mLayoutInflater;
private static FragmentManager sFragmentManager;
public GuessCustomAdapter(Context context, FragmentManager fragmentManager) {
super(context, android.R.layout.simple_expandable_list_item_2);
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
sFragmentManager = fragmentManager;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final View view;
if (convertView == null) {
view = mLayoutInflater.inflate(R.layout.custom_guess, parent, false);
} else {
view = convertView;
}
final Guess guess = getItem(position);
final int _id = guess.getId();
final String title = guess.getTitle();
final String answer = guess.getAnswer();
final String hint1 = guess.getHint1();
final String hint2 = guess.getHint2();
final String hint3 = guess.getHint3();
final String hint4 = guess.getHint4();
final String hint5 = guess.getHint5();
((TextView) view.findViewById(R.id.guess_title)).setText(title);
((TextView) view.findViewById(R.id.guess_answer)).setText(answer);
((TextView) view.findViewById(R.id.guess_hint1)).setText(hint1);
((TextView) view.findViewById(R.id.guess_hint2)).setText(hint2);
((TextView) view.findViewById(R.id.guess_hint3)).setText(hint3);
((TextView) view.findViewById(R.id.guess_hint4)).setText(hint4);
((TextView) view.findViewById(R.id.guess_hint5)).setText(hint5);
return view;
}
public void setData(List<Guess> guesses) {
clear();
if (guesses != null) {
for (Guess guess : guesses) {
add(guess);
}
}
}
}
Contract class:
package com.example.derek.guessinggame;
import android.net.Uri;
import android.provider.BaseColumns;
public class GuessContract {
interface GuessColumns{
String GUESS_ID = "_id";
String GUESS_TITLE = "guess_title";
String GUESS_ANSWER = "guess_answer";
String GUESS_HINT1 = "guess_hint1";
String GUESS_HINT2 = "guess_hint2";
String GUESS_HINT3 = "guess_hint3";
String GUESS_HINT4 = "guess_hint4";
String GUESS_HINT5 = "guess_hint5";
}
public static final String CONTENT_AUTHORITY = "com.example.derek.guessinggame.provider";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
private static final String PATH_GUESS = "guess";
public static final Uri URI_TABLE = Uri.parse(BASE_CONTENT_URI.toString() + "/" + PATH_GUESS);
public static final String[] TOP_LEVEL_PATHS = {
PATH_GUESS
};
public static class Guess implements GuessColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendEncodedPath(PATH_GUESS).build();
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd." + CONTENT_AUTHORITY + ".guess";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd." + CONTENT_AUTHORITY + ".guess";
public static Uri buildGuessUri(String guessId) {
return CONTENT_URI.buildUpon().appendEncodedPath(guessId).build();
}
public static String getGuessId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
}
Getters and Setter class:
package com.example.derek.guessinggame;
public class Guess {
private int _id;
private String title;
private String answer;
private String hint1;
private String hint2;
private String hint3;
private String hint4;
private String hint5;
public Guess(int _id, String title, String answer, String hint1, String hint2, String hint3, String hint4, String hint5) {
this._id = _id;
this.title = title;
this.answer = answer;
this.hint1 = hint1;
this.hint2 = hint2;
this.hint3 = hint3;
this.hint4 = hint4;
this.hint5 = hint5;
}
public int getId() {
return _id;
}
public void setId(int _id) {
this._id = _id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public String getHint1() {
return hint1;
}
public void setHint1(String hint1) {
this.hint1 = hint1;
}
public String getHint2() {
return hint2;
}
public void setHint2(String hint2) {
this.hint2 = hint2;
}
public String getHint3() {
return hint3;
}
public void setHint3(String hint3) {
this.hint3 = hint3;
}
public String getHint4() {
return hint4;
}
public void setHint4(String hint4) {
this.hint4 = hint4;
}
public String getHint5() {
return hint5;
}
public void setHint5(String hint5) {
this.hint5 = hint5;
}
}