I would like to add Task name from pop up and It automatically will add to list. So, is there any way to update database automatically. Here is my method
SampleDB = this.openOrCreateDatabase("SampleDB", SQLiteDatabase.CREATE_IF_NECESSARY, null);
String query = "select *from TaskList";
Cursor c = SampleDB.rawQuery(query, null);
c.moveToFirst();
do{
String Task = c.getString(c.getColumnIndex("task"));
/* Add current Entry to results. */
results.add(Item);
}while(c.moveToNext());
this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));
This method can add items to your database:
public void addTaskToDb(SQLiteDatabase database, String task) {
ContentValues values = new ContentValues();
values.put("task", task);
database.insert("TaskList", null, values);
}
And then replace your code like this:
SampleDB = this.openOrCreateDatabase("SampleDB", SQLiteDatabase.CREATE_IF_NECESSARY, null);
ArrayAdapter<String> adapter = (ArrayAdapter<String>)this.getListAdapter();
this.addTaskToDb(SampleDB, Item);
adapter.add(Item);
Related
My MainActivity have a listview with some categories,If I click a particular category in my listview,it's need to redirect to another activity,which need to have the details of that particular category.
Eg: IF I select FOOD in Mainactivity,I want to redirect to another activity where the activity want to have the budget amount of food.
public class addbudget extends ActionBarActivity implements View.OnClickListener{
SimpleCursorAdapter adapter;
DBhelper helper;
SQLiteDatabase db;
EditText txtBudget;
TextView txr;
ListView rldlist,list;
Button btn66;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addbudget);
btn66=(Button)findViewById(R.id.btn_addBudget);
btn66.setOnClickListener(this);
helper=new DBhelper(addbudget.this);
txr=(TextView)findViewById(R.id.addbud);
txtBudget=(EditText)findViewById(R.id.etBudget);
rldlist = (ListView) findViewById(R.id.rldlist);
list = (ListView) findViewById(R.id.list);
Bundle data_from_list= getIntent().getExtras();
String value_in_tv= data_from_list.getString("passed data key");
txr.setText(value_in_tv);
fetchData2();
}
private void clearfield(){
txtBudget.setText("");
}
public void onClick(View v) {
if (btn66 == v) {
ContentValues value = new ContentValues();
value.put(DBhelper.Amount, txtBudget.getText().toString());
value.put(DBhelper.Description,txr.getText().toString());
if (txtBudget.length() == 0) {
txtBudget.requestFocus();
txtBudget.setError("Field Cannot Be Empty");
} else {
db = helper.getWritableDatabase();
db.insert(DBhelper.TABLE2, null, value);
db.close();
clearfield();
Toast.makeText(this, "Budget add Successfully", Toast.LENGTH_LONG).show();
fetchData2();
}
}
}
private void fetchData2() {
db = helper.getReadableDatabase();
Cursor c = db.query(DBhelper.TABLE2, null, null, null, null, null, null);
adapter = new SimpleCursorAdapter(
this,
R.layout.row2,
c,
new String[]{DBhelper.Amount},
new int[]{R.id.lbl});
list.setAdapter(adapter);
}
}
This is how ,I'm fetching data to a listview from database.Here I'm fetching Amount from database.
How can I change the fetchdata method to get the BudgetAmount of a specific category ?(I'm using bundle to get the name of the category from the listview of MainActivity)
You can use sql syntax:
String sql = "select * from DBhelper.TABLE2 where category_name_column = " + category";
Cursor c = db.rawQuery(sql.toString(), null);
Or if you want to use params:
String whereClause = "your_category_column = ?";
String[] whereArgs = new String[] {
"category_name"
};
Cursor c = db.query(DBhelper.TABLE2, null, whereClause, whereArgs, null, null, null);
So your method can be as such:
private void fetchData2(String category) {
db = helper.getReadableDatabase();
String whereClause = "your_category_column = ?";
String[] whereArgs = new String[] {"category"};
Cursor c = db.query(DBhelper.TABLE2, null, whereClause, whereArgs, null, null, null);
adapter = new SimpleCursorAdapter(
this,
R.layout.row2,
c,
new String[]{DBhelper.Amount},
new int[]{R.id.lbl});
list.setAdapter(adapter);
}
I'm relatively new to Android and I was making a To-Do List application. I have a database containing a column of tasks. How can I put these tasks into an ArrayList and display it ?
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.query(TaskContract.TABLE, new String[]{TaskContract.Columns._ID,TaskContract.Columns.TASK}, null, null, null, null, null);
arrayListToDo = new ArrayList<String>();
arrayAdapterToDo = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayListToDo);
ListView listViewToDo = (ListView) findViewById(R.id.listViewToDo);
listViewToDo.setAdapter(arrayAdapterToDo);
Try this code
while (cursor.moveToNext()) {
arrayListToDo.add(cursor.getString(cursor.getColumnIndex("Your column name")));
}
You can get the data in Array list :-
ArrayList<String> arrayListToDo= new ArrayList<String>();
//your query will returns cursor
if (cursor.moveToFirst()) {
do {
arrayListToDo.add(get you string from cursor);
} while (cursor.moveToNext());
}
now add this aray list to your Adapter.
get list data from database this is only overview
ArrayList<String> data = databaseObject.GetList();
ListView listViewToDo = (ListView) findViewById(R.id.listViewToDo);
arrayAdapterToDo = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
listViewToDo.setAdapter(arrayAdapterToDo);
ArrayList<String> GetList()
{
ArrayList<String> arrayListtemp= new ArrayList<String>();
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.query(TaskContract.TABLE, new String[]{TaskContract.Columns._ID,TaskContract.Columns.TASK}, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
arrayListtemp.add("");// added your table value from database
} while (cursor.moveToNext());
}
return arrayListtemp;
}
The problem is i inserted only two rows but on execution it enters into infinite loop and repeatedily showing the same data..Any kind of help would be appreciated
Here is my code.
This is my databse class (i.e DbAdapter)
public Cursor getAllRows() {
String[]columns = new String[]{ KEY_MODEL,KEY_BRAND, KEY_PRICE};
Cursor c = db.query(TABLE_LAPTOPS, columns, null, null, null, null, null);
if (c != null) {
c.moveToLast();
}
return c;
}
This is my main class (i.e Laptops)
DbAdapter obj = new DbAdapter(this);
obj.open();
obj.insertRow("Dell1", "Dell", 345);
obj.insertRow("Hp1", "HP", 546);
obj.close();
obj.open();
Cursor c1 = obj.getAllRows();
try{
if(c1 != null){
ListView empListView = (ListView)findViewById(R.id.listView1);
ArrayList<String> data1 = new ArrayList<String>();
for(c1.moveToFirst();!c1.isAfterLast();c1.moveToNext())
{
Toast.makeText(getApplicationContext(), c1.getString(0), Toast.LENGTH_LONG).show();
}
//empListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data1));
}}catch(SQLException e){
e.printStackTrace();
}
obj.close();
c.moveToLast();
here is the issue
c.moveToFirst();
try this..
Try with Like This
listView = (ListView) rootView.findViewById(R.id.Assignment_VM_List);
AssignmentDatabaseConnector dao = new AssignmentDatabaseConnector(getActivity());
List<AssignmentPojo> assignments = dao.getAllAssignmentList();
AssignmentCustomAdapter assignmentCustomAdapter = new AssignmentCustomAdapter(getActivity(),
assignments, this);
listView.setAdapter(assignmentCustomAdapter);
AssignmentDatabaseConnector :
public List<AssignmentPojo> getAllAssignmentList() {
open();
List<AssignmentPojo> assignmentList = new ArrayList<AssignmentPojo>();
// Select All Query
String selectQuery = "SELECT * FROM Assignment";
Cursor cursor = database.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) { // ##Your Main Issue is Here ##
do {
AssignmentPojo assignment = new AssignmentPojo();
assignment.setAssign_Id(cursor.getString(0));
assignment.setAssign_Course(cursor.getString(1));
// Adding contact to list
assignmentList.add(assignment);
} while (cursor.moveToNext());
}
cursor.close();
database.close();
// return contact list
return assignmentList;
}
This is just a sample code you can utilize this code according to your requirements
i want to display data from sqlite to textview,here is my code.What i have dont wrong.It is not displaying the data no error but crashes
main class
private void loadTextViewData()
{
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
List<String> lables = db.getAllLabels();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.test_list_item, lables);
text.setText(??);
}
sql class
public List<String> getAllLabels(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
instead of ArrayAdapter use for example SimpleCursorAdapter (or any subclass of CursorAdapter)
i want to get the value from the cursor without the SimpleCursorAdapter part.here is the code
public Cursor queueAll(){
String[] columns = new String[]{KEY_ID, KEY_CONTENT1, KEY_CONTENT2,KEY_CONTENT3};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
null, null, null, null, null);
return cursor;
}
and the activity side code
cursor = mySQLiteAdapter.queueAll();
from = new String[]{SQLiteAdapter.KEY_ID, SQLiteAdapter.KEY_CONTENT1, SQLiteAdapter.KEY_CONTENT2, SQLiteAdapter.KEY_CONTENT3};
int[] to = new int[]{R.id.id, R.id.text1, R.id.text2,R.id.text3};
cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
while(!cursor.isAfterLast())
{
String tilt = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT1));
String pkg = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT3));
if(tilt.equals("LEFT"))
{
Log.v("LEFT",pkg);
}
else if(tilt.equals("RIGHT"))
{
Log.v("RIGHT",pkg);
}
cursor.moveToNext();
}
i am getting the pkg value correct.but i want to get the values directly from the cursor while removing SimpleCursorAdapter part the code doesn't work.
any help would be appreciated :)
You can get values without declaring adapters. Adapters are need if you want to show the data in the list widgets. So your can be the following:
cursor = mySQLiteAdapter.queueAll();
if (cursor == null) {
//check if there are errors or query just return null
}
if (cursor.moveToFirst()) {
while(!cursor.isAfterLast())
{
String tilt = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT1));
String pkg = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT3));
if(tilt.equals("LEFT"))
{
Log.v("LEFT",pkg);
}
else if(tilt.equals("RIGHT"))
{
Log.v("RIGHT",pkg);
}
cursor.moveToNext();
}
}
First you must count how many rows are in your table. Then assign that count to variable and it use to create an array. For array size you can use that count variable. Then create a for loop and use that count variable for rounds. After create your query and assign values to your arrays. 100% worked!.
int sqlcount;
Cursor mFetch;
SQLiteDatabase mydb = openOrCreateDatabase("your database name", MODE_PRIVATE, null);
mydb.execSQL("create table if not exists customer(name varchar,email varchar)");
Cursor mCount = mydb.rawQuery("select count(*) from customer", null);
mCount.moveToFirst();
sqlcount = mCount.getInt(0);
mCount.close();
String cname[] = new String[sqlcount];
String cemail[] = new String[sqlcount];
for(int i=0;i<sqlcount;i++) {
mFetch= mydb.rawQuery("select name,email from customer", null);
mFetch.moveToPosition(i);
cname[i] = mFetch.getString(0);
cemail[i] = mFetch.getString(1);
}
mFetch.close();
Toast.makeText(MainActivity.this,String.valueOf(cname[0]),Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this,String.valueOf(cemail[1]),Toast.LENGTH_SHORT).show();