iam a very dumb newbie android programmer,
here i have some problem in my case i want to run my android programs that i make on Android Studio IDE.
But when i run the program, the error field said
"Process: com.example.ever_ncn.cashflow, PID: 6317
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference"
I still dont understand with explanation on another question.
I am very confuse cuz of this error, i have googling for it but it still unsolved.
Please master, answer my question with simple and easy understanding explanation.
Thank you.
NB. My main activity is to show an activity that contain a spinner which is the spinner value is taken from database.
This is my source code for Main_Activity.java :
public class MainActivity extends ActionBarActivity {
private static Button BtnINewTrans;
private static Button BtnIViewCash;
private static Button BtnIAddCateg;
DatabaseHelper dbHelper = new DatabaseHelper(this);
Spinner selectCategory;
ArrayAdapter<String> adapterCategory;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onButtonClickButtonListener();
select_spinner_Category();
}
public void select_spinner_Category (){
ArrayList<String> AllCategoryListing= dbHelper.getAllCategory();
selectCategory = (Spinner) findViewById(R.id.spnCategSelect);
adapterCategory = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, R.id.spnCategSelect, AllCategoryListing);
adapterCategory.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selectCategory.setAdapter(adapterCategory);
selectCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), parent.getItemAtPosition(position) + " selected", Toast.LENGTH_LONG).show();
String currencyValue = String.valueOf(parent.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void onButtonClickButtonListener(){
BtnINewTrans = (Button)findViewById(R.id.btnNewTrans);
BtnINewTrans.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentNewTrans = new Intent ("com.example.ever_ncn.cashflow.NewTransaction");
startActivity(intentNewTrans);
}
}
);
BtnIViewCash = (Button)findViewById(R.id.btnViewCashflow);
BtnIViewCash.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentViewCash = new Intent ("com.example.ever_ncn.cashflow.ViewCashflow");
startActivity(intentViewCash);
}
}
);
BtnIAddCateg = (Button)findViewById(R.id.btnAddCateg);
BtnIAddCateg.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentAddCateg = new Intent ("com.example.ever_ncn.cashflow.AddCategory");
startActivity(intentAddCateg);
}
}
);
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
and this one for database_helper.java :
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String MyVillageSoftware = "MyVillageSoftware";
public static final String DATABASE_NAME = "Cashflow.db";
public static final String TABLE_Categ_NAME = "category_table";
public static final String COL1 = "CategId";
public static final String COL2 = "CategName";
public static final String COL3 = "Note";
public static final String COL4 = "Currency";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 2);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create table " + TABLE_Categ_NAME +
" (CategID Integer PRIMARY KEY AUTOINCREMENT, " +
"CategName Text," +
" Note Text," +
" Currency Text)");
}
public boolean insertCategData(String categname, String note, String currency){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, categname);
contentValues.put(COL3, note);
contentValues.put(COL4, currency);
long result = db.insert(TABLE_Categ_NAME, null, contentValues);
if (result == -1)
return true;
else
return false;
}
public ArrayList<String>getAllCategory(){
ArrayList<String> AllCategoryList = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
String selectCateg="Select * FROM " +TABLE_Categ_NAME;
Cursor cursor = db.rawQuery(selectCateg, null);
if(cursor.getCount()>0){
while (cursor.moveToNext()){
String categname=cursor.getString(cursor.getColumnIndex(COL2));
AllCategoryList.add(COL2);
}return AllCategoryList;
}
return AllCategoryList;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " +TABLE_Categ_NAME);
onCreate(db);
}
}
Basically the the error is explained in the error message. Learning to program included learning to read error messages.
You are calling a setText() method on a TextView object, except that your TextView you're calling it on doesn't exist (in memory, as in it's not allocated). Without know what line it reports the error comes from I have no way of helping beyond that. I would suggest debugging it and check objects that turn up being null when they shouldn't be.
Related
I'm making a project in Android/Java. I have an activity with a listview that displays values from a database and a remove button. For the moment, each row of this list view consists of a checktextview. This last one displays the name of an element of the database. I want to select different elements (with the check text view) and then if I press the remove button, all the selected elements have to be removed from the list and from database. In the following I put the essential parts of my classes. I already done most of the work.
This is my activity:
public class ShoppingListActivity extends AppCompatActivity {
// Variables for the management of the database
private DBManagerShoppingList dbShoppingList;
private Cursor crs;
// List view for the shopping list elements
private ListView shoppingListListView;
private ShoppingListViewAdapter shoppingListViewAdapter;
// Generic variables
private String selectedShoppingList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_list);
// Find of the useful widgets
shoppingListListView = findViewById(R.id.listViewSelShoppingList);
shoppingListsSpinner = findViewById(R.id.spinnerShoppingLists);
selectedShoppingList = "List_1";
populateListView();
}
// Populate list view from database
public void populateListView() {
// Database management
dbShoppingList = new DBManagerShoppingList(this, selectedShoppingList);
crs = dbShoppingList.query();
new Handler().post(new Runnable() {
#Override
public void run() {
shoppingListViewAdapter = new ShoppingListViewAdapter(ShoppingListActivity.this, crs, 0);
shoppingListListView.setAdapter(shoppingListViewAdapter);
}
});
}
// Remove selected elements
public void removeSelectedElements(View btnRemove) {
// TODO
}
}
This is my custom adapter:
public class ShoppingListViewAdapter extends CursorAdapter {
private LayoutInflater layoutInflater;
private List<Integer> elementsPosArrayList = new ArrayList<>();
private HashMap<String, Integer> elementsMap = new HashMap<>();
public ShoppingListViewAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
return layoutInflater.inflate(R.layout.list_view_row, viewGroup, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// CheckBox management
final CheckBox checkBoxElementName = view.findViewById(R.id.checkBoxElementName);
String elementName = cursor.getString(cursor.getColumnIndex(DBFieldsShoppingList.FIELD_ELEMENT_NAME));
checkBoxElementName.setText(elementName);
elementsMap.put(elementName, cursor.getPosition());
checkBoxElementName.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
elementsPosArrayList.add(elementsMap.get(checkBoxElementName.getText().toString()));
} else {
elementsPosArrayList.remove(elementsMap.get(checkBoxElementName.getText().toString()));
}
}
});
}
public long getElementId(Cursor crs, int position) {
crs.moveToPosition(position);
return crs.getLong(crs.getColumnIndex(DBFieldsShoppingList.FIELD_ID));
}
public List<Integer> getElementsPosArrayList() {
return elementsPosArrayList;
}
}
Classes for the database management are the following:
DBHelper:
public class DBHelperShoppingList extends SQLiteOpenHelper {
private String DBName;
public DBHelperShoppingList(#Nullable Context context, int dbVersion, String dbName) {
super(context, dbName, null, dbVersion);
this.DBName = dbName;
}
#Override
public void onCreate(SQLiteDatabase shoppingListDB) {
String q = "CREATE TABLE " + DBFieldsShoppingList.FIELD_TABLE_NAME +
" ( _id INTEGER PRIMARY KEY AUTOINCREMENT," +
DBFieldsShoppingList.FIELD_ELEMENT_NAME + " TEXT," +
DBFieldsShoppingList.FIELD_ELEMENT_TYPE + " TEXT," +
DBFieldsShoppingList.FIELD_ELEMENT_QUANT + " TEXT)";
shoppingListDB.execSQL(q);
}
#Override
public void onUpgrade(SQLiteDatabase shoppingListDB, int oldVersion, int newVersion) {}
}
Class for the fields of the database:
public class DBFieldsShoppingList {
public static final String FIELD_ID = "_Id";
public static final String FIELD_TABLE_NAME = "Shopping_List";
public static final String FIELD_ELEMENT_NAME = "Element_Name";
public static final String FIELD_ELEMENT_TYPE = "Element_Type";
public static final String FIELD_ELEMENT_QUANT = "Element_Quant";
}
Class database manager:
public class DBManagerShoppingList {
private DBHelperShoppingList dbHelperShoppingList;
public DBManagerShoppingList(Context ctx, String shoppingListName) {
dbHelperShoppingList = new DBHelperShoppingList(ctx, 1, shoppingListName);
}
public void dbSave(String elementName, String elementType, String elementQuantity) {
SQLiteDatabase db = dbHelperShoppingList.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(DBFieldsShoppingList.FIELD_ELEMENT_NAME, elementName);
cv.put(DBFieldsShoppingList.FIELD_ELEMENT_TYPE, elementType);
cv.put(DBFieldsShoppingList.FIELD_ELEMENT_QUANT, elementQuantity);
try {
db.insert(DBFieldsShoppingList.FIELD_TABLE_NAME, null, cv);
} catch (SQLiteException ignored) {}
}
public boolean deleteElement(long id) {
SQLiteDatabase db = dbHelperShoppingList.getWritableDatabase();
try {
return db.delete(DBFieldsShoppingList.FIELD_TABLE_NAME, DBFieldsShoppingList.FIELD_ID + "=?", new String[]{Long.toString(id)})>0;
} catch(SQLiteException exc) {
return false;
}
}
public static void deleteDB(Context ctx, String DBName) {
ctx.deleteDatabase(DBName);
}
public Cursor query() {
Cursor crs;
try {
SQLiteDatabase db = dbHelperShoppingList.getReadableDatabase();
crs = db.query(DBFieldsShoppingList.FIELD_TABLE_NAME, null, null, null, null, null, null, null);
} catch (SQLiteException exc) {
return null;
}
return crs;
}
}
I tought, in bindView method of the adapter class, to save a map between element name and its position. Then, to create a list of the element names of the checked elements. In this way, I can know the positions of the checked elements, from the map. Now, I have to get indexes of the checked elements, in order to remove them from database, with delete method of the database manager class.
How can I solve this problem? If my structure is not correct, say me how to change.
Thank you very much in advance.
Marco
Hy to everybody,
I found the solution. In database manager class, I changed the delete method in the following way:
public boolean deleteElement(String elementName) {
SQLiteDatabase db = dbHelperShoppingList.getWritableDatabase();
try {
return db.delete(DBFieldsShoppingList.FIELD_TABLE_NAME, DBFieldsShoppingList.FIELD_ELEMENT_NAME + "=?", new String[]{(elementName)})>0;
} catch(SQLiteException exc) {
return false;
}
}
This allows, to search by name in database.
In adapter class, I removed the map, and I wrote an arraylist of string, where I put name of the checked elements:
#Override
public void bindView(View view, Context context, Cursor cursor) {
// CheckBox management
final CheckBox checkBoxElementName = view.findViewById(R.id.checkBoxElementName);
String elementName = cursor.getString(cursor.getColumnIndex(DBFieldsShoppingList.FIELD_ELEMENT_NAME));
checkBoxElementName.setText(elementName);
checkBoxElementName.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
elementNamesArrayList.add(checkBoxElementName.getText().toString());
} else {
elementNamesArrayList.remove(checkBoxElementName.getText().toString());
}
}
});
}
Finally, in the activity class, the remove method is the following:
public void removeSelectedElements(View btnRemove) {
List<String> elementNamesArrayList = shoppingListViewAdapter.getElementNamesArrayList();
for (String item: elementNamesArrayList) {
dbShoppingList.deleteElement(item);
}
populateListView();
}
In this way I solved my problem.
Marco
I do not understand why my note taking application keeps crashing. I click on a button to insert a note that shows in a listView using a SQLite database.
The error given is:
(1) no such column: TITLE
FATAL EXCEPTION: main
Unable to resume activity: android.database.sqlite.SQLiteException: no such column: TITLE (code 1 SQLITE_ERROR): , while compiling: SELECT ID, TITLE FROM note_table
located here in mainactivity.java:
cursor = database.query(table_name, columns, where, where_args, group_by, having, order_by);
Database:
public class DBOpenHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "notes.db";
public static final String TABLE_NAME = "note_table";
public static final String ID_COLUMN = "ID";
public static final String TITLE_COLUMN = "TITLE";
public static final String TEXT_COLUMN = "ITEM2";
public static final String DATE_COLUMN = "DATE";
SQLiteDatabase db = this.getWritableDatabase();
public DBOpenHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
" TITLE TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table notes_table");
onCreate(db);
}
Mainactivity.java:
public class MainActivity extends AppCompatActivity {
private ListView listView;
private ArrayList<String> notes_list;
private ArrayAdapter adapter;
private DBOpenHelper helper;
private SQLiteDatabase database;
private TextView noNotesView;
private Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Edit_notes.class);
startActivity(intent);
}
});
noNotesView = findViewById(R.id.empty_notes);
listView = (ListView) findViewById(R.id.listView);
notes_list = new ArrayList<>();
helper = new DBOpenHelper(this);
database = helper.getWritableDatabase();
}
private void ViewData(){
String table_name = "note_table";
String[] columns = {"ID", "TITLE"};
String where = null;
String where_args[] = null;
String group_by = null;
String having = null;
String order_by = null;
cursor = database.query(table_name, columns, where, where_args, group_by, having, order_by); // the error is here
String total_text = "total number of rows: " + cursor.getCount() + "\n";
cursor.moveToLast();
notes_list = new ArrayList<>();
adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,notes_list);
for(int i = 0; i < cursor.getCount(); i++) {
// total_text += c.getInt(0) + " " + c.getString(1) + "\n";
notes_list.add(cursor.getString(1));
listView.setAdapter(adapter);
cursor.moveToPrevious();
}
// noNotesView.setText(total_text);
}
private void hide_or_show() {
if (cursor.getCount() == 0) {
noNotesView.setVisibility(View.VISIBLE);
} else {
noNotesView.setVisibility(View.GONE);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.delete_all) {
Delete_all();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume()
{
super.onResume();
ViewData();
hide_or_show();
}
public void Delete_all() {
database.execSQL("delete from " + "note_table");
adapter.clear();
}
I don't understand why I get this error message since my column name is right. I have tried deleting and recompiling my application without success.
Your problem is with your database class's constructor:
public DBOpenHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
Specifically the 1 in the final argument of super(). That's your database version, and is key to introducing changes to your database structure. You mentioned in your comments that TITLE was previously called ITEM1, on your device it is still called ITEM1 as your app is unaware that the database structure has changed.
You can fix this by introducing a version constant in your class like so:
private static final int DB_VERSION = 2;
And using this variable in your constructor:
public DBOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DB_VERSION);
}
Whenever you make any structural changes to your database, increment DB_VERSION and this will cause SQLiteOpenHelper to call its onUpgrade() method.
Hello every one I am new to android SQLiteDatabase. I am following tutorial from this site ORIGINAL CODE . The below code is about Add, update, Delete name from the database.
Everything is working fine. I am able to add, update and delete name from the database.
Problem:
For example I added 4 names.
ID name
1 A
2 B
3 C
4 D
when I delete A it get deleted from the listview and database. It is updated in listview.
Now the database looks like this
ID name
1 null
2 B
3 C
4 D
And Listview looks like this
B
C
D
So when I click on B to delete or edit it shows nothing in my edit and delete view but when I click on C it shows me B in delete view.
I gone through all the solutions which is available in stackoverflow and I know it is repeated questions but is there any solution for this example.
I want when I click on B it should show B not null and when I click on C it should show C, After deleting A.
NOTE: Can any one fix the code please. I am very sure there are many developers who are looking for to fix this issue. Specially beginners like me. It would be great help.Thank you in advance.
DBHelper
public Integer deleteContact (Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllCotacts() {
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
devicedetailsActivity
public class devicedetailsActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "MESSAGE";
private ListView obj;
DBHelper mydb;
ArrayList array_list ;
public ArrayAdapter arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.devicedetails_layout);
mydb = new DBHelper(this);
}
public void onResume() {
refreshList();
super.onResume();
}
public void refreshList() {
array_list = mydb.getAllCotacts();
arrayAdapter=new ArrayAdapter(this,R.layout.simple_list_item_1, array_list);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(),DetailsActivity.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case R.id.item1:Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
Intent intent = new Intent(getApplicationContext(),DetailsActivity.class);
intent.putExtras(dataBundle);
startActivity(intent);
return true;
case R.id.item2: dataBundle = new Bundle();
dataBundle.putInt("id", 0);
intent = new Intent(getApplicationContext(),MainActivity.class);
intent.putExtras(dataBundle);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
DetailsActivity
public class DetailsActivity extends AppCompatActivity {
private DBHelper mydb ;
ArrayAdapter arrayAdapter;
TextView name ;
int id_To_Update = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
name = (TextView) findViewById(R.id.editTextName);
mydb = new DBHelper(this);
Bundle extras = getIntent().getExtras();
if(extras !=null) {
int Value = extras.getInt("id");
if(Value>0){
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
if(rs.moveToFirst()) {
id_To_Update = Value;
rs.moveToFirst();
String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
name.setText((CharSequence)nam);
name.setFocusable(false);
name.setClickable(false);
}
if (!rs.isClosed()) {
rs.close();
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Bundle extras = getIntent().getExtras();
if(extras !=null) {
int Value = extras.getInt("id");
if(Value>0){
getMenuInflater().inflate(R.menu.display_contact, menu);
} else{
getMenuInflater().inflate(R.menu.back, menu);
}
}
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case R.id.Edit_Contact:
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.VISIBLE);
name.setEnabled(true);
name.setFocusableInTouchMode(true);
name.setClickable(true);
return true;
case R.id.Delete_Contact:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mydb.deleteContact(id_To_Update);
Toast.makeText(getApplicationContext(), "Deleted Successfully",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),devicedetailsActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();
return true;
case R.id.back:
Intent intent = new Intent(getApplicationContext(),devicedetailsActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void run(View view) {
Bundle extras = getIntent().getExtras();
if(extras !=null) {
int Value = extras.getInt("id");
if(Value>0){
if(mydb.updateContact(id_To_Update,name.getText().toString()
)){
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),devicedetailsActivity.class);
startActivity(intent);
} else{
Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
}
} else{
if(mydb.insertContact(name.getText().toString())){
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(getApplicationContext(), "not done",
Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(),devicedetailsActivity.class);
startActivity(intent);
}
}
}
}
The Issue
The 3rd argument (arg2) to the onItemClickListener is the position (as will be the 4th unless you use a Cursor Adapter).
The position will never equate to the id (unless you forced id's to have certain values) that is because the first item has a position of 0. The id of the first row will be 1. If you start deleting rows then life gets more complicated as you have found.
Soultions (in theory)
What you have to do is get the correct id.
You could use a complimentary ArrayList of Longs ArrayList<Long> or an Array of longs long[] (you need two methods to build the ArrayList<String> and the ArrayList<long> or long[]). However if you used a filter then this may then also be out of sync. As such this method is not really recommended.
You could use a Cursor Adapter and a Cursor as the source for the ListView and then the 4th parameter would be the id (requires that a column named _id which should be the row's id). I'd Recommended using Cursors as there is no need for intermediate objects
You could use an ArrayList of objects ArrayList<your_object>, in which case the object would have at least two members id and name. You could then use the Adapter's getItem(arg2) method to retrieve the object and then get the id from the object.
Working Example with 2 Solutions
The following is code for an App that displays 3 Listviews the first sourced by a String ArrayList (what you currently have), the second by an object ArrayList (an appropriate object i.e. a MyTableObject ArrayList) and the third via a Cursor. The data displayed being identical.
Clicking on an item displays the values that can be obtained (the values that could be passed to a deletion).
the first ListView only the position can be obtained and that is displayed (as if it were the ID),
the second ListView shows the ID obtained from the object and the ID obtained from the position (they will not match)
the 3rd ListView shows the ID obtained via the Cursor (equivalent to the object) and the ID obtained from the 4th parameter, they always match.
Note each time the App is run more data will be added.
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper mDBHlpr;
ListView mListView01,mListVeiw02,mListView03;
ArrayAdapter<String> mAdapterStringArrayList;
ArrayAdapter<MyTableObject> mAdapterMyTableObjectArrayList;
SimpleCursorAdapter mAdapterCursor;
ArrayList<String> mMyTableListAsStrings;
ArrayList<MyTableObject> mMyTableAsObjects;
Cursor mMyTableListAsCursor;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
mListView01 = this.findViewById(R.id.listview01);
mListVeiw02 = this.findViewById(R.id.listview02);
mListView03 = this.findViewById(R.id.listview03);
mDBHlpr = new DatabaseHelper(this);
mDBHlpr.addRow("Fred");
mDBHlpr.addRow("Bert");
mDBHlpr.addRow("Harry");
mDBHlpr.addRow("Fred");
//String Array List
mMyTableListAsStrings = mDBHlpr.getAllAsStringArrayList();
mAdapterStringArrayList = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
mMyTableListAsStrings
);
mListView01.setAdapter(mAdapterStringArrayList);
//Object Array List
mMyTableAsObjects = mDBHlpr.getAllAsMyTableObjectArrayList();
mAdapterMyTableObjectArrayList = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
mMyTableAsObjects
);
mListVeiw02.setAdapter(mAdapterMyTableObjectArrayList);
// Cursor
mMyTableListAsCursor = mDBHlpr.getAllAsCursor();
mAdapterCursor = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
mMyTableListAsCursor,
new String[]{DatabaseHelper.COL_MYTABLE_NAME},
new int[]{android.R.id.text1},
0
);
mListView03.setAdapter(mAdapterCursor);
mListView01.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String name = mAdapterStringArrayList.getItem(position);
Toast.makeText(
mContext,
"Name is " + name +
". ID is " + String.valueOf(id) +
" (note may not match)",
Toast.LENGTH_SHORT
).show();
}
});
mListVeiw02.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
MyTableObject mytable = mAdapterMyTableObjectArrayList.getItem(position);
String name = mytable.getName();
long id_in_object = mytable.getId();
Toast.makeText(
mContext,
"Name is " + name +
". ID from object is " + String.valueOf(id_in_object) +
". ID from adapter is " + String.valueOf(id),
Toast.LENGTH_SHORT
).show();
}
});
mListView03.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Cursor csr = mAdapterCursor.getCursor(); // already positioned
String name = csr.getString(csr.getColumnIndex(DatabaseHelper.COL_MYTABLE_NAME));
long id_in_cursor = csr.getLong(csr.getColumnIndex(DatabaseHelper.COl_MYTABLE_ID));
Toast.makeText(
mContext,
"Name is " + name +
". ID from object is " + String.valueOf(id_in_cursor) +
". ID from adapter is " + String.valueOf(id),
Toast.LENGTH_SHORT
).show();
}
});
}
}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydb";
public static final int DBVERSION = 1;
public static final String TB_MYTABLE = "mytable";
public static final String COl_MYTABLE_ID = BaseColumns._ID; //<<<< use standard android id column name
public static final String COL_MYTABLE_NAME = "_name";
private static final String mytable_crtsql =
"CREATE TABLE IF NOT EXISTS " + TB_MYTABLE +
"(" +
COl_MYTABLE_ID + " INTEGER PRIMARY KEY, " +
COL_MYTABLE_NAME + " TEXT " +
")";
SQLiteDatabase mDB;
public DatabaseHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(mytable_crtsql);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public long addRow(String name) {
ContentValues cv = new ContentValues();
cv.put(COL_MYTABLE_NAME,name);
return mDB.insert(TB_MYTABLE,null,cv);
}
public ArrayList<String> getAllAsStringArrayList() {
ArrayList<String> rv = new ArrayList<>();
Cursor csr = mDB.query(
TB_MYTABLE,
null,
null,
null,
null,
null,
null
);
while (csr.moveToNext()) {
rv.add(csr.getString(csr.getColumnIndex(COL_MYTABLE_NAME)));
}
csr.close();
return rv;
}
public ArrayList<MyTableObject> getAllAsMyTableObjectArrayList() {
ArrayList<MyTableObject> rv = new ArrayList<>();
Cursor csr = mDB.query(
TB_MYTABLE,
null,
null,
null,
null,
null,
null
);
while (csr.moveToNext()) {
rv.add(new MyTableObject(
csr.getLong(csr.getColumnIndex(COl_MYTABLE_ID)),
csr.getString(csr.getColumnIndex(COL_MYTABLE_NAME))
)
);
}
csr.close();
return rv;
}
public Cursor getAllAsCursor() {
return mDB.query(
TB_MYTABLE,
null,
null,
null,
null,
null,
null
);
}
}
MyTableObject.java
public class MyTableObject {
private long id;
private String name;
public MyTableObject(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/*
NOTE toString method returns just the name
*/
#Override
public String toString() {
return name;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="ArrayList-String"
/>
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="ArrayList-object"
/>
<TextView
android:text="Cursor"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<ListView
android:id="#+id/listview01"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:background="#ffffaaaa">
</ListView>
<ListView
android:id="#+id/listview02"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:background="#ffaaffaa">
</ListView>
<ListView
android:id="#+id/listview03"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:background="#ffaaaaff">
</ListView>
</LinearLayout>
</LinearLayout>
Working Example Updated with Deletion Added
The following is the above but with the ability to delete rows on a longclick (only for the 2nd and 3rd ListView).
The MainActivity has been changed to
include OnItemLongClick listeners for the 2nd and 3rd ListViews
The newly added delete method is invoked with the id passed
The refreshAllListViews is then called to refresh all the ListViews
Note There is no reliable way to delete from the 1st ListView
The changed MainActivity.java :-
public class MainActivity extends AppCompatActivity {
DatabaseHelper mDBHlpr;
ListView mListView01,mListVeiw02,mListView03;
ArrayAdapter<String> mAdapterStringArrayList;
ArrayAdapter<MyTableObject> mAdapterMyTableObjectArrayList;
SimpleCursorAdapter mAdapterCursor;
ArrayList<String> mMyTableListAsStrings;
ArrayList<MyTableObject> mMyTableAsObjects;
Cursor mMyTableListAsCursor;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
mListView01 = this.findViewById(R.id.listview01);
mListVeiw02 = this.findViewById(R.id.listview02);
mListView03 = this.findViewById(R.id.listview03);
mDBHlpr = new DatabaseHelper(this);
mDBHlpr.addRow("Fred");
mDBHlpr.addRow("Bert");
mDBHlpr.addRow("Harry");
mDBHlpr.addRow("Fred");
//String Array List
mMyTableListAsStrings = mDBHlpr.getAllAsStringArrayList();
mAdapterStringArrayList = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
mMyTableListAsStrings
);
mListView01.setAdapter(mAdapterStringArrayList);
//Object Array List
mMyTableAsObjects = mDBHlpr.getAllAsMyTableObjectArrayList();
mAdapterMyTableObjectArrayList = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
mMyTableAsObjects
);
mListVeiw02.setAdapter(mAdapterMyTableObjectArrayList);
// Cursor
mMyTableListAsCursor = mDBHlpr.getAllAsCursor();
mAdapterCursor = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
mMyTableListAsCursor,
new String[]{DatabaseHelper.COL_MYTABLE_NAME},
new int[]{android.R.id.text1},
0
);
mListView03.setAdapter(mAdapterCursor);
mListView01.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String name = mAdapterStringArrayList.getItem(position);
Toast.makeText(
mContext,
"Name is " + name +
". ID is " + String.valueOf(id) +
" (note may not match)",
Toast.LENGTH_SHORT
).show();
}
});
mListVeiw02.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
MyTableObject mytable = mAdapterMyTableObjectArrayList.getItem(position);
String name = mytable.getName();
long id_in_object = mytable.getId();
Toast.makeText(
mContext,
"Name is " + name +
". ID from object is " + String.valueOf(id_in_object) +
". ID from adapter is " + String.valueOf(id),
Toast.LENGTH_SHORT
).show();
}
});
mListVeiw02.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
mDBHlpr.delete(mAdapterMyTableObjectArrayList.getItem(i).getId());
refreshAllListViews();
return true;
}
});
mListView03.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Cursor csr = mAdapterCursor.getCursor(); // already positioned
String name = csr.getString(csr.getColumnIndex(DatabaseHelper.COL_MYTABLE_NAME));
long id_in_cursor = csr.getLong(csr.getColumnIndex(DatabaseHelper.COl_MYTABLE_ID));
Toast.makeText(
mContext,
"Name is " + name +
". ID from object is " + String.valueOf(id_in_cursor) +
". ID from adapter is " + String.valueOf(id),
Toast.LENGTH_SHORT
).show();
}
});
mListView03.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
mDBHlpr.delete(l);
refreshAllListViews();
return true;
}
});
}
public void refreshAllListViews() {
mMyTableListAsStrings.clear();
ArrayList<String> newStringArray = mDBHlpr.getAllAsStringArrayList();
mMyTableListAsStrings.addAll(newStringArray);
mAdapterStringArrayList.notifyDataSetChanged();
mMyTableAsObjects.clear();
ArrayList<MyTableObject> newObjectArray = mDBHlpr.getAllAsMyTableObjectArrayList();
mMyTableAsObjects.addAll(newObjectArray);
mAdapterMyTableObjectArrayList.notifyDataSetChanged();
mMyTableListAsCursor = mDBHlpr.getAllAsCursor();
mAdapterCursor.swapCursor(mMyTableListAsCursor);
}
}
DatabaseHelper.java has been changed to include a new method to delete a row according to the id
i.e. the following method has been added :-
public int delete(long id) {
String whereclause = COl_MYTABLE_ID + "=?";
String[] whereargs = new String[]{String.valueOf(id)};
return mDB.delete(TB_MYTABLE,whereclause,whereargs);
}
I have an application that supposed to take the text that the user enters from 4 EditTexts and a Spinner, and create a new item in the database when a button is clicked. (Image Below)
I have created a method in my database helper class that adds a new item, so in this activity I create a new item, and then pass that item to the method that should create it in the database. But for some reason weird text appear on the screen instead of a new item in the RecyclerView.
I don't know why I get the strings from the editTexts and the int (Which is the Arrival Time) and the string from the spinner and I pass it to a new item (Train) but this error keeps happening.
Here are my DatabaseHelper Class:
public class TrainDatabaseHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "train.db";
public static final String TABLE_NAME = "train";
public static final String COLUMN_ID ="_id";
public static final String COLUMN_PLATFORM = "platform";
public static final String COLUMN_ARRIVAL_TIME = "arrival_time";
public static final String COLUMN_STATUS = "status";
public static final String COLUMN_DESTINATION = "destination";
public static final String COLUMN_DESTINATION_TIME = "destination_time";
public static final String[] COLUMNS = {COLUMN_ID, COLUMN_PLATFORM, COLUMN_ARRIVAL_TIME
, COLUMN_STATUS,COLUMN_DESTINATION,COLUMN_DESTINATION_TIME};
private static TrainDatabaseHelper sInstance;
public synchronized static TrainDatabaseHelper getInstance(Context context) {
if (sInstance == null){
sInstance = new TrainDatabaseHelper(context.getApplicationContext());
}
return sInstance;
}
private TrainDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " ("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_PLATFORM + " TEXT, "
+ COLUMN_ARRIVAL_TIME + " INTEGER, "
+ COLUMN_STATUS+ " TEXT, "
+ COLUMN_DESTINATION + " TEXT, "
+ COLUMN_DESTINATION_TIME + " TEXT"
+ ")"
);
addTrain(db, new Train(0, "Albion Park Platform 1", 3,"On Time",
"Allawah", "14:11"));
addTrain(db, new Train(1, "Arncliffe Platform 2", 4, "Late",
"Central", "14:34"));
addTrain(db, new Train(2, "Artarmion Platform 3", 7, "On Time",
"Ashfield", "15:01"));
addTrain(db, new Train(3, "Berowra Platform 4", 12, "Late",
"Beverly", "15:18"));
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch (oldVersion){
case 1:
db.execSQL("alter table " + TABLE_NAME + " add column description TEXT");
case 2:
db.execSQL("alter table " + TABLE_NAME + " add column air_conditioned TEXT");
}
}
public void addTrain(Train train){
addTrain(getWritableDatabase(), train);
}
private void addTrain(SQLiteDatabase db, Train train){
ContentValues values = new ContentValues();
values.put(COLUMN_PLATFORM, train.getPlatform());
values.put(COLUMN_ARRIVAL_TIME, train.getArrivalTime());
values.put(COLUMN_STATUS, train.getStatus());
values.put(COLUMN_DESTINATION, train.getDestination());
values.put(COLUMN_DESTINATION_TIME, train.getDestinationTime());
db.insert(TABLE_NAME,null,values);
}
public void deleteTrains (){
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_NAME,null,null);
}
public Train getTrain(int position){
return getTrains().get(position);
}
public List<Train> getTrains(){
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, COLUMNS, null, null, null, null, null);
List<Train> trains = new ArrayList<>();
if (cursor.moveToFirst()) {
do {
Train train = new Train(cursor.getInt(0),cursor.getString(1),cursor.getInt(2),
cursor.getString(3),cursor.getString(4),cursor.getString(5));
trains.add(train);
} while (cursor.moveToNext());
}
cursor.close();
return trains;
}
Here is the activity where we add a new item (Train):
public class AddTrainActivity extends AppCompatActivity {
private Spinner mSpinner;
private EditText mPlatformEt, mArrivalEt, mDestinationEt, mDestinationTimeEt;
private String mStatus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_train_activity);
mPlatformEt = findViewById(R.id.platform_entry);
mArrivalEt = findViewById(R.id.arrival_time_entry);
mDestinationEt = findViewById(R.id.destination_entry);
mDestinationTimeEt = findViewById(R.id.destination_time_entry);
mSpinner = findViewById(R.id.status_spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> mAdapter = ArrayAdapter.createFromResource(this,
R.array.status_array, android.R.layout.simple_spinner_item);
// Apply the adapter to the spinner
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
mSpinner.setAdapter(mAdapter);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0:
mStatus = getString(R.string.status_on_time);
break;
case 1:
mStatus = getString(R.string.status_late);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(AddTrainActivity.this, R.string.status_toast, Toast.LENGTH_LONG).show();
}
});
}
public void addTrainButton (View view) {
int arrivalTime = Integer.valueOf(mArrivalEt.toString());
String platform = mPlatformEt.toString();
String destination = mDestinationEt.toString();
String destinationTime = mDestinationTimeEt.toString();
Train train = new Train(4,platform,arrivalTime, mStatus,
destination ,destinationTime);
TrainDatabaseHelper helper = TrainDatabaseHelper.getInstance(this);
helper.addTrain(train);
Toast.makeText(this, R.string.add_train_toast, Toast.LENGTH_SHORT).show();
goBackHome();
}
public void cancelButton(View view) {
goBackHome();
}
public void goBackHome(){
startActivity(new Intent(AddTrainActivity.this, MainActivity.class));
}
And this is the MainActivity Class:
public class MainActivity extends AppCompatActivity {
private RecyclerView mTrainsRv;
private TrainAdapter mTrainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mTrainsRv = findViewById(R.id.train_rv);
mTrainsRv.setLayoutManager(new LinearLayoutManager(this));
mTrainAdapter = new TrainAdapter(this);
mTrainsRv.setAdapter(mTrainAdapter);
FloatingActionButton fab = findViewById(R.id.fab);
/** a FAB onClick Listener that starts a new activity to add a train */
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,AddTrainActivity.class));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
/* Inflate the menu; this adds items to the action bar if it is present. */
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
/* Handle action bar item clicks here */
switch (item.getItemId()) {
case R.id.action_delete:
// TODO deleting all trains from database
mTrainAdapter.notifyDataSetChanged();
return true;
case R.id.action_refresh:
return true;
case R.id.action_quit:
Toast.makeText(this, R.string.quit_menu,
Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onResume() {
super.onResume();
TrainDatabaseHelper helper = TrainDatabaseHelper.getInstance(this);
}
Thanks in advance and if you need more code let me know.
The problem was I forgot to do .getText() before doing .toString()
example:
mPlatformEt.getText().toString();
instead of
mPlatformEt.toString();
I'm doing a small project for my mobile app subject. I need to link it with sqlitedatabase.
I've been the tutorial at the Youtube, I followed the tutorial step by step. I didn't got any error from the code.
I need to insert the value into the db and display it back but the user input didn't inserted into db so I couldn't display the data from the DB.
I hope someone could help me. I've been stuck for 2 days because of this problem with no error display.
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper
{
public static final String DATABASE_NAME = "STUDENT.DB";
//create table
public static final String TABLE_STUDENT = "STUDENT_TABLE";
public static final String COL_STD_ID = "STD_ID";
public static final String COL_STD_NAME = "STD_NAME";
public static final String COL_STD_EMAIL = "STD_EMAIL";
public static final String COL_STD_ADDRESS = "STD_ADDRESS";
public DatabaseHelper(Context context) {
super(context,DATABASE_NAME, null, 1);
Log.e("DATABASE OPERATION","Database created/opend...");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_STUDENT +" (STD_ID INTEGER PRIMARY KEY AUTOINCREMENT,STD_NAME TEXT,STD_EMAIL TEXT, STD_ADDRESS TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_STUDENT );
onCreate(db);
}
public boolean insertData(String STD_NAME, String STD_EMAIL, String STD_ADDRESS)
{
SQLiteDatabase db = this.getWritableDatabase();
//get the data from user into db
ContentValues contentValues = new ContentValues();
contentValues.put(COL_STD_NAME,STD_NAME);
contentValues.put(COL_STD_EMAIL,STD_EMAIL);
contentValues.put(COL_STD_ADDRESS,STD_ADDRESS);
//SEE WHETHER THE DATA INSERT INTO DB OR NOT
//IF RETURN -1, DATA NOT SUCCESSFUL INSERTED
long result = db.insert(TABLE_STUDENT,null,contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor result = db.rawQuery("SELECT * FROM " + TABLE_STUDENT,null);
return result;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDB;
EditText etstdName, etstdEmail, etstdAddress;
Button btnInsertData, btnViewData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new DatabaseHelper(this);
etstdName = (EditText)findViewById(R.id.etstdName);
etstdEmail = (EditText)findViewById(R.id.etstdEmail);
etstdAddress = (EditText)findViewById(R.id.etstdEmail);
btnViewData = (Button)findViewById(R.id.btnViewData);
btnInsertData = (Button)findViewById(R.id.btnInsertData);
InsertStdData();
}
// I think i get stuck at here but theres not error display at InsertStdData() methid
public void InsertStdData() {
btnInsertData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDB.insertData(etstdName.getText().toString(),
etstdEmail.getText().toString(),
etstdAddress.getText().toString());
if(isInserted = true)
Toast.makeText(MainActivity.this,"Data successfully inserted.",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not successfully inserted.",Toast.LENGTH_LONG).show();
}
});
}
public void viewStdData(View view) {
Cursor result = myDB.getAllData();
if(result.getCount() == 0) {
//showmessage method
showMessage("ERROR", "NO DATA FOUND");
return;
}
StringBuffer buffer = new StringBuffer();
while (result.moveToNext()){
buffer.append("STD_ID : "+result.getString(0)+"\n");
buffer.append("STD_NAME : "+result.getString(1)+"\n");
buffer.append("STD_EMAIL : "+result.getString(2)+"\n");
buffer.append("STD_ADDRESS :"+result.getString(3)+"\n\n");
}
//show all data
showMessage("DATA",buffer.toString());
}
public void showMessage(String title, String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
}
You called InsertStdData() but you didnt call viewStdData(View view) in your MainActivity.