How to write SQLite database in Fragment Android - android

while I am creating a database on android SQLite database with fragment if I write inside the onViewCreated method couldn't write the database name and Listview findViewById get the error I don't know. what I tried so I wrote below.
cannot resolve the method openOrCreateDatabase
SQLiteDatabase db = openOrCreateDatabase("course", Context.MODE_PRIVATE, null);
lst1 = findViewById(R.id.lst1);
cannot resolve the method findViewById
cannot resolve the constructor ArrayAdapter
**arrayAdapter = new ArrayAdapter(this, `R.layout.support_simple_spinner_dropdown_item, titles);**`
lst1 = findViewById(R.id.lst1);
ListView lst1;
ArrayList<String> titles = new ArrayList<String>();
ArrayAdapter arrayAdapter;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SQLiteDatabase db = openOrCreateDatabase("course", Context.MODE_PRIVATE, null);
lst1 = findViewById(R.id.lst1);
final Cursor c = db.rawQuery("select * from category", null);
int id = c.getColumnIndex("id");
int title = c.getColumnIndex("title");
int description = c.getColumnIndex("description");
titles.clear();
arrayAdapter = new ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, titles);
lst1.setAdapter(arrayAdapter);
final ArrayList<cate> cat = new ArrayList<cate>();
if (c.moveToFirst()) {
do {
cate stu = new cate();
stu.id = c.getString(id);
stu.course = c.getString(title);
stu.description = c.getString(description);
cat.add(stu);
titles.add(c.getString(id) + " \t " + c.getString(title) );
} while (c.moveToNext());
arrayAdapter.notifyDataSetChanged();
lst1.invalidateViews();
}
lst1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String aa = titles.get(position).toString();
cate stu = cat.get(position);
Intent i = new Intent(getApplicationContext(), editcategory.class);
i.putExtra("id", stu.id);
i.putExtra("category", stu.course);
i.putExtra("description", stu.description);
startActivity(i);
}
});
}

You can't directly call openOrCreateDatabase() in a fragment because it is a method from Context. A fragment is not a context. To get the context / Activity, just call getActivity()
It will result in the following :
SQLiteDatabase db = getActivity().openOrCreateDatabase("course", Context.MODE_PRIVATE, null);
For findViewById() you have to call that on the parent view
view.findViewById(R.id.lst1);
For the adapter constructor, R.layout.support_simple_spinner_dropdown_item is not a string but an id from R class, so no need for '
arrayAdapter = new ArrayAdapter(getActivity(), R.layout.support_simple_spinner_dropdown_item, titles);

Related

Android onListItemClick exception: "java.lang.String cannot be cast to android.database.Cursor"

As title says, it get this exception from the code I pasted below. I tried to make it work both with the uncommented code and also with the commented part insted of the IF block just before it.
The error I get is: java.lang.ClassCastException: java.lang.String cannot be cast to android.database.Cursor which I don't understand, since the item in the listview should exactly be a String! Any idea?
public class ListScoutActivity extends ListActivity {
private DBHelper database;
private ListView listav;
private Cursor cursor;
ArrayList<String> stringlist = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_scout);
database = new DBHelper(getApplicationContext());
SQLiteDatabase db = database.getWritableDatabase();
listav = this.getListView();
listav.setVisibility(View.VISIBLE);
int codpartita;
String team;
cursor = db.rawQuery("SELECT _codpartita as _id, team, FROM partita ORDER BY _codpartita DESC", null);
cursor.moveToFirst();
while ( !cursor.isAfterLast() ) {
team = cursor.getString(cursor.getColumnIndex("team"));
stringlist.add(team);
cursor.moveToNext();
}
cursor.moveToFirst();
if (cursor.getCount()>0) {
SimpleCursorAdapter adapter = new SimpleCursorAdapter(ListScoutActivity.this,
android.R.layout.simple_list_item_1, cursor, new String[]{"team"},
new int[]{android.R.id.text1}, 0);
listav.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListScoutActivity.this,
// android.R.layout.simple_list_item_1, android.R.id.text1, stringlist);
// listav.setAdapter(adapter);
db.close();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Cursor cursor = (Cursor)l.getItemAtPosition(position);
//.. other things..
}

Android 2 sqlite database tables in the same listview adapter

I have made an android SQLite database with two tables, each of them are performing in separate activities. And I'm trying to put them in the same listview.
This is my activity where the listview is.
public class MainActivity extends ActionBarActivity {
ListView lv;
SQLController dbcon;
TextView incomeID_tv, incomePayer_tv, incomeAmount_tv;
TextView incomeDate_tv, incomeCategory_tv, incomePayments_tv;
TextView expenseID_tv, expensePayee_tv, expenseAmount_tv;
TextView expenseDate_tv, expenseCategory_tv, expensePayments_tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbcon = new SQLController(this);
dbcon.open();
lv = (ListView) findViewById(R.id.incomeList_id);
Cursor cursor = dbcon.readIncomeData();
String[] from = new String[] { DBHelper.INCOME_ID, DBHelper.INCOME_AMOUNT, DBHelper.INCOME_PAYER,
DBHelper.INCOME_DATE, DBHelper.INCOME_CATEGORY, DBHelper.INCOME_PAYMENTS};
int[] to = new int[] { R.id.income_id, R.id.income_amount, R.id.income_payer, R.id.income_date,
R.id.income_category, R.id.income_payments};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
MainActivity.this, R.layout.income_entry, cursor, from, to);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
Cursor ecursor = dbcon.readExpenseData();
String[] efrom = new String[] { DBHelper.EXPENSE_ID, DBHelper.EXPENSE_AMOUNT, DBHelper.EXPENSE_PAYEE,
DBHelper.EXPENSE_DATE, DBHelper.EXPENSE_CATEGORY, DBHelper.EXPENSE_PAYMENTS};
int[] eto = new int[] { R.id.expense_id, R.id.expense_amount, R.id.expense_payee, R.id.expense_date,
R.id.expense_category, R.id.expense_payments};
SimpleCursorAdapter eadapter = new SimpleCursorAdapter(
MainActivity.this, R.layout.expense_entry, ecursor, efrom, eto);
eadapter.notifyDataSetChanged();
lv.setAdapter(eadapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
incomeID_tv = (TextView) view.findViewById(R.id.income_id);
incomeAmount_tv = (TextView) view.findViewById(R.id.income_amount);
incomePayer_tv = (TextView) view.findViewById(R.id.income_payer);
incomeDate_tv = (TextView) view.findViewById(R.id.income_date);
incomeCategory_tv = (TextView) view.findViewById(R.id.income_category);
incomePayments_tv = (TextView) view.findViewById(R.id.income_payments);
String incomeID = incomeID_tv.getText().toString();
String incomeAmount = incomeAmount_tv.getText().toString();
String incomePayer = incomePayer_tv.getText().toString();
String incomeDate = incomeDate_tv.getText().toString();
String incomeCategory = incomeCategory_tv.getText().toString();
String incomePayments = incomePayments_tv.getText().toString();
Intent modify_intent = new Intent(getApplicationContext(),
IncomeEdit.class);
modify_intent.putExtra("incomeID", incomeID);
modify_intent.putExtra("newIncomeAmount", incomeAmount);
modify_intent.putExtra("newIncomePayer", incomePayer);
modify_intent.putExtra("newIncomeDate", incomeDate);
modify_intent.putExtra("newIncomeCategory", incomeCategory);
modify_intent.putExtra("newIncomePayments", incomePayments);
startActivity(modify_intent);
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
expenseID_tv = (TextView) view.findViewById(R.id.expense_id);
expenseAmount_tv = (TextView) view.findViewById(R.id.expense_amount);
expensePayee_tv = (TextView) view.findViewById(R.id.expense_payee);
expenseDate_tv = (TextView) view.findViewById(R.id.expense_date);
expenseCategory_tv = (TextView) view.findViewById(R.id.expense_category);
expensePayments_tv = (TextView) view.findViewById(R.id.expense_payments);
String expenseID = expenseID_tv.getText().toString();
String expenseAmount = expenseAmount_tv.getText().toString();
String expensePayer = expensePayee_tv.getText().toString();
String expenseDate = expenseDate_tv.getText().toString();
String expenseCategory = expenseCategory_tv.getText().toString();
String expensePayments = expensePayments_tv.getText().toString();
Intent modify_intent = new Intent(getApplicationContext(),
ExpenseEdit.class);
modify_intent.putExtra("expenseID", expenseID);
modify_intent.putExtra("newExpenseAmount", expenseAmount);
modify_intent.putExtra("newExpensePayee", expensePayer);
modify_intent.putExtra("newExpenseDate", expenseDate);
modify_intent.putExtra("newExpenseCategory", expenseCategory);
modify_intent.putExtra("newExpensePayments", expensePayments);
startActivity(modify_intent);
}
});
}
The problem is that it shows just the expenses. I think the problem is from the adapter, but I don't know how to include both of them in the same adapter. :)
set doesn't mean add. If you setAdapter it means the old one (if any) will be replaced. The same goes for the OnItemClickListener.
If the cursors had the same column names, you could combine them however they differ and the adapter has no means to distinguish between the data of the 2 cursors (expenses and incomes).
Furthermore each click listener has type-specific actions like putting specific intent extras. This just means that you want multiple adapters therefore multiple ListView's.
You need to make your table and app design more generic or continue using 2 ListViews.

filling ListView from database in Android

I'm new in Android programming and I'm wondering witch is the most appropriate way to fill a ListView from DataBase.
Here the method I'm using in database to get my items
// Getting All stats
public List<StatParcours> getAllSats() {
List<StatParcours> statList = new ArrayList<StatParcours>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_STATS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
StatParcours stat = new StatParcours();
stat.setID(Integer.parseInt(cursor.getString(0)));
stat.setDate(cursor.getString(1));
stat.setDuration(cursor.getString(2));
stat.setDistance(Double.parseDouble(cursor.getString(3)));
stat.setSpeed(Double.parseDouble(cursor.getString(4)));
stat.setCondition(cursor.getString(5));
// Adding contact to list
statList.add(stat);
} while (cursor.moveToNext());
}
// return contact list
return statList;
}
and in the main activity, I'm using this. I know there is something wrong with the populateMyStatsList method, but I still don't know how to fix it.
public class History extends Activity {
public DatabaseHandler db;
private List<StatParcours> MyStats = new ArrayList<StatParcours>();
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("oncreate", "ok");
super.onCreate(savedInstanceState);
setContentView(R.layout.history);
populateMyStatsList ();
populateListView();
registerClickCallback();
}
private void populateMyStatsList (){
MyStats = db.getAllSats();
}
private void populateListView() {
ArrayAdapter<StatParcours> adapter = new MyListAdapter();
ListView list = (ListView) findViewById(R.id.HistListView);
list.setAdapter(adapter);
Log.i("Populate", "ok");
}
private void registerClickCallback() {
ListView list = (ListView) findViewById(R.id.HistListView);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long id) {
StatParcours clickedCar = MyStats.get(position);
String message = "You clicked position " + position
+ " Which is car make " + clickedCar.getDate();
Toast.makeText(History.this, message, Toast.LENGTH_LONG).show();
}
});
}
private class MyListAdapter extends ArrayAdapter<StatParcours> {
public MyListAdapter() {
super(History.this, R.layout.item_view, MyStats);
Log.i("MyListAdapter", "ok");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null) {
Log.i("Make sure", "ok");
itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false);
}
Log.i("getview", "ok");
StatParcours currentStat = MyStats.get(position);
TextView makeText = (TextView) itemView.findViewById(R.id.item_txtMake);
makeText.setText(currentStat.getDate());
TextView yearText = (TextView) itemView.findViewById(R.id.item_txtYear);
yearText.setText("" + currentStat.getDistance());
TextView condionText = (TextView) itemView.findViewById(R.id.item_txtCondition);
condionText.setText(currentStat.getCondition());
return itemView;
}
}
}
You need to use a SimpleCursor Adapter. I can't reach the developer site for the documentation but here is an example with your code above.
EDIT: Here is the link to the android developer website.
http://developer.android.com/reference/android/widget/SimpleCursorAdapter.html
SECOND EDIT: This would go in the populateListView()
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_STATS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Set your layout to int[]
int[] to = new int[]{R.id.item_txtMake,R.id.item_txtYear,R.id.item_txtCondition};
//set your columns to string[]; fill in your actual column names
string[] from = new string[]{"make","year","condition"};
//set up adapter
SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(),R.layout.item_view, cursor, from,to,null);
//set adapter to listview
ListView list = (ListView) findViewById(R.id.HistListView);
list.setAdapter(adapter);
Since you only have TextView in your ListView you can just simply use SimpleCursorAdapter.
// Getting All stats
public Cursor getAllSats() {
List<StatParcours> statList = new ArrayList<StatParcours>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_STATS;
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery(selectQuery, null);
}
And in your History class
public class History extends Activity {
public DatabaseHandler db;
private List<StatParcours> MyStats = new ArrayList<StatParcours>();
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("oncreate", "ok");
super.onCreate(savedInstanceState);
setContentView(R.layout.history);
Cursor c = getAllSats();
String[] fromColumns = {Your database column name for date,
Your database column name for distance,
Your database column name for condition};
int[] toViews = {R.id.item_txtMake,
R.id.item_txtYear,
R.id.item_txtCondition};
adapter = new SimpleCursorAdapter(this, R.layout.item_view,
c, fromColumns, toViews, 0);
ListView list = (ListView) findViewById(R.id.HistListView);
list.setAdapter(adapter);
registerClickCallback();
}

Android load data from SQLite Database into next activity

I have a listView which loads data from SQLite database and right now I would want to implement an onclicklistener to the list. When users click on the list, it should bring them to the next activity and load the corresponding data into TextView. My question is how would I pass the data of the list for example it is a list of "Topics" and user click on the topic "My Home". I want to pass the topic "My Home" to the next activity so that I know which corresponding data to be retrieved respectively.
How do I go about it? Do I "putExtras" to the new Intent? or there is another way. Below are part of my codes which display the listview:
ListView listContent = (ListView) findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToRead();
Cursor cursor = mySQLiteAdapter.queueAll();
startManagingCursor(cursor);
String[] from = new String[] { SQLiteAdapter.KEY_CONTENT };
int[] to = new int[] { R.id.text };
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.listrow, cursor, from, to);
listContent.setAdapter(cursorAdapter);
mySQLiteAdapter.close();
//Onclick ListView setlistener
listContent.setTextFilterEnabled(true);
listContent.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent summaryIntent = new Intent(DocumentListActivity.this, ViewDocumentActivity.class);
// summaryIntent.putExtra("SummTopic", value);
}
});
EDITED:
This part is on the next activity.
Intent i = getIntent();
extraTopic = i.getStringExtra("SummTopic");
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
Cursor allrows = mydb.rawQuery("SELECT * FROM "+ TABLE + " WHERE topic = \" " + extraTopic + " \" " , null);
Integer cindex = allrows.getColumnIndex("topic");
Integer cindex1 = allrows.getColumnIndex("text1");
Integer cindex2 = allrows.getColumnIndex("text2");
I got an error while retrieving from database:
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0
Please help.
Thank you.
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent summaryIntent = new Intent(DocumentListActivity.this, ViewDocumentActivity.class);
Cursor c = (Cursor)parent.getItemAtPosition(position);
summaryIntent.putExtra("SummTopic", c.getString(c.getColumnIndex(SQLiteAdapter.KEY_CONTENT)));
startActivity(summaryIntent);
}
or you can pass id (summaryIntent.putExtra("SummTopicId", id);) of this row and "ask db" in next Activity for Topic with this id
EDIT:
protected void onCreate(Bundle savedInstanceState){
Intent i = getIntent();
String extraTopic = i.getStringExtra("SummTopic");
//or long extraTopic = i.getLongExtra("SummTopic"); if you put id there (which is better)
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
String[] args = new String[] { extraTopic };
//or String[] args = new String[] { Long.toString(extraTopic) }; with id version
Cursor singleRow = mydb.rawQuery("SELECT * FROM "+ TABLE + " WHERE topic=?" , args);
//args is better then escaping special chars in query
//and it should be single row so we've changed var name :)
if(singleRow.moveToFirst()){ //we should do moveToFirst before we can use Cursor
Integer cindex = allrows.getColumnIndex("topic");
Integer cindex1 = allrows.getColumnIndex("text1");
Integer cindex2 = allrows.getColumnIndex("text2");
//setup views and stuff ....
}else{
Toast.makeText(this, "Oops we did not find topic, detail activity was closed", Toast.LENGTH_SHORT).show();
finish();
}
}
After you have used setContentView(...) you need to reference your String and get the text such as...
EditText et = (EditText) findViewById(R.id.my_edit_text);
String theText = et.getText().toString();
To pass it to another Activity you use an Intent. Example...
Intent i = new Intent(this, MyNewActivity.class);
i.putExtra("text_label", theText);
startActivity(i);
In the new Activity (in onCreate()), you get the Intent and retrieve the String...
public class MyNewActivity extends Activity {
String uriString;
#Override
protected void onCreate(...) {
...
Intent i = getIntent();
uriString = i.getStringExtra("text_label");
}
}
EDITED :
to get String From Listview you can apply below code and get ITEM String and Pass it to Next Activity:
listContent.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String ITEM=listContent.getItemAtPosition(position);
//Intent summaryIntent = new Intent(DocumentListActivity.this, // ViewDocumentActivity.class);
// summaryIntent.putExtra("SummTopic", value);
}
});
You can use Intent for this.
Intent intent= new Intent(context,classname.class);
intent.putExtra("name",string);
You can get it in the target class name using intent.getextra().
I guess you are using an adapter to fill your list with some data. So you need to override getItem(int position) method in your adapter:
#Override
public Object getItem(int position) {
//Note that return type should be the same you you use to initilise items oof the adapter. E.g. String or some custom Topic class
Object someObject = mObjects[position];
return someObject;
}
Then you need to set an item click listener to you list
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Object someObject = adapterView.getItemAtPosition(i);
Intent i = new Intent(this, MyNewActivity.class);
i.putExtra("text_label", someObject.toString());
startActivity(i);
}
});

How to pass the name checked from checkbox to another activity

I am currently having a difficulty in passing the name from the checkbox from one activity to another activity. Actually the name should be inserted into my database table after it is checked and then it will be passed to the activity mentioned earlier. Anyone have any idea on doing it? Any help provided will be greatly appreciated.
For reference, the codes for my project.
BuddyDBAdapter buddyDB = new BuddyDBAdapter(this);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts_list);
ListView list = (ListView) findViewById(android.R.id.list);
//ListView list = getListView();
list.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id)
{
Cursor cursor = null;
cursor = (Cursor) parent.getItemAtPosition(position);
Intent intent = new Intent(ContactsList.this, Create_Events.class);
intent.putExtra("name", cursor.getString(cursor.getColumnIndex(buddyDB.KEY_NAME)));
startActivity(intent);
}
});
Uri allContacts = Uri.parse("content://contacts/people");
Cursor c = managedQuery(allContacts, null, null, null, null);
String[] columns = new String[] {ContactsContract.Contacts.DISPLAY_NAME};
int[] views = new int[] {R.id.contactCheckbox};
startManagingCursor(c);
SimpleCursorAdapter friendsAdapter = new SimpleCursorAdapter(this, R.layout.contacts_list, c, columns, views);
this.setListAdapter(friendsAdapter);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
buddyDB.open();
//long name_id;
super.onListItemClick(l, v, position, id);
Cursor c = ((SimpleCursorAdapter)l.getAdapter()).getCursor();
c.moveToPosition(position);
/*TextView contactName = (TextView) v.findViewById(R.id.contactName);
String NameValue = contactName.getText().toString();
name_id = buddyDB.insertNames(NameValue);
Toast.makeText(getBaseContext(),
"Selected: " + buddiesList[position], Toast.LENGTH_SHORT).show();
buddyDB.close();*/
nameCheck = (CheckBox) v.findViewById(R.id.contactCheckbox);
nameCheck.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked)
{
long name_id;
String NameValue = nameCheck.getText().toString();
name_id = buddyDB.insertNames(NameValue);
/*if(isChecked)
{
nameCheck = 1;
}else
{
nameCheck = 0;
}*/
}
});
buddyDB.close();
}
}
Again, any help from anyone will be greatly appreciated. Thanks a lot!
this may helps you
To pass the name values from oneActivity
Intent n = new Intent(actA.this , actB.class);
n.putExtra("name", NameValue);
startActivity(n);
To get the given values
Intent igetlist = getIntent();
String singleid = igetlist.getExtras().getString("name");
use this code where you want to pass parameter to another activity.
Intent n = new Intent(actA.this , actB.class);
n.putExtra("name", NameValue);
startActivity(n);

Categories

Resources