[Tutorial] Use OkHttp to make Network Requests on Android - Android Software Development

Hello,
I create that thread to present you a tutorial learning you to use OkHttp to make Network Requests on Android. Note that you can enjoy this tutorial in video on Youtube :
Created by Square, OkHttp is an open source project designed to be an efficient HTTP and HTTP/2 client. It lets you to make fast requests and save bandwith. It offers some great features out of the box like to share a socket for all HTTP/2 requests to the same host, a connection pooling mechanism when HTTP/2 is not available, transparent GZIP feature to reduce download sizes and a caching mechanism for responses. Besides, OkHttp has a great mechanism to manage common connection problems. And now, it supports also WebSocket.
OkHttp offers a request / response API that makes developers life easier. It supports synchronous and asynchronous calls. Even better, OkHttp is also available for Java projects with Java 7 as requirement.
First you need to add the following dependency to your build.gradle file :
Code:
compile 'com.squareup.okhttp3:okhttp:3.5.0'
For our example, we are going to consume a simple JSON Rest Web Service from the SSaurel’s Website : http://www.ssaurel.com/tmp/todos . So, we are going to create a simple layout with a Button to start the network request and a TextView to display the date got from the Web Service :
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.ssaurel.okhttptut.MainActivity">
<Button
android:id="@+id/getBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:layout_centerHorizontal="true"
android:text="Get WebService"/>
<TextView
android:id="@+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result ..."
android:layout_centerHorizontal="true"
android:textSize="17sp"
android:layout_below="@id/getBtn"
android:layout_marginTop="20dp"/>
</RelativeLayout>
Now, it’s time to write the Java code to make the Network Request by using the OkHttp API. First, we create the OkHttpClient instance. Then, we need to create the request via the Request object and its Builder class. Next step is to pass the request in parameter of the newcall method of the OkHttpClient instance created. OkHttp supports asynchronous and synchronous calls. Here, we are going to use asynchronous request so we call the enqueue method. It takes a Callback object in parameter which has two methods : onFailure and onResponse. Note that these methods are executed in a separate thread. So, if you want to update your User Interface with data got from the Network inside this method, you must embed this in a runOnUiThread call to ensure the update will be made on the UI Thread.
The Java code to consume the JSON Web Service with OkHttp will have the following form :
Code:
package com.ssaurel.okhttptut;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private Button getBtn;
private TextView result;
private OkHttpClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
getBtn = (Button) findViewById(R.id.getBtn);
getBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getWebservice();
}
});
client = new OkHttpClient();
}
private void getWebservice() {
final Request request = new Request.Builder().url("http://www.ssaurel.com/tmp/todos").build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
result.setText("Failure !");
}
});
}
@Override
public void onResponse(Call call, final Response response) {
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
result.setText(response.body().string());
} catch (IOException ioe) {
result.setText("Error during get body");
}
}
});
}
});
}
}
Now, you can try your application and you should obtain the following result by clicking on the Get WebService button :
{
"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"
}
Don't hesitate to give it a try to this tutorial and give me your feedbacks. To discover more tutorial on Android development, you can read my blog : https://www.ssaurel.com/blog
Thanks.
Sylvain

Related

parsing links??

hey everyone
im having a lil bit of trouble here and im hoping someone will have the knowledge i need...im using eclipse trying to build an app. i have a real simple app inmind and it consists of 4 icons that will link to their own forum, but im stuck trying to figure out how to link these websites when clicked...that being said im fairly new to the java world and im just looking for a nudge in the right direction here on where/how to make these buttons work.
{
"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"
}
[/URL] Uploaded with ImageShack.us[/IMG]
Android uses a Uri scheme to access resources outside the scope of your program. Checkout the Uri class and the startActivity method in the Context class.
As far as what the uri needs to contain, it is very simple, just the website address you want to go to. Here is the uris needed to access google services
http://developer.android.com/guide/appendix/g-app-intents.html
From something awesome
thanks for your advice.i really wish i knew more about java; i take it all my changes will be in my java & manifest files?? i dont know what actions to take really and i need a lil bit more indepth answer on exactly what i need to add/change...
this example assumes you used an xml layout file called http_button_layout.xml and has a button inside called button1
Code:
/**
* Created by IntelliJ IDEA.
* User: Tyler
* Date: 5/10/11
* Time: 6:47 PM
*/
public class HTTPClickButton extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
//call the parents onCreate
super.onCreate(savedInstanceState);
//set the view to some xml layout file with a button in it
setContentView(R.layout.http_button_layout);
//get an instance of that button to be used in the code
Button launchWebPage = (Button)findViewById(R.id.button1);
//attach an onClickListener to the button and define its action
launchWebPage.setOnClickListener(new View.OnClickListener() {
//the action to partake upon pressage of said button
public void onClick(View view) {
//the Uri.parse() method takes a string and converts it to a uri that android knows what to do with.
//in this case it sees a link and launches the web browser
//changing Intent.ACTION_VIEW will change the behavior of the link
//Intent.ACTION_WEB_SEARCH is the other option
startActivity(new Intent( Intent.ACTION_VIEW , Uri.parse("http://www.fistfulofneurons.com/") ));
}
});
}
}
hope this helps. of course this is one button but it will work for more. just rinse and repeat
to answer that i haven't made an xml layout file yet called http_button_layout.xml but i take it i will have to make an xlm layout file and java class for each icon? sorry supernewb when it comes to this code stuff, almost like learning a new language,lol...
you dont have to. but you will have to perform the .setOnClickListener() on each button.
are you using the Button class or is it just an image or someother class? cause it doesnt matter if it is a Button or not. even if its a TextView you can still perform the .setOnClickListener() i believe it is a function defined in the View abstract class.
im using an imagebutton option, fyi....dont know how much that changes things here tho...
You are golden. Since you are using java as the layout you just need to perform the setOnClickListener() on a reference of your ImageButton and forget anything i said about xml. Although you should investigate xml for layouts as its alot easier and faster to make a layout
You mind posting what you have so far to generate that screen grab up top?
From something awesome
HTML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/xlapps"
>
<ImageButton
android:id="@+id/imageButton1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/xlnet"
></ImageButton>
<ImageButton
android:id="@+id/imageButton2"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/xlnet"
></ImageButton>
<ImageButton
android:id="@+id/imageButton3"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/xlnet"
></ImageButton>
<ImageButton
android:id="@+id/imageButton4"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/xlnet"
></ImageButton>
</LinearLayout>
this is my main xml if this answers your question about the screen grab? rightnow i only have my main app icon, i need to get my 4 other icons inserted but other than that this parsing is my only hurdle, really..
lol now im confused, so does that mean i only need to do this part of your code in java, and does that mean i don't have to make a button_layout.xml? lol sorry java's not my first langauge, they totally should of taught this in school
Code:
//attach an onClickListener to the button and define its action
launchWebPage.setOnClickListener(new View.OnClickListener() {
//the action to partake upon pressage of said button
public void onClick(View view) {
//the Uri.parse() method takes a string and converts it to a uri that android knows what to do with.
//in this case it sees a link and launches the web browser
//changing Intent.ACTION_VIEW will change the behavior of the link
//Intent.ACTION_WEB_SEARCH is the other option
startActivity(new Intent( Intent.ACTION_VIEW , Uri.parse("http://www.fistfulofneurons.com/") ));
}
});
K so you are using an xml layout. Is that called main.xml? In my example you would replace my R.layout.http_button_layout with R.layout.main
And then when referencing the buttons you would change my R.id.button1 to the @+id of each button in your layout. So it would be R.id.imagebutton1.
The R class is a class generated at compile time to help reference ui elements defined in xml from your java code
And i don't think you can have ids defined in xml with capital letters. So you might want to change imageButton1 to image_button1
From something awesome
awesome yea im using main.xml for the layout.... so all i need to do is set up 1 java class for all the icons and do all your code there?...
well i started a new java class, i just called it buttons, im not sure if thats the right way to do all this but i changed what you said and im getting alot less errors so thats good.lol but heres a look at my buttons.java file. any idea what could be wrong? it showed my imagebutton1 of (R.id.imagebutton1) and image_button1 in the (find view by id) could not be resolved or is not a field...
Code:
package com.frostXLNetwork;
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 buttons {
public class HTTPClickButton extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
//call the parents onCreate
super.onCreate(savedInstanceState);
setContentView(R.id.imagebutton1);
Button launchWebPage = (Button)findViewById(R.id.image_button1);
launchWebPage.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startActivity(new Intent( Intent.ACTION_VIEW , Uri.parse("http://xlfx.30.forumer.com/index.php?") ));
}
you are making it harder than it is. when you see what has to be done you'll kick yourself... =)
i cleaned up some of the tags in your main.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/xlapps">
<ImageButton android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/xlfx"
android:id="@+id/XLFx"/>
<ImageButton android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/xlenlightenment"
android:id="@+id/XLEnlightenment"/>
<ImageButton android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/xlfit"
android:id="@+id/XLFit"/>
<ImageButton android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/stylelife"
android:id="@+id/XLife"/>
</LinearLayout>
and your main activity called XLNetwork.java
Code:
public class XLNetwork extends Activity {
//Define some String Constants that will point to the website of your choice
public static final String XLF_X = "http://xlfx.30.forumer.com/index.php?";
public static final String XL_ENLIGHTENMENT = "http://www.facebook.com/enlightenment2011?ref=ts";
public static final String XL_FIT = "http://xlfx.30.forumer.com/index.php?";
public static final String X_LIFE = "http://xlfx.30.forumer.com/index.php?";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageButton b1 = (ImageButton) findViewById(R.id.XLFx);
linkOnButtonPress(b1, XLF_X);
ImageButton b2 = (ImageButton) findViewById(R.id.XLEnlightenment);
linkOnButtonPress(b2, XL_ENLIGHTENMENT);
ImageButton b3 = (ImageButton) findViewById(R.id.XLFit);
linkOnButtonPress(b3, XL_FIT);
ImageButton b4 = (ImageButton) findViewById(R.id.XLife);
linkOnButtonPress(b4, X_LIFE);
}
/*
* linkOnButtonPress()
*
* i made this so i wouldnt have to type the same process over and over.
* what gets passed is the reference to the button you want, and the web address you
* want the button to link to.
*
*/
private void linkOnButtonPress(ImageButton button, final String webSite) {
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startActivity(new Intent( Intent.ACTION_VIEW , Uri.parse(webSite) ));
}
});
}
}
i cant thank you enough, you were a lifesaver!!

[Tutorial] Learn to Auto Restart an Android App after a Crash or a Force Close Error

Hello,
I create that thread to present you a tutorial learning you how to Auto Restart an Android App after a Crash or a Force Close Error. You can also discover this tutorial and the demo video associated directly on Youtube :
How to auto restart an Android Application after a Crash or a Force Close Error ?
The biggest nightmare of Android developers is the Crash or Force Close Error that can occur when a user uses one of their applications. Indeed, it’s always a bad message sent to the user and the major risk is that the user uninstalls the application. Unfortunately, you can’t always catch properly all errors and sometimes you can’t avoid a Crash or a Force Close Error. In these specific cases, a good approach is to configure auto restart for your Android Application. With this approach, you have better chances to keep users on your application.
{
"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"
}
To start, you need to create a custom Application class implementation to get an instance of your context continuously :
Code:
package com.ssaurel.appcrash;
import android.app.Application;
import android.content.Context;
public class MyApplication extends Application {
public static MyApplication instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
@Override
public Context getApplicationContext() {
return super.getApplicationContext();
}
public static MyApplication getInstance() {
return instance;
}
}
Don’t forget to add this Application implementation on your Android Manifest :
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ssaurel.appcrash">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:name=".MyApplication">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
To try the auto restart feature, we need to define a button in the layout of the Main Activity. When we will click on the button, we’re going to crash the application. The layout will have the following form :
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.ssaurel.appcrash.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Crash Me !"
android:onClick="crashMe"/>
</RelativeLayout>
Now, we enter in the core of our auto restart feature. You need to create a custom implementation of the UncaughtExceptionHandler interface. What is the purpose of this interface ? It’s an interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception.
Our custom implementation will have the following form :
Code:
package com.ssaurel.appcrash;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
public class MyExceptionHandler implements Thread.UncaughtExceptionHandler {
private Activity activity;
public MyExceptionHandler(Activity a) {
activity = a;
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
Intent intent = new Intent(activity, MainActivity.class);
intent.putExtra("crash", true);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(MyApplication.getInstance().getBaseContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager mgr = (AlarmManager) MyApplication.getInstance().getBaseContext().getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, pendingIntent);
activity.finish();
System.exit(2);
}
}
When an uncaught exception occurs, the uncaughtException method will be called. We’re going to create an Intent to restart our application at the defined moment via an Alarm. Then, we finish the current activity and we exit the application. Note that we put a boolean parameter to indicate that the application is restarted.
Last step is to install the UncaughtExceptionHandler during the start of the application by calling the static setDefaultUncaughtExceptionHandler method of the Thread class :
Code:
package com.ssaurel.appcrash;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
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);
Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this));
if (getIntent().getBooleanExtra("crash", false)) {
Toast.makeText(this, "App restarted after crash", Toast.LENGTH_SHORT).show();
}
}
public void crashMe(View v) {
throw new NullPointerException();
}
}
Note that we launch a NullPointerException in the crashMe method to force the crash of the application and test the auto restart feature. Other thing to note is the crash boolean parameter test when the activity is launched. Like said previously, it lets us to know when the application is restarted after a crash or when the application is launched for the first time.
Now, you can launch the application and you should see the following screen after a click on the crashMe button :
Don't hesitate to give it a try and give me your feedbacks if you have some ideas for new tutorials.
Thanks.
Sylvain
Really good guide, it resembles an implementation I had of a simple "restart" feature in my app. Only thing I'm wondering is why does System.exit if given enough time before the activity is restarted (in my case roughly AlarmManager.RTC, System.currentTimeMillis() + ~ 1.5 seconds) will display the annoying "Unfortunately XYZ has stopped" and prevent the application from fully starting until OK is clicked? Is there any potential risk or downside to setting the alarm manager delay to only +100? I'm thinking something along the lines of not enough time to flush resources?

[Tutorial] Learn to create a Flip Coin Application on Android

Hello,
When you start to learn Android Development, it can be interesting to make some little and fun applications. It’s good to motivate yourself and it is also a great way to discover some specific part of the Android SDK. Today, I propose you to create a Flip Coin Application on Android to help you to discover how to use the Animation API.
Note that you can discover this tutorial directly in video on Youtube :
To create a Flip Coin Application, the first thing is to have two images for the head and the tail of the coin. We will use a Minnesota Quarter Coin here :
{
"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"
}
The second step is to define an ImageView and a Button in the layout of the Main Activity :
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.ssaurel.coinflip.MainActivity">
<ImageView
android:id="@+id/coin"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/heads"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"/>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/coin"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp"
android:text="Flip"/>
</RelativeLayout>
Now, we can write the Java code. The most interesting part of our application is implemented in the flipCoin() method. We create two animations :
- A Fade Out animation to let the coin disappear when the user will click on the button to flip the coin
- A Fade In animation to let the coin appear after we flip the coin randomly
The Fade Out and Fade In animations are created via the AlphaAnimation class on Android. We are going to animate the alpha property from 1 to 0 for the Fade Out effect and then from 0 to 1 for the Fade In effect.
We add an AnimationListener on the Fade Out animation to be sure to flip the coin and to start the Fade In animation just when the Fade Out effect will be ended.
The code for the Main Activity will have the following form :
Code:
package com.ssaurel.coinflip;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
public static final Random RANDOM = new Random();
private ImageView coin;
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
coin = (ImageView) findViewById(R.id.coin);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
flipCoin();
}
});
}
private void flipCoin() {
Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setInterpolator(new AccelerateInterpolator());
fadeOut.setDuration(1000);
fadeOut.setFillAfter(true);
fadeOut.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
coin.setImageResource(RANDOM.nextFloat() > 0.5f ? R.drawable.tails : R.drawable.heads);
Animation fadeIn = new AlphaAnimation(0, 1);
fadeIn.setInterpolator(new DecelerateInterpolator());
fadeIn.setDuration(3000);
fadeIn.setFillAfter(true);
coin.startAnimation(fadeIn);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
coin.startAnimation(fadeOut);
}
}
Now, you can run the application and enjoy the final result :
Don't hesitate to give it a try and give your feedbacks.
Thanks.
Sylvain
nice

[Tutorial] Learn to create the game "Spin The Bottle" for Android

Hello,
I create that thread to present you a tutorial learning you to create the game "Spin The Bottle" for Android. It is also a good way to discover how to use Android Animations API.
What is better that creating some funny games to learn the basics of Android development ? Today, you’re going to discover more on the Android Animation API by creating the game “Spin The Bottle”.
Note that you can discover this tutorial in video on Youtube too :
Spin the bottle is a party game in which several players sit/stand/kneel in a circle. A bottle is placed on the floor in the center of the circle. A player spins the bottle, and must kiss the person to whom the bottle points when it stops spinning.
With our application, it is not necessary any more to have a real bottle, you will just need a smartphone. And it’s great because everyone has always a smartphone on him nowadays.
First step is to find two specific images : one for the floor which will be defined as background of the game and an other for the bottle which will be rotated during the game.
We have chosen to use these both images :
Floor image for the background
{
"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"
}
Bottle image
Now, we need to define the layout of our game “Spin The Bottle”. We have a Relative Layout with the floor image as background and we add a bottle in the center of this layout :
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background">
<ImageView
android:id="@+id/bottle"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/beer_bottle"
android:layout_centerInParent="true" />
</RelativeLayout>
The next step is to write the Java code of the Main Activity. First, we get references for the views. Then, we install a click listener on the main layout of the Main Activity. Thus, the user will just have to touch the screen to spin the bottle and to start the game.
The core of the game is in the spinTheBottle() method. We are going to define a RotateAnimation from start angle to end angle centered on the center of the bottle. The end angle will be defined randomly to simulate really the game “Spin The Bottle”. We should store the last end angle value to restart the bottle in the same position for the next turn of the game.
The Code of the Main Activity will have the following form :
Code:
package com.ssaurel.spinthebottle;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
public static final Random RANDOM = new Random();
private View main;
private ImageView bottle;
private int lastAngle = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
main = findViewById(R.id.root);
bottle = (ImageView) findViewById(R.id.bottle);
main.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
spinTheBottle();
}
});
Toast.makeText(this, R.string.touch_to_spin, Toast.LENGTH_SHORT).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_spin :
spinTheBottle();
break;
case R.id.action_zero :
resetTheBottle();
break;
}
return super.onOptionsItemSelected(item);
}
private void spinTheBottle() {
int angle = RANDOM.nextInt(3600 - 360) + 360;
float pivotX = bottle.getWidth() / 2;
float pivotY = bottle.getHeight() / 2;
final Animation animRotate = new RotateAnimation(lastAngle == -1 ? 0 : lastAngle, angle, pivotX, pivotY);
lastAngle = angle;
animRotate.setDuration(2500);
animRotate.setFillAfter(true);
bottle.startAnimation(animRotate);
}
private void resetTheBottle() {
float pivotX = bottle.getWidth() / 2;
float pivotY = bottle.getHeight() / 2;
final Animation animRotate = new RotateAnimation(lastAngle == -1 ? 0 : lastAngle, 0, pivotX, pivotY);
lastAngle = -1;
animRotate.setDuration(2000);
animRotate.setFillAfter(true);
bottle.startAnimation(animRotate);
}
}
You can run the application and play your game :
To go further, you can download the game “Spin The Bottle” created in this tutorial on the Google Play Store :
https://play.google.com/store/apps/details?id=com.ssaurel.spinthebottle

[Tutorial] Learn to create an Anagram Game for Android

Hello,
In that tutorial, you are going to learn how to create an Anagram game for Android by using Android Studio.
{
"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"
}
But what is an Anagram ?
An anagram is direct word switch or word play, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once; for example, the word anagram can be rearranged into “nag a ram”.
Note that you can discover this tutorial in video on YouTube :
Create the User Interface
To start, we are going to create the User Interface of our Anagram game. In our User Interface, we will have a TextView to display the anagram. Then, an EditText to let the users to enter the word they found. And finally both buttons : one to validate the word entered and another to start a new game.
We make some customizations on these views. For example, we center them horizontally and this gives us the following code :
Code:
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/wordTv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Word To Find"
android:textSize="22sp"
android:textStyle="bold" />
<EditText
android:id="@+id/wordEnteredEt"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="@id/wordTv"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:inputType="textCapCharacters" />
<Button
android:id="@+id/validate"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="@id/wordEnteredTv"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp"
android:text="Validate" />
<Button
android:id="@+id/newGame"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="@id/validate"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:text="New Game" />
</RelativeLayout>
Core of the Anagram Game
Now, we can create the core of our game : the Anagram class. We will use this class to generate new words to find and to shuffle the word to find. Note that the list of words used for the game will be defined in this class :
Code:
package com.ssaurel.anagram;
import java.util.Random;
/**
* Created by ssaurel on 05/09/2017.
*/
public class Anagram {
public static final Random RANDOM = new Random();
public static final String[] WORDS = {"ACCOUNT", "ADDITION",
"AGREEMENT", "ANGRY", "ANIMAL", "BEHAVIOUR", "BETWEEN", "BLACK", "CHEMICAL", "FOOLISH",
"FREQUENT", "GOVERNMENT", "GRAIN", "GRASS", "HOSPITAL", "PAYMENT", "POLITICAL",
"PROCESS", "SHAME", "SMASH", "SMOOTH", "STATEMENT", "SUBSTANCE", "TEACHING", "TENDENCY",
"TOMORROW", "TOUCH", "UMBRELLA", "WEATHER", "YESTERDAY"};
public static String randomWord() {
return WORDS[RANDOM.nextInt(WORDS.length)];
}
public static String shuffleWord(String word) {
if (word != null && !"".equals(word)) {
char a[] = word.toCharArray();
for (int i = 0; i < a.length; i++) {
int j = RANDOM.nextInt(a.length);
char tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return new String(a);
}
return word;
}
}
Code of the Main Activity
Now, we can write the Java code of the main activity. The code is pretty simple. We get references of the views in the onCreate method. Then we install OnClickListener for both buttons.
In the validate method, we are going to check if the word entered by the user if equal to the word to find. If yes, we display a message of congratulations to the user and we start a new game by calling the newGame method.
The newGame method is used to start a new Anagram game. We generate a random word to find by calling the randomWord method of the Anagram class. Then, we shuffle this word via the shuffleWord method of the Anagram class. Finally, we display the word shuffled on the screen. The game starts and the user must find the word.
This gives us the following code :
Code:
package com.ssaurel.anagram;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private TextView wordTv;
private EditText wordEnteredTv;
private Button validate, newGame;
private String wordToFind;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wordTv = (TextView) findViewById(R.id.wordTv);
wordEnteredTv = (EditText) findViewById(R.id.wordEnteredEt);
validate = (Button) findViewById(R.id.validate);
validate.setOnClickListener(this);
newGame = (Button) findViewById(R.id.newGame);
newGame.setOnClickListener(this);
newGame();
}
@Override
public void onClick(View view) {
if (view == validate) {
validate();
} else if (view == newGame) {
newGame();
}
}
private void validate() {
String w = wordEnteredTv.getText().toString();
if (wordToFind.equals(w)) {
Toast.makeText(this, "Congratulations ! You found the word " + wordToFind, Toast.LENGTH_SHORT).show();
newGame();
} else {
Toast.makeText(this, "Retry !", Toast.LENGTH_SHORT).show();
}
}
private void newGame() {
wordToFind = Anagram.randomWord();
String wordShuffled = Anagram.shuffleWord(wordToFind);
wordTv.setText(wordShuffled);
wordEnteredTv.setText("");
}
}
Play to our Anagram Game
Now, it’s time to play to our Anagram Game. We launch the Anagram Game on an Android device and we see the following screen :
We have to enter the word to find in the EditText and then clicking to the validate button to win the game.
That’s all for that tutorial. To discover more tutorials on Android Development, don’t hesitate to subscribe to the SSaurel’s Channel on YouTube : https://www.youtube.com/channel/UCXoh49OXVg1UGjgWX1JRvlw
You can also discover this tutorial directly on the SSaurel's Blog : https://www.ssaurel.com/blog/learn-to-create-an-anagram-game-for-android/
Don't hesitate to give it a try and give me your feedback.
Thanks.
Sylvain

Categories

Resources