how to Display the particular field details in editext by giving id here i write code in database handler but i dont know what to do in MainActivity
i have fields when i gave id and click show button the details in database for that particular id want to be load in edittext
My database Handler class
Try this.
set editText as number only
android:inputType="number|numberDecimal"
public void show()
{
bshow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(uid.getText().toString().equals(""))
return;
int id = Integer.parseInt(uid.getText().toString());
Cursor res=myDB.getData(id);//i got an error Here and i dont know what to do
String NAME = res.getString(res.getColumnIndex("NAME"));
String SURNAME = res.getString(res.getColumnIndex("SURNAME"));
String MARKS = res.getString(res.getColumnIndex("MARKS"));
editname.setText(NAME);
editsurname.setText(SURNAME);
editmark.setText(MARKS);
}
});
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from student_details where id="+id+"", null );
if(res != null && res.moveToFirst()) {
return res;
}
return res;
}
In your activity initialize your Db class.
Now you can get value like below code ; -
Cursor mCur = myDb.getData(some integer value);
Now you can fetch value from cursor by ;-
mCur .getString(mCur .getColumnIndex("column name");
Related
I am facing a problem in displaying a data from SQLite database to a textview. The column of the data that I want is in column 13 and the table only have 1 row of data.
I have try for few hours but still cannot retrieve the data into the textview.
Problem: The textview is not showing the data from the table in SQLite database.
In my DatabaseHelper, I have created a cursor to get the data:
public Cursor getNameData() {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return cursor;
}
Activity file:
public class showName extends AppCompatActivity {
TextView name;
DatabaseHelper userDb = new DatabaseHelper(this);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showcvv);
getSupportActionBar().hide();
name = findViewById(R.id.userName);
Cursor cursor = userDb.getNameData();
if (cursor.getCount() == 0) {
Toast.makeText(showName.this, "No data generate", Toast.LENGTH_SHORT).show();
return;
}
if (cursor.moveToFirst()) {
do {
String username = cursor.getString(12);
name.setText(username);
} while (cursor.moveToNext());
}
}
Is there any error for the code? Any suggestion to improve this code?
i want to retrieve id from database where name = saqib into the EditText(textbox) in android, i have tried different ways but can't achieve my desired output instead of that the given output will be shown every time. output
onButtonClick:
final EditText i=(EditText)findViewById(R.id.id_etxt);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res= mydatabase.fet();
i.setText(res.toString());
}
});
Database.java class
public Cursor fet(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res=db.rawQuery("select ID from record where Name=?",new String[] {"saqib"});
return res;
}
Cursor res = mydatabase.fet();
if (res.getCount() > 0) {
res.moveToFirst();
i.setText(res.getString(0));
} else {
throw new SQLiteException("e");
}
Currently you set the whole Cursor as String in EditText, which is not right way to set ID.
You have to extract the ID from Cursor like below to use it in EditText:
public void onClick(View v) {
Cursor res = mydatabase.fet();
if(res != null && res.moveToFirst()) {
String id = Integer.toString(res.getInt(res.getColumnIndex("ID")));
i.setText(id);
}
}
I want to display only one record from the database in listview. (ENTERED PASSWORD RECORD FROM LOGIN).
DATABASE FILE CODE [DatabaseHelper.java]
public static final String TABLE_NAME = "Master";
public static final String ColumnID = "user_id";
public static final String Column_2 = "f_name";
public static final String Column_3 = "l_name";
public static final String Column_4 = "password";
SELECT RECORD CODE IN DATABASE FILE
public Cursor SelectRecord(String pass) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c=db.rawQuery("SELECT * FROM TABLE_NAME WHERE password = ?",new String[]{pass});
if (c != null)
c.moveToFirst();
return c;
}
JAVA FILE CODE (CODE TO BE EXECUTED) [Edit.java]
final DatabaseHelper db=new DatabaseHelper(getApplicationContext());
Cursor c =db.SelectRecord(t1.setText(getIntent().getStringExtra("text")));
String[] from={"_id","f_name","l_name","password"};
int[] to={R.id.textView1,R.id.textView2,R.id.textView3,R.id.textView4};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(Edit.this,R.layout.list_data,c,from,to);
//ListView lv=(ListView)findViewById(R.id.listview1);
// lv.setAdapter(adapter);
LOG IN FILE CODE [LogIn.java]
if (database.checkdata(e1.getText().toString().trim()))
{
Intent i=new Intent(Login.this,Edit.class);
i.putExtra("text",e1.getText().toString());
startActivity(i);
Toast.makeText(getApplicationContext(), "Login Successfully Done", Toast.LENGTH_LONG).show();
e1.getText().clear();
}
I want to get Only one record in listview which password I entered while login.
Edit
Now this code is correct
Cursor c =db.SelectRecord(getIntent().getStringExtra("text"));
If you want to get only one record based on the password, you need to pass a parameter to SelectRecord method.
Assume one of the user password is "pass"
Cursor c = db.SelectRecord("pass");
Select record code
public Cursor SelectRecord(String pass) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM YOUR_TABLE_NAME
WHERE password = ? LIMIT 1", new String[]{pass});
if (cursor != null)
cursor.moveToFirst();
return cursor;
}
Edit
From our conversation:
The Error is in the cursor line : Cursor c =
db.SelectRecord(t1.setText(getIntent().getStringExtra("text")));
The error says SelectRecord (Java.lang.String) in DatabaseHelper
cannot be applied to (void)
The error is in this line
Cursor c =db.SelectRecord(t1.setText(getIntent().getStringExtra("text")));
You need to pass key "text" from Log In to Java File code, so modify this line to
Cursor c =db.SelectRecord(getIntent().getStringExtra("text"));
No need to have setText.
So, in my app you have to add eletrical equipment to every room in the house so it can measure how much energy you spend and etc.
What I want is when I click the button to remove a specific equipment, that equipment will be deleted from the database where it was stored, and this would be with only the name of the equipment as entry.
I have a code but when I hit the remove button the app kinda crashes and goes back to the home activity.
Can someone help pls?
That's the button:
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
button2.setVisibility(View.GONE);
tableLayout1.setVisibility(View.GONE);
imageView1.setVisibility(View.GONE);
textView12.setVisibility(View.GONE);
DatabaseOperations DOP;
String equipamento;
equipamento = textView12.getText().toString();
DOP = new DatabaseOperations(CTX);
Cursor CR = DOP.getUserInfo(DOP, equipamento);
CR.moveToFirst();
DOP.deleteEquip(DOP, equipamento);
Toast.makeText(getBaseContext(),"O equipamento foi removido com sucesso.", Toast.LENGTH_LONG).show();
}
});
And this is the class:
public Cursor getUserInfo (DatabaseOperations DOP, String equipamento){
SQLiteDatabase SQ = DOP.getReadableDatabase();
String selection = TableData.TableInfo.EQUIPAMENTO +" LIKE ?";
String coloumns[] = {TableData.TableInfo.POTENCIA, TableData.TableInfo.QUANT, TableData.TableInfo.HORAS, TableData.TableInfo.SIMULT};
String args [] = {equipamento};
Cursor CR = SQ.query(TableData.TableInfo.TABLE_NAME, coloumns, selection, args, null, null, null);
return CR;
}
public void deleteEquip(DatabaseOperations DOP, String equipamento){
String selection = TableData.TableInfo.EQUIPAMENTO;
String args[] = {equipamento};
SQLiteDatabase SQ = DOP.getWritableDatabase();
SQ.delete(TableData.TableInfo.TABLE_NAME, selection, args);
}
#EngWatt this code is in the DBHelper Class you will need to change the rowid to reflect the name of the item you want to delete. I assume that is equipamento
We hope you have a MVP design to make all this easy
/* Delete a record from database table named "TABLE_INFO" */
/* based on the selected records id in Col_ID*/
public void deleteDBRow(String rowid){
db = this.getWritableDatabase();
db.delete(TABLE_INFO, Col_ID + " = ?", new String[] { rowid });
db.close();
return;
}
I am creating app in which i register user and store user's information in database,so i have created database and storing value in databse but i don't know how to fetch data from database and show in textview?Using below query to fetch data but it has error.What is correct way?
public void insertEntry(String fname, String lname, String gen,String weight)
{
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("firstname", fname);
values.put("lastname", lname);
values.put("gender", gen);
values.put("weight",weight);
}
public Cursor fetchData()
{
SQLiteDatabase mDB = dbHelper.getWritableDatabase();
return mDB.rawQuery("SELECT * FROM Register WHERE firstname=? lastname =?" , null);
}
Using this to set fetched value on textview in different activity
Cursor name = sqliteDataBase.fetchData();
tv_name.setText((CharSequence) name);
Try this,
try {
SQLiteDatabase mDB = dbHelper.getReadableDatabase();
String selectQuery = "SELECT * FROM Register WHERE firstname= "+first+" lastname =" + last + ";";
cursor = db.rawQuery(selectQuery, null);
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
String firstName = cursor.getString(cursor.getColumnIndex("firstname")));
}
}
} catch(Exception e) {
e.printSTackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
public String fecthResults()
{
String name = null;
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
Cursor cursor = sqLiteDatabase.query(TABLE_NAME, null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
name = cursor.getString(cursor.getColumnIndex("firstname")
} while (cursor.moveToNext());
cursor.close();
}
sqLiteDatabase.close();
return name;
Get the name and then set it directly to a texView
A Cursor is an interface that provides random read-write access to the result set returned by the query. It contains multiple rows of data and this data can be easily processed by help of For loop.
Lets take an example to understand the process. Suppose, you need to access data from a column name "col_1" and show the data in TextView. The For loop for the process will be as follows.
for (cursor.moveToNext()) {
textView.setText(cursor.getString(cursor.getColumnIndex("col_1")));
}
Now, if we need only one value (from only one record or tuple) then, we can opt out the For loop and change the code as shown below.
if (cursor.moveToFirst()) {
textView.setText(cursor.getString(cursor.getColumnIndex("col_1")));
}
Always remember to close the cursor after using it.
To close the cursor, use the following line of code.
cursor.close();
For more information, please visit the following links:
https://developer.android.com/reference/android/database/Cursor.html
https://developer.android.com/training/basics/data-storage/databases.html#ReadDbRow