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?
Related
I wrote a code in which i can retrieve the data from the database but when i run it and try to search something. The application crashes as soon as i press Submit
public class search extends AppCompatActivity {
Button SearchButton;
EditText SearchText;
TextView SearchResult;
SQLiteDatabase db;
String builder;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
SearchButton=(Button)findViewById(R.id.searchbutton);
SearchText=(EditText)findViewById(R.id.Searchtext);
SearchResult=(TextView)findViewById(R.id.SearchCourse);
db=this.openOrCreateDatabase("Courses", Context.MODE_PRIVATE,null);
SearchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int GetID = Integer.valueOf(SearchText.getText().toString());
Cursor TuplePointer = db.rawQuery("Select from Course where ID="+GetID+"",null);
TuplePointer.moveToFirst();
String Course = TuplePointer.getString(TuplePointer.getColumnIndex("Course"));
SearchResult.setText(Course);
}
});
}
}
Replace this line
Cursor TuplePointer = db.rawQuery("Select from Course where ID=" + GetID + "", null);
with
Cursor TuplePointer = db.rawQuery("Select Course from Course where ID=" + GetID + "", null);
Where Course is your column name
Write your code within try catch first. Afterthat try to catch exact exception. you will be clear what are you doing wrong.
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS + " Where " + KEY_APP_BOOKINGID + " = " + id;
Cursor cursor = db.rawQuery(selectQuery, null);
Please Try this
SQLiteDatabase db = this.getReadableDatabase();
String GetID = SearchText.getText().toString();
Cursor cursor = db.rawQuery("SELECT * FROM Course WHERE ID = ?", new String[]{String.valueOf(GetID)}, null);
if (cursor.moveToFirst()) {
do {
String Course = cursor.getString(cursor.getColumnIndex("Course"));
SearchResult.setText(Course);
} while (cursor.moveToNext());
}
Thank You everyone I figured out what i was doing wrong on the get Column index i targeted course but what i didnt realize is that there was no such field as course :)
Keep practice like below code you will debug proper
public void getFirstName(String id) {
String sql = "select first_name from basic_info WHERE contact_id="+ id;
Cursor c = fetchData(sql);
if (c != null) {
while (c.moveToNext()) {
String FirstName = c.getString(c.getColumnIndex("first_name"));
Log.e("Result =>",FirstName);
}
c.close();
}
return data;
}
public Cursor fetchData(String sql) {
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery(sql, null);
}
I read out data from a database into a String. Now i want to put this String into a textview to show my data in list. I execute the read method and want to show the return string mit the data. Problem is: Android studio cannot resolve the "symbol" aka dbString.
Databasetostring:
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
//Every Column and row
String query = "SELECT * FROM " + TABLE_TODO + " WHERE 1";
//Cursor points to a location in your results
//First row point here, second row point here
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()){
//Extracts first name and adds to string
if(c.getString(c.getColumnIndex("firstName"))!=null){
dbString += c.getString(c.getColumnIndex("firstName"));
c.moveToNext();
/*
* Displaying all other columns
*/
}
}
db.close();
return dbString;
MainActivity:
Button refresh_list;
ToDoDB showDb;
TextView datalist;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datalist = (TextView)findViewById(R.id.showallData);
refresh_list = (Button)findViewById(R.id. refresh_list);
refresh_list.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View view) {
datalist.setText(dbString);
}
});
}
I have a column ShopName, and another column called LocationCode, if the LocationCode equals to "SKP", the corresponding ShopName will be added to an array, my question is, how can I do that?
I got something like this:
public List<String> getQuotes() {
String WhiteFarm = "WhiteFarm";
List<String> list = new ArrayList<>();
Cursor cursor = database.rawQuery("SELECT * FROM WhereToEat WHERE 'LocationCode' = " + WhiteFarm, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
return list;
}
And another class like this:
public class DatabaseGrabber extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.selection_main);
final TextView Shop_name = (TextView)findViewById(R.id.ShopName);
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(this);
databaseAccess.open();
final List<String> ShopName = databaseAccess.getQuotes();
databaseAccess.close();
Button StartDraw = (Button)findViewById(R.id.draw_start);
StartDraw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Collections.shuffle(ShopName);
String random = ShopName.get(0);
Shop_name.setText(random);
}
});
}
}
If your LocationCode contains a String (or TEXT for SQLite) type of data then your value should be enclosed in a single quote as shown in the code below:
Cursor cursor = database.rawQuery("SELECT * FROM WhereToEat WHERE LocationCode = " + "'" + WhiteFarm "'", null);
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");
I have class called unviersityClient and method name `getallstudent,but how to include them in cursor to get results displayed
this is in mainactivity
public class MainActivity extends ActionBarActivity {
private TextView tv;
private Button bt;
private Context mycontext;
Cursor c;
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.textView1);
bt=(Button)findViewById(R.id.button1);
mycontext=this.getApplication();
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// universityClient.addStudents(mycontext, "christy");
// universityClient.addStudents(mycontext, "joe");
universityClient.getAllStudents(mycontext);
c.moveToFirst();
while(!c.isAfterLast()){
String dir =c.getString(c.getColumnIndex("name"));
tv.setText("Name : "+dir);
c.moveToNext();
}
and this is in .java created by json. it's already created the db
public static Cursor getAllStudents(Context c) {
ContentResolver cr = c.getContentResolver();
String[] result_columns = new String[]{
universityDB.STUDENTS__ID_COLUMN,
universityDB.STUDENTS_NAME_COLUMN,
};
String where = null;
String whereArgs[] = null;
String order = null;
Cursor resultCursor = cr.query(university.STUDENTS_URI, result_columns, where, whereArgs, order);
return resultCursor;
}
if you have all the students in a database you can use this to get all the names and then send them to a variable
String SELECT_QUERY = "SELECT * FROM Tutores t1 INNER JOIN Tutorados t2 ON t1._id = t2.id_tutor and t1._id = " + ET1.getText().toString().trim();
cursor = db.rawQuery(SELECT_QUERY, null);
if (cursor.getCount() != 0) {
if (cursor.moveToFirst()) {
do {
C1 = cursor.getString(cursor
.getColumnIndex("_id"));
C2 = cursor.getString(cursor
.getColumnIndex("name"));
Fin += C1 + "-" + C2 + "\n";
} while (cursor.moveToNext());
}
}
cursor.close();
Fin is a String and you can get all the names or whatever you want from the columns with the getColumnIndex("nameOfTheColumn") and send "Fin" to a textview or something like that
hope that helps!, see ya
Cant understand why you want to put json data in cursor while json parsing is the best way to do the same. If your priority is to bring data somewhere else and fetch one by one using loop, you can use arraylist/hashmap like collection objects. If you have many fields in one json object, you can create a class having those fields and make an arraylist of that having type of class and store data in that. Like this:
1. Fetch single json object at a time, fetch values of fields.
2. create class object by passing those values in constructor.
3. Create arraylist of that class type.
4. put class objects in that arraylist one by one and fetch as well.
ArrayList<Person> person = new ArrayList<Person>();
Person newPerson = new Person("balvier", "27", "Male");
person.add(newPerson);
Person newPersonAnother = new Person("Adel", "20", "FeMale");
person.add(newPersonAnother);