I want to show an item from editext to spinner and save to db... how to store item in the db...
my code :
spinner populating
final DBAdapter db = new DBAdapter(this);
db.open();
Spinner spin = (Spinner) findViewById(R.id.spinner1);
AdapterCountries = new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_item);
AdapterCountries.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(AdapterCountries);
Cursor cursor = db.getAllTitles1();
while (cursor.moveToNext()){
results=cursor.getString(2);
AdapterCountries.add(results);
}
db.close();
and
Button d_ok=(Button)dialog.findViewById(R.id.d_ok);
final EditText filename=(EditText)dialog.findViewById(R.id.filename);
d_ok.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
//
}});
any one can help me with example
Thank you...
If you don't have one already, then I really think you should have a SQL helper class extending the given SQLiteOpenHelper Android class. It really simplifies DB operations. See: http://developer.android.com/guide/topics/data/data-storage.html#db
It's heavily recommended.
If you set up the helper class and the instance of that class is set up like SQLHelper sql = new SQLHelper(this); then modifying the database is fairly simple. You should set up a method that you call from your buttons onClickListener (and possibly run it in an AsyncTask or a background thread):
private void addFileName(final String filename) {
SQLiteDatabase db = sql.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(yourKeyHere, filename);
db.insert(yourDBNameHere, null, values);
}
And then call the method and add it to your adapter from the listener:
d_ok.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
addFileName(filename.getText().toString();
AdapterCountries.add(filename);
}
});
Related
updated my code. My issue happens when i back out of the activity. Listview items are lost. I checked the Sqlite database and all items are saved, just not showing up again on listView when I reStart-Activity.
MainActivity
private ListView lst;
private CustomeAdapter cv;
private EditText nameEd, middleEd, lastEd;
private ArrayList<People> peopleArrayList;
private DataHelper myData;
peopleArrayList = new ArrayList<>();
OnCreate.....
public void addPerosn(View view) {
String myName = nameed.getText().toString();
String myMiddle = middleed.getText().toString();
String myLast = lasted.getText().toString();
boolean insert = myData.addData(myName, myMiddle, myLast);
if (insert == true) {
peopleArrayList.add(new People(myName, myMiddle, myLast));
cv = new CustomeAdapter(this, peopleArrayList);
lst.setAdapter(cv);
nameed.setText("");
middleed.setText("");
lasted.setText("");
} else {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
}
}
My DataHelper method i want to call to Show All
public Cursor showData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return data;
}
Any suggestions are appreciated . Thanks
Make sure you have overridden getCount and it returns proper count.
#Override
public int getCount() {
return items.length;
}
Apart from above solution, I would recomment you to do it in proper way
a) Create a model/pojo class say Person which will have firstName,lastName and middleName
b) create a data set of Person, i.e list of person
c) create a method addPerson in adapter class, and call whenever you want to add new Person data into the list. addPerson method will also refresh the adapter by calling notifyDataSetChanged
d) In activity create adapter object only once, later on just use method of it say adapter.addPerson(person)
I have a cursor that filled my database and i would like to delete the elements from this table.
her is the removal code fro my database:
public void deleteItem(int id){
SQLiteDatabase database = this.getWritableDatabase();
database.delete(ContractParaGastos.GASTO, ContractParaGastos.Columnas.MONTO + " = ?", new String[]{String.valueOf(id)});
database.close();
}
And here is the removal code in recyclerviewAdapter:
viewHolder.button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
databaseHelper.deleteItem(i);
}
});
}
I add this line in my adapter:
databaseHelper = new DatabaseHelper(context, ContractParaGastos.GASTO, null, 4);
But when i click on the delete button nothing happens. the line is still present in my recyclerview.
Help me please!
Because you didn't initialised the databaseHelper.
Try this code:
DatabaseHelper databaseHelper = new DatabaseHelper(this); //in case of activity.
DatabaseHelper databaseHelper = new DatabaseHelper(getActivity()); //in case of Fragment.
Paste this code in onCreate() of Activity or onCreateView() of Fragment.
Thanks and let me know if some need to know more.
from the little code you provided I would check that the variable i in:
databaseHelper.deleteItem(i);
represents really an existing id of the record I need to delete.
While inserting my listview gets refreshed automatically but not update when the item in the listview is updated. It only updates on database. I can see the listview is updated when I close the application and open again, or come back from previous activity.
I found some discussion related to my problem. Like: Refresh ListView with ArrayAdapter after editing an Item . Her I found that make a new method to populate the Listview and call it in the onResume method of your activity.
And the problem has been solved using this. But I do not get how to make new method mentioned like there. Could anybody help me to make it understandable?
My code in activity class:
personNamesListView = (ListView) findViewById(R.id.traineeslist);
traineeListAdapter = new ArrayAdapter<Trainee>(this,
android.R.layout.simple_list_item_1,
currentTraining.getTraineeArrayList());
personNamesListView.setAdapter(traineeListAdapter);
protected void onResume() {
super.onResume();
}
And this way I populated my personNamesListView using method stringToString() in model class;
public void loadTraineeList() {
DatabaseHelper db = DatabaseHelper.getInstance();
this.traineeArrayList = new ArrayList <Trainee>();
Cursor cursor = db.select("SELECT * FROM person p JOIN attendance a ON p._id = a.person_id WHERE training_id="+Integer.toString(this.getId())+";");
while (cursor.moveToNext()) {
Trainee trainee = new Trainee();
trainee.setID(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.PERSON_ID)));
trainee.setFirstname(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_FIRSTNAME)));
trainee.setLastname(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_LASTNAME)));
trainee.setJobTitle(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_JOBTITLE)));
trainee.setEmail(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_EMAIL)));
trainee.setCompany(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_COMPANY)));
trainee.setDepartment(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_DEPARTMENT)));
trainee.setBadgeNumber(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_BADGE)));
// Pass to the arraylist
this.traineeArrayList.add(trainee);
}
}
public ArrayList<Trainee> getTraineeArrayList() {
return traineeArrayList;
}
public void setTraineeArrayList(ArrayList<Trainee> traineeArrayList) {
this.traineeArrayList = traineeArrayList;
}
I insert and Update data into database into one method:
public void storeToDB() {
DatabaseHelper db = DatabaseHelper.getInstance();
db.getWritableDatabase();
if (this.id == -1) {
// Person not yet stored into Db => SQL INSERT
// ContentValues class is used to store a set of values that the
// ContentResolver can process.
ContentValues contentValues = new ContentValues();
// Get values from the Person class and passing them to the
// ContentValues class
contentValues.put(DatabaseHelper.PERSON_FIRSTNAME, this
.getFirstname().trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_LASTNAME, this
.getLastname().trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_JOBTITLE, this
.getJobTitle().trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_EMAIL, this.getEmail());
contentValues.put(DatabaseHelper.PERSON_COMPANY, this.getCompany()
.trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_DEPARTMENT, this
.getDepartment().trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_BADGE, this
.getBadgeNumber().trim().toUpperCase());
// here we insert the data we have put in values
this.setID((int) db.insert(DatabaseHelper.TABLE_PERSON,
contentValues));
} else {
// Person already existing into Db => SQL UPDATE
ContentValues updateTrainee = new ContentValues();
updateTrainee.put(DatabaseHelper.PERSON_FIRSTNAME, this
.getFirstname().trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_LASTNAME, this
.getLastname().trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_JOBTITLE, this
.getJobTitle().trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_EMAIL, this.getEmail());
updateTrainee.put(DatabaseHelper.PERSON_COMPANY, this.getCompany()
.trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_DEPARTMENT, this
.getDepartment().trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_BADGE, this
.getBadgeNumber().trim().toUpperCase());
db.update(DatabaseHelper.TABLE_PERSON, updateTrainee,
DatabaseHelper.PERSON_ID+"= ?", new String[]{Integer.toString(this.getId())});
System.out.println("Data updated");
}
}
You should call traineeListAdapter.notifyDataSetChanged() whenever you update your ArrayList representing the items in the ListView.
There's a similar question here that can give you some help.
Although I've accomplished something similar using
yourlistview.invalidateViews()
after changing the data to show in the listview
when notifyDataSetChanged() didn't work.
EDIT:
After making all the operations in the data that I want to show i just set the adapter and try to refresh my listview by calling invalidateViews().
selectedStrings = new ArrayList<String>(typeFilterStrings);
adapter.setArrayResultados(selectedStrings);
listTypeFilter.invalidateViews();
It's not obligatory to set the adapter again in my case worked.
use like this:
Create an instance of your custom adapter, so you can use it anywhere you like...
public class ScoreList extends SherlockFragmentActivity {
private ListView listViewScore;
private ScoreListAdapter adapter;
static List<Score> listScore = new ArrayList<Score>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.score_list);
ctx = this;
listScore = dbh.getAllScores();
listViewScore = (ListView) findViewById(R.id.score_list);
adapter = new ScoreListAdapter(ctx, R.layout.score_row_item, listScore);
listViewScore.setAdapter(adapter);
((BaseAdapter) listViewScore.getAdapter()).notifyDataSetChanged();
}
}
By the way, if your listScore array is already loaded, then you do not need to use
adapter.notifyDatasetChanged();
when button is pressed i want to the text to change to the database collumn values, i know its wrong but here is the code:
private void MostraDados() {
// TODO Auto-generated method stub
final TextView text = (TextView) findViewById(R.id.tvUSUARIO);
Button mostrar = (Button) findViewById(R.id.bMostrar);
mostrar.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
db = openOrCreateDatabase("dbtest.db", Context.MODE_PRIVATE, null);
String q = "SELECT * FROM dbtest.db WHERE usuarioorigem='";
text.setText(q);
//text.execSQL("DROP COLUMN IF EXISTS usuarioorigem");
}
});
}
Your code is missing some critical parts for example a DatabaseClass that manages the cursor and database.
private void MostraDados() {
final TextView text = (TextView) findViewById(R.id.tvUSUARIO);
Button mostrar = (Button) findViewById(R.id.bMostrar);
mostrar.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// our missing a database helper
MyDatabaseClass dbhelper = new MyDatabaseClass();
dbhelper.open();
Cursor result = dbhelper.doMyQuery();
String mystring = result.getString(0);
text.setText(mystring);
dbhelper.close();
}
});
....
public class WorkoutDbAdapter {
....
public Cursor doMyQuery()
{
return this.mDb.query( yourQuery );
}
}
This is the minimum you'd need and even with the above i'm missing a lot of the smaller detail. Search for some tutorials on creating and using Databases.
Essentially however you need to get the cursor back, set the position of the cursor, or cursor.moveNext() and then get the value that you can assign to the textField.
Your source code lacks a correct call to a database and access to the cursor. Hopefully you'll find some decent tutorials that will flesh the rest out for you.
The SQL is not written correctly. You must SELECT from a column. And you're passing the query string the the text view. You should first review how to query the database with the cursor, and how to retrieve what you want from the cursor.
So I would look into how to use the curosr, all of that's available in the Android docs, and you might want to try the API demos in the emulator I'm sure you can learn how to work with the cursor there as well. So look here, http://developer.android.com/reference/android/database/Cursor.html.
And here, Is Android Cursor.moveToNext() Documentation Correct?.
After getting the cursor, you could do something like this:
while(c.moveToNext(){
text.setText(c.getString(0))
}
I am basically trying to get information from an sqlite db in another class. I've done this without any problems inside the onCreate method, but when I try to use it inside an onClickListener which is inside that onCreate I cannot find the right context to use. My code is as follows:
private AutoCompleteTextView search;
private Button showInfoButton;
private TextView courseInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_courses);
final Context baseContext = getBaseContext();
courseInfo = (TextView) this.findViewById(R.id.text);
DataBase db = new DataBase(this.getApplicationContext());
db.openDataBase();
final ArrayList<String> aCourses = db.getCoursesArr();
db.close();
search = (AutoCompleteTextView) findViewById(R.id.autocomplete_course);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_courses, aCourses);
search.setAdapter(adapter);
showInfoButton = (Button) this.findViewById(R.id.show_info_button);
showInfoButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (aCourses.toString().contains(search.getText()) == false ) {
courseInfo.setText("Please select a course from the drop-down menu and click on the \"Show course information\" button");
}
else{
String selectedCourse = search.toString();
DataBase db1 = new DataBase(baseContext);
db1.openDataBase();
ArrayList<String> courseAttributes = db1.getCourseAttributes();
ArrayList<String> attributeValues = db1.getAttributeValues(selectedCourse);
db1.close();
String courseInformation = "";
for (int i=0; i < courseAttributes.size(); i++){
courseInformation = courseInformation + courseAttributes.get(i) + ": " + attributeValues.get(i) + System.getProperty("line.separator");
}
courseInfo.setText(courseInformation);
}
}
});
}
the problem comes with
DataBase db1 = new DataBase(baseContext);
I've tried changing it to
DataBase db = new DataBase(this.getApplicationContext());
and
DataBase db = new DataBase(null);
and every way I try it, the program does run, but when it get's in the else case it throws an error and shuts down. Could anyone tell me what context should I use in order to make it run?
As you may need the database connection more than once, I recommend to open and close the database connection in your own application class which extends Application.
There you have onCreate and onDestroy methods where you can open and close the database (because it has a context). If you make the database object as a class variable (public static) you should be able to use this like MyApplication.mDatabase.