Quick variable type question. - Android Software Development

I have an EditText object (et_travel) on my screen that's asking for miles traveled. I grab that data like this:
Code:
float travel = Float.parseFloat(et_travel.getText().toString());
if(travel > 40000){
I just discover that if someone puts 40000 in the EditText, everything works fine, but if they put 40,000 (adding a comma to the number), I force close on the float travel = ...statement.
How can I evaluate the number without having a problem from the user adding a comma?

you should parse the string before you run it through Float.parseFloat() so that there are no bad characters in the string. use some of the String methods to find and remove bad characters.

Also that parsefloat method probably throws some sort of exception. You could catch it and let your user know that there value is invalid and to try again
Sent from my Desire HD using XDA App

Set the properties on the edittext so it accepts numbers only.
android:inputtype="numberDecimal|numberSigned"
________________________________
http://ron-droid.blogspot.com

Related

[Q] Converting an editable text box to be used as a integer

I have a edit able text box that is next to a button lets say onclick of the button it will take the text from the editable text box and converted to an integer so it can be subracted by.. oh lets say 32 so my first method was this.
number = EText.getText();
textOutcome.setText(number - 32);
this gave me an error of
The operator - is undefined for the argument type(s) Editable, int
my second attempt was
textOutcome.setText((Integer.parseInt(EText.getText().toString()) - 32));
This gave me no errors and it ran fine untill i clicked the button which causes the command above to run. and it force closed my application.
Does any one have any ideas i can do, or any sample code?
Thanks,
Blue.
Bumping the topic.
Please can anyone help me with this..!
Have you tried stepping through the code with the debugger? Otherwise, the code you posted looks fine. There is probably something else at play here.
Basicall it force closes whea subtraction is made..
Sent from my Samsung Epic 4g.
Ahh the debugger found something early in the code thanks for the idea !
You have to do any mathematical arithmetic with the integer type, not with string, So when you extract the number from the EditText you have to convert the string into a integer, or whatever type of number it may be.
WHen you have the integer then you can apply the arithmetic.
when this is done you then have to convert the total into a string type again.
Hope this helps.
So basically im going to write a little of code off the top of my head which obviously can have errors. Since im not testing it.
EditText txbox = (EditText)findViewById(R.id.EditText01);
String txdata = txbox.getText().toString();
int txval = Integer.ParseInt(txdata);
//you should make sure that the value is an integer, if not i think //Integer.ParseInt() will just cut off the rest if its irrational.
//Now you can do arithmetic//
int b = 2;
int t;
t = txval - b;
//The total value is in variable t.
So lets convert this into a string and put it back into an object like edittext or textview
txbox.setText(String.valueOf(t));
//Thats all, hope that helps.

[Q] SQLITE Issue

Hello All,
I am working on learning about SQLITE and I came across a a problem I can't seem to find a solution to.
I have the following code to create a table and then insert some info. The problem is that every time I refresh I adds another insert. I been searching around and I have tried several of methods but can't seem to make it work:
Code:
db = openDatabase(shortName, version, displayName, maxSize);
db.transaction(
function(transaction) {
transaction.executeSql(
'CREATE TABLE IF NOT EXISTS info ' +
' (name VARCHAR, lastname VARCHAR);'
);
}
);
db.transaction(
function(transaction) {
transaction.executeSql(
'INSERT OR REPLACE INTO info (name, lastname) VALUES ("Jose", "Lopez");'
);
}
);
});
What am I missing? Every where I search it said that if I use "NSERT OR REPLACE INTO" it would insert if it doesn't exist but if it does it would replace the info. It just keeps adding a new row. Any suggestions?
Thank you in advance.
Not sure, but since there's no index on the table to force unique rows, it'll just keep inserting a new row.
Sent from my PC36100 using XDA App
mixerman826 said:
Not sure, but since there's no index on the table to force unique rows, it'll just keep inserting a new row.
Sent from my PC36100 using XDA App
Click to expand...
Click to collapse
I search and read about it so I added "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT" and also learn about "TEXT UNIQUE" and added that as well. So it looks like this:
Code:
transaction.executeSql(
'CREATE TABLE IF NOT EXISTS info ' +
' (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ' +
' name TEXT UNIQUE, lastname TEXT UNIQUE);'
);
it worked like a charm! Thanks for pointing me into the direction. Thank you so much!

Trouble with database

Hello all! I'm somewhat new to Android development, I'm using eclipse to do all of my development. Right now I am working on an "away message text" application. I am having trouble with database query returning a string of the first index of data. Here is my code where i am trying to pull data from the database. This is being done inside my ReceiveText class, which extends BroadcastReceiver.
mDbHelper = new TextsDbAdapter(context);
mDbHelper.open();
getText = mDbHelper.fetchText(0);
message = getText.getString(getText.getColumnIndex(mDbHelper.KEY_BODY)).toString();
The error that I am getting is Cursor index out of bounds...any recommendations? Thanks!
you always start out of bounds.... you have to moveToFirst() first...
Thanks. Would I moveToFirst() before I fetchText()?
you're probably going to have to change how the fetchText method is implemented.
you'll probably want something like
Code:
public String fetchText(int id){
Cursor c = getContentResolver().query( uri,
new String[] { <name_of_text_column> } ,
"_id == " + id, null, null);
String text = null;
if( c != null ){
if( c.moveToFirst() ){
text = c.getString( c.getColumnIndex( <name_of_text_column> ) );
}
c.close();
}
return text;
}
Thanks. The method I have for fetchText returns a Cursor, however I made another method that returns a string, similar to what you recommended. For some reason, there is something wrong with the rowid sending in, I want to just get the first one, if I'm not mistaken, wouldn't it be 0? I have a seperate ReceiveText.java class, which extends Broadcast Receiver. The part where the messages are stored into the database is very similar to androids notepad demo. When a text is received, I want the ReceiveText class to query the database and just pull the first text that was actually stored into the database. I have 3 columns, KEY_ROWID, KEY_TITLE, and KEY_BODY. For some reason there is an issue when trying to query the database from the ReceiveText class. Any ideas that would make better sense or be easier to implement? Any help is much appreciated.
oh, right. I wasn't paying attention and for some reason I thought it was returning a string. I see now that it's obviously a cursor..
what you are doing sounds fine but you sure really look at the database on the phone/emulator.
open up adb and type
Code:
sqlite3 /data/data/<name_of_app>/databases/<name_of_db>
then you can do
Code:
select * from <name_of_table>
personally, I find it way easier to read if you change the mode with a ".mode line" command(the dot is important).
that should give you a good idea of why it is not working properly.
How do I open up the adb? I looked online, and it says i can run it through command line, or terminal since I use ubuntu, but I'm not sure exactly how to open it. Apologies for my noobness with android development i'm trying to learn!
if you're running it on a phone/tablet, you'll have to set up the adb drivers
but if you're just using the emulator, you're fine
Code:
cd /<path_to_sdk>/platform-tools/
./adb devices ##this should list the device. if not you have a problem.
./adb shell
and now you can execute commands on the device, like sqlite3
Awesome, I got that to work, and i can see the three "texts" that i've added to the database...looks like this...
1|Sleeping|Sleeping...text you when I wake up.
2|Driving|Driving right now...text you when I'm done.
3|Xbox|Playing xbox...text you later.
So this means that my database works. The numbers 1,2, and 3 are the KEY_ROWID, sleeping, driving, and xbox are the KEY_TITLE, and the third part is the KEY_BODY.
For some reason the ReceiveText class is having trouble pulling this information from the database, I really think it has something to do with when i Query the database, it asks for a columnindex, and i am putting a 0 as the parameter. Any ideas? Thanks again for all your help. It's a great learning process.
yeah, there doesn't seem to be a column with _id == 0
that is strange. when you defined it did you use "integer primary key autoincrement"? This should start at 0, I believe.. maybe you deleted your first entry at some point?
try it with 1 and see if that works.
Man, thanks so much for your help...it works! Here is how I did it from the ReceiveText class.
mDbHelper = new TextsDbAdapter(context);
mDbHelper.open();
getText = mDbHelper.fetchText(1);
message = getText.getString(2).toString();
getText is a Cursor type, and message is a String type.
I really appreciate the help, I understand a lot more now. My next step is to set the text to use without having to specify from the ReceiveText class...any suggestions? I was thinking adding another column in the database that would hold either a 1 or 0, and if it is selected, it updates the database and changes that field to a 1, then the ReceiveText class will query the database to return the field that has the 1...make sense? lol
Just to clear this up a bit for those still a little fuzzy:
Code:
Cursor c = db.query(TABLE_NAME3, new String[] {NAMESHORT, LAPTIME, LAPNUMBER}, null ,null, null, null, orderBy);
The column indexes are what you have in the "new String[]" area whether you have 1 or 50 items. So, NAMESHORT is index 0, LAPTIME is index 1 and LAPNUMPER is index 2. It's NOT the column number of where it is in the table
Just a personal preference of mine, but I code all this in the database methods and return what I need from there. Seeing hard-coded numbers in a program always bothers me. Instead of returning cursors I'll return a StringBuilder or ArrayList or whatever. Just sayn'

APK development help - encoding characters from a string

I am trying to swap out characters from one string to those in another (like the simple alphabetic offset code people used as kids), the code I am using is
public void convertMe(){
//lets convert the text
rInput = etrInput.getText().toString();
//lets extract the input characters to a chararray
char[] inputArray = rInput.toCharArray();
//lets get the numbers and make them a string
rNumbers = etrNumbers.getText().toString();
//lets extract them and place them in an chararray
char[] numbersArray = rNumbers.toCharArray();
for (int i=0; i<inputArray.length; i++){
rResult = rNumbers.replace(numbersArray, inputArray);
}
}
Clarification of the behaviour of my code above:
If the string rInput is smaller than the rNumbers array then the app crashes. If not then the only character that is encoded is the last character looped through the array.
I would like to be able to 'encode' all characters in the array, and also be able to encode any number of characters, not be limited to matching the length of the numbersArray.
How can I deal with the arrays of different lengths to substitute the values?
rInput must be 10character word
rNumbers can be any length string but only containing numbers.
The result should be that the numbers are "coded" in simple terms using the letters from the rInput charArray:
ACHROMATIC
0123456789
So encoding 5501 should give the answer MMAC, or 5512345 should give MMCHROM.
User enters a 10character word with no 2 characters the same (like the example achromatic)
User can then enter a series of numbers. (5501)
The substitution should then take the int value of each digit entered by the user, look up that value from the first word and substitute that character:
The fifth letter in the word achromatic is m (assuming you count from 0). The result of 5501 being substituted should be MMAC.
Thanks;
Andy
Anyone able to give me a steer on how i should adjust my code for this to work?

[Library] StoreBox, an open-source Android library for streamlining SharedPreferences

When getting a value from any preferences, whether private Activity or default shared preferences, you would normally have to get a reference to a SharedPreferences instance, for example using
Code:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(someContext);
Only after that we can start getting/saving the values, such as
Code:
String username = prefs.getString("username", "");
prefs.edit().putString("username", "androiduser").apply();
This can get tedious if the values need to be saved and retrieved from multiple places as the caller is always required to supply the key of the preference, know under what type it is saved, and know what default should be used. This can also become error prone as more keys get used. Putting commonly accessed preferences behind a wrapper is a reasonable solution, but still requires some boilerplate code.
What if however we could define an interface like
Code:
public interface MyPreferences {
@KeyByString("username")
String getUsername();
@KeyByString("username")
void setUsername(String value);
}
for everyone to use in order to save and get values? The caller doesn't need to worry about the key, neither needs to think about what type the key should use, and the process of retrieving/saving is hidden behind a method name with improved semantics.
With StoreBox that becomes reality. Given the above interface definition you can easily create an instance of the interface using
Code:
MyPreferences prefs = StoreBox.create(context, MyPreferences.class);
and you will be able to retrieve/save the value just by calling the defined methods
Code:
String username = prefs.getUsername();
prefs.setUsername("androiduser");
You can read more about the project here, including details on how it can be used and added to a project.
Let me know what you think and whether you find it useful. Thanks!
great! ty
Great work!

Categories

Resources