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))
}
Related
I hope straightforward questions.
1) I managed to get the data from Sqlite db and showing them on recyclerview. The question is for example when i click on the recyclerview items and do some operations (for example copying the content or updating) is it better to use an arraylist and get the data first when application loads then do the operations on this arraylist elements (then notifying db eventually)?
2) If there is no need for extra arraylist on onContextItemSelected() operations while clicking recyclerview item again, i ve some trouble in choosing the element and its values.
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.idshare :
//implicit intent
shareImplicitIntent();
return true;
......
for the shareImplicitIntent() method
private void shareImplicitIntent() {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
Cursor cursor=WordListOpenHelper.mReadableDB.rawQuery("SELECT * FROM
diary", null);
cursor.moveToPosition(XYZ);
Entry_Model entry_model= new Entry_Model();
entry_model.setmEntry(cursor.getString(cursor.getColumnIndex(WordListOpenHelper.KEY_ENTRY)));
String title = entry_model.getmEntry(); ......
basically using cursor and getting the title of the cursor at XYZ position.
But how can I choose that XYZ position ?
Working hours on it but couldnt find a clue. Please help me.Thanks a lot
To answer my question myself, shortly no, for example for getting input from the user and putting them in the arraylist then doing the database operations on the arraylist not very useful nor necessary. (Yet if your database is planned to hold only small amount of entries though you can use arraylist/linkedlists for fast CRUD manipulations on the recyclerview adapter).
For the second part of the question it s easy to copy the content of the clicked recyclerview element by creating setonclicklistener in the viewholder constructor of the viewholder innerclass, for example;
(note unlike in the example you dont have to use contentresolver if you dont plan to share the datas in the database with other applications)
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
int pos =getAdapterPosition();
String entry = "";
String[] mProjection =
{ Contract.WordList.KEY_ENTRY, // Contract class constant for the _ID column name };
Cursor cursor = mContext.getContentResolver().query(Uri.parse(
queryUri), mProjection, null, null, sortOrder);
if (cursor != null) {
if (cursor.moveToPosition(pos)) {
int indexEntry = cursor.getColumnIndex(Contract.WordList.KEY_ENTRY);
entry = cursor.getString(indexEntry);
}
}
Toast.makeText(v.getContext(), "copied entry is " + entry, Toast.LENGTH_LONG).show();
return false;
}
});
I have a table, c_question in which I stored some questions with this structure
autoincrement column _id,
question,
option1,
option2,
option3,
correct_answer
Now I want to retrieve the question in a TextView and the answers in a RadioGroup.
If the user selects the correct answer, then the question and options will change
in the same page.
Logcat: fatal exception at main ..... cursorIndexOutOfBoundException
The output shows the last data (question with answers) I entered in the db and if I click any answer, the app crashes.
String row="SELECT* FROM c_question";
final Cursor c=db.rawQuery(row, null);
c.moveToFirst();
if(c.moveToFirst())
{
do
{
tv1.setText(c.getString(1));
r0=(RadioButton)findViewById(R.id.radio0);
r0.setText(c.getString(2));
r1=(RadioButton)findViewById(R.id.radio1);
r1.setText(c.getString(3));
r2=(RadioButton)findViewById(R.id.radio2);
r2.setText(c.getString(4));
k.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int idd=r.getCheckedRadioButtonId();
r0=(RadioButton)findViewById(idd);
String r=r0.getText().toString();
if(r.equals(c.getString(5)))
{
Toast.makeText(QuestionsOn.this, "correct!!!", 123).show();
;
} else
Toast.makeText(QuestionsOn.this, "Incorrect!!!", 123).show();
}
});
} while(c.moveToNext());
}
Output showing the last data(Question with options) I entered in DB
That's what you get when you update the save views in a loop; only the last "row" will get shown.
If you want to show a list of data from the database, you need some Adapter class in a ListView / ViewPager
and if I click any option, the app crashes...
According to the error, c.getString(5) doesn't exist, so seems like you didn't create your database with the correct number of columns.
I have a ADD TO CART Button to add the products to cart and in database.I would like to show the same button as ALREADY IN CART if the product is already in cart.I tried using if else,but it is not working.It does n't crash VM.But no effect on clicking.
My Code
add2cart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String nm=name.getText().toString();
String rate=price.getText().toString();
mydb=Product_Details.this.openOrCreateDatabase("addcart", MODE_PRIVATE, null);
Cursor cur=mydb.rawQuery("select * from add2cart where pnme='"+nm+"'",null);
while (cur.moveToNext())
{
String name=cur.getString(cur.getColumnIndex("pnme"));
if (nm.equals(name))
{
add2cart.setText("Already in Cart");
}
else {
mydb.execSQL("INSERT INTO add2cart (pnme,prate)VALUES('"+nm+"','"+prprice+"')");
Toast.makeText(getApplicationContext(),"add to cart",Toast.LENGTH_SHORT).show();
Intent in=new Intent(Product_Details.this,add2cart.class);
startActivity(in);
} }
}
});
Perhaps you should try to rename one of your "name" variables. You could use this.name to specify which one you are referring to but I don't see the need to do that. The problem in fact might be that when you do if(nm.equals(name)) you are referring to the global variable name and not the one you set in the previous line. Hope I could help
I am trying to update my database. It is not really updating. I think it is due to my update command
my main activity is a listview activity. I have a button on the action bar that basically starts a new activity with two editboxes. So once I click that button, I create a new database item. It is originally set to two empty strings. On my second activity, I have a save button that is supposed to save my changes into the textboxes
so after my main activity takes me to my second activity, the code is as follows
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
// if new then create new db, else retrieve old database, right now
// assume everything is new
db = new DBHandler(this);
nowAdd = new UENote("", "");
db.addNote(nowAdd);
}
i update my nowAdd contact strings through this function
public void updateColumnData() {
// gets the strings from edittext
EditText textTitle = (EditText) findViewById(R.id.editText1);
EditText textSubject = (EditText) findViewById(R.id.editText2);
// converts the string
String titleString = textTitle.getText().toString();
String subjectString = textSubject.getText().toString();
nowAdd.setSubject(subjectString);
nowAdd.setTitle(titleString);
db.updateNote(nowAdd);
}
the update note function is as follows
public int updateNote(UENote note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, note.getTitle());
values.put(KEY_SUBJECT, note.getSubject());
// updating row
return db.update(TABLE1, values, KEY_ID + " = ? ",
new String[] { String.valueOf(note.getID()) });
}
Make sure that the id you are passing in the db.update() is really the same one that you want to update. From the code snippet, it's not obvious how you are getting the value of note.getID(). Are you making query for empty record to get the id?
Assuming that KEY_ID is an auto incremented primary key, I would then debug getID() to check if it returns the same id of the record you wanted to update.
In my activity I need to call to query different databases depending on which one the user chooses. Instead of calling each one individually I would like to have one code for a query and simply change the intent or class of the database from a string value. Basically I need to change my database name reference from my class "EmployeeDatabase" to whatever database the user currently has selected. I need to set the selected string x as class y and then have class y able to query. I'm trying to explain to the best of my knowledge, sorry if it is confusing. Thank you for your help!
Somehow I need to be able to set variable y as whichever class the user chooses and then be able to query like: c=db.query(y.EMP_TABLE4, null,null,null,null,null,null); It says EMP_TABLE4 cannot be resolved or is not a field.
How my database works right now with only one database option:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.redlight2);
EmployeeDatabase db=null;
try{
ListContent = (ListView)findViewById(R.id.listView1);
db=new EmployeeDatabase(this);
c=db.query(EmployeeDatabase.EMP_TABLE4, null,
null,null,null,null,null);
mydisplayadapter4 adapter = new mydisplayadapter4(this, c);
ListContent.setAdapter(adapter);
}
catch(Exception e){System.out.println("problem");}
How I want it to work:
String x;
Class<?> y;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.redlight2);
String x = "my database class name";
try {
y = Class.forName(x);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// I want to replace everything that says EmployeeDatabase with y
EmployeeDatabase db=null;
try{
ListContent = (ListView)findViewById(R.id.listView1);
db=new EmployeeDatabase(this);
c=db.query(EmployeeDatabase.EMP_TABLE4, null,
null,null,null,null,null);
mydisplayadapter4 adapter = new mydisplayadapter4(this, c);// OWN ADAPTER
ListContent.setAdapter(adapter);
If you want to access various databases with all having the same schema ( from your code it seems like it is), then it should be very simple.
Make a derived class from SQLiteOpenHelper.
When you create this object, pass the database name. The other parts of the application do not need to know what database it is using.
Also make sure to make this class a singleton. So you can switch to other database easily by closing the currently used one and then opening the new one.
When you will be calling getWritableDatabase() for database operations from any place, it will return the correct db handle.