How can I change the Data that I got from my Database? - java

I get my data out of my db with the following code:
private void fillData() {
cursor = mDbAdapter.fetchAllSubjects();
startManagingCursor(cursor);
String[] from = new String[] { DatabaseAdapter.KEY_TITLE, DatabaseAdapter.KEY_LECTURER, DatabaseAdapter.KEY_BEGIN };
int[] to = new int[] { R.id.title, R.id.lecturer, R.id.time };
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter subjects = new SimpleCursorAdapter(this, R.layout.subject_row, cursor, from, to);
setListAdapter(subjects);
}
Now my problem is, that I want to add 3 other columns from my db and want to get the following:
"("+DatabaseAdapter.KEY_TYPE+") "+DatabaseAdapter.KEY_TITLE
DatabaseAdapter.KEY_LECTURER
new Date(DatabaseAdapter.KEY_BEGIN)
new Date(DatabaseAdapter.KEY_END)
--> these two should be in one TextView in the way dd.MM. HH:mm (this is from BEGIN) - HH:mm (this is from END)
I don't know how I'm able to do that - please help me :)

Ok I finally figured out what you really wanted.
Instead of using "SimpleCursorAdapter" directly, you can create your own Cursor adapter, inside which you can mainipulate the data as you want.
Create a new Adapter "SubjectsAdapter.java". In this Adapter you will override the "bindView" and "newView". This allows us to apply a view to the cursor. But before doing so, gives us the opportunity to change the data from the cursor.
This will give you an idea what has to be done.
private void fillData()
{
cursor = mDbAdapter.fetchAllSubjects();
startManagingCursor(cursor);
SubjectsAdapter subjectsAdapter = new SubjectsAdapter(this, cursor);
setListAdapter(subjectsAdapter);
}
//SubjectsAdapter.java - make changes to fix bugs/compilation errors. This is untested.
public class SubjectsAdapter extends ResourceCursorAdapter
{
public SubjectsAdapter(Context context, Cursor cur) {
super(context, R.layout.subject_row, cur);
}
#Override
public View newView(Context context, Cursor cur, ViewGroup parent)
{
LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return li.inflate(R.layout.subject_row, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor)
{
TextView titleText = (TextView)view.findViewById(R.id.title);
titleText.setText(cursor.getString(cursor.getColumnIndex(DatabaseAdapter.KEY_TITLE)));
//You can add code to retrieve other columns here.
//This is where you retrieve the date in long format from cursor, convert it to a required format, and then using it.
TextView beginTimeText = (TextView)view.findViewById(R.id.time);
Long lBeginDate = cursor.getLong(cursor.getColumnIndex(DatabaseAdapter.KEY_BEGIN));
String sBeginDate = getFormattedDate(lBeginDate);
beginTimeText.setText(sBeginDate);
}
private String getFormattedDate(Long lDate)
{
SimpleDateFormat smdf = new SimpleDateFormat("MM/dd/yyyy h:mm:ss a");
String sDate = smdf.format( lDate ));
return sDate;
}
}

Related

Error querying sqlite database in android studio

I have a problem in my application, to see if there is someone who can help me.
It turns out that in my application I have made a database with SQLite that has two tables, one for players and one for results.
#Override
public void onCreate(SQLiteDatabase BaseDeDades) {
BaseDeDades.execSQL("create table jugadors(codi int primary key, nom text, cognoms text, data date, club text, categoria text)");
BaseDeDades.execSQL("create table resultats(codipuntuacio int primary key, codijugador int,codiexercici text, puntuacio text, temps long, data date)");
}
To consult the first of the tables (players) that shows a list of all the players entered in the database, I did it as follows.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_llistajug);
Llistajugadors();
}
public void Llistajugadors(){
AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper(this,"administracio",null,1);
SQLiteDatabase BaseDeDades = admin.getWritableDatabase();
if(BaseDeDades!=null){
Cursor c= BaseDeDades.rawQuery("select * from jugadors",null);
int quantitat = c.getCount();
int i=0;
String[] array = new String[quantitat];
if (c.moveToFirst()){
do{
String linia = c.getInt(0)+"-"+c.getString(1);
array[i] = linia;
i++;
}while(c.moveToNext());
}
ArrayAdapter<String>adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,array);
final ListView llista = (ListView)findViewById(R.id.llista);
llista.setAdapter(adapter);
llista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = getIntent();
intent.putExtra("dato2", llista.getItemAtPosition(position).toString());
setResult(RESULT_OK,intent);
finish();
}
});
}
}
}
The problem has arisen when trying to consult the data of the other table (results) since I have tried to do it the same way
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_llistajug);
jugador = getIntent().getStringExtra("name");
exercici = getIntent().getStringExtra("exercise");
nom = jugador.split("-")[1];
codi = Integer.parseInt(jugador.split("-")[0]);
Resultats();
}
public void Resultats() {
AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper(this, "administracio", null, 1);
SQLiteDatabase BaseDeDades = admin.getWritableDatabase();
if (BaseDeDades != null) {
Cursor c2 = BaseDeDades.rawQuery("select * from resultats",null);
int quantitat2 = c2.getCount();
int i2 = 0;
String[] array2 = new String[quantitat2];
if (c2.moveToFirst()) {
do {
String linia2 = c2.getInt(0) + "-" + c2.getString(1);
array2[i2] = linia2;
i2++;
} while (c2.moveToNext());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array2);
final ListView llista2 = (ListView) findViewById(R.id.llista2);
llista2.setAdapter(adapter);
}
}
}
But when executing this activity, in this case the application stops.
Does anyone know why if I have done it the same way? Thank you
This is the error that appears in Logcat when executing the activity:
Logcat error
Thanks, the bug was fixed. But now I have another problem with the query. How can I make the query for a string?
codijugador i codi are integers and it works correctly but adding another parameter codiexercici = exerici which are strings gives me an error, are they not done the same way?
Thanks, the bug was fixed. But now I have another problem with the query. How can I make the query for a string?
Thanks, the bug was fixed. But now I have another problem with the query. How can I make the query for a string?
co-player i codi are integers and it works correctly but adding another parameter codiexercici = exerici which are strings gives me an error, are they not done the same way?
Cursor c = BaseDeDades.rawQuery("select * from resultats where codijugador = "+codi+" and codiexercici="+exercici, null);
String must be enclosed inside single quotes, but this is something that you should not do by concatenating the parameters and the single quotes.
Use ? placeholders for the parameters and the 2nd argument of rawQuery() to pass them:
Cursor c = BaseDeDades.rawQuery(
"select * from resultats where codijugador = ? and codiexercici = ?",
new String[] {String.valueOf(codi), exercici}
);

Why my sqlite insert method is not working

Save data with SQLite
Hi guys, I'm new to Android and i'm working in a Notes App, until now I have done with the main interphace and recieve the inputs from the Edittext, but when it comes to saving data to my SQLite DB, my code is failling, can you please tell me what I been doing wrong ?.
FormActivity method
public void saveToDB(View view) {
try {
String subjet = asunto.getText().toString();
String body = cuerpo.getText().toString();
int day = myCalendar.get(Calendar.DAY_OF_MONTH);
int month = myCalendar.get(Calendar.MONTH);
int year = myCalendar.get(Calendar.YEAR);
Note note = new Note(subject,body,day,month,year); // Create an instance of Note class
DBHelper db = new DBHelper(this,"TaskList.db",null,1); // New Instance of DBHelper class
db.InsertIntoTable(note); // pass the newly created Note instance to DBHelper insert method
db.close(); // we close Database
Toast.makeText(this,"Note saved !!",Toast.LENGTH_SHORT).show(); // Notify the user of the operation success
Intent intent = new Intent(FormActivity.this,MainActivity.class); // Lets return to MainActivity again
startActivity(intent);
}
catch (Exception e){
Toast.makeText(this,"Unable to save note",Toast.LENGTH_SHORT).show();
}
}
DBHelper insert method
public Long InsertIntoTable(Note note){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
/* We organize the values in the respective rows */
values.put(col_subject,note.getSubject());
values.put(col_note,note.getBody());
values.put(col_day,note.getDay());
values.put(col_month,note.getMonth());
values.put(col_year, note.getYear());
// Time to insert data to Database
long rowID = db.insert(table_name,null,values);
return rowID;
}
I put a Toast, to prevent my app from crashing in case and to see if the operation succed, but it fails everytime.
RecyclerAdapter class
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.itemview,null);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
Note note = noteList.get(i);
viewHolder.asunto.setText(note.getAsunto());
viewHolder.nota.setText(note.getCuerpo());
viewHolder.fecha.setText(note.getDia() + "/" + note.getMes() + "/" + note.getAno());
viewHolder.etiqueta.setText(note.getTag());
}
This is in my stacktrace:
E/RecyclerView: No adapter attached; skipping layout

How to display data fetched from the database table into listview?

My Function In SQLAdapter class is
public ArrayList<Airline> getairlinedetails(String bookingdate) {
Cursor curCalllog =db.rawQuery("SELECT * FROM "+ BOOK +
" WHERE " + date +
" BETWEEN '" + startdate + "' AND '" + enddate + "'", null);
if (curCalllog != null) {
if (curCalllog.moveToFirst()) {
do {
a=new Airline();
//a.setBookingdate(curCalllog.getString(1));
a.setPickupadd(curCalllog.getString(2));
a.setCity(curCalllog.getString(3));
a.setTrip(curCalllog.getString(4));
a.setFdate(curCalllog.getString(5));
a.setFtime(curCalllog.getString(6));
a.setCdate(curCalllog.getString(7));
a.setPtime(curCalllog.getString(8));
a.setSeats(curCalllog.getInt(9));
a.setAmount(curCalllog.getInt(10));
update.add(a);
} while (curCalllog.moveToNext());
}
}
return update;
}
M Fetching data between two dates and
I Want To show the fetched data into listview please help me how to do it I m new in android development.
You can use SimpleCursorAdapter for showing Databse contents in Listview. Make instance of SimpleCursorAdapter and pass Cursor object into it. Refer this link
If you want Customized Listview, you can customize SimpleCursorAdapter by extending this with your custom adapter class.
you can follow this example :
DataManipulator.java -helper class
//to retrieve data in a list
public List<String[]> selectAll()
{
List<String[]> list = new ArrayList<String[]>();
Cursor cursor = db.query(TABLE_NAME, new String[] { "id","name","number","skypeId","address" },
null, null, null, null, "name asc");
int x=0;
if (cursor.moveToFirst()) {
do {
String[] b1=new String[]{cursor.getString(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4)};
list.add(b1);
x=x+1;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
cursor.close();
return list;
}
CheckData.java
// to show data in a list view
public class CheckData extends ListActivity {
TextView selection;
public int idToModify;
DataManipulator dm;
List<String[]> list = new ArrayList<String[]>();
List<String[]> names2 =null ;
String[] stg1;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.check);
dm = new DataManipulator(this);
names2 = dm.selectAll();
stg1=new String[names2.size()];
int x=0;
String stg;
for (String[] name : names2) {
stg = name[1]+" - "+name[2]+ " - "+name[3]+" - "+name[4];
stg1[x]=stg;
x++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_list_item_1,
stg1);
this.setListAdapter(adapter);
selection=(TextView)findViewById(R.id.selection);
}
public void onListItemClick(ListView parent, View v, int position, long id) {
selection.setText(stg1[position]);
}
}
follow this link for complete tutorial
I assume you are getting data from database and there by complete ArrayList with Airline objects.
Now to display data in ListView from ArrayList<Airline>, you have to define Custom adapter class by extending either BaseAdapter or ArrayAdapter.
Here you go: How to define custom adapter for ListView?
I Want To show the fetched data into listview please help me how to do
it I m new in android development
Simpliest way is to use ArrayAdapter with build-in ListView's row layout.
ListView list = (ListView) findViewById(R.id.yourList);
ArrayList<Airline> data = db.getairlinedetails("someString");
ArrayAdapter<Airline> adapter = new ArrayAdapter<Airline>(this,
android.R.layout.simple_list_item_1, data);
list.setAdapter(adapter);
But since this you need to also override toString() method in your Airline class.
Reason is that your ArrayAdapter will convert each child(provided list of airlines) to String and if you won't override toString() you will get default string representation of object but you probably need to show for instance name of airline so your method can looks like
#Override
public String toString() {
return this.name;
}
Note:
This is simple way. But if you want to get more control over ListView and create custom list i recommend you to create own subclass of ListAdapter for example BaseAdapter and define your own Adapter. Sorry but i won't write you implementation because it requires much more code but nice examples you can find here:
Customizing Android ListView Items with Custom ArrayAdapter
Android ListView, ListActivity and ListFragment - Tutorial
Android Custom ListView with Image and Text

SimpleCursorAdapter remove values

I have a ListView on each row i have a LinearLayout with some objects in it (mostly some TextViews).
This ListView i fill it dynamically from a cursor. In this cursor i have one value true or false.
I want to hide or make non clickable the lines with value false. I try this code but doesn't work
public void contentProviderInitialized(final Cursor cursor) {
SimpleCursorAdapter commonTickets = new SimpleCursorAdapter(MyClass.this,
R.layout.row_ticketing, cursor, new String[] {"price", "productName", "stopName" },
new int[] { R.id.ticketing_price, R.id.ticketing_product, R.id.ticketing_stop_name }
) {
#Override
public void bindView(View view, Context context, Cursor cursor) {
String enabledStr = cursor.getString(cursor.getColumnIndex("enabled"));
String product = cursor.getString(cursor.getColumnIndex("productName"));
boolean enabled = Boolean.parseBoolean(enabledStr);
LinearLayout ticketingRow = (LinearLayout) view.findViewById(R.id.ticketing_row);
if (enabled) {
ticketingRow.setEnabled(true);
} else {
ticketingRow.setEnabled(false);
}
super.bindView(view, context, cursor);
};
MyClass.this.ticketing_list_view.setAdapter(commonTickets);
}
}
Override isEnabled on the adapter
http://developer.android.com/reference/android/widget/BaseAdapter.html#isEnabled(int)
This answer seems to hint at it. Use movetoposition on the cursor. It sounds like the performance would be bad with that, though, so you might want to do some caching of true/false values based on numeric position? Try it out. See how it goes. The caching might be a waste.
This was a great help to try another aproach:
Android - how to delete item from a cursor?
Add the positions you want to see to a new MatrixCursor and swap your Cursor to the new Matrix Cursor

How do I implement autocomplete with cursoradapter

I have an SQLite database containing 2 tables 4000+ rows each used for autocomplete. I saw very simple examples that use an array of strings to provide autocomplete or they use the list of contacts to do the same. Obviously none of these work in my case. How do I use my own SQLite database with my own autocomplete data, for the autocomplete. Do I have to create content providers? How? Please give me some examples because I couldn't find any. I have managed to override SQLiteOpenHelper to copy the database from the assets folder to the /data/data/MY_PACKAGE/databases/ folder on the android. I have created a custom CursorAdapter that uses my custom SQLiteOpenHelper and returns a cursor from runQueryOnBackgroundThread. I get strange errors about some _id column missing. I have added the _id column to my tables. I also don't understand what is the Filterable interface doing and when does my data get filtered. What methods/classes do I need to override? Thanks.
It works.
You need the SQLiteOpenHelper from here. You basically have to copy your database into a specific folder from your assets folder. Then you need a custom CursorAdapter that uses your custom SQLiteOpenHelper.
Here is the onCreate method for my activity.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
KeywordsCursorAdapter kwadapter = new KeywordsCursorAdapter(this, null);
txtKeyword = (AutoCompleteTextView)this.findViewById(R.id.txtKeyword);
txtKeyword.setAdapter(kwadapter);
txtCity = (AutoCompleteTextView)this.findViewById(R.id.txtCity);
btnSearch = (Button)this.findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(this);
}
Here is the cursoradapter. You can pass null for cursor when constructing.
public class KeywordsCursorAdapter extends CursorAdapter {
private Context context;
public KeywordsCursorAdapter(Context context, Cursor c) {
super(context, c);
this.context = context;
}
//I store the autocomplete text view in a layout xml.
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.keyword_autocomplete, null);
return v;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
String keyword = cursor.getString(cursor.getColumnIndex("keyword"));
TextView tv = (TextView)view.findViewById(R.id.txtAutocomplete);
tv.setText(keyword);
}
//you need to override this to return the string value when
//selecting an item from the autocomplete suggestions
//just do cursor.getstring(whatevercolumn);
#Override
public CharSequence convertToString(Cursor cursor) {
//return super.convertToString(cursor);
String value = "";
switch (type) {
case Keywords:
value = cursor.getString(DatabaseHelper.KEYWORD_COLUMN);
break;
case Cities:
value = cursor.getString(DatabaseHelper.CITY_COLUMN);
break;
}
return value;
}
#Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
//return super.runQueryOnBackgroundThread(constraint);
String filter = "";
if (constraint == null) filter = "";
else
filter = constraint.toString();
//I have 2 DB-s and the one I use depends on user preference
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
//String selectedCountryCode = prefs.getString("selectedCountry", "GB");
String selectedCountryCode = prefs.getString(context.getString(R.string.settings_selected_country), "GB");
selectedCountryCode += "";
//Here i have a static SQLiteOpenHelper instance that returns a cursor.
Cursor cursor = MyApplication.getDbHelpers().get(selectedCountryCode.toLowerCase()).getKeywordsCursor(filter);
return cursor;
}
}
Here is the part that returns the cursor: it's just a select with a like condition.
public class DatabaseHelper extends SQLiteOpenHelper {
...
public synchronized Cursor getKeywordsCursor (String prefix) {
if (database == null) database = this.getReadableDatabase();
String[] columns = {"_id", "keyword"};
String[] args = {prefix};
Cursor cursor;
cursor = database.query("keywords", columns, "keyword like '' || ? || '%'", args, null, null, "keyword", "40");
int idcol = cursor.getColumnIndexOrThrow("_id");
int kwcol = cursor.getColumnIndexOrThrow("keyword");
while(cursor.moveToNext()) {
int id = cursor.getInt(idcol);
String kw = cursor.getString(kwcol);
Log.i("keyword", kw);
}
cursor.moveToPosition(-1);
return cursor;
}
...
}
You can also create a custom content provider but in this case it would be just another useless class you need to override.

Categories