After Binded Spinner , How to Do not select first item? - java

public void DatabaseConn(){
DataBaseHelper myDbHelper = new DataBaseHelper(this.getApplicationContext());
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
SQLiteDatabase db = myDbHelper.getReadableDatabase();
//SQLiteDatabase db = SQLiteDatabase.openDatabase("/data/data/com.example.abc2/databases/DB_BusData", null, 0);
Cursor c = db.rawQuery("SELECT * FROM Tbl_Driver", null);
startManagingCursor(c);
//create an array to specify which fields we want to display
String[] from = new String[]{"Driver_Name"};
//create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
//create simple cursor adapter
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
//get reference to our spinner
Spinner s = (Spinner) findViewById( R.id.DriverSpin);
s.setAdapter(adapter);
db.close();
}
This is the code how i bind my Spinner with my DataBase,
But After Binded Spinner, will automatically selected first item,
i would like to let User select the Spinner by themself, how to do with this?

read this documentation page: http://developer.android.com/reference/android/widget/AbsSpinner.html

Just add a default selection after populating the spinner something like --select driver-- then do a check in your listener to not do anything when the spinner position is 0

SQLiteDatabase db = myDbHelper.getReadableDatabase();
//SQLiteDatabase db = SQLiteDatabase.openDatabase("/data/data/com.example.abc2/databases/DB_BusData", null, 0);
Cursor c = db.rawQuery("SELECT * FROM Tbl_Vehicle", null);
//=====Add Additional=====
MatrixCursor extras = new MatrixCursor(new String[] { "_id", "Plat_No" });
extras.addRow(new String[] { "-1","< Select Vehicle >" });
Cursor[] cursors = { extras, c };
c = new MergeCursor(cursors);
//===========================
Just Add the First Items as blank or i have added "< Select Vehicle >" as the first item

Related

RecyclierView's notifyItemInserted does not work with arrayList

I have 1 ArrayList and 1 RecyclerView. Data from DB are retrieved and stored in the ArrayList for displaying in the RecyclerView. All the things work fine with adding new item to the RecyclerView, but without the adding animation. I know I should use notifyItemInserted for the adding animation, but it didn't work. No inserting animation was appearing. Now I have to go back to the previous page and then get in the page again so that the added item was showing. So, how to add back the inserting animation?
Any help will be very much appreciated. Thanks.
Code to pass the data and set the adapter:
db = new DatabaseHelper(this);
dbList = new ArrayList<>();
dbList = db.getFilteredItems();
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
//newest to oldest order (database stores from oldest to newest)
llm.setReverseLayout(true);
llm.setStackFromEnd(true);
mRecyclerView.setLayoutManager(llm);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new RecyclerAdapter(this, llm, dbList);
mRecyclerView.setAdapter(adapter);
Code to retrieve data from DB:
//retrieve filtered data from DB
public List<AudioItem> getFilteredItems(){
List<AudioItem> audioList = new ArrayList<>();
String titleName = EditActivity.titleName;
String query = "select * from " + TABLE_NAME + " where " + COLUMN_NAME_RECORDING_NAME + " like '" + titleName + "%'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query,null);
if (cursor.moveToFirst()){
do {
AudioItem audio = new AudioItem();
audio.setId(Integer.parseInt(cursor.getString(0)));
audio.setName(cursor.getString(1));
audio.setFilePath(cursor.getString(2));
audio.setLength(Integer.parseInt(cursor.getString(3)));
audio.setTime(Long.parseLong(cursor.getString(4)));
audioList.add(audio);
}while (cursor.moveToNext());
cursor.close();
}
return audioList;
}
Code to insert data into the DB:
/* Insert data into database */
public void addRecording(String recordingName, String filePath, long length) {
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME_RECORDING_NAME, recordingName);
cv.put(COLUMN_NAME_RECORDING_FILE_PATH, filePath);
cv.put(COLUMN_NAME_RECORDING_LENGTH, length);
cv.put(COLUMN_NAME_TIME_ADDED, System.currentTimeMillis());
db.insert(TABLE_NAME, null, cv);
db.close();
if (mOnDatabaseChangedListener != null) {
mOnDatabaseChangedListener.onNewDatabaseEntryAdded();
}
}
Code to invoke the inserting animation:
#Override
public void onNewDatabaseEntryAdded() {
//item added to top of the list
Log.e("Count: ", Integer.toString(getItemCount()));
// notifyDataSetChanged();
notifyItemInserted(getItemCount());
//llm.scrollToPosition(getItemCount() - 1);
}
If you make a new ArrayList every time something changes and assign it to a new adapter and assign that new adapter to the RecyclerView, wonky things happen.
You should break the ArrayLists out into a Model type of object or integrate them into your current DB model object. If you do this, you can simply update itemlist and the changes will be reflected in your RecyclerView.
Here's some pseudo code since I don't really have much of your code to work off of:
public class DataModel {
private ArrayList<Foo> itemlist = new ArrayList<>();
public DataModel(){}
public ArrayList<Foo> getItemList() { return itemlist; }
}
public class YourActivity extends Activity {
private DataModel data = new DataModel();
#Override
protected void onCreate(Bundle b) {
if (b == null) {
RecyclerView dataView = (RecyclerView) findViewById(R.id.recyclerView);
dataView.setAdapter(new RecyclerAdapter(this, new LinearLayoutManager(this), data.getItemList()));
}
}
}
After you set things up this way, whenever you update itemlist, you should be seeing the changes automatically reflected. If not, call notifyDataSetChanged().

How to fetch data into a textview?

This is my code to fetch database values into the listview.
private void fetchData2() {
db = helper.getReadableDatabase();
Cursor c = db.query(DBhelper.TABLE2, null, null, null, null, null, null);
adapter = new SimpleCursorAdapter(
this,
R.layout.row2,
c,
new String[]{DBhelper.Amount},
new int[]{R.id.lbl});
list.setAdapter(adapter);
}
I just want to change this code to get the values into a textview,
You can do like this...
if(c.moveToFirst()){
String data = c.getString(c.getColumnIndex("Column's Index"));
yourTextView.setText(data);
}

ANDROID STUDIO >> Sql Listview

I have this code which displays the content of the JOUEUR column.
This table has other columns, but I do not know how to display the column _ID next to the JOUEUR name
private void show_tab() {
helper = new TaskDBHelper(ValiderJoueurs.this);
SQLiteDatabase sqlDB = helper.getReadableDatabase();
Cursor cursor = sqlDB.query(Round.TABLE,
new String[]{Playas.Columns._ID, Playas.Columns.JOUEUR, Playas.Columns.PLACE},
null, null, null, null, null);
listAdapter = new SimpleCursorAdapter(
this,
R.layout.players_view,
cursor,
new String[]{Playas.Columns.JOUEUR},
new int[]{R.id.nomdujoueur},
0
);
this.setListAdapter(listAdapter);
}
Thank you very much!
Lets say you have a text view that has id = R.id.myid
listAdapter = new SimpleCursorAdapter(
this,
R.layout.players_view,
cursor,
new String[]{Spray.Columns._ID,Playas.Columns.JOUEUR},
new int[]{R.id.myid, R.id.nomdujoueur},
0
);

How to Fill a Spinner with Database Info

I have a spinner that I need to fill with information from a database, but the examples that i found don't work.
Here is my code:
public void consulta() {
AdminSQLiteOpenHelper admin =
new AdminSQLiteOpenHelper(this, "administracion", null, 1);
SQLiteDatabase bd=admin.getWritableDatabase();
Cursor c = bd.rawQuery("select name from category",null);
startManagingCursor(c);
// create an array to specify which fields we want to display
String[] from = new String[]{"name"};
// create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
// create simple cursor adapter
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
// get reference to our spinner
spinner1.setAdapter(adapter);
bd.close();
}
This is how I do it:
db = SQLiteDatabase.openDatabase("/data/data/packagename/databases/mydata.db", null, SQLiteDatabase.OPEN_READONLY);
Cursor c_cat = db.rawQuery("select _id, column_desc from your_table", null);
startManagingCursor(c_cat);
spinner = (Spinner) findViewById(R.id.spinnername);
String[] from = new String[]{"column_desc"};
int[] to = new int[]{android.R.id.text1};
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c_cat, from, to);
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(mAdapter);
db.close();
I did all that in my onCreate. I declared all my variables outside the method so that they are public to the whole class. One thing I made a mistake of in the past was closing the cursor after filling the spinner. The cursor must remain open if you want to see data in the spinner.
I hope this solves it for you.
EDIT: I noticed you are not querying for _id in your rawQuery. You must include that if you wish to populate the spinner. Analyze the code I provided.
Assuming you didn't leave any code out, you need to find/define spinner1, so that the framework knows where to put your info from the adapter.
private Spinner spinner1;
spinner1 = (Spinner) view.findViewById(R.id.yourspinnerid);
// rest of your code

How to set a contact's number in an auto complete textview in android?

I have a code from where I can get the contacts name in a auto complete text view, here is my code
autoContacts=(AutoCompleteTextView)findViewById(R.id.actvContacts);
Cursor emailCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
startManagingCursor(emailCursor);
autoContacts.setAdapter(new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, emailCursor, new String[] {Email.DATA1}, new int[] {android.R.id.text1}));
autoContacts.setThreshold(0);
but when I click in one of the name then it sets a text in that Autocomplete textview like this:
android.content.ContentResolver$CursorWrapperInner#44efc9c8
but here I want to set the specific phone number on that, how to fix this issue?
You need to use the setCursorToStringConverter
Sets the converter used to convert the filtering Cursor into a String.
http://developer.android.com/reference/android/widget/SimpleCursorAdapter.html
In your case you could do something like this:
String[] from = new String[] {
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
autoContacts=(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);
Cursor emailCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
startManagingCursor(emailCursor);
SimpleCursorAdapter adapter =new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, emailCursor, from, new int[] {android.R.id.text1});
adapter.setCursorToStringConverter(new CursorToStringConverter() {
#Override
public CharSequence convertToString(Cursor cursor) {
final int columnIndex = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER);
final String str = cursor.getString(columnIndex);
return str;
}
});
autoContacts.setAdapter(adapter);
autoContacts.setThreshold(0);

Categories