• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Code in try {} doesn't seem to be running?

icydash

Newbie
Jun 8, 2011
12
0
Hey guys. So I have some code that, upon clicking an item on a list, creates an AlertDialog which asks you if you'd like to delete the item. For some reason, when you hit the "yes" button, the code doesn't seem to be deleting the user from the sql database. There are no errors or anything, though, in compiling or when i run the program.

Strangely, actually, the code in the "try {}" doesn't seem to be running at all. I tried putting a Toast in there, and it doesn't come up, which leads me to think the try {} code isn't executing.

Any ideas? The relevant parts of the code is below, but i can give you my full code if necessary.

Code:
lv1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() 
        { 
        	@Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, 
                int position, long id) 
            {                 
              //dialogue
              final CharSequence name = ((TextView) view).getText();
              AlertDialog.Builder builder = new AlertDialog.Builder(uNear.this);
              builder.setMessage("Select an Option")
                     .setPositiveButton("User Information", new DialogInterface.OnClickListener() {
                         public void onClick(DialogInterface dialog, int id) {
                             //----------------alert "user info"
                         }
                     })
                     .setNegativeButton("Delete User", new DialogInterface.OnClickListener() {
                         public void onClick(DialogInterface dialog, int id) {
                             //alert "are you sure?"
               
                             AlertDialog.Builder subbuilder1 = new AlertDialog.Builder(uNear.this);
                             subbuilder1.setMessage("Are you sure you want to delete "+name+"?")
                                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int id) {
                            			    
                            				//--------------------DATABASE-----------------------    
                            		         SQLiteDatabase myDB = null;
                            		         
                            		         try {
                            				        myDB = openOrCreateDatabase("uNearDatabase", MODE_PRIVATE, null);
                            			            myDB.execSQL("DELETE * FROM uNearTable WHERE Field1='"+name+"';");
                            				        Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_SHORT).show(); 
                            	              }
                            	        	  catch(Exception e) 
                            	        	  {
                            	        	       Log.e("Error", "Error", e);
                            	        	  } 
                            	        	  finally 
                            	        	  {
                            	        	      if (myDB != null)
                            	        	           myDB.close();
                            	        	  }
                            		         //-------------------------------------------------------------  
                            	        	
                            		        //Toast.makeText(getApplicationContext(), name+" deleted", Toast.LENGTH_SHORT).show(); 
                                        }
                                    })
                                    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int id) {
                                             
                                        }
                                    });
                             subbuilder1.show();
                           //end secondary alert
                         }
                     });
              builder.show();
              //end dialogue
          	return true;
            } 
          });
 
maybe your method to open the db is not correct
try debugging , set a bullet point on the SQLiteDatabase initialization line and click on the debug icon
walk with it and see what's happening exactly .. if it goes inside try then to catch, then you are doing something wrong
you can also check the log in DDMS to see what kind of exception is being thrown

if that's too much .. then put a toast inside the catch block
if that one gets executed , then there is something wrong with the try block , see what you are doing

I'm assuming the part where u say that there is no errors or anything actually means that you are not getting a force close (crash) , you won't get that if you are catching the exception


Edit: I'm not an SQL expert , but shouldn't the line
Code:
 myDB.execSQL("DELETE * FROM uNearTable WHERE Field1='"+name+"';");
be
Code:
 myDB.execSQL("DELETE * FROM uNearTable WHERE Field1="+name);
?
 
Upvote 0
I'm assuming you are using eclipse
when you downloaded the ADT plugin for eclipse , you can also check something called DDMS
if you enable it in eclipse , you should get a tab on the top right that says DDMS
that'll show you the app log and you can also access the data files [pull and push files including databases] ,take screenshots, and simulate gps

edit: pressing on the thanks button is appreciated :p
 
  • Like
Reactions: alostpacket
Upvote 0
Havent looked too closely at this but for reference, SQL statements should be built with a bind, not by manually constructing a string. When you manually contruct a string you open yourself up to SQL injection attacks.

This is one of those things I'm still going back and fixing lots of old code for because I never took the time to learn it correctly the 1st time, so I thought I would point it out :)

Also I suspect this is a scope issue.

openOrCreateDatabase() is not a global method you can call from onClick()


I would expect the error to look something like:

The method openOrCreateDatabase(String, int, null) is undefined for the type new View.OnClickListener(){}"
You need to call that method on something that is a subclass of Context (such as an Activity).

Whenever I create onClick() functions I always call out to a different private or protected method to make the scope clear and code more readable.

For example:
Code:
myButton.setOnClickListener( new OnClickListener()  
{    
    @Override public void onClick( View v )     
    {
         handleClick( v );
    }
});

protected void handleClick( View v )
{
   //do something here, if this method is in the activity
   // then you can call the methods of the activity directly
}
hth
 
  • Like
Reactions: JiMMaR
Upvote 0
Whenever I create onClick() functions I always call out to a different private or protected method to make the scope clear and code more readable.

why not define the onClickListener as a saperate object ? instead of calling a function from inside ? I've always done that, doesn't exactly look pretty .. but I think it looks less uglier than defining a new listener inside the onClick function

ps: thanks for the thanks :p
 
Upvote 0
why not define the onClickListener as a saperate object ? instead of calling a function from inside ? I've always done that, doesn't exactly look pretty .. but I think it looks less uglier than defining a new listener inside the onClick function

ps: thanks for the thanks :p


Yes, that's actually how I generally do it too, for readability. Not sure why I wrote it that way, was supposed to be a fast response heh.

Edit: I should note though, I'd still call out of the View.OnClickListener object to make the scope more obvious and/or if I needed access to the Application/Activity Context.
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones