[17/03] Basic Java Tutorials and Android Examples! - Android Software Development

I'm by no means a good java developer, but i've had to search ALOT for some of these java examples and i thought others might benifeit from them.
For someone starting out in android app developing (especially someone with no prior Java background like me) it can be a very tedious and irritating process.
Hopefully this thread will help some people
This list is not very complete yet, but over the next few days i will be adding more examples (especially more Basic Java examples) and will be generally improving everything.
This is all written from my own memory and in my own words, but i can't remember where i learned it all from. If i'm using your or someone else's code please let me know so i can add credit where it's due!
Basic Java (general java examples)
All these 'Basic' tutorials are taken from my lectures at Manchester Metropolitan University where i'm taking Software Engineering. More will be added week by week!
Please be aware that these should be viewed in order, as any tutorial will assume you understand the ones before it.
All the files are included in a zip file attached to this post.
ALL CREDIT FOR THESE GO TO NICK COSTEN AND MMU UNIVERSITY!!
Those in RED are the latest tutorials.
******************************
Contents
- Lecture 1 - Values, Variables and Expressions
- Lecture 2 - Integers and Floating Point Numbers
- Lecture 3 - Casting and Type Boolean
- Lecture 4 - Object Types and Strings
- Lecture 5 - Input and Selection
- Lecture 6 - Complex Decision Making
- Lecture 7 - The 'for' Loop
- Lecture 8 - The 'while' Loop
- Lecture 9 - The 'do while' Loop
- Lecture 10 - Methods 1
- Lecture 11 - Methods 2
- Lecture 12 - Methods 3
- Lecture 13 - Test Case Design
- Lecture 14 - (OUTDATED. USE LECTURE 15)
- Lecture 15 - Applets 1
- Lecture 16 - Applets 2
- Lecture 17 - Applets 3
- Lecture 18 - Methods 3 (continued)
- Lecture 19 - Applet Test
- Code for 19 - Applet Code
- Lecture 20 - Objects 2
- Lecture 21 - Inheritance
*******************************

Android Java (Android specific examples)
******************************
Contents
- Root Access
- Buttons
- Exit Button
- Intents (next screen)
- Writing files to SDcard
*******************************
- Root Access
If you're developing an application that requires root access this is something you will need to know.
There are a few variations and diferent ways of acheiving this, but in my opinion, this is the most stable and problem free way i've found.
Simply insert this bit of code after the 'setContentView'.
Code:
try {
Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
{
os.writeBytes("mount -o rw,remount -t yaffs2 /dev/block/mtdblock03 /system\n" +
"exit \n");
os.flush();
process.waitFor();
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
What does this do?
Well, not only does it attempt to gain root access, it will pause the application untill the user grants it SU access. Without the "process.waitFor();' line (and the second 'catch'), your application can get a little messy because the screen will be displayed underneath.
The 'os.writeBytes' statement is, as you probable guessed, holds the command you want to execute as SU. In the above example, it will remount the filesystem as Read/Write and then exit. Remember, whatever commands you use, you will need to put a '\n' to signify the end of a line.
Warning: NEVER leave this bit completely blank, as your application will lock up. This is because you're opening up a command line and not closing it.
Simply chaning it to "exit\n" would not issue any command, but would still ask for root access, so this could be quite useful.
- Buttons
Perhaps one of the most important parts of your application; buttons are very simple to implement but can be a little confusing at first.
First of all you will need to place one on your "main.xml", or whatever yours is called, or type in the code below (which i prefer, as dragging it across from the Views list messes up the indentation and makes it hard to edit).
You don't have to bother with code for the button layout if you don't want to, as it can all be done from the properties menu, but i wouldn't advise you do it this way.
Type this in your 'main.xml':
Code:
<Button
android:text="Button01"
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
As you probably guessed, "wrap_content" can be replaced by either "fill_parent" or a numerical value in either 'px' or 'dp'. You should also give your button a more relevent name than Button01. For ease, i will call it ExampleButton.
Now that's done, move across to your .Java file. For your button to work we will need to implement a 'click listener', but first you will need to add the following to the top of your java file (before the Public Void bit).
Code:
private Button ExampleButton;
and then, in the main body add:
Code:
ExampleButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {;
*/ code goes here /*
}
});
Then your button is ready for code! (see below!)
- Exit Button
This one stumped me for a while, but as it turns out, it's incredibly simple to do. First you will need to create a button (see above) to act as the Exit button.
Once you've done that, add the following before the public void (this code can be added directly to the button, but i prefer doing it like this so it can be called from anywhere instead of typing it all out again).
For example:
Code:
public class Example extends Activity {
[B]public void killActivity() {
this.finish();
}[/B]
public void ...etc
Once done, this will allow you to simply insert "KillActivity();" to close your application!
So here's my exit button:
Code:
Exit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {;
killActivity();
}
});
Easy!
- Intents (next screen)
When your app starts getting a bit more advanced you may want more than one screen. This is quite easy to acheieve but can be quite messy if not done right.
Ok, first you'll have to create another .xml file (just copy and paste main.xml and delete all it's contents, that's the easy way! We'll call it screen2.xml).
Now, in your main.xml add the following code:
Code:
Intent a = new Intent(main.this, screen2.class);
startActivity(a);
You'll notice it will kick out a few errors. That's because your new screen2.xml hasn't been given an activity yet.
Open up your AndroidManifest.xml and add the following under your main activity (After the </activity> tag, but before the </application> tag!):
Code:
<activity android:name=".screen2"
android:label="@string/app_name">
<intent-filter>
</intent-filter>
</activity>
This should open up another identical activity over the top of the original one. If you want to close your original one instead of having both open you can just add your 'KillActivity();' after the code above!
- Writing files to SDcard
This little tutorial will tell you how to store files in your program and then on a button press, move them to a directory on your SDcard.
First of all, this tut requires you to create an additional folder for your app, so locate where the project is stored and under the folder 'res' (where you have drawable, layout, etc.) create another folder called "raw".
Now, whatever files you wish to store will have to be renamed.
For the files to be accepted you must remove any capital letters from the file name, any symbols and you also must remove any extension. So, a text file called 'Text1.2.txt' would have to be renamed to 'text1'. You must remember the extention though, as this will have to be restored manually later.
once your file is in place, you can create a directory for your files to go in. Using the command we learned for the 'Gaining Root Access' tutorial, we will create an 'Example' folder on your sdcard:
Code:
try {
Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
{
os.writeBytes("mkdir sdcard/example\n" +
"exit \n");
os.flush();
process.waitFor();
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
Once that's done, you can add the code to move the file (usually to a button press):
Code:
try {
InputStream ins = getResources().openRawResource(R.raw.text1);
int size = ins.available();
// Read the entire resource into a local byte buffer.
byte[] buffer = new byte[size];
ins.read(buffer);
ins.close();
FileOutputStream fos = new FileOutputStream("/sdcard/Example/Text1.2.txt");
fos.write(buffer);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
More to come!

Thank you thank you thank you!!!!! I am learning java for android apps right now and I really needed a quick source for some extra info. If u have any tutorials on learning java for development outside of android that would be great also.
Thanks a bunch,
Ljbaumer

Meltus said:
Once done, this will allow you to simply insert "KillActivity();" to close your application!
So here's my exit button:
Click to expand...
Click to collapse
That will only kill the activity that calls it. If your application has many activities you need to call finish() on all of them individually.

jgittins said:
That will only kill the activity that calls it. If your application has many activities you need to call finish() on all of them individually.
Click to expand...
Click to collapse
Yeah, but i'm writing it from the perspective of a basic android app with only 1 activity.
These are only proper basic tutorials to help people starting out

i've just started developing in general, with the hope of one day being a rom developer. These are the kind of resources that I need thanks!

Basic Universal java tutorials added to the first post.
ALL CREDIT FOR THESE GO TO NICK COSTEN (whoever he is!) AND MMU UNIVERSITY!!

[UPDATE]
Universal Java tutorials 'Methods 1' and 'Methods 2' added.

[UPDATE]
Universal Java Tutorials "Methods 3", "Test Case Design" and "Applets 1" added.

Good stuff...
I will def have to take a look sometime...hardware +...software/programming...D+ lol

[UPDATE]
Universal Java Tutorials "Applets 1" and "Applets 2" added.
Note: Lecture 14 has been replaced by a more up-to-date and concise Lecture 15.

Hi Meltus, just started on Android not long ago I'm still new to coding as well.
Would you assist me in how to code this part for my Android App?
I have a list of Name & Number both stored in String[] phoneNumbers, name.
How can I make a ListView with Checkbox and then upon clicking a button it does a check on those checked and add their position into an int[] ?
+-----------+----------+----------+
| Checkbox | Name | phoneNumbers|
+-----------+----------+----------+
Would be great if you could do up the code I'll definitely donate as a token of appreciation.
You could PM me if you prefer.
Cheers!

Cool,
Thanks for the tuts! You can never have enough material. I am a beginner, but i'm picking it up pretty fast.

Hehe. I took the easy way out and just use ListView with Multi Choice option.

Awesome man thanks for sharing. I'm not a dev but I can see how helpful this could be to someone who is starting out, because I know how much of a pain it can be searching for very specific things sometimes.
Thanks for the contribution!

Universal Tutorials added.
- Lecture 17 - Applets 3
- Lecture 18 - Methods 3 (continued)
- Lecture 19 - Applet Test
- Code for 19 - Applet Code
- Lecture 20 - Objects 2
- Lecture 21 - Inheritance

can u make a video tutorial pliz3?i realy bad at reading english and when i translate it on google translate its going wrong..

Related

event handling in dynamically created control

Hi all,
I am using eVC++ 4.0, and i've dynamically created a CListView like this:
Code:
lv.Create(0,_T(""),WS_CHILD|WS_VISIBLE,r,this,5);
but I dont know how to handle the events of this control... any ideas??
Mohammad
To get events from a listview (win32) I normally subclass it. I use the subclassing routine to post a message back to the parent when the user is doing something like tapping on it, then the windows routine can check whats selected etc and act on it. Is subclassing possible in mfc ?( I don't use it).
Thank u
but can anybody post some code??
thnx
Ok, I am a bit lazy to look up code at the moment, but here's something:
Yes, subclassing is possible in MFC. You just derive your class from the basic class provided like this:
Code:
class MyListView : pubic CListView
Then you add message handlers in the normal matter.
EDIT: The following passage is incorrect:
But I think subclassing may not be necessary in you case. List box controls send WM_COMMAND messages with notifications of major events like selection change to the parent window. All you have to do is to create a WM_COMMAND handler in your parent class.
Sorry I was thinking of ListBox not list view when I wrote it.
To manually add message handlers you need to put macros like ON_MESAGE or ON_COMMAND in the DECLARE_MESSAGE_MAP section of the class cpp file. All the detaisl are available on MSDN.
Are you saying that a listview will send the same WM_COMMAND as a list box in mfc? Dose this also happen in win32 made listviews. I have always thought it was a bit too tedious to find out when the user taps an item in the listview.
After reading your post levenum I had a quick look and it says that a WM_NOTIFY gets sent to the parent with a LVN_ITEMCHANGED for example. I had not used the LVN_**** because when I looked at them there was none that seem to deal with selections. I would guess that LVN_ITEMACTIVATE or LVN_ODSTATECHANGED would be usefull for this but then a second tap would not be picked up still leaving me wanting subclassing in many situations to get the users tap.
Ok, I have read what u wrote guys and my problem is almost solved, I used the OnNotify() method to handle messages sent from child controls like this:
Code:
BOOL CTest2Dlg::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult)
{
// TODO: Add your specialized code here and/or call the base class
if(wParam ==5 ) //5 is control ID
{
NMHDR *ph =(NMHDR*)lParam;
if(ph->code==NM_CLICK)
MessageBox("Click");
else if(ph->code==HDN_ITEMCLICK)
MessageBox("Item Click");
else
{
CString str;
str.Format("%d",ph->code);
MessageBox(str);
}
}
return CDialog::OnNotify(wParam, lParam, pResult);
}
Now there still a very small prolem: what messages should I handle for 'Selected Item Changed' event ?? I know its easy but I couldnt find it
Regards
mohgdeisat: I am sorry, I made a mistake about WM_COMMAND.
OdeeanRDeathshead is right, I was thinking of a list box not list view.
To make up for this, here is some sample code from a win32 dialog app that uses list view control. I hope it will be of some help:
Code:
//this is from the dialog window function:
case WM_NOTIFY: //handle events:
nmhdr = (LPNMHDR)lParam;
switch (nmhdr->idFrom)
{
case IDC_LEDLIST: //list control ID.
return OnLEDListEvent(hwndDlg, (LPNMLISTVIEW)lParam);
break;
}
break;
BOOL OnLEDListEvent(HWND hwndDlg, LPNMLISTVIEW nmlv)
{
/////
// Handles list view control notification messages
switch (nmlv->hdr.code)
{
case LVN_ITEMCHANGED:
return OnLEDListItemChanged(hwndDlg, nmlv);
break;
}
return 0;
}
BOOL OnLEDListItemChanged(HWND hwndDlg, LPNMLISTVIEW nmlv)
{
if (ListView_GetSelectionMark(nmlv->hdr.hwndFrom) != nmlv->iItem) return 0;
/* do what you need here */
return 0;
}
Don't mind the fact that I used 3 different functions. This is part of a bigger program and I am trying to keep things well organized without resorting to classes.
As I understand it, LVN_ITEMCHANGE is received for different reasons so I try to handle only the one coming from selected item. LVN_ITEMACTIVATE is only sent when you double click the item so if you just want to catch selection change you need to use LVN_ITEMCHANGE.
Once again, sorry for confusing you before.
thanx pals, good job!!!
I think my problem is now solved with ur help :wink:
Mohammad
Ok guys, I said that my problem was solved, yet, another problem arises...
When the list view is in the report mode, how can I determine when a header button is clicked, and determine which one was clicked???????
thanx in advance
To identify a header column click, you need to handle the WM_NOTIFY/HDN_ITEMCLICK message. Normally this message will be received by the header's parent control (i.e. the listview) -- some frameworks may redirect the message to the header control itself. I haven't worked with MFC in 10 years so I can't really if it reflects notification messages back to the control.
If you're trying to implement column sort, do yourself a favor and check out the Windows Template Library (WTL) at sourceforge.net. It's a set of C++ template classes that provide a thin yet useful wrapper around the standard Windows UI components. One of the classes is a sortable listview control. I've been using WTL with big Windows for more than 5 years -- you couldn't pay me to go back to MFC.
hi,
I have seen the WTL library and it seems very useful and time-saver, but I have a couple of questions about it:
1. can WTL 8.0 be installed with VC++ 6.0, specifically the appwizard stuff??how?? I see only javascript files of vc7.0 and 7.1 and 8.0!!
2. is there a good documentation about those classes??
Mohammad
I don't know about WTL 8; I'm still using WTL 7.5 with VS .Net 2003 for all my Win32 development. My guess is that it wouldn't work too well, as WTL is based on ATL, which has substantially changed between VC 6 and 7.
Good references for WTL include www.codeproject.com/wtl, and the WTL group over at Yahoo groups (reflected at www.gmane.org).

My newbie thread.

Some background: 10 years ago I had classes in basic, pascal, and c++( I missed something simple some where with functions or classes which messed me up in this I believe.)
So far I've watched a tutorial and set up my emulator and eclipse..
http://www.youtube.com/watch?v=z7bvrikkG7c
I then did a tutorial that ran my first program helloworld
http://www.youtube.com/watch?v=2gdhvwYUNJQ
I then did a tutorial and made a simple program that changes between two screens on a button click ( Why it is an hour long is beyond my understanding)
http://www.youtube.com/watch?v=m-C-QPGR2pM
I've proceeded to learning how to create menus and simply retrieved example code from the Google android site
Source: http://developer.android.com/guide/topics/ui/menus.html
Here's an example of this procedure, inside an Activity, wherein we create an Options Menu and handle item selections:
/* Creates the menu items */
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_NEW_GAME, 0, "New Game");
menu.add(0, MENU_QUIT, 0, "Quit");
return true;
}
/* Handles item selections */
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_NEW_GAME:
newGame();
return true;
case MENU_QUIT:
quit();
return true;
}
return false;
}
Click to expand...
Click to collapse
As I copy and pasted it into ecplise within an Activity, I realize there is some assumed information that I am missing when i received a bunch of errors
So.. I found A video tutorial
http://www.youtube.com/watch?v=6UYNnQOxCS8
and it instructs me to make sure I put these two lines of codes in first
Private static final int MENU1 = MENU.FIRST;
private static final int MENU2 = MENU.FIRST + 1;
I under line the menu's because it gives me errors on them as well... there seems to be some assumed knowledge I'm missing as well....
What specific piece of information am I missing to not have known that i would need those two lines as well as what I need to do to know the appropriate fix out of the suggestions they give me...
Are there any online tutorials or videos that'll bring me up to speed specifically with programming android apps... all the stuff I find just keeps leading me down a path to where I realize I've gotten ahead of myself because people are teaching things while assuming certain knowledge is known.
The tutorial I am following and getting errors on is for an 8th grade class of students...
Me: I'm pissed at that java toturial...
http://forum.xda-developers.com/showpost.php?p=6521891&postcount=6
Bastards.
Following the suggestion from this post
http://forum.xda-developers.com/showpost.php?p=6522089&postcount=7
I obtained a copy of Hello android.
Following the example to create a menu I used the code
I place this into my strings.xml
<string name="settings_label">Settings...</string>
name="settings_title">Sudoku settings</string>
<string
<string name="settings_shortcut">s</string>
<string name="music_title">Music</string>
<string name="music_summary">Play background music</string>
<string name="hints_title">Hints</string>
<string name="hints_summary">Show hints during play</string>
Click to expand...
Click to collapse
I place this into my main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/settings"
android:title="@string/settings_label"
android:alphabeticShortcut="@string/settings_shortcut" />
</menu>
Click to expand...
Click to collapse
I import this files into my src app.java
right uner the other imports
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
Click to expand...
Click to collapse
I place this inside my activity ( where I think it would belong since it doesn't say where to put it. ) and ERROR
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
Click to expand...
Click to collapse
Quick fix says that menu needs to be either a field or constast so i give it a go and click field and it modifies a file called R.java.
I go back to app.java and not only is the menu highlighted but now R.menu.menu is entirely highlighted and says cannot be resolved or is not a field..
I try to modify the R.java file to remove what its done...
It won't let me..
Epic fail. on the third tutorial to create a menu.
I guess ill redo everything in a new project and then do the quick fix making menu a constant....
[edit] never mind ill look else where for help
http://www.youtube.com/watch?v=X3QO0ffg2Tc&feature=related
ok the toturial looks like it will work but when he types in this line in his app.java
public boolean onCreateOptionsMenu(Menu menu) {
Click to expand...
Click to collapse
it is under lined with an error on his screen as well as mine and then he says he is importing the missing classes and the error just disappeas with no demonstrations of what missing classing or what key combination he used to import them...
http://www.google.com/#hl=en&q=impo...=f&aqi=&aql=&oq=&gs_rfai=&fp=d059ab474882bfe2
WOO HOO found what he left out...
Compiled and installed...
Boo hoo menu key does nothing!! time to go back through the other menu tutorials and see if i cant get it working now that i know of this hot key..
Went back to this toturial with the elusive import missing classes hotkey..
http://www.youtube.com/watch?v=6UYNnQOxCS8
It worked like a charm
just had to remove
newGame();
and
quit();
and i have buttons that do nothing so far
More missing pieces.
I created a new activity as shown to me in previous tutorials giving it its own seperate XML file in the res/layouts as well as a jave file and I made sure it is calling for the right layout.
I also added the activity in the androidmanifest as shown to me as well..
off this site
http://developer.android.com/guide/topics/ui/menus.html
I've taken the code to create menus.. ( i got it working )
I then followed this and made the changes
Set an intent for a single menu item
If you want to offer a specific menu item that launches a new Activity, then you can specifically define an Intent for the menu item with the setIntent() method.
For example, inside the onCreateOptionsMenu() method, you can define a new menu item with an Intent like this:
MenuItem menuItem = menu.add(0, PHOTO_PICKER_ID, 0, "Select Photo");
menuItem.setIntent(new Intent(this, PhotoPicker.class));
Android will automatically launch the Activity when the item is selected.
Note: This will not return a result to your Activity. If you wish to be returned a result, then do not use setIntent(). Instead, handle the selection as usual in the onOptionsMenuItemSelected() or onContextMenuItemSelected() callback and call startActivityForResult().
Click to expand...
Click to collapse
It doesn't work... I don't understand why the intent would be in the onCreateOptionsMenu... it doesn't seem to work so I tried the alternative and replaced setIntent with with startActivityForResult.. and then I noticed it says "As usual" in the onOptionsMenuItemSelected()... which is where I would think the code would belong in the first place... but when I originally failed and tried to move the code there it errors...
Is ever step of the way really going to be half assed instructions.. i was beginning to think I had the hang of this.
Are the instructions bad or am i missing something???
Guess ill go dig in my hello android book.
EDIT: Wow that helped
startActivity(new Intent(this, register.class));
Click to expand...
Click to collapse
guess that book is worth something after all...
guess im just intending to start an activity with a particular intent and setting an intent alone isn't going to start the activity.... i suppose there must be some purpose behind setting an intent as they had describe on the google page.. just not seeing it yet...
Got to what i wanted tho.

[Q] Review for my game/app

I´v published my first app on the Android Market. However I have little people in my direct suroundings who have Android Phones so hopefully there are a few people here who can help me by telling my what my application misses.
e.g. I think my app uses little battery power. So maybe anyone can confirm this to me?
becouse i am new to the forum (or .. well not new, but little posts) I can not put the link to my app here. Search on Triton Bubble Breaker on Appbrain or Market to download.
It is a bubble breaker game. Why I developed it when there are other alternatives on the market already? Because I missed the feeling I got when playing it on a old phone for the first time. Wanted to make it faster, simpler, free and maybe add some extra features (that should not be disturbing the simplicity of the game)
(when you are a coder.. I have (maybe a simple) question. When the game is finished I like to save the Score. However I can not do this from a DrawView? only from the main activity, so that i have to use menu buttons to call saving the score... is there a way to save data from view/drawview? )
Thanks in advance, and i wander what you think of my first attempt building a android app.
Good work! Very impressive for a first app!
for saving stuff, use these commands:
(put this at the begining of your class)
public static final String PREFERENCE_FILENAME = "AppGamePrefs";
(put this where you need it, usually located where you are doing the saving)
SharedPreferences gameSettings = getSharedPreferences("MyGamePreferences", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = gameSettings.edit();
(get saved data like this)
score=gameSettings.getInt("score", 0); //"score" is the saved variables name, 0 is the default value incase the variable "score" has not been saved yet
(save like this)
prefEditor.putInt("score", points); // saves to variable "score" with value of variable points (you can change the putInt to putString, putBoolean, etc.)
(this finalizes the save VERY IMPORTANT)
prefEditor.commit();
Hope that helps, keep up the good work!
thanx for the reply. Starting writing in Java (?) was getting used to. I did had some experience with coding in Matlab (if that can be labled programming )
I have tried your advice, I have come across the same code on other fora and samples from google. Only problem is that it doesn't work in the class I am programming in, the drawview class.
In essence my program is setup like this:
public class activity extends Activity
...
public void onCreate(Bundle savedInstanceState) {
...
setContentView(drawView);
...
}
.. some other functions for the menu (from which i can do the code for storing data!)
then it goes into the drawView.
Here my program just draws and draws, until there is a touch on the screen, then it will calculate the new situation. But at a given moment, the game is finished. Then i will draw the finish screen (in the same drawview). I can not get out of this drawview. So i can not do setContentView(results_layout) or something like that. And i can not call the code for saving data because that can not be defined in that class (according to Eclipse).
public class DrawView extends View implements OnTouchListener {
...
@Override protected void onDraw(Canvas canvas) {
Draw everything
...
if game_end = true then {
drawResults
save-code here gives error
}
...
}
public boolean onTouch(View view, MotionEvent event) {
calculate everyting
...
game_end = check_game_end(); //return true or false
}
this is my code in essence. Ofcourse it not all, but this i hope you get my idea/problem.
Thanx for the response again

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'

the dreaded asynctask

Hi guys,
i've started making an app recently.. and i needed a task to run in the backgound every 2 or 5 minutes.. and i collect the data and i display it when the app is opened.. so am using a sync task.... I'm having a bit of diffculty unerstanding how its used as every example is different..
and FYI am using a seperate .java file to runt he asynctask...
When we go through the android developers page this is the code we see...
They start with
Code:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
1) whats the deal with the URL Integer Long ????? If i skip it what will happen???
next is this
Code:
protected void onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]);
2) whats the integer doig there?? even if its not used in the function they put it... whats the deal??
3) Also how do we pass values like strings to a class??? i know about functions but the functions used in this class are like a group like so i cant exactly pass values to just one particular function...
Async Task
nvyaniv said:
Hi guys,
i've started making an app recently.. and i needed a task to run in the backgound every 2 or 5 minutes.. and i collect the data and i display it when the app is opened.. so am using a sync task.... I'm having a bit of diffculty unerstanding how its used as every example is different..
and FYI am using a seperate .java file to runt he asynctask...
When we go through the android developers page this is the code we see...
They start with
Code:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
1) whats the deal with the URL Integer Long ????? If i skip it what will happen???
next is this
Code:
protected void onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]);
2) whats the integer doig there?? even if its not used in the function they put it... whats the deal??
3) Also how do we pass values like strings to a class??? i know about functions but the functions used in this class are like a group like so i cant exactly pass values to just one particular function...
Click to expand...
Click to collapse
Code:
public class async extends AsyncTask<Params , Progress , Result>{
}
here 'params' is the argument that is input to the object of the class...
for eg..
Code:
public class async extends AsyncTask<int , Progress , Result>{
}
then when you will call its object then it will like this.
Code:
public class async extends AsyncTask<int , Progress , Result>{
}
async c;
c.execute(10); // passed int value 10 to execute the async thread in the background...
it has 3 methods that should be implemented
Code:
class load extends AsyncTask<int, Void, Void>{
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// all the ui updation is done here after doing the calculation...
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
// before the starting of calculation if ui needs to be adjusted then it is done here
}
@Override
protected Void doInBackground(int... arg0) {
// TODO Auto-generated method stub
// all calculation stuf is done here
}
}
IF U WANT SOME MORE HELP REGARDING ASYNC TASK THEN PLZZZ ASK AGAIN....
nvyaniv said:
Hi guys,
i've started making an app recently.. and i needed a task to run in the backgound every 2 or 5 minutes.. and i collect the data and i display it when the app is opened.. so am using a sync task.... I'm having a bit of diffculty unerstanding how its used as every example is different..
and FYI am using a seperate .java file to runt he asynctask...
When we go through the android developers page this is the code we see...
They start with
Code:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
1) whats the deal with the URL Integer Long ????? If i skip it what will happen???
next is this
Code:
protected void onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]);
2) whats the integer doig there?? even if its not used in the function they put it... whats the deal??
3) Also how do we pass values like strings to a class??? i know about functions but the functions used in this class are like a group like so i cant exactly pass values to just one particular function...
Click to expand...
Click to collapse
OK, so you're probably using it in a service, aren't you?
First of all, carefully read the tutorials here and here on vogella, to help you understand what it does.
1) these are the type of variables that are passed to the respective methods:
An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute
Click to expand...
Click to collapse
The Params get passed to the onPreExecute method, the Progress is the one you need to pass calling publishProgress and which is passed to onProgressUpdate. The result one should be returned by your doInBackground method and gets passed to the onPostExecute.
2) the Integer... Is actually an array of the corresponding object to int. Just ignore it and use the progress[0] as if it was a normal int.
3) set your Params variable to String so
AsyncTask <String, Integer, String> if you want to return a string as well
Ok i think i'm getting it... But when we say "Params , Progress , Result" its still a bit confusing..
we first hit pre execute then do iin BG then post execute... But the order in which the params are stated are not the same ...
when i give string first it always takes it for the during BG process... not for the pre execute...
For ex i say asymctask<int, string,void>
so my pre execute should get a int..
then my bg process should get a string..
the post execute should get nothing..
am i right???
nvyaniv said:
Ok i think i'm getting it... But when we say "Params , Progress , Result" its still a bit confusing..
we first hit pre execute then do iin BG then post execute... But the order in which the params are stated are not the same ...
when i give string first it always takes it for the during BG process... not for the pre execute...
For ex i say asymctask<int, string,void>
so my pre execute should get a int..
then my bg process should get a string..
the post execute should get nothing..
am i right???
Click to expand...
Click to collapse
Almost, the Progress variable is passed to the onProgressUpdate. This is something to indicate progress and publish on the UI Thread (for instance update a progress bar), usually an Integer. You can update the Progress from your doInBackground method by calling publishProgress, passing a Progress variable.
The point of this is that the doInBackground method runs in a seperate thread and all other methods run in the UI Thread! So you can't directly pass data between those, only with these values. Consider using a Bundle if you want to pass more than one variable!

Categories

Resources