Toast in an AlertDialog in a try/catch - android

I am trying to have an error message when the use enters a number for an item that cannot be deleted in the database. I have gotten it so the user can delete an item from the database and I think used the try catch to avoid a run time error if the number does not exist. What I am trying to do is have a toast pop up when the user enter an invalid number. I have already looked at other similar postings on stack and have not have any luck. Here is my code. If you need me to post more code let me know.
public void onClick(DialogInterface dialog, int which) {
try {
String id=idNum.getText().toString();
long primaryId=Long.parseLong(id);
info.open();
info.deleteInspection(primaryId);
info.close();
dbInfo();
} catch(Exception e) {
Toast.makeText(getApplicationContext(), "Number not found", Toast.LENGTH_SHORT).show();
}
}

You could make your deleteInspection() method return a boolean value, telling wether or not a given id was deleted. Then check for it in your onClick method:
boolean result = info.deleteInspection(primaryId);
if(!result) {
Toast.makeText(getApplicationContext(), "Number not found", Toast.LENGTH_SHORT).show();
}

It's not about try/catch here, that you want to post "number not found"
the thing you need is the return the result from your Database that it found this id to delete or not
As Soren.Qvist said.
you need to return some value from your Database to your code (maybe -1, false, etc.) and check at it

Related

Trying to get an Android jabber app to check for a string in new messages and return a toast message

I have been able to create the if statement that checks for the string and it returns the toast message that i created but it keeps showing the toast message every time i open the chat. even if the most recent message doesn't contain the string I am looking for so i am assume it isn't checking to see if it is the last message received and it doesn't check to see if it is unread. the code is below. the reason i am trying to do this is because my parents share a facebook account and i want an easy way to display if the message is signed mom or dad. the code below only has the check for mom once it works i will be adding the check for dad signature. I am using the open source message client Xabber. Thank you for help.
public void setVisibleChat(String account, String user) {
final boolean remove = !AccountManager.getInstance()
.getArchiveMode(account).saveLocally();
AbstractChat chat = getChat(account, user);
if (chat == null)
chat = createChat(account, user);
else {
// Mark messages as read and them delete from db if necessary.
final ArrayList<MessageItem> messageItems = new ArrayList<MessageItem>();
for (MessageItem messageItem : chat.getMessages()) {
if (!messageItem.isRead()) {
messageItem.markAsRead();
messageItems.add(messageItem);
}
if (chat.getLastText().contains("Mom") && (!messageItem.isRead()));{
Toast.makeText(Application.getInstance(), "Message from Mom!", Toast.LENGTH_SHORT).show();
}
}
Application.getInstance().runInBackground(new Runnable() {
#Override
public void run() {
Collection<Long> ids = getMessageIds(messageItems, remove);
if (remove)
MessageTable.getInstance().removeMessages(ids);
else
MessageTable.getInstance().markAsRead(ids);
}
});
}
visibleChat = chat;
}
You've got an extra semi-colon here
if (chat.getLastText().contains("Mom") && (!messageItem.isRead())); <------
So your next block of code containing the Toast show statement will always be executed.
Remove the semi-colon

Android not waiting for DB response before finishing statement

I have an interesting problem that I've never run into in programming before. I have an onClickListener that does a lot of username and password checks (makes sure the username is proper length, not taken, etc). I'm using MobDB, and I was using a conditional statement that would return a row if the username already existed. The problem is that the Listener skips the DB and goes to the final check that, if everything works, posts a new username and password to my DB. How can I make it wait for a response from the DB before skipping to the last check?
Here is the relevant code:
usernamecheck3 = true;
MobDB.getInstance().execute(APP_KEY, null, rd, null, false, new MobDBResponseListener() {
#Override public void mobDBSuccessResponse() {
usernamecheck3 = false;
Log.e("mobdbSuccess:", "success");
}
#Override public void mobDBResponse(Vector<HashMap<String, Object[]>> row) {
}
#Override public void mobDBResponse(String jsonObj) {
/*Log.e("mobdbSuccess:", "jsonObj");
Log.e("mobdbSuccess:", jsonObj);
JSONObject mainObject;
try {
mainObject = new JSONObject(jsonObj);
// need to parse the json object.
} catch (JSONException e1) {
e1.printStackTrace();
} */
}
#Override public void mobDBFileResponse(String fileName, byte[] fileData) {
//get file name with extension and file byte array
}
#Override public void mobDBErrorResponse(Integer errValue, String errMsg) {
usernamecheck3 = false;
Log.e("doesnt", "work");
}
});
if(usernamecheck3 == false){
Toast.makeText(getApplicationContext(), "Username is taken, please choose another", Toast.LENGTH_SHORT).show();
}
Basically the check always returns true, and then logcat will say mobdbSuccess: success, which should have set the Bool to false.
Thanks.
MobDBResponseListener is executing on a different thread. What happens here is that the processing is split, while a thread is doing the query, the main thread on which you added the listener, skips right ahead to the validation. Your best bet is to place the validation inside the MobDBResponseListener, on the mobDBResponse method.
Try to debug your code and calls, the Listener may be using an async task. If so, you may do anything you please from the response method, as it will be executing in the main thread again. Otherwise, you should look at solutions that handle threaded execution like Handlers

Standalone return expression explanation

I was online looking at some android coding examples and i came across a method that had a return expression by itself,and i was wondering if someone could explain what that means.
Here is the code sample:
if(tempText.getText().length() ==0){
Toast.makeText(this, "Please enter a valid number", Toast.LENGTH_LONG).show();
return;
}
This is the If condition which checks for the length of the text which is "0" or not. If its "0" then it will show the Toast message and will return from or exit from the if loop an no further execution will processed.
using if condition you are checking for the length of text, if it is 0 then you are showing Toast
Using a return Keyword within a class, with a method
A method returning nothing
public void Void_Method()
{
<statements>
return;
}
A method returning a String
public String String_Method()
{
String s = "its Ridiculous to do such kind of work, people here are just aim less";
return s;
}
A method returning an Int value
public int Int_Method()
{
int i = 5;
return(i);
}
I hope this will help you understand the use of return keyword, and as name suggest - The return keyword is always used with a method only to specify that the method is going to return something.

How to keep activity on Force Close?

I have this piece of code that's really prone to errors so I wrapped it with try{}catch statement. I don't want to go back to the previous activity, I just want it to stay on the current activity so that the user can edit whatever is wrong with them.
How do I implement this?
try{
orgi.insertOrThrow(tableName, null, values);
Toast.makeText(this, "You have successfully created a new profile!", 2).show();
gotoProfileList();
Log.e(getClass().getSimpleName(),"Successfully added to database");
}catch(SQLiteException se){
Log.e(getClass().getSimpleName(), "Database connection failed!" + se);
//Stay in this activity...
}finally{
if (orgi != null){
orgi.close();
}
}
Forget it, I was able to solve my own problem by showing up an alertDialog that tells the user about the error. Thanks anyways. :)
try{
orgi.insertOrThrow(tableName, null, values);
Toast.makeText(this, "You have successfully created a new profile!", 2).show();
gotoProfileList();
Log.e(getClass().getSimpleName(),"Successfully added to database");
}catch(SQLiteException se){
Log.e(getClass().getSimpleName(), "Database connection failed!" + se);
displayError();
//stayInThisActivity();
}finally{
if (orgi != null){
}
public void displayError(){
AlertDialog.Builder error = new AlertDialog.Builder(this);
error.setMessage("That profile name already exists, try another one.").setCancelable(false).setPositiveButton("Yes",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = error.create();
alert.setTitle("Error");
alert.show();
}
Force closes are caused by uncaught exceptions. You only catche the SQLiteException in your example. You need to catch other Exceptions and handle them gracefully.
Now a classical cause for FCs are use of null objects and resulting NullPointerExceptions. You shouldn't catch these. Your application will be too messed up to continue correctly in many cases. You can read more here: Catch_NullPointerException
In any case, you should run the app in the emulator or on a connected phone, cause the crash and then log into the device log with DDMS or "adb logcat". See the backtrace, find the error, fix it. If your app is in the market, the market will list backtraces send by your users devices for you. If you do not (yet?) user Android Market, you can have your app remotely log stacktraces through a PHP script running on a web server with android-remote-stacktrace
BTW it is better to pass the Exception as third parameter to the Log methods instead of concatenating the second parameter to the exception (thereby implicitly calling toString()). In your example that would be:
Log.e(getClass().getSimpleName(), "Database connection failed!", se);

Can any body explain this code from Hello Android book

I cannot understand this code in page number 68-69 in Hello Android book. Some methods used in the code are new to me. Can anybody elaborate and explain the code.
private static final String TAG = "Sudoku" ;
private void openNewGameDialog() {
new AlertDialog.Builder(this)
.setTitle(R.string.new_game_title)
.setItems(R.array.difficulty, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface,int i) {
startGame(i);
}
})
.show();
}
private void startGame(int i) {
Log.d(TAG, "clicked on " + i);
// Start game here...
}
All it does is when you call openNewGameDialog() it will create an alertdialog with an assigned title and list of options from a resource file ("R.array.difficulty" is an integer value ultimately pointing to a string-array declared in the file /res/values/arrays.xml). An AlertDialog is a simple to create way of getting input from the user. It can also be used for output, but many prefer Toast for that task. The
.show() at the end of it brings the dialog to the foreground.
When the items are added in that call they are assigned an onClick listener which when an item is clicked it sends the index of that item to startGame. In that function it only sends a message including the index to the logcat debug system.

Categories

Resources