Guys!! Please help me!! - Java for Android App Development

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:

Related

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.

add new calendar event

please help ,
i'm trying to make an app which i need to add event to the phone calendar by development of-course, how can i start, any sample code, i'm new to android development
moamenam said:
please help ,
i'm trying to make an app which i need to add event to the phone calendar by development of-course, how can i start, any sample code, i'm new to android development
Click to expand...
Click to collapse
if there is any document i can read please support me with it, i really need to make my first android app
code snipped
Code:
private void SetCalenderEntry(String calID, long date, String subject, String body, String location)
{
ContentValues event = new ContentValues();
event.put("calendar_id", calID);
event.put("title", subject);
event.put("description", body);
event.put("eventLocation", location);
long startTime = date;
event.put("dtstart", startTime);
event.put("dtend", startTime);
Uri eventsUri = Uri.parse("content://calendar/events");
getContentResolver().insert(eventsUri, event);
}

Button2 doesnt work until Button1 is clicked

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.

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!

[Q] Need help with a program.

public void click(View view) {
String one = "one";
EditText et = (EditText)findViewById(R.id.editText1);
String entered_text = et.getText().toString();
if(et.getText().toString() == one){
TextView tv1 = (TextView)findViewById(R.id.textView1);
tv1.setText("Correct!");
}
else{
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(one+entered_text); }
}
This is a code snippet extracted from my program, i didn't post the whole program because it wasn't necessary, as the program runs fine without any runtime exceptions.
So, the program when executed on eclipse doesn't show any errors and runs fine, but when run the "if" condition "et.getText().toString() == "one"" always returns false even when the "entered_text" is "one" i.e.; it never prints "correct!" and the code always prints "one+entered_text" that is the statement in the else clause. And the interesting thing is, if you enter "one" the output will be "oneone", that is the else statement.
Please help me where i went wrong.
Thanks in advance.
You're passing view argument in function so try initialize edit text with (EditText)view.findViewById(R.id.edittext);
panwrona said:
You're passing view argument in function so try initialize edit text with (EditText)view.findViewById(R.id.edittext);
Click to expand...
Click to collapse
Thanks for the reply.
I did what you said and got a runtime exception.
You're running it in fragment or activity?
panwrona said:
You're running it in fragment or activity?
Click to expand...
Click to collapse
Activity.
Are you initializing it in oncreate or somewhere else?
That's easy. Instead of == use text.equals(one)
String are not compared by mathematical signs
Sent from my XT1033 using XDA Premium 4 mobile app

Categories

Resources