update My Spinner from SQlite Database - android

I FOUND A SOLUTION FOR RESTORING MY VALUES, SEE MY NEW VERSION of populateFields()
Okay so I have been reading through all the Spinner and SQlite posts on here and cannot seem to find a good answer for what I am looking for so I am posting this scenario.
My app has two screens and uses the sqlite database on my device saving a name and weight fields from editTexts as strings like so
String eName = name.getText().toString();
String eWeight = weight.getText().toString();// where name and weight are EditTexts
and I have two spinners as follows
String eReps = spinReps.getSelectedItem().toString();
String eSets = spinSets.getSelectedItem().toString();
Then I call this to add to the database
long id = mDbHelper.createExercise(eName, eWeight, eReps, eSets);
Here is where my issue is, upon someone selecting to create a new exercise my app crashes because it is trying to populate a spinner incorrectly. Here is what I have currently.
private void populateFields(){
if(mRowId != null){ // where mRowId is the selected row from the list
Cursor exercise = mDbHelper.fetchExercise();
name.setText(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_NAME)));
weight.setText(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_WEIGHT)));
// this is the part that i need help with, I do not know how to restore
// the current items spinner value for reps and sets from the database.
spinReps.setSelection(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS)));
spinSets.setSelection(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_SETS)));
}
I assume I need to use some sort of adapter to restore my list items along with the current value from the database, I am just not sure how.
Can someone please help me with this???
** BELOW IS MY SOLUTION**
I had to move my ArrayAdapters repsAdapter, spinAdapter out of my onCreate()
and then implement this new populateFields()
private void populateFields(){
if(mRowId != null){
Cursor exercise = mDbHelper.fetchExercise(mRowId);
// same as before
name.setText(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_NAME)));
// get the string for sReps and sSets from the database
String sReps = exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS));
String sSets = exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_SETS));
// use the strings to get their position in my adapters
int r = repsAdapter.getPosition(sReps);
int s = setsAdapter.getPosition(sSets);
// set their returned values to the selected spinner Items
spinReps.setSelection(r);
spinSets.setSelection(s);
// same as before
weight.setText(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_WEIGHT)));
}
}

The way to set a Spinner to a value, not a position, depends on what adapter you are using.
ArrayAdapter, this one is easy:
int position = adapter.getPosition(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS)));
spinReps.setSelection(position);
SimpleCursorAdapter, this one is a little harder:
String match = exercise.getString(exercise.getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS));
Cursor cursor = adapter.getCursor();
cursor.moveToPosition(-1);
int columnIndex = cursor.getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS);
while(cursor.moveToNext()) {
if(cursor.getString(columnIndex).equals(match))
break;
}
spinReps.setSelection(cursor.getPosition());
If you are using a different type of adapter and can't modify the code above to fit it, let me know. Hope that helps!

Related

Android - Cursor not properly working

I have an app that inserts data into a database with 2 tables (project and alvara)
The insertion method for the second table depends on what type the first table gets. (1 or 2) for resumed idea.
This is a method that I made for looking into the second table with cursor. If it finds, it sets in setters from alvara_db class. And later on, I use getters to show info on textviews in another activity. The issue is that it's not setting info at all. Is anything wrong in my Cursor?
Thanks in advance!
public ArrayList<alvara_db> getAlvaras(){
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<alvara_db> projects = new ArrayList<>();
String[] project = new String[]{String.valueOf(tipoprojetoid)};
Cursor cur = db.rawQuery("SELECT placa, proj_exec, resp_tec, rtnum, parecer FROM alvara WHERE projetoid = ?", project);
cur.moveToFirst();
alvara_db alvaras = new alvara_db();
alvaras.setPlaca(cur.getInt(cur.getColumnIndex("placa")));
alvaras.setProj_exec(cur.getInt(cur.getColumnIndex("proj_exec")));
alvaras.setResp_tec(cur.getString(cur.getColumnIndex("resp_tec")));
alvaras.setRtnum(cur.getInt(cur.getColumnIndex("rtnum")));
alvaras.setParecer(cur.getString(cur.getColumnIndex("parecer")));
projects.add(alvaras);
return projects;
}
Fragment where I call getAlvaras method:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detalhes_projeto_alvara);
db.getAlvaras();
placa = alvaras.getPlaca();
resp_tec = alvaras.getResp_tec();
proj_exec = alvaras.getProj_exec();
rtnum = alvaras.getRtnum();
}
You are not using the returned value from db.getAlvaras().
Instead the alvaras variable in your second snippet is something that is likely not initialized - the code you posted does not show that exactly.
(In addition, you might want to check the return value of moveToFirst() in case the query matches no rows, and add a do-while loop to retrieve more than one row.)

Android : Different Background colors for different CardViews?

I have a SQLite database which feeds data to the cardviews via an ArrayList. Every record in the database consists of a different color code, I want to set the background color of each individual card to its respective color present in the database. Color codes are under the "color" column inside the database.
Now here's my code, as you can see my SQL SELECT Query should only select ONE PARTICULAR RECORD for each individual card but what is doing here is that it selects all the records present in database.
If I use c.moveToFirst(); it selects the first row of the table and if I use c.moveToLast(); it selects the last row of the table? If I am clearing mentioning ...where id ="+cardid+";", isn't it supposed to select only one particular row?
The problem I am facing here is that it sets a common background color for all cardviews, I need it to be different for every card. What am I doing wrong?
Code Reference :
TextView myid consists of the unique identifier of every record in the database
PersonViewHolder(View itemView, final Activity theact) {
super(itemView);
personName = (TextView)itemView.findViewById(R.id.person_name);
personAge = (TextView)itemView.findViewById(R.id.person_age);
personPhoto = (ImageView)itemView.findViewById(R.id.person_photo);
myid = (TextView)itemView.findViewById(R.id.IDTAG);
ohcolor = (TextView)itemView.findViewById(R.id.COLORCODE);
cv = (CardView)itemView.findViewById(R.id.cv);
cv.setUseCompatPadding(true);
openDatabase();
final String cardid = myid.getText().toString().trim();
c = db.rawQuery("SELECT color FROM persons WHERE id ="+cardid+";", null);
c.moveToFirst();
colorbro = c.getString(0);
i = Integer.parseInt(colorbro);
cv.setCardBackgroundColor(i);
cv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// do something
}
});
}
Problem is you are having only one reference to cardView which is getting updated, the moment you assign new object to it.
Replace this line of code
cv = (CardView)itemView.findViewById(R.id.cv);
with this
CardView cv = (CardView)itemView.findViewById(R.id.cv);
This should fix your problem.
The docs for db.rawQuery say "The SQL string must not be ; terminated", so that is potentially your problem. http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
The right way to get color from colors.xml file is either provide color name or its id to getColor method:
i = Integer.parseInt(colorbro);
cv.setCardBackgroundColor(ContextCompat.getColor(context, i));
I am not sure what you have in your i variable. Debug and see if it has the correct value.
I found a solution myself, we can set the background color of the card inside OnBindViewHolder method
public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {
personViewHolder.myid.setText(persons.get(i).id);
personViewHolder.personName.setText(persons.get(i).name);
personViewHolder.personAge.setText(persons.get(i).age);
personViewHolder.personPhoto.setImageResource(persons.get(i).photoId);
personViewHolder.ohcolor.setText(persons.get(i).color);
//setting background color here
personViewHolder.cv.setCardBackgroundColor(Integer.parseInt(persons.get(i).color));
}
Here, persons is an ArrayList getting data from the SQLite database. As my database also has a column for color codes, I feed it to the ArrayList and retrieve it inside OnBindViewHolder and set the background color for each individual card.

How to load database data, and store it into array list, and show it into ListVIew

So, I want to build an app to view some data from database. I already have the database, also already made some entities that have exactly same properties name with the column names in database. And also I put the database into database directory by copying from assets folder.
What I want to achieve is, I want to pull some data, and put it into array list, so I can show it in ListView in fragment.
Is there any convenient way to pull some data without querying (like loadAll() function) ?
For now, I'm using cursor to save the pulled data using query, and assign its properties one by one using set function like setName(String name).
After that, I show the list using CursorAdapter.
It would be like this
public class FrameCursor extends CursorWrapper{
/**
* Creates a cursor wrapper.
*
* #param cursor The underlying cursor to wrap.
*/
public FrameCursor(Cursor cursor) {
super(cursor);
}
public ZFrame getFrame(){
if(isBeforeFirst() || isAfterLast()){
return null;
}
ZFrame frame = new ZFrame();
ZFrameDao frameDao = new ZFrameDao();
int frameEdition = getInt(getColumnIndex(COLUMN_FRAME_EDITION));
int frameId = getInt(getColumnIndex(COLUMN_FRAME_ID));
int frameNumber = getInt(getColumnIndex(COLUMN_FRAME_NUMBER));
int frameType = getInt(getColumnIndex(COLUMN_FRAME_TYPE));
int frameBookmark = getInt(getColumnIndex(COLUMN_FRAME_BOOKMARK));
int frameGlyph = getInt(getColumnIndex(COLUMN_FRAME_GLYPH));
int frameLesson = getInt(getColumnIndex(COLUMN_FRAME_LESSON));
String frameAllReading = getString(getColumnIndex(COLUMN_FRAME_ALL_READING));
String frameReadingNumber = getString(getColumnIndex(COLUMN_FRAME_READING_NUMBER));
String frameReference = getString(getColumnIndex(COLUMN_FRAME_REFERENCE));
String frameWritingNumber = getString(getColumnIndex(COLUMN_FRAME_WRITING_NUMBER));
frame.setZEDITION(frameEdition);
frame.setZFRAME_ID(frameId);
frame.setZFRAME_NUMBER(frameNumber);
frame.setZFRAME_TYPE(frameType);
frame.setZBOOKMARK(frameBookmark);
frame.setZGLYPH((long)frameGlyph);
frame.setZLESSON((long)frameLesson);
frame.setZALL_READING_NUMBER(frameAllReading);
frame.setZREADING_NUMBER(frameReadingNumber);
frame.setZREFERENCE(frameReference);
frame.setZWRITING_NUMBER(frameWritingNumber);
return frame;
}
}
It would be consume lot of work for doing this for every table.
So anyone could help me?
Why not using CursorLoader ? Use CursorLoader to handle the cursor query issue, and it works perfectly with CursorAdapter, Here is the google's guide
Maybe this is what you need, a light weight orm api? You can go here for more information.

Displaying Country and its calling code, but returning its Abbreviated code using Android XML

I am trying to develop a Registration screen from Android XML. As in every Registration form, I would need to display the list of countries. I am able to do this using string-array in strings.xml file.
The greater part of the problem is, when a user selects a country, the phone number field just below it should be initially filled with its respective country code, which may or may not be editable. Here, my problem is how do I get the country code when the country is selected. Do I need to use a database or is it achievable using xml itself?
Besides that, when user submits the Register form, I would have to send the abbreviated code of the country, not the full country name. Now, again this would require either a database or xml?
My app doesn't use database till now, it would not be so good to use database for this purpose. Moreover, almost any application that uses a registration needs this thing to be done, but I cannot find any resources on how to do this in Android.
Also, I would like to tell you that my minimum sdk is version 7.
Please help.
I was finally able to do it without using database. I'm writing down the steps so that it may help anyone else who needs the same thing to be done.
First I downloaded the CSV available at: https://github.com/mledoze/countries/blob/master/countries.csv
I removed all other fields, except those I needed. It left me with 3 fields: name, abbreviation and calling code.
Next, I downloaded the CSVReader from: http://code.google.com/p/secrets-for-android/source/browse/trunk/src/au/com/bytecode/opencsv/CSVReader.java
Got the items from the CSV as mentioned in How to parse the CSV file in android application? by "Kopfgeldjaeger" as:
String next[] = {};
List<String[]> list = new ArrayList<String[]>();
try {
CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("countries.csv")));
for(;;) {
next = reader.readNext();
if(next != null) {
list.add(next);
} else {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
Next I added an ArrayList for each of the values like:
ArrayList<String> countryNames = new ArrayList<String>();
ArrayList<String> countryAbber = new ArrayList<String>();
ArrayList<String> countryCodes = new ArrayList<String>();
for(int i=0; i < list.size(); i++)
{
countryNames.add(list.get(i)[0]); // gets name
countryAbber.add(list.get(i)[1]); // gets abbreviation
countryCodes.add(list.get(i)[2]); // gets calling code
}
Then added it to the spinner in the XML layout as:
ArrayAdapter<String> countryAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, countryNames);
spinner.setAdapter(countryAdapter);
// adding event to display codes when country is selected
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
// display the corresponding country code
TextView tvCountryCode = (TextView) findViewById(R.id.country_code);
tvCountryCode.setText("+"+list.get(pos)[2]);
countryPosition = pos;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
This way, I was able to display country code in the xml file, when a country was selected from the dropdown list.
Remember to add the setOnItemSelectedListener() to achive that.
I hope this helps somebody in future.
I would advise you to use a database. API level 7 supports SQLite databases (I used them in android 2.1 myself). Create one table that has all the required info:
create table countries (
_id integer primary key autoincrement,
country_code char(2),
country_name varchar,
phone_code char(4),
editable integer
);
Then store your country information into this table. When populating your list of countries, use this table instead of XML; display country names and associate country codes with each corresponding list item. Then on selection, use the country code to get the phone code and the 'editable' flag - and act upon this info.

Android: having basic problems with sqlite database

I am having some trouble implementing a sqlite database in my simple android application:
a user is displayed a list of animals in a Listview.Upon selecting an animal the user is brought to an activity "Animal",which will display a picture of the animal and give them options to
view Animal Bio
Back
All very simple so far, right?
I have working the database, which will populate the listView of animals.Database currently looks like
Table Animal-
_ID,
Name
Table Biography-
_ID,
Bio
This is where I would welcome any helpful advice on my problem, or on how to improve my implementation.
Currently populating the DB as follows
long populateDB(){
String[] animalName = {"Lion" "Zebra", "Tiger", "Gorilla",...};
String[] animalBios = {"Found in the "...}
ContentValues animalNameVals = new ContentValues();
ContentValues animalBioVals = new ContentValues();
long[] rowIds = new long[animalName.length];
// Populate the animal table
for(int i = 0; i < animalName.length; i++){
animalNameVals.put(KEY_ANIMALNAME, animalName[i]);
rowIds[i] = db.insert(ANIMAL_TABLE, null, animalNameVals);
}
// Populate the Bio table
for(int j = 0; j < bios.length; j++){
animalBioVals.put(KEY_BIO, bios[j]);
rowIds[j] = db.insert(BIOS_TABLE, null, animalBioVals);
}
return rowIds[0];
}
And had planned on being able to tell database which animal on list was selected by passing extras with the intent, eg if position on listItemClick == 1, pass in tiger and retrieve tiger bio from db.
Problems:
Then on the Animal activity page is getExtra() == tiger, telling the activity that tiger was selected from the list and to load this bio from the DB..well, I cannot see an efficient method of implementation for this idea and am struggling to do so.
My second headache comes from adding the bio to the application from the Db.Originally I had a test bio hardcoded in a string, shown in a TextView.Is there a way to retrieve a string from a cursor and add it to the TextView id?I understand I will need some adapter, what I do not understand is why cant it be as simple as setResource(R.id.bio) = bio.
Thanks you for reading and any help is much appriciated.
First problem: First of all, I'm not sure why you don't have the column Bio in the Animal-table? As no Bio would fit to any other animal than itself, you can safely do this. By doing this you can query the database upon selection and pass the entire object (including name of animal and bio) to the next Activity and use this to get your information. If this was somewhat unclear, let me know and I'll try to explain it better.
Second problem: You can get values from tables (there of also Strings) using a Cursor. To get the String you can do something like this where cursor is the Cursor with your result from the database:
String bio;
// Move Cursor to its first element
if(cursor.moveToFirst()) {
// Make sure the cursor is not null
if(cursor != null) {
bio = cursor.getString(cursor.getColumnIndex("Bio")));
}
}
Sidenote: If I read the code correctly, it seems that you use long for ID's? The usual thing to go about ID's is integers as far as I know.

Categories

Resources