[Guide} [Basic] App development basics and first android app fully functional - Samsung Galaxy Fit GT 5670

This is basic guide to start to off app development for android..........
This is just a basic guide and not a comprehensive one which covers the whole lot of it but a rather a guide to get a basic simple app of your own running without any issues
Requirements
A bit of java
linux , darwin or a windows 7 machine
internet connection
basic idea of how programming works
sdk with atleast one api installed and configured path
Part 1 setting up everthing and explaining used variables and terms
Now let's get started
[windows}
Download eclipse as any other software and install it by the .exe file and follow the instructions
(linuc macosx )
if you are on a older ditribution of linux the minimum required version of eclipse 3.6 is not supplied via ubuntus main repository ....
so you need to download it from the eclipse official website and install it....
[common}
Installing ADT(Android developer tools) plugin
open up eclipse
Start Eclipse, then select Help > Install New Software.
Click Add, in the top-right corner.
In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the following URL for the Location:
https://dl-ssl.google.com/android/eclipse/
Click OK.
If you have trouble acquiring the plugin, try using "http" in the Location URL, instead of "https" (https is preferred for security reasons).
In the Available Software dialog, select the checkbox next to Developer Tools and click Next.
In the next window, you'll see a list of the tools to be downloaded. Click Next.
Read and accept the license agreements, then click Finish.
If you get a security warning saying that the authenticity or validity of the software can't be established, click OK.
When the installation completes, restart Eclipse.
Configure the ADT Plugin
Once Eclipse restarts, you must specify the location of your Android SDK directory:
In the "Welcome to Android Development" window that appears, select Use existing SDKs.
Browse and select the location of the Android SDK directory you recently downloaded.
Click Next.
If you haven't encountered any errors, you're done setting up ADT and can continue to Next Steps.
the path to the sdk is case sensitive and absolute so be careful guys....
Now you have virtually everything set up to start building apps
go to file>new>project>android>android application project
something like this will pop up
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
now
the first three fields are yours to choose
now the second part
The build sdk is the sdk that you are targeting in laymans words its like building a building on a certain specific site.....
the minimum required sdk
now if choose this as froyo(api 8) your app will run on froyo os and above and will be compatible with older flavours of android....
once you are done creating a new project hit finish
now you will see something like this
now the calculator is my app name the name that you gave a few minutes ago will be yours...
Now the android is basically divided into three main things
The android manifest
The src folder
The xml
The android manifest basically is a traffic police in lay mans words
it determines which activity comes first when it ends etc...
note:i will be referring the xml to a activty
the src folder contains all of your java
xml's are the skeltel system of android they define the size layout colour or the whole look of your android project....
Note: dont tinker with the gen folder you alone will be responsible for your mistakes
in this tutorial you will be working with only src,res and xml's as i cant dig deeper into it because its a subject too broad to teach....
now lets get started
navigate to res > layout double click on main_activty.xml
below the screen click on activty_main.xml next to graphical layout...
something like this will appear
HTML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world"
tools:context=".MainActivity" />
</RelativeLayout>
this is the text appearing to you
Note this is auto generated....
now i will explain each line of it with my limited knowledge
HTML:
]<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
This is the auto generated refernce by eclipse yours may vary and might not be same as mine
HTML:
android:layout_width="match_parent"
android:layout_height="match_parent"
now you can see that the layout is set to match_parent by deafult
match_parent utilizes the whole screen into your layout...
and observe this guys the
HTML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
the relative layout has started with <relativelayout and ended with > anything code started should be finished up by > or />
both are literally same
now the next junk of code to deal with
HTML:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world"
tools:context=".MainActivity" />
Textview is basically a method by google to display some text on the screen...
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
These two lines suggest that your app has both vertcal and horizontal layout
android:text="@string/hello_world"
this is the text being displayed on your graphical layout
now go to layout > values > strings.xml
double click it
you will see something like this
now basically strings are resource files used to show text on display...
the string name cant have any spaces if it has then u will see errors
but the value of the string can have spaces
Activity
change the text in value field and see the result in graphical layout of the xml
now you basically need to use strings for each and every text that has to be displayed.......
End of part 1
Part 2
Adding of buttons and modifying them
now guys lets add some buttons to our project
navigate to src
in that you will find a java file open it (.java)
you will find something like this
HTML:
package com.exmple.addandsubract;
import android.R;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Layout extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_layout, menu);
return true;
}
}
now you might be wondering what is this crap code ...
now lets add buttons
navigate into layout open up the xml
your screen will show up this
HTML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world"
tools:context=".MainActivity" />
</RelativeLayout>
now within the closing of relative layout
copy paste this
HTML:
<Button
android:id="@+id/bsub"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="79dp"
android:text="@string/sub" /
every button must have an id for our convenience we have added a bsub as our program is to add and subtract a number
HTML:
android:layout_width="match_parent"
the layout width specifies the size of the width of the button
as i have said before match_parent is to occupy the whole screen..if you want it smaller you can set it in dp(density pixels)
HTML:
android:text="@string/sub"
you cant hard code stuff into the button u need to refernce it to a string i have referred it to the string sub
for this to work it requires you to add a string by the name sub in strings.xml
now do the same code again for button add
after this you will have something like this showing up
now that we have our button's set up we need to make this work (in real add java to it)
to accomplish this we need to link xml's to java
this may sound like greek and latin but guys stick with it u will understand everything
now below
HTML:
public class Layout extends Activity {
type this
HTML:
int counter=0;
Button add,sub;
TextView display;
as u may all know we should define a variable before we use them
as we are working with number (basically integars we use integar to define them
now we basically define display as textview
now coming to the real java part
HTML:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
after this chunk of code
type
HTML:
counter=0;
the counter is the number which should be displayed on the screen for us
i have decided to start with 0 you can set it to any number that you prefer
now type this
HTML:
add = (Button) findViewById(R.id.badd);
sub = (Button) findViewById(R.id.bsub);
what this basically says is that add is a button and its id(in the xml) is badd.. findviewbyid is the method for referencing
now its the same for sub button too
HTML:
display = (TextView) findViewById(R.id.textView1);
this will set our display to textview1 which is our activity.xml this may sound as bloat to you but its handy when working with many xmls
now type
HTML:
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
display.setText("Your total is " + counter );
}
});
sub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
display.setText("Your total is " + counter );
}
});
i will explain what this does
HTML:
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
display.setText("Your total is " + counter );
}
});
type add. then all lists will popup select onclicklistener(this makes the button clickable)
within the brackets of onclicklistener type new(as its a new button) leave a space type view.onlclicklistener(again you will see popups
now what is between this two brackets is what happens when the button is clicked now add this in between these brackets
HTML:
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
counter=counter+1;
display.setText("Your total is " + counter );
}
});
sub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter=counter-1;
display.setText("Your total is " + counter );
}
});
HTML:
counter=counter-1;
this decrements the counter value by 1
after the counter is decremented we need to change the display to show the value of it
we do that by typing this
HTML:
counter=counter-1;
display.setText("Your total is " + counter );
now do this for both buttons test the app on emulator
Have doubts comment below
liked the thread rate it that gives me moral confidence and motivation

1st reserved op has plans of increasing

reservation
2nd

one final one for the day... :cyclops:

thanks! :good:
its to the point and very precise!
View attachment HelloWorld.apk
how do i add an icon? mine is the default andy.
And is it possible to open an app (eg launcher pro) in eclipse and mod it as per my wish?

Harryhades said:
thanks! :good:
its to the point and very precise!
View attachment 1401833
how do i add an icon? mine is the default andy.
And is it possible to open an app (eg launcher pro) in eclipse and mod it as per my wish?
Click to expand...
Click to collapse
There are two ways to add icon after giving the package name in the next menu you can change the icon....or go re drawabl-hdpi and replace the icon.png by the one that u want it should be case sensitive and it should be the same text....
For the 2nd question
yes you can mod these apps i have tried adw from cm'r repo but it should work with launhcer pro to btw the app has to deodexed.....

Thanks

Thanks bro i have started developing one :good:

completing the guide this sunday

I realize this is a few years old but I'm new to developing apps and I been trying to get this to work so that I can add a number to a number stored in a database. The number is put in the database via "edittext". When I try this my number gets replaced with "false" when I hit the add button.
Sent from my LG-LS995 using XDA Free mobile app

Related

[APP] Zune software remote control

Instructions + download: http://forum.xda-developers.com/showpost.php?p=17254652&postcount=7
I have finally found a way to control the Zune software running on Windows. The Zune API is horrible so there are few(if any) programs that interface with the software externally. Today I came across the SendMessage method. The idea is your Android device is a big remote control for the Zune software. If you already have a media remote then this application isn't needed. I only have a remote on my laptop, not desktop so that's why I'm bothering to write it. I thought I would share it on XDA for free.
http://pastebin.com/C85isGsW - that was my test program. When I opened it my music paused(yay!).
Anyways this will be a 2-part system. The Windows app will run in the background(either as a service or in the system tray) and listen on some random TCP port for a connection. It will be relatively small, using less than 50MB RAM. This one uses 27MB right now(yes, C# is bloated).
The Android app will simply connect over the wifis or even over the internet(just remember to forward ports) and after a quick handshake it will be able to send and receive data from the service/app in tray. First I'll start with simple play/pause buttons and a volume slider and eventually I'll add all the interfaces listed here: http://msdn.microsoft.com/en-us/library/ms646275(v=vs.85).aspx
Step 1: install service or open the Windows program
Step 2: type computer IP in android app
Step 3: press play/pause or control volume etc. It will save the IP so you don't have to keep typing it in. In fact I will have a dropdown list so you can select different computers(HTPC, basement computer etc.)
I just started writing the program so it will by done by the end of the weekend. Figured I would create the thread since I know it will work.
inb4 zune sucks
Interested in seeing this.
Sent from my Transformer TF101 using XDA Premium App
yes dude yes!!! imso amped for this! thanks so much.
OK I got the windows side app 95% done... started the Android version and well.. I'm a noob. Looks like honeycomb makes you interface with TCP in a separate thread...
Windows server code:
Code:
hile (stop != 1)
{
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
//Console.WriteLine("Received: {0}", data);
if (Convert.ToString(data).CompareTo("PP") == 0) SendMessageW(hwnd, WM_APPCOMMAND, hwnd, (IntPtr)APPCOMMAND_MEDIA_PLAY_PAUSE);
if (Convert.ToString(data).CompareTo("UP") == 0) SendMessageW(hwnd, WM_APPCOMMAND, hwnd, (IntPtr)APPCOMMAND_VOLUME_UP);
if (Convert.ToString(data).CompareTo("DN") == 0) SendMessageW(hwnd, WM_APPCOMMAND, hwnd, (IntPtr)APPCOMMAND_VOLUME_DOWN);
if (Convert.ToString(data).CompareTo("PR") == 0) SendMessageW(hwnd, WM_APPCOMMAND, hwnd, (IntPtr)APPCOMMAND_MEDIA_PREVIOUSTRACK);
if (Convert.ToString(data).CompareTo("NE") == 0) SendMessageW(hwnd, WM_APPCOMMAND, hwnd, (IntPtr)APPCOMMAND_MEDIA_NEXTTRACK);
// Process the data sent by the client.
//device.AudioEndpointVolume.MasterVolumeLevelScalar = (Convert.ToInt64(data) / 100.0f);
//byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
//byte[] msg = System.Text.Encoding.ASCII.GetBytes("Successfully set to " + data);
// Send back a response.
//stream.Write(msg, 0, msg.Length);
//Console.WriteLine("Sent: {0}", data);
}
// Shutdown and end connection
client.Close();
}
}
What needs to happen to connect to the server(client code)
Code:
static void Connect(String server, String message)
{
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
Int32 port = 13000;
TcpClient client = new TcpClient(server, port);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
MessageBox.Show("ArgumentNullException: " + e.ToString());
}
catch (SocketException e)
{
MessageBox.Show("SocketException: " + e.ToString());
}
}
So I would call Connect("192.168.1.40", "PP"); to pause/play the server(desktop running Zune)
Code:
package com.pwn.control;
import android.app.Activity;
import java.io.*;
import java.net.*;
import android.widget.*;
import android.os.Bundle;
import android.os.StrictMode;
public class ControlActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
tv.setText("HELLO WORLD");
setContentView(tv);
run();
}
TextView tv;
public void run()
{
new Thread(new Runnable() { public void run() {
Socket socket;
try
{
InetAddress serverAddr = InetAddress.getByName("192.168.1.40");
socket = new Socket("192.168.1.40", 13000);
//socket.connect();
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeBytes("PP");
//PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
//out.println("PP");
socket.close();
}
catch (Exception e)
{
tv.setText(e.toString());
//setContentView(R.layout.main);
}
}
} ).start();
}
}
Unfortunately the above code doesn't work. Kinda stuck lol... maybe someone knows more about writing android apps than I do.
http://www.youtube.com/watch?v=PMjNrd1d4FM
Got it working with an ASP site...
now the annoying part... I tried setting it up with a default IIS instance and it doesn't have permissions to use the user32.dll!!! I tried forced impersonation and tons of different tricks but for some reason it isn't getting as high permissions as the ASP.NET debugging server.
So I need to either fix the android app so it will communicate with the service, or I need to find a way to get the IIS instance enough permissions to interact with the desktop. I did set the IIS Admin service to "interact with desktop" but nothing happened.
I also tried setting up Apache 2.2 with mod_asp installed but it has the same result... blocked from interacting.
Ok I got it working but it's really really makeshift right now...
ASP website --> loopback on port 13000 --> C# app(that will actually interface with the Zune software)
I couldn't make the API call from the C# code in the ASP site because IIS doesn't have enough permissions. So since my only drawback before was that I couldn't communicate between .NET TcpListener and Java, I can just use the ASP site to make the TcpClient connection.
The good thing is you can access this interface from anything with a web browser. Just make http://computer-ip:port/ZuneControl a favorite on any device and you can control Zune from it.
http://www.youtube.com/watch?v=haVLCOY0l6U
If you're really eager to try the alpha build with IIS that's fine...
Just set up IIS like I do in the video and add port 13000 to your inbound and outbound firewall rule. I'll work on the UI when I get some time next weekend.
Here is the code for the C# app. http://pastebin.com/08kCjKQW
The web code is in the RAR file. I just copied and pasted out of that pastebin with some extra buttons.
http://tunerspotter.com/\dropbox\misc\ZuneControl.rar
In that ZuneControl folder, ZuneControl.exe is the app. Click start, then minimize it after you set up IIS. It will work for Apache installations also. I have Apache on port 82. http://sourceforge.net/projects/mod-aspdotnet/
Instruction video: http://www.youtube.com/watch?v=ClCQhmQxC7Q
Well i've been using the web interface for a few days and it kicks ass. Does exactly what i want. I can be in bed and change songs/volume from another tab in Opera.
Next weekend Ill see if i can get the program to listen on port 81 as a web service so instead of setting up IIS or apache all you have to do is open the app and click start(then minimize it)
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
hey are you still working on this? I would really love something like this!
well i gave up on the app and just turned it into a ASP site + windows application. so yeah i've been using it for a few months. works great, i can pull up on any web capable device and adjust my music. Whether it's my zune, tablet, computer, or phone, i can adjust volume, go back/next, and pause/play from any device. i set up port forwarding with dyndns.org so it works over 3G

[Q] how to make a select all check box

hi, i am trying to make a check all check box and i didnt know how to do that, i cant really explain it that well so i will just show you the code:
xml:
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<CheckBox
android:id="@+id/cbAll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="25"
android:text="Select All"
android:checked="true" />
<CheckBox
android:id="@+id/cb1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:checked="true" />
<CheckBox
android:id="@+id/cb2"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:checked="true" />
<CheckBox
android:id="@+id/cb3"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:checked="true" />
<CheckBox
android:id="@+id/cb4"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:checked="true" />
<CheckBox
android:id="@+id/cb5"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:checked="true" />
java:
Code:
CheckBox cb1, cb2, cb3, cb4, cb5, cbAll;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cb1 = (CheckBox) findViewById(R.id.cb1);
cb2 = (CheckBox) findViewById(R.id.cb2);
cb3 = (CheckBox) findViewById(R.id.cb3);
cb4 = (CheckBox) findViewById(R.id.cb4);
cb5 = (CheckBox) findViewById(R.id.cb5);
cbAll = (CheckBox) findViewById(R.id.cbAll);
cbAll.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (cbAll.setChecked(true)){
cb1.setChecked(true);
cb2.setChecked(true);
cb3.setChecked(true);
cb4.setChecked(true);
cb5.setChecked(true);
}else{
cb1.setChecked(false);
cb2.setChecked(false);
cb3.setChecked(false);
cb4.setChecked(false);
cb5.setChecked(false);
}
}
});
what i am asking is, is this part right, and if not can you tell me the right way to do it please:
Code:
cbAll.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (cbAll.setChecked(true)){
cb1.setChecked(true);
cb2.setChecked(true);
cb3.setChecked(true);
cb4.setChecked(true);
cb5.setChecked(true);
}else{
cb1.setChecked(false);
cb2.setChecked(false);
cb3.setChecked(false);
cb4.setChecked(false);
cb5.setChecked(false);
}
}
});
thank you.
Your problem is this line...
Code:
if (cbAll.setChecked(true)) {
...
You're setting the value of the cbAll checkbox, not getting it. You should use...
Code:
if (cbAll.isChecked()) {
...
Archer said:
Your problem is this line...
Code:
if (cbAll.setChecked(true)) {
...
You're setting the value of the cbAll checkbox, not getting it. You should use...
Code:
if (cbAll.isChecked()) {
...
Click to expand...
Click to collapse
Thank you!
I also have one more question, how can you have a button that when its clicked it brings me to another activity? Like if you click the button it goes to com.example.example.Example. How would I do that?
steineronie said:
Thank you!
I also have one more question, how can you have a button that when its clicked it brings me to another activity? Like if you click the button it goes to com.example.example.Example. How would I do that?
Click to expand...
Click to collapse
No worries mate. Have a look here...
http://www.dotnetexpertsforum.com/how-to-open-a-new-activity-from-button-click-in-android-t1322.html
I'm not being dismissive when I say this, like I often am with people on xda who ask how to do things that are heavily documented, but googling is a VERY useful tool for development work. I use it heavily on a daily basis. You just need to get good at searching with it and there's very little you can't find.
Eg. for your query I just googled for android button open new activity.
I'm happy to help, as I'm sure others on here are also happy to help, but sometimes Googling will get you a quicker answer.
Good luck mate
Edit: Forgot to mention, there's also a dedicated Android dev forum on here...
http://forum.xda-developers.com/forumdisplay.php?f=524
Archer said:
No worries mate. Have a look here...
http://www.dotnetexpertsforum.com/how-to-open-a-new-activity-from-button-click-in-android-t1322.html
I'm not being dismissive when I say this, like I often am with people on xda who ask how to do things that are heavily documented, but googling is a VERY useful tool for development work. I use it heavily on a daily basis. You just need to get good at searching with it and there's very little you can't find.
Eg. for your query I just googled for android button open new activity.
I'm happy to help, as I'm sure others on here are also happy to help, but sometimes Googling will get you a quicker answer
.
Good luck mate
Edit: Forgot to mention, there's also a dedicated Android dev forum on here...
http://forum.xda-developers.com/forumdisplay.php?f=524
Click to expand...
Click to collapse
Sorry for not looking on google, i will next time, and thank you again.
steineronie said:
Sorry for not looking on google, i will next time, and thank you again.
Click to expand...
Click to collapse
Don't worry about it mate - glad to help.

[TUT] Extend your HelloWorld App Step by Step with a Toast Message

Hi guys, this Tutorial is mainly intended for looking into some other concepts like GUI of Android development. The concept of "Toast" would be actually covered.
First you have to do this (Create a HelloWorld app) : [TUT] Making a HelloWorld App Step by Step w/pictures. - Tutorial created by rezo609
After you've created your first HelloWorld app, its time for some additional tasks!
(NOTE:- Make sure you've set your AVD already)
I know some of you guys are wondering what a Toast is, well here's the answer: Click Me!
Starting development :
Step 1: The first thing we are going to accomplish is changing the strings.xml (Path:- AppName > res > values > strings.xml) file to add another node under app_name. We will do this by copying the node above it and pasting the copied material directly under the last </string> element. Then we will change the name of the string to press and in between we will write Press Me!. Next we will alter the hello node and change the text to say Enter Your Name Here: instead of Hello Android, Hello World!.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Click to expand...
Click to collapse
Step 2: Next step, is to design the GUI (Graphical User Interface). To do this navigate to main.xml (Path:- AppName > res > layout > main.xml) and we are going to go over what everything does up to this point. Set your main.xml file as shown in the below picture.
Make sure you've set the Orientation as vertical, otherwise ie, if its horizontal maybe the GUI controls won't be shown when the app is run.(in an HVGA Emulator, or maybe its me) Anyways you are free to toggle between vertical/horizontal and see what happens.
Click to expand...
Click to collapse
Step 3: Now this is a tricky step, and it includes Java code modifications. I suggest you to google to know exactly what all these codes means be it functions, classes, methods, objects or imports. You can refer the Wiki or the Oracle docs if you want to learn more about Java. Anyways for keeping this Tutorial simple, just modify the Java file (Path:- AppName > src > com.example.helloworld > HelloWorldActivity.java) as shown in the below picture.
I'll also give it as CODE, but don't just copy-paste. If you run into massive errors or problems only, do that. Its better to type the codes by yourself and see what all AutoFill options/suggestions are given by Eclipse. Anyways try to correct the errors by yourself, it maybe only a spelling-mistake, but you have to identify it where.
Code:
package com.example.helloworld;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.view.View.OnClickListener;
import android.content.Context;
import android.view.View;
public class HelloWorldActivity extends Activity {
EditText helloName;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Capture our button from layout
Button button = (Button)findViewById(R.id.go);
// Register the onClickListener with the implementation above
button.setOnClickListener(maddListener);
}
// Create an anonymous implementation of OnClickListener
private OnClickListener maddListener = new OnClickListener() {
public void onClick(View v) {
long id = 0;
// Do something when the button is clicked
try {
helloName = (EditText)findViewById(R.id.helloName);
Context context = getApplicationContext();
CharSequence text = "Hello " + helloName.getText() +"!";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
catch(Exception e) {
Context context = getApplicationContext();
CharSequence text = e.toString() + "ID = " + id;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
};
}
Click to expand...
Click to collapse
Step 4: After doing all these above mentioned tasks, its time for the output. Be sure to click "Save All" (Ctrl+Shift+S) button in the Eclipse. Also make sure your Project is free from errors, otherwise it would not run. You can also clean your Project (Some errors maybe automatically fixed) by navigating to Project > Clean...
Right Click your Project > Run As > 1 Android Application
Your Emulator would start, and you'll see in the Eclipse as apk installing, running etc..
If your Project is a Success, you'll get the output as shown in the below picture:
Click to expand...
Click to collapse
And that's it
I hope you enjoyed this tutorial. Its made as simple as possible and omitted some theories from the Original source. You can get to it, and see the xml parts explained.
After you have succeeded in this app, head over to next Tutorial : Create your First Widget Step by Step
Thanks for this.
This is great!!
Sent from my HTC Wildfire S using xda premium
Welcome guys, hope you guys tried/will try and get successful.
Tutorial now featured at XDA-Portal : Here
Thanks to the Author.
So I decided to look at this. I've got everything as you have above but I have errors.
Current errors are in the following lines:
Code:
Button button = (Button)findViewById(R.[COLOR="Red"]id[/COLOR].go);
Code:
helloName = (EditText)findViewById(R.[COLOR="red"]id[/COLOR].helloName);
The error states: id cannot be resolved or is not a field
If I follow the listed fixes it places lines in the R.java. However, I then get errors on go and helloName for which there are no listed fixes.
Still looking to see if I can find it myself but wanted to tell you about this to see if it was just me (probably) or a missing section in the info above.
EDIT: Sigh. It's amazing what missing one line will do to you. This was my fault. Forgot to add the Press me string and it created these errors. Working great now.
blazingwolf said:
So I decided to look at this. I've got everything as you have above but I have errors.
Current errors are in the following lines:
Code:
Button button = (Button)findViewById(R.[COLOR="Red"]id[/COLOR].go);
Code:
helloName = (EditText)findViewById(R.[COLOR="red"]id[/COLOR].helloName);
The error states: id cannot be resolved or is not a field
If I follow the listed fixes it places lines in the R.java. However, I then get errors on go and helloName for which there are no listed fixes.
Still looking to see if I can find it myself but wanted to tell you about this to see if it was just me (probably) or a missing section in the info above.
EDIT: Sigh. It's amazing what missing one line will do to you. This was my fault. Forgot to add the Press me string and it created these errors. Working great now.
Click to expand...
Click to collapse
please check the imports ...
if you find line import android.R; ... remove it and then clean build....
blazingwolf said:
EDIT: Sigh. It's amazing what missing one line will do to you. This was my fault. Forgot to add the Press me string and it created these errors. Working great now.
Click to expand...
Click to collapse
There you are
Actually we should edit all the XML files first like android:id="@+id/go" and it will show error in XML file for sure (Because id can't be found anywhere) but finally when you code the java file, and when the id is referenced, all errors will be gone
Anyways the R.java file can't be modified manually. It will revert back to original state if you do so, that is even if you apply the suggested fixes by Eclipse.
pmapma1 said:
please check the imports ...
if you find line import android.R; ... remove it and then clean build....
Click to expand...
Click to collapse
Actually unnecessary imports will not cause the application to malfunction. It will only use more resources based on program. Eclipse will give a warning to remove unused imports, as its not used anywhere.
Hi there,
I've been wondering this so I thought I'd ask here since it seems nice and n00b friendly ;-)
I was wondering if you could tell me if there's any direct benefit to creating an OnClickListener in Java instead of using the android:OnClick="" attribute for the layout and having it go to a specified method.
Thanks,
Tom
TommiTMX said:
Hi there,
I've been wondering this so I thought I'd ask here since it seems nice and n00b friendly ;-)
I was wondering if you could tell me if there's any direct benefit to creating an OnClickListener in Java instead of using the android:OnClick="" attribute for the layout and having it go to a specified method.
Thanks,
Tom
Click to expand...
Click to collapse
Benefit?! ... Hmm !!
It all depends upon the logic of the programmer that he/she is comfortable with. Actually there will be many methods or many ways we can create for the same process. But as this is just a Tutorial/Illustration application, we don't know exactly what its effects. Maybe in real time application there maybe some beneficiaries. Just we need to sort it out to know.
can you make a tutorial how to make a background process? Or service of somekind.
E.g. process that shows blue led while BT is on
thanks in advance!
Shmarkus said:
can you make a tutorial how to make a background process? Or service of somekind.
E.g. process that shows blue led while BT is on
thanks in advance!
Click to expand...
Click to collapse
I'll definitely try, but can't guarantee when because I'm also a learning candidate in Android app development. So making Tutorials, that I've already learned and tried. Once I've learned about it, I'll of course include the Tutorial for it.
why we need try/catch for one-way trigger? ... what in toast can throw exception?
Flowyk said:
why we need try/catch for one-way trigger? ... what in toast can throw exception?
Click to expand...
Click to collapse
Well, I just checked myself by removing the try-catch block, and yes you are right as no exceptions are actually caught. Anyways the code is not actually written by me, and if you checked the original source you'd have known that.
And Thanks for the point mate. Maybe I'll review the code from next time onwards.
np ... im just learning
Error?
FIXXED

[GUIDE] Create “deathless” Android application: Protected from removal and stop

Author: Apriorit (@andruwik777, Driver Development Team)
Some types of applications require that the end users can not be able to remove or at least stop the application. For example, all types of Parental Controls, Data Leak Prevention, and applications with similar concepts should work on devices regardless of the user’s intentions. On the other hand, when trying to search proven solutions for implementing such applications, we cannot find some comprehensive answers in the Internet. This article describes one of the possible solutions.
Intro
Though, there are individual solutions for the "Disable force stop and uninstall button on Android" tasks, but in order to activate these buttons, you simply need to perform the user’s actions in reverse order.
As for the task of creation of an unkillable application, there are opinions that it cannot be supported by the concept of Android (1, 2, 3), because the basic idea of this OS is to give the user permission to work with his device as he wishes.
However, we are going to consider one of the ways to create an application that can be stopped or removed only by the user (Admin), who installed it.
The task
Appearance of the application
Task: Create the TryStopOrUninstallMe application.
After the application start and security policy acceptance, within a 10 seconds timeout, application displays the information that it successfully works (Toast with the “Ooops! Try to kill me ” text).
If you stop the service, it will be restarted no later than in 2 seconds (by timeout).
The ForceStop and Uninstall buttons are inactive in the application menu. When you try to activate these buttons by disabling DeviceAdministrator for the application, phone is locked. At the same time the previous user password is deleted and further calls can be made only after unlocking the phone by administrator, who knows the password.
Used technologies
Programming language: Java.
Used libraries and technologies: Android SDK.
Minimum supported version of Android: 2.2
Maximum supported version of Android: 5.0.2 (the newest one for today)
ROOT-permissions requirements on the device: not required
Testing: the application was tested on Nexus 5 with Android 5.0.1.
Pending issues
In order to keep this article short and because of the triviality of the problem, we do not consider:
1. Creation of start Activity, in which the administrator would set a master password. Instead, we have simply hardcoded it (e.g., "12345");
2. Application startup at system startup.
The general principles of the mechanism
The following approaches will be used to implement this idea:
1. Disabling the application forced stop and uninstall will be implemented using Device Administration API. Although it is designed for a little bit different purposes (some of which will be shown later), we’ll use it as a "deactivator" of the ForceStop and Uninstall buttons for our application (a side effect is actually what we need):
To uninstall an existing device admin application, users need to first unregister the application as an administrator.
2. There is no standard mechanism to disable the DeviceAdmin mode unlocking for user. However, we can sign up to receive event alerts on removing our application from the list of administered ones. And in this case we can:
1. Reset the current password for device locking (one of the DeviceAdmin API purposes);
2. Lock the phone (another great DeviceAdmin API feature).
3. Our application will use the service to run in the background. For the cases when user tries to stop our service (Settings -> Application -> RunningServices) we will implement auto-start using the AlarmManager system mechanism.
4. If user stop the service and have enough time to go to the application menu until the system restarts the service, then the application (not the service) stop button will be available for him.
After application is stopped, nothing can be restarted by itself. Thus, to deprive user of this chance, we will redirect him to his desktop and lock the device. While user is returning to the target Activity, system has enough time to restart the service (during my testing, it always takes 1-2 seconds).
Graphical representation
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Implementation of the mechanism
Activation of the mechanism for self-protection against the application stop and uninstall, and the service launch (MainActivity.java)
Code:
public class MainActivity extends Activity {
private static final int REQUEST_CODE = 0;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
// Initiate DevicePolicyManager.
DevicePolicyManager policyMgr = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
// Set DeviceAdminDemo Receiver for active the component with different option
ComponentName componentName = new ComponentName(this, DeviceAdminDemo.class);
if (!policyMgr.isAdminActive(componentName)) {
// try to become active
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
"Click on Activate button to protect your application from uninstalling!");
startActivity(intent);
}
} catch (Exception e) {
e.printStackTrace();
}
startService(new Intent(this, BackgroundService.class));
}
}
Everything that is done in the main (and only one) Activity is DeviceAdmin activation and service launch. It is expected that the device administrator activates the protection by pressing Activate.
Otherwise, the user can stop or remove the application in a standard way.
The service launch and its running (BackgroundService.java)
Code:
public class BackgroundService extends Service {
private static final int FIRST_RUN_TIMEOUT_MILISEC = 5 * 1000;
private static final int SERVICE_STARTER_INTERVAL_MILISEC = 1 * 1000;
private static final int SERVICE_TASK_TIMEOUT_SEC = 10;
private final int REQUEST_CODE = 1;
private AlarmManager serviceStarterAlarmManager = null;
private MyTask asyncTask = null;
@override
public IBinder onBind(Intent intent) {
return null;
}
@override
public void onCreate() {
super.onCreate();
// Start of timeout-autostarter for our service (watchdog)
startServiceStarter();
// Start performing service task
serviceTask();
Toast.makeText(this, "Service Started!", Toast.LENGTH_LONG).show();
}
private void StopPerformingServiceTask() {
asyncTask.cancel(true);
}
private void GoToDesktop() {
Intent homeIntent= new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(homeIntent);
}
private void LockTheScreen() {
ComponentName localComponentName = new ComponentName(this, DeviceAdminDemo.class);
DevicePolicyManager localDevicePolicyManager = (DevicePolicyManager)this.getSystemService(Context.DEVICE_POLICY_SERVICE );
if (localDevicePolicyManager.isAdminActive(localComponentName))
{
localDevicePolicyManager.setPasswordQuality(localComponentName, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC);
}
// locking the device
localDevicePolicyManager.lockNow();
}
@override
public void onDestroy() {
// performs when user or system kills our service
StopPerformingServiceTask();
GoToDesktop();
LockTheScreen();
}
private void serviceTask() {
asyncTask = new MyTask();
asyncTask.execute();
}
class MyTask extends AsyncTask<Void, Void, Void> {
@override
protected Void doInBackground(Void... params) {
try {
for (;;) {
TimeUnit.SECONDS.sleep(SERVICE_TASK_TIMEOUT_SEC);
// check if performing of the task is needed
if(isCancelled()) {
break;
}
// Initiating of onProgressUpdate callback that has access to UI
publishProgress();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@override
protected void onProgressUpdate(Void... progress) {
super.onProgressUpdate(progress);
Toast.makeText(getApplicationContext(), "Ooops!!! Try to kill me :)", Toast.LENGTH_LONG).show();
}
}
// We should register our service in the AlarmManager service
// for performing periodical starting of our service by the system
private void startServiceStarter() {
Intent intent = new Intent(this, ServiceStarter.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, this.REQUEST_CODE, intent, 0);
if (pendingIntent == null) {
Toast.makeText(this, "Some problems with creating of PendingIntent", Toast.LENGTH_LONG).show();
} else {
if (serviceStarterAlarmManager == null) {
serviceStarterAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
serviceStarterAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + FIRST_RUN_TIMEOUT_MILISEC,
SERVICE_STARTER_INTERVAL_MILISEC, pendingIntent);
}
}
}
}
Everything here is also relatively simple.
At the start, service activates reset mechanism. If for some reason it is stopped, PendingIntent with information about our service will be created and transferred to the AlarmManager system service indicating restart timeout.
As a task, service creates a thread, which uses an infinite loop to periodically display the "Ooops !!! Try to kill me " message on the user’s desktop.
The service “autostarter” code (ServiceStarter.java)
"Autostarter" is presented by a standard BroadcastReceiver, in which the attempt to start the service is performed.
Receiver triggers according to timeout due to the AlarmManager service, because receiver was registered at the start of the service.
If the service is already running, then the second onCreate for it will not be called. And that is exactly what we need.
Code:
public class ServiceStarter extends BroadcastReceiver {
@override
public void onReceive(Context context, Intent intent) {
Intent serviceLauncher = new Intent(context, BackgroundService.class);
context.startService(serviceLauncher);
}
}
The DeviceAdmin component code (DeviceAdminComponent.java)
We need DeviceAdmin in order to:
• prohibit user to stop or uninstall the application;
• have the possibility to change the password and lock the device if user attempts to disable the DeviceAdmin component.
Also note that the administrator password is hardcoded as the "12345" string.
The onDisableRequested code works out after the confirmation of the DeviceAdmin deactivation, but before the deactivation itself.
Code:
public class DeviceAdminComponent extends DeviceAdminReceiver {
private static final String OUR_SECURE_ADMIN_PASSWORD = "12345";
public CharSequence onDisableRequested(Context context, Intent intent) {
ComponentName localComponentName = new ComponentName(context, DeviceAdminComponent.class);
DevicePolicyManager localDevicePolicyManager = (DevicePolicyManager)context.getSystemService(Context.DEVICE_POLICY_SERVICE );
if (localDevicePolicyManager.isAdminActive(localComponentName))
{
localDevicePolicyManager.setPasswordQuality(localComponentName, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC);
}
// resetting user password
localDevicePolicyManager.resetPassword(OUR_SECURE_ADMIN_PASSWORD, DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY);
// locking the device
localDevicePolicyManager.lockNow();
return super.onDisableRequested(context, intent);}}
Results
Thus, without using ROOT-permissions, incidents, or undocumented system features, we have managed to create the application that is practically impossible to be stopped or removed without knowing the administrator password. Although in some cases you can try to do it.
After studying this technique, we once again come to the conclusion that:
• it is almost always possible to find loopholes to circumvent any restrictions;
• it is strongly not recommended to install applications from untrusted sources. Especially if it requires the acceptance of the DeviceAdmin policies…
And what about you? Do you know a way to create a similar system?
Download sources at www(dot)apriorit(dot)com/dev-blog/355-create-deathless-android-applications.
This article is the intellectual property of Apriorit Inc. and their authors.
All materials are distributed under the Creative Commons BY-NC License.
Very, very cool.
How would you go about doing the same when a phone was rooted and/ or the user had access to ADB?
Creed14 said:
Very, very cool.
How would you go about doing the same when a phone was rooted and/ or the user had access to ADB?
Click to expand...
Click to collapse
I was going to ask the same thing. Is the protection absolute?
Sent from my SM-G920F using Tapatalk
Hello guys.
Thanks for questions and sorry for delay.
Do you ask exactly about ADB commands?
I am not sure all devices have similar behavior (but I really hope they do it), but my devices (moto X 1st gen; Android 4.4.4; both root and non-root) don't start adb demon on the device after it locks with some screen lock (pin/pattern/password).
So, you can't access to your device via adb commands if it has been previously detached from the PC.
Really? Cuz ADB is the most common suggestion for getting past a lockscreen if you forget the password. Not to mention from a softbricked phone, you should even be able to use it
You can try to overcome your own password via adb and share you results here (device brand, model, root/non-root, Android version etc.).
For the purity of the experiment I suggest to perform the next steps:
1) Unplug the device from the PC
2) Set your device screen lock password to "12345"
3) Reboot the device
4) Plug the device to the PC and try to unlock the device (or to find the correct password) using ADB.
The intrigue persists ...

Question A newbie Android Application

I'm a newbie to Android Application.
I would like to add a functionality to my button. What should I touch ?
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
pax0 said:
I'm a newbie to Android Application.
I would like to add a functionality to my button. What should I touch ?
View attachment 5523271
Click to expand...
Click to collapse
You appear to have successfully created the graphical portion of your application. For it to do something truly useful requires code: Java or Kotlin. I think this app you're working on is setup for Java. So the short answer is "Write some Java code and put it into MainActivity.java."
Since you mention you're a beginner here's a longer answer. You might was to skim through this tutorial until they get to the parts about writing Java code.
Build Your First Android App in Java | Android Developers
In this codelab, you’ll build your first Android app. You’ll learn how to use Android Studio to create an app, add UI elements, known as views, to your app, and add click handlers for the views. You’ll finish by adding a second screen to your app.
developer.android.com
Here's a couple of lines code of which might make sense to you. I've added the attribute "onClick" onto the button in the XML file. And I've added a few lines of Java code which will run when the button is clicked. The end result is a brief message (this message is called "a toast") on the phone's screen saying "Click!" Obviously you'll want to do more than this trivial example.
So, consider adding these attributes to your activity_main.xml file's "button"
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="button1"
android:text="First Button" />
And you MainActivity.java might look like:
package com.example.my;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {n
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void button1(View view) {
Toast.makeText(getApplicationContext(), "Click!", Toast.LENGTH_LONG).show();
}
}
Hope this is helpful to you.
wpscully said:
You appear to have successfully created the graphical portion of your application. For it to do something truly useful requires code: Java or Kotlin. I think this app you're working on is setup for Java. So the short answer is "Write some Java code and put it into MainActivity.java."
Since you mention you're a beginner here's a longer answer. You might was to skim through this tutorial until they get to the parts about writing Java code.
Build Your First Android App in Java | Android Developers
In this codelab, you’ll build your first Android app. You’ll learn how to use Android Studio to create an app, add UI elements, known as views, to your app, and add click handlers for the views. You’ll finish by adding a second screen to your app.
developer.android.com
Here's a couple of lines code of which might make sense to you. I've added the attribute "onClick" onto the button in the XML file. And I've added a few lines of Java code which will run when the button is clicked. The end result is a brief message (this message is called "a toast") on the phone's screen saying "Click!" Obviously you'll want to do more than this trivial example.
So, consider adding these attributes to your activity_main.xml file's "button"
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
androidnClick="button1"
android:text="First Button" />
And you MainActivity.java might look like:
package com.example.my;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void button1(View view) {
Toast.makeText(getApplicationContext(), "Click!", Toast.LENGTH_LONG).show();
}
}
Hope this is helpful to you.
Click to expand...
Click to collapse
That's a good start, but I think you did some iOS button handling
For a button, you need to get a reference to it in your Java and assign a click listener. It won't automatically find it like Xcode by using the same name.
Code:
...
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button1);
button.setOnClickListener(view -> {
Toast.makeText(getApplicationContext(), "Click!", Toast.LENGTH_LONG).show();
});
...
In older Android Studio, you had to do
Code:
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
but now you can use a lambda (->) to replace the "common" stuff
the suggested solutions gives plenty of errors see below.
Hi. Speaking of Android development anybody know where can I find the C++ and Java Android development section of this forum? Thanks!
It gives plenty of errors
The sample Java program I posted in post #2 was meant to "largely replace" all the lines in MainActivity.java. It looks like you cut/pasted some of the suggested code into the middle of the existing skeleton Java code which Android Studio creates on your behalf. That approach won't work... a bit more effort is involved.
For example, there should be one and only one record in the Java file starting with the work "package". In your screen shot I see two. The second occurrence is incorrect and probably causing most of the errors. I would keep the first occurrence of package, because that's the naming that your Android Studio gave to the program. Delete the second "package com.example.my" which I think you pasted from me into the original file.
Also, there are several "import" records needed. In my post I included the only four I thought would be needed. However in your screen shot, on the second line, I see an import record with "three dots" (an ellipsis). This is Android Studio's way of hiding code from your view, which can be confusing to new users. You should mouse-click on those three dots to expose the hidden code. Then make sure there are no duplicate import records, when comparing what was originally in the file with what you cut/pasted.
I sent a private message to you with a link to my example code. It might work for you if you copied the folder into the same location you save your Android Studio projects. Of course, I can't be sure it will work. That's why I thought it best to include just a few lines of code in my original post.
Naming of things in Android Studio matters. I called my button "button" and my onClick "button1" and it must match eXaCtLy in the XML file and the Java code. (Case matters.) I can't see all your code so you'll need to ensure the naming matches exactly. (It's intuitively better if you name your button more appropriately... like "submit" if that's what the button is supposed to do.) Also, the number of braces { } will matter, as they indicate the structure of the program in Java.
In closing, it's very hard to explain all the nuances of this development environment through posting on XDA. Which is why it may be worth your time to run through the tutorial from Google. The tutorial creates a very simple application, but it also shows a lot of what I think you want to do, which is layout an end-user interface and have a button which when pressed will go off and do some additional work.
PS: I saw some errors in post 2, which I've cleaned up. A colon and the oh was interpreted as an emoticon. Ugh.
There's a learning curve involved here... learning Android Studios. If you can figure it out you might be able to earn a good living! I confess it's too hard for me. ;-)
pax0 said:
the suggested solutions gives plenty of errors see below.
View attachment 5523855
Click to expand...
Click to collapse
Your best bet is to start small. Download an example project from an online tutorial. The ones from Google are typically garbage. Plenty of sites include a sample with their getting started.
Make a small change and see what happens when you run it. Try a bigger change next. Try adding something. Try starting a new project. Try adding your stuff to that. Next thing you know, you're explaining it to the next person.
Admittedly, this isn't a section really made for learning the basics of app development. It's more focused on one device. General will be more help.

Categories

Resources