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.
Related
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..
Howdy all. Have a question about allowing users to configure any widgets they place from an app I am developing.
I came across PreferenceActivity and it seems perfect, however I have no idea how to implement it. I have got a configuration activity working so when the user places a widget on a homescreen t opens a configuration activity.
So is there a way to use PreferenceActivity instead? Or PreferencceFragment as it is now. I already have a preference xml file to define the layout but I can't get the java to launch it.
Here is the Java I have so far:
Code:
public class PreferenceTest extends PreferenceFragment {
private static String CONFIGURE_ACTION = "android.appwidget.action.APPWIDGET_CONFIGURE";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
Any ideas? Thanks in advance! I was told this would be the best place to ask by a mod.
RED_ said:
Howdy all. Have a question about allowing users to configure any widgets they place from an app I am developing.
I came across PreferenceActivity and it seems perfect, however I have no idea how to implement it. I have got a configuration activity working so when the user places a widget on a homescreen t opens a configuration activity.
So is there a way to use PreferenceActivity instead? Or PreferencceFragment as it is now. I already have a preference xml file to define the layout but I can't get the java to launch it.
Here is the Java I have so far:
Code:
public class PreferenceTest extends PreferenceFragment {
private static String CONFIGURE_ACTION = "android.appwidget.action.APPWIDGET_CONFIGURE";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
Any ideas? Thanks in advance! I was told this would be the best place to ask by a mod.
Click to expand...
Click to collapse
you can call what ever you want as long as it is in your manifest.
you would just need to change the "android:configure=" to point to the new activity. eg.
android:configure="com.epic.widget.ConfigurationScreenActivity"
i would recommend a PreferenceActivity they are easy to code and run on there own. also that the PreferenceFrag wont work pre honeycomb.
if you know how to use a Activity you can use a PreferenceActivity.
https://github.com/pvyParts/EDT-Twe...om/roman/tweaks/activities/ClockActivity.java
this is a link my git hub, was a fork of someone else original but it does the job.
or use this code here if you are targeting post honeycomb devices.
http://developer.android.com/reference/android/preference/PreferenceActivity.html
Pvy.
Thanks for replying. I assumed PreferenceFragment worked pre-honycomb just that it was an updated way of working. Fair enough, guess I'll go back to PreferenceActivity. Only problem with that is that "addPreferencesFromResource(R.xml.preferences);" shows up as depreciated with PreferenceActivity. It's a warning only but still, it gets a strike-through so I don't know if it is actually being called.
This is my android:configure - android:configure="com.android.wifi.PreferenceTest" So it's calling the PreferenceFragment I posted above.
My manifest has the following activity that relates to the java code above:
Code:
<activity
android:name=".PreferenceTest"
android:label="God knows what">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
</intent-filter>
</activity>
When I place the widget on the homescreen however, an alert shows up telling me my app has stopped. Can't see why.
Thanks for the github link as well, I'll dissect that and see if I can learn more!
EDIT: IT WORKS! I added the following from the github link to my code and it now works.
Code:
String pref;
Context mContext;
mContext = this.getApplicationContext();
PreferenceScreen prefs = getPreferenceScreen();
RED_ said:
Thanks for replying. I assumed PreferenceFragment worked pre-honycomb just that it was an updated way of working. Fair enough, guess I'll go back to PreferenceActivity. Only problem with that is that "addPreferencesFromResource(R.xml.preferences);" shows up as depreciated with PreferenceActivity. It's a warning only but still, it gets a strike-through so I don't know if it is actually being called.
This is my android:configure - android:configure="com.android.wifi.PreferenceTest" So it's calling the PreferenceFragment I posted above.
My manifest has the following activity that relates to the java code above:
Code:
<activity
android:name=".PreferenceTest"
android:label="God knows what">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
</intent-filter>
</activity>
When I place the widget on the homescreen however, an alert shows up telling me my app has stopped. Can't see why.
Thanks for the github link as well, I'll dissect that and see if I can learn more!
EDIT: IT WORKS! I added the following from the github link to my code and it now works.
Code:
String pref;
Context mContext;
mContext = this.getApplicationContext();
PreferenceScreen prefs = getPreferenceScreen();
Click to expand...
Click to collapse
Glad you got it sorted.
Pvy
Sent from my LT18i using xda premium
Hi All!
I'm new here and new to the Android Eclipse/development side and I'm having a bit of a problem with a java script.
I have a small advertising app with 2 buttons (looking to expand to 4 but that's a different thread), one for Facebook (Button1) and one for Twitter (Button2) and Button2 won't work until Button1 is clicked. It works fine except for that.
Any ideas on solutions? Aggravating me a bit lol
Thanks!!
We will need to see your layout XML and java code to help out.
not sure how i'd do that atm cos im a new member? i know that some admin members get pi**y when you dont wrap any code for formatting reasons??
i've got ready and i can imagine a senior member such as yourself will notice the mistake straight away.
Use pastebin http://pastebin.com/
not sure how to use it, just tried and i got the same message about not being able to post things outside links until 10 posts and so on? even tried pasting the raw text and still wouldnt let me
any suggestions?
thanks
Or use the CODE tags: [CODE ] and [/CODE ], but without the extra spaces.
adamj1910 said:
not sure how to use it, just tried and i got the same message about not being able to post things outside links until 10 posts and so on? even tried pasting the raw text and still wouldnt let me
any suggestions?
thanks
Click to expand...
Click to collapse
Take http off or www and just paste it as text
pastebin.com/4Q0g9ryg
pastebin.com/rHvFePNM
hopefully that should work?
thanks!
You had your button definition in the wrong place for your twitter button
Code:
package com.MYAPP.MYAPP;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //Set the screen's view to your xml file
Button facebookbutton = (Button) findViewById(R.id.button1); // Retrieve the button from the XML file
facebookbutton.setOnClickListener(new View.OnClickListener() { //Add a listener for when the button is pressed
[user=439709]@override[/user]
public void onClick(View v) {
sendToFacebook();
}
});
Button twitterbutton = (Button) findViewById(R.id.button2); // Retrieve the button from the XML file
twitterbutton.setOnClickListener(new View.OnClickListener() { //Add a listener for when the button is pressed
[user=439709]@override[/user]
public void onClick(View v) {
sendToTwitter();
}
});
}
protected void sendToFacebook() {
String url = "https://www.facebook.com"; // You could have this at the top of the class as a constant, or pass it in as a method variable, if you wish to send to multiple websites
Intent i = new Intent(Intent.ACTION_VIEW); // Create a new intent - stating you want to 'view something'
i.setData(Uri.parse(url)); // Add the url data (allowing android to realise you want to open the browser)
startActivity(i); // Go go go!
}
protected void sendToTwitter() {
String url = "https://www.twitter.com"; // You could have this at the top of the class as a constant, or pass it in as a method variable, if you wish to send to multiple websites
Intent i = new Intent(Intent.ACTION_VIEW); // Create a new intent - stating you want to 'view something'
i.setData(Uri.parse(url)); // Add the url data (allowing android to realise you want to open the browser)
startActivity(i); // Go go go!
}
}
Thanks for that ill give that a try!!! Really appreciate it
Sent from my GT-I9305 using xda app-developers app
it works!!! would i just repeat that for any additional buttons, same format;
Button onclicklistener etc etc etc
Button onclicklistener etc etc etc
protected void
protected void
and so on
does it work like that?
thanks!
Yes, just besure you place the code in your onCreate method for defining your buttons
Ill remember that haha thanks again really appreciate it!! =D
Sent from my GT-I9305 using xda app-developers app
zalez said:
Yes, just besure you place the code in your onCreate method for defining your buttons
Click to expand...
Click to collapse
Hey zalez
I just tried adding a youtube button in the exact same format obviously changing the button source and so on, eclipse couldn't find any problems so I ran it and it just crashed the app on the avd and on a real device?
Sent from my GT-I9305 using xda app-developers app
There are multiple ways. I like setting a listener, then using an onClick method with switch-case statements for every button.
Sent from my GT-I9300 using Tapatalk 4
you've lost me lol i understand the onclick but switch cases? if you check my .xml and .java from pastebin or the .java that another member posted further up ^ ^ ^ ^ that might show where im going wrong?
edit *** i just googled the switch case thing and ive seen it before, just not sure how i'd implement it into my .java?
thanks
bump?
adamj1910 said:
you've lost me lol i understand the onclick but switch cases? if you check my .xml and .java from pastebin or the .java that another member posted further up ^ ^ ^ ^ that might show where im going wrong?
edit *** i just googled the switch case thing and ive seen it before, just not sure how i'd implement it into my .java?
thanks
Click to expand...
Click to collapse
Sorry, I'm away. I'll look up an example from one of my apps later.
Basically, just make an onClickListener. You are then required to use that interface and implement the onClick method. Do that, you have an empty method, with a parameter like View v.
Then, make a switch statement for v.getId(), and do cases for the buttons (use their XML IDs!) that you have.
Hope that's kind of clear?
Sent from my GT-I9300 using Tapatalk 4
bassie1995 said:
Sorry, I'm away. I'll look up an example from one of my apps later.
Basically, just make an onClickListener. You are then required to use that interface and implement the onClick method. Do that, you have an empty method, with a parameter like View v.
Then, make a switch statement for v.getId(), and do cases for the buttons (use their XML IDs!) that you have.
Hope that's kind of clear?
Sent from my GT-I9300 using Tapatalk 4
Click to expand...
Click to collapse
That's actually starting to make sense! But it's just putting that into a script, not really my strong point yet, I'm more of a designer lol
It would be good if you could find some examples for URL buttons, it'd really help. Thanks!
There shouldn't have been any issues adding more. I would need to see your updated java code. Using switch cases is a good idea but at this point, if I was you, I would avoid it for now until you get the hang of the basics. Also, a log cat would be beneficial in debugging.
Guys. Help me. I'm learning to ''Respond to the Send Button'' but I don't know what to do. I follow this step but I still can't understand.
http://developer.android.com/training/basics/firstapp/starting-activity.html
If you guys can help me, I'm really grateful.
Merivex95 said:
Guys. Help me. I'm learning to ''Respond to the Send Button'' but I don't know what to do. I follow this step but I still can't understand.
http://developer.android.com/trainin...-activity.html
If you guys can help me, I'm really grateful.
Click to expand...
Click to collapse
That link didn't work, but if you Google 'android java button onclick listener' that will get you started with plenty of helpful links.
When the button is clicked, you then need to check the content of the Edit Text field - Something like this:
Code:
public void onClick(final View v) {
final String commandText = inputText.getText().toString();
if (commandText != null && commandText.length() > 0) {
Where inputText is the Edit Text field you've assigned in your OnCreate method.
Getting started involves a lot of head scratching, but don't give up! There's so much Open Source code out there, that the penny will drop soon.
brandall said:
That link didn't work, but if you Google 'android java button onclick listener' that will get you started with plenty of helpful links.
When the button is clicked, you then need to check the content of the Edit Text field - Something like this:
Code:
public void onClick(final View v) {
final String commandText = inputText.getText().toString();
if (commandText != null && commandText.length() > 0) {
Where inputText is the Edit Text field you've assigned in your OnCreate method.
Getting started involves a lot of head scratching, but don't give up! There's so much Open Source code out there, that the penny will drop soon.
Click to expand...
Click to collapse
OMG !! this is the link : http://developer.android.com/training/basics/firstapp/starting-activity.html
I don't know how to compile the code properly. hummmm ... maybe you can help me by correcting my code ?
Paste code (variables, functions, etc) inside your MainActivity class and don't write 3 dots, it's just a replacement for skipped parts
Mikanoshi said:
Paste code (variables, functions, etc) inside your MainActivity class and don't write 3 dots, it's just a replacement for skipped parts
Click to expand...
Click to collapse
Ohhh yeahhh :cyclops: .. how can I be so stupid
btw ,, where should I put this code ?
code:
Code:
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
Code:
Merivex95 said:
btw ,, where should I put this code ?
Click to expand...
Click to collapse
Replace existing onCreate function with it.
Mikanoshi said:
Replace existing onCreate function with it.
Click to expand...
Click to collapse
But I get an error after doing that ..
Merivex95 said:
But I get an error after doing that ..
Click to expand...
Click to collapse
You need to import TextView and Intent first. Just hover over the names and select import from the menu you will see.
Seriously, my advice would be to learn and understand Java first. It doesn't make sense to learn Android if you don't know Java (and it won't work).
nikwen said:
You need to import TextView and Intent first. Just hover over the names and select import from the menu you will see.
Seriously, my advice would be to learn and understand Java first. It doesn't make sense to learn Android if you don't know Java (and it won't work).
Click to expand...
Click to collapse
Thanks for the advice
nikwen said:
It doesn't make sense to learn Android if you don't know Java (and it won't work).
Click to expand...
Click to collapse
Unless you know any other similar languages. Java was the easiest lang to learn for me, after years of writing on Object Pascal/Object C/C++/JavaScript/PHP. The most troublesome part of coding for Android is creating an UI, especially cross-version compatible :laugh:
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!