I have used a database class, datamodel class and main activity in my application. I am not populating spinner values from sqlite database but I am storing selected spinner values in db. I have a text entry too. I declared datamodel object separately.
StudentModel student=new StudentModel();
I have used this is at two diff places.The first one inside Onclick(text)
if(v == findViewById(R.id.add)){
tv.setText("");
student.name = name.getText().toString();
}
The next inside OnItemSelected(Spinner)
student.subject=subject.getItemAtPosition(position).toString();
In the databasehelper class I insert value like
public long addStudentDetail(StudentModel student) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_SUBJECT, student.subject);
values.put(KEY_NAME, student.name);
long insert = db.insert(TABLE_STUDENT, null, values);
return insert;
}
And in the databasehelper class I retrieve them like
if (c.moveToFirst()) {
do {
StudentModel students = new StudentModel();
students.id = c.getInt(c.getColumnIndexOrThrow(KEY_ID));
students.name = c.getString(c.getColumnIndexOrThrow(KEY_NAME));
students.subject = c.getString(c.getColumnIndexOrThrow(KEY_SUBJECT));
studentsArrayList.add(students);
} while (c.moveToNext());
}
I get java.lang.IllegalArgumentException: column 'subject' does not exist while running.
Related
I check if customer index=0 then inserting the data on OnCREATE method and else part inserting the data on click button.
if (C_Id==0){
helper.CustomerAdd(new CustomerModel("developer","test","test#gmail.com","9874643212","test",null,"abc road","gurgaon","india",null));
}
public int CustomerAdd(CustomerModel fm){
int cust_id=0;
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
ContentValues cv = new ContentValues();
cv.put( C_NAME, fm.getC_name() );
cv.put( C_NO, fm.getC_phone() );
cv.put( C_EMAIL, fm.getC_email() );
cv.put( BILL_NAME, fm.getC_bill_name() );
cv.put( GST_NO, fm.getGst_no() );
cv.put( C_ADDRESS, fm.getC_address() );
cv.put( CITY, fm.getC_city() );
cv.put( Country, fm.getC_country() );
cv.put( DESCRIPTION, fm.getDescription() );
cv.put( JOB_Tittle, fm.getJob_title());
SimpleDateFormat sdfdndj = new SimpleDateFormat( "dd/MM/yy" );
String Timedatanew = sdfdndj.format( new java.util.Date() );
cv.put( Created_date, Timedatanew );
try{
db.insert( CUSTOMER_TABLE, null, cv );
Cursor cursor = db.rawQuery( "Select C_ID from CUSTOMER Order by C_ID DESC limit 1",null);
if (cursor.moveToLast()){
cust_id= cursor.getInt( 0 );
}else {
cust_id=0;
}
}
I tried like this but don't know how to add data on the first row.
any help would be appreciated!
Your issue could be that you begin a transaction but don't commit (setTransactionSuccessful) and end the transaction.
However, for a single action such as inserting a row then there is no need to begin/commit/end as being a single action it will be it's own transaction.
As such, you could just remove the line db.beginTransaction();
If your issue is how to add a row to the CUSTOMER table, if there are no rows, in the onCreate method of an activity, then you could code and call the following method (this assumes that the CustomerAdd method is in a class named MyDatabaseHelper, therefore you may need to change accordingly)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper = new MyDatabaseHelper(this);
addFirstCustomerIfNone(); //<<<<<<<<<<
}
private void addFirstCustomerIfNone() {
SQLiteDatabase db = helper.getWritableDatabase();
if(DatabaseUtils.queryNumEntries(db,"CUSTOMER") < 1) {
if (helper.CustomerAdd(new CustomerModel("developer","test","test#gmail.com","9874643212","test",null,"abc road","gurgaon","india",null)) ==0) {
Toast.makeText(this,"Customer Added Successfully.",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this,"Customer was not added.",Toast.LENGTH_SHORT).show();
}
}
}
Thus when the activity is started and the onCreate method is invoked helper (an instance of the database helper class) is instantiated and then the addFirstCustomerIfNone method is called.
The addFirstCustomerIfNone method checks to see if the CUSTOMER table has any rows, if not then the first row is added. If rows already exists then nothing is added.
Note the above is based upon the available information and makes some assumptions and may therefore not cater for all circumstance.
Learning how to program in android by following a tutorial but i am trying to also update the entry in the data base though not entirely how to do so. Any help please?
package dev.edmt.todolist;
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;
/**
* Created by reale on 06/10/2016.
*/
public class DbHelper extends SQLiteOpenHelper {
private static final String DB_NAME="EDMTDev";
private static final int DB_VER = 1;
public static final String DB_TABLE="Task";
public static final String DB_COLUMN = "TaskName";
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VER);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = String.format("CREATE TABLE %s (ID INTEGER PRIMARY KEY AUTOINCREMENT,%s TEXT NOT NULL);",DB_TABLE,DB_COLUMN);
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = String.format("DELETE TABLE IF EXISTS %s",DB_TABLE);
db.execSQL(query);
onCreate(db);
}
public void insertNewTask(String task){
SQLiteDatabase db= this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DB_COLUMN,task);
db.insertWithOnConflict(DB_TABLE,null,values,SQLiteDatabase.CONFLICT_REPLACE);
db.close();
}
public void editTask(String task){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DB_COLUMN,task);
db.update(DB_TABLE,values,DB_COLUMN + " = " + task,null) > 0;
db.close();
}
public void deleteTask(String task){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(DB_TABLE,DB_COLUMN + " = ?",new String[]{task});
db.close();
}
public ArrayList<String> getTaskList(){
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(DB_TABLE,new String[]{DB_COLUMN},null,null,null,null,null);
while(cursor.moveToNext()){
int index = cursor.getColumnIndex(DB_COLUMN);
taskList.add(cursor.getString(index));
}
cursor.close();
db.close();
return taskList;
}
}
More specifically this part, cant really say i quite understand the way it works:
public void editTask(String task){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DB_COLUMN,task);
db.update(DB_TABLE,values,DB_COLUMN + " = " + task,null) > 0;
db.close();
}
More specifically this part, cant really say i quite understand the
way it works:
It may work, as in not fail, but as explained below it probably does nothing of any use.
The SQLiteDatabase update method is a convenient way of issuing the SQL to perform an update. It writes/creates the underlying SQl, executes it, and also returns the result (the number of rows updated).
Using your code as an example, to do the similar without using the update method you could create the SQL :-
UPDATE Task SET TaskName = 'your_value' WHERE Task = 'your_value'
Note that this is actually useless as you are effectively saying (assuming for demonstration that the value passed to the editTask method is task001); Update the task row(s) that has/have the value of task001 in the TaskName column to be changed from task001 to task001.
Note the update method uses UPDATE OR IGNORE...... so :-
When an applicable constraint violation occurs, the IGNORE resolution algorithm skips the one row that contains the constraint
violation and continues processing subsequent rows of the SQL
statement as if nothing went wrong. Other rows before and after the
row that contained the constraint violation are inserted or updated
normally. No error is returned when the IGNORE conflict resolution
algorithm is used. SQL As Understood By SQLite - ON CONFLICT clause
Suggestion
Perhaps what would be more useful if say you wanted to change a row that before the update, has a value task001. Changing it say to task002.
in this case the SQL could be :-
UPDATE Task SET TaskName = 'your_new_value' WHERE Task = 'your_original_value'
Your editTask method could then be :-
public void editTask(String original_task, String new_task){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DB_COLUMN,new_task);
db.update(DB_TABLE,values,DB_COLUMN + " = '" + original_task + "'" ,null) > 0;
db.close();
}
e.g. using edittask("task001","task002");
Note how the value original_task is enclosed in single quotes.
However, the recommended way, would be to utilise arguments (which would automatically be enclosed in quotes) so the above could be :-
public void editTask(String original_task, String new_task){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DB_COLUMN,new_task);
String[] whereargs = new String[]{original_task};
db.update(DB_TABLE,values,DB_COLUMN + "=?",whereargs) > 0;
db.close();
}
each ? coded in the WHERECLAUSE (3rd parameter) replaced by the respective argument in the WHEREARGS (4th parameter) on a 1 by 1 basis.
Additional
In addition to creating the SQL, the update method also invokes the SQL using an appropriate means e.g. it does the equivalent of db.execSQL(your_sql) for you.
Additionally in the case of update it then does the equivalent of :-
Cursor csr = db.rawQuery("SELECT total_changes()",null);
int total_changes = 0;
if(csr.moveToFirst()) {
total_changes = csr.getInt(0);
}
return total_changes;
Hence returning the number of updated rows.
db.update method will create SQL statement according to your given parameters and execute it. You could see the db.update() method to find a better understanding.
i am beginning in SQLiteDatabase i am trying to insert data where i fetch it from Internet and i am using asynTask to fetch data and insert it
but data is duplicate in recycleview when rotate the mobile and when reload activity or login to activity
below is my code
#Override
protected String doInBackground(String... arg) {
JSONObject json = jsonFromHttp.makeHttpRequest(URLS.CATEGORIES_URL, "Get", params);
try {
JSONArray products = json.getJSONArray("cat1");
for (int i=0;i< products.length();i++) {
JSONObject Arrobj= products.getJSONObject(i);
String cat_id=Arrobj.getString("cat_id");
String cat_name=Arrobj.getString("cat_name");
String cat_photo=Arrobj.getString("cat_photo");
Integer id=Integer.parseInt(cat_id);
// here i insert data
ContentValues values = new ContentValues();
values.put(DataContract.DataEntry.COLUMN_CATEGORY_NAME, cat_name);
values.put(DataContract.DataEntry.CATEGORY_ID, id);
values.put(DataContract.DataEntry.COLUMN_CATEGORY_IMAGE, "mm");}
Uri newUri = getContext().getContentResolver().insert(DataContract.DataEntry.CONTENT_URI, values);
categoriesList.add(new CategoryModel(cat_name,cat_photo,cat_id,"","")); //put object which carry values in list
i don't know how to solve this problem .
i make cat_id is primary key this prevent data to duplicate
How can I populate a spinner content from database (SQLite)
I have POJO: categories, contain id and name,
I have the table already, with a function to get the ArrayList like this:
public List<SetcardCategory> getAllSetcardCategory()
{
List<SetcardCategory> setcardCategories = new ArrayList<SetcardCategory>();
String selectQuery = "SELECT * FROM " + TABLE_SETCARD_CATEGORIES;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
SetcardCategory setcardCategory = new SetcardCategory();
setcardCategory.setId(c.getInt((c.getColumnIndex("id"))));
setcardCategory.setName(c.getString(c.getColumnIndex("name")));
// adding to tags list
setcardCategories.add(setcardCategory);
} while (c.moveToNext());
}
return setcardCategories;
}
Then on Activity I call it like this:
List<SetcardCategory> setcardCategories = db.getAllSetcardCategory();
ArrayAdapter<SetcardCategory> arrayAdapter = new ArrayAdapter<SetcardCategory>(
this, android.R.layout.simple_spinner_item, setcardCategories);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner sItems = (Spinner) findViewById(R.id.setcardCategory);
sItems.setAdapter(arrayAdapter);
when I run it, it loads string like this: "schema.SetcardCategory#22293c98" and many others values similar to that.
How can I populate the spinner to show the name field as a label, and id field as the value that we fetch to save into DB?
class Pojo{
private String name;
#Override
public String toString() {
return name;
}
}
do it like this in the pojo class, so this will return a value for the object when it uses the to string method in the adapter, to load the data
Solution 1
Overide the toString method in your SetcardCategory class
class SetcardCategory {
...
...
#Override
public String toString() {
return this.name;
}
}
Solution 2
If you just want to show the name, Just pick name only from DB
public List<String> getAllSetcardCategory()
{
List<String> setcardCategories = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_SETCARD_CATEGORIES;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
// adding to tags list
setcardCategories.add(c.getString(c.getColumnIndex("name")));
} while (c.moveToNext());
}
return setcardCategories;
}
And create Array Adapter as
List<String> setcardCategories = db.getAllSetcardCategory();
ArrayAdapter<SetcardCategory> arrayAdapter = new ArrayAdapter<SetcardCategory>(
this, android.R.layout.simple_spinner_item, setcardCategories);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
I have a JSON Array. I'm using DatabaseHelper to transfer the data but I'm not able to fetch the data. I know I'm making a simple mistake but it's just not visible.
This is the onCreate method
arrayList = database.getAllData();
ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(),
android.R.layout.activity_list_item,
android.R.id.text1,
arrayList);
listView.setAdapter(adapter);
And this is the getAllData
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
This is something I did once. Can you get an idea from this? :)
public ArrayList<Item_Record> getAllRecords_ArrayList (String Table_Name) {
// Create an array list
ArrayList<Item_Record> List_Of_Records = new ArrayList<>();
// Create a database object
SQLiteDatabase DB = this.getReadableDatabase();
// Create a cursor file we get from executing this above command
Cursor crsr = DB.query(
Table_Name,
new String[] {COLUMN_DATE, COLUMN_CATEGORY, COLUMN_AMOUNT},
null, null, null, null, COLUMN_DATE);
crsr.moveToFirst();
while (! crsr.isAfterLast()) {
// Add that to the array list
List_Of_Records.add(new Item_Record(
crsr.getString(crsr.getColumnIndex(COLUMN_DATE)),
crsr.getString(crsr.getColumnIndex(COLUMN_CATEGORY)),
crsr.getDouble(crsr.getColumnIndex(COLUMN_AMOUNT))));
// Go to the next row
crsr.moveToNext();
}
// Closes database and cursor and return the list
crsr.close(); DB.close();
return List_Of_Records;
}