Getting db string in textview - android

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);
}
});
}

Related

how to retrieve a selected data from sqlite and display in textview?

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?

Retrieving specific data based on ID from SQLite in ANDROID

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);
}

SQLiteLog no such table in android using Sqllite Database

By using assets folder, we are reading data i.e,address details based on search keyword:
Here is my code
private SQLiteDatabase db;
private Cursor c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_search = (EditText) findViewById(R.id.et_search);
img = (ImageView) findViewById(R.id.img_search);
list = (ListView) findViewById(R.id.list_search);
db = openOrCreateDatabase("sample", Context.MODE_PRIVATE, null);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
search_keyword = et_search.getText().toString();
arr_data = new ArrayList<ListItems>();
if (isValid()) {
SELECT_SQL = "SELECT ROWID AS _id,* FROM Addresses where Type LIKE '%" + search_keyword + "%'";
Log.d("daatt",SELECT_SQL);
try {
c = db.rawQuery(SELECT_SQL, null);
c.moveToFirst();
showRecords();
} catch (SQLiteException e) {
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
}
}
}
});
}
private void showRecords() {
String ugName = c.getString(c.getColumnIndex("Name"));
String ugaddress = c.getString(c.getColumnIndex("Address"));
String ugtype = c.getString(c.getColumnIndex("Type"));
ListItems items = new ListItems();
// Finish reading one raw, now we have to pass them to the POJO
items.setName(ugName);
items.setAddress(ugaddress);
items.setType(ugtype);
// Lets pass that POJO to our ArrayList which contains undergraduates as type
arr_data.add(items);
}
ListDataAdapter adapter = new ListDataAdapter(arr_data);
list.setAdapter(adapter);
if (c != null && !c.isClosed()) {
int count = c.getCount();
c.close();
}
Log.d("ListData", "" + arr_data);
}
private boolean isValid() {
if (search_keyword.length() == 0) {
Toast.makeText(getApplicationContext(), "please enter valid key word", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
For 1st build we got successful data loaded using list adapter
But after clean project, & Rebuild project showing a no such table expection
Please guide us wr we r going wrong
Advance Thanks
As far as I can see from your print, the table you're referring to is called ListOfAddress, ain't it? your SQL is:
SELECT_SQL = "SELECT ROWID AS _id,* FROM Addresses where Type LIKE '%" + search_keyword + "%'";
I might be wrong, but I would double check the query.

Android SQLite get value from column

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);

Android-Null pointer Exception in setText

I have a SQLite database to store items in cart. I need to get the count of products in cart corresponding to each user and set it to a textview,each time the user clicks addtocart button.But my code throws an null point exception.please help me.
I am getting nullpointer Exception in line 109: if (!crtno.getText().toString().equals(""))
code
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.product_dtls);
crtno=(TextView)findViewById(R.id.crtno);
imgbtn=(ImageButton)findViewById(R.id.cartimg);
add2cart=(Button)findViewById(R.id.add2cart);
DataBaseHandler dbh = new DataBaseHandler(this);
SQLiteDatabase db = dbh.getWritableDatabase();
Intent in = getIntent();
Bundle bn = in.getExtras();
Bundle bun=in.getExtras();
final String dtl=bun.getString("key");
nme = bn.getString("name");
Cursor cr = db.rawQuery("SELECT * FROM product WHERE pname = '"+nme+"'", null);
while(cr.moveToNext())
{
String name = cr.getString(cr.getColumnIndex("pname"));
String pr1price = cr.getString(cr.getColumnIndex("pprice"));
String prspc=cr.getString(cr.getColumnIndex("pspec"));
String prfeature=cr.getString(cr.getColumnIndex("pfeature"));
pname = name;
prprice = pr1price;
pspec=prspc;
pfeature=prfeature;
}
name.setText(pname);
price.setText("Rs " +prprice + "/-");
specification.setText(pspec);
feature.setText(pfeature);
add2cart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean incart=false;
String nm=name.getText().toString();
mydb=Product_Details.this.openOrCreateDatabase("addcart", MODE_PRIVATE, null);
mydb.execSQL("CREATE TABLE IF NOT EXISTS add2cart(usr TEXT,img BLOB,pnme TEXT,prate NUMERIC,pqty NUMERIC,ptotl NUMERIC)");
Cursor cur=mydb.rawQuery("select * from add2cart where pnme='"+nm+"' AND usr='"+dtl+"'",null);
if (cur.moveToFirst()){
String prdname=cur.getString(cur.getColumnIndex("pnme"));
if (nm.equals(prdname)){
add2cart.setText("Already in Cart");
incart=true;
}
}
if(incart==false){
mydb.execSQL("INSERT INTO add2cart (usr,pnme,prate)VALUES('"+dtl+"','"+nm+"','"+prprice+"')");
Toast.makeText(getApplicationContext(),"added to cart",Toast.LENGTH_SHORT).show(); Cursor crsr=mydb.rawQuery("select pnme from add2cart where usr='"+dtl+"'", null);
int count=0;
if (!crtno.getText().toString().equals("")) {
count=crsr.getCount();
}
crtno.setText(Integer.toString(count));
}
}
});
}
}
Try like
crtno.getText().toString().equals("")
instead of
crtno.equals("")
Because crtno.getText().toString().equals("") is the command for checking equality of the text inside the textview.
At first you should first pull string displayed in textview and it's done as by:
getText()
Return the text the TextView is displaying.
so your way should be
crtno.getText().toString().equals("")
also try this
crtno.getText().toString().equals(null)

Categories

Resources