[GUIDE] Adding Splash Screen to Your Application. - Java for Android App Development

A splash screen is an image that appears while a game or program is loading. Splash screen can be used to show app / company logo for a couple of second.
In this GUIDE we are going to learn how to implement splash screen in your android application.
I have created a application with name com.example.assassin.splash.screen.test
Browse through res/drawable-hdpi and paste a png image into the folder.
[Note: Image used in this guide is with name = splash.png , height=800 , width=480]
Now browse to res/layout folder and create a splash activity.
To create a splash activity Right click on layout folder and select New>Other>Android>Android XML File
And create a file called splash
Having problem? See the snapshots.
ScreenShot
{
"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 open your splash.xml file and paste the following codes.
Code:
[B]<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/splash"
>
</LinearLayout>[/B]
Save it.
Browse to src/com.example.assassin.splash.screen.test and create a new class name Splash
ScreenShot
Code for Splash.java
Code:
package com.example.assassin.splash.screen.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class Splash extends Activity{
@Override
protected void onCreate(Bundle assassin) {
// TODO Auto-generated method stub
super.onCreate(assassin);
setContentView(R.layout.splash);
Thread timer = new Thread(){
public void run(){
try{
sleep(5000); //time to display splash screen in millisecond
}
catch (InterruptedException e){
e.printStackTrace();
}
finally{
Intent openStartingPoint = new Intent("com.example.assassin.splash.screen.STARTINGPOINT");
startActivity(openStartingPoint);
}
}
};
timer.start();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
Save It.
ScreenShot
Now open AndroidManifest.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.assassin.splash.screen.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".Splash"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.assassin.splash.screen.test.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="com.example.assassin.splash.screen.STARTINGPOINT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
Save It.
ScreenShot
Well now you have successfully created a splash sceen activity for your application.
Designing MainActivity.xml is up to you.
MainActivity.xml used in this guide looks like this:
ScreenShot
​
Please correct me if the code goes wrong somewhere.
Saurabh Shah

Code:
package com.example.arpit;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.app.AlertDialog;
import android.content.Intent;
public class New extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
Thread timer = new Thread(){
public void run(){
try{
sleep(5000); //time to display splash screen in millisecond
}
catch (InterruptedException e){
e.printStackTrace();
}
finally{
Intent openStartingPoint = new Intent("com.example.arpit.Extra");
startActivity(openStartingPoint);
}
}
};
timer.start();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
Log says activity com.example.arpit.Extra not found
But it is present there .Is there any format to be included with the like .class or .java
Sent from my GT-S5570 using XDA Premium 4 mobile app

arpitkh96 said:
Code:
package com.example.arpit;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.app.AlertDialog;
import android.content.Intent;
public class New extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
Thread timer = new Thread(){
public void run(){
try{
sleep(5000); //time to display splash screen in millisecond
}
catch (InterruptedException e){
e.printStackTrace();
}
finally{
Intent openStartingPoint = new Intent("com.example.arpit.Extra");
startActivity(openStartingPoint);
}
}
};
timer.start();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
Log says activity com.example.arpit.Extra not found
But it is present there .Is there any format to be included with the like .class or .java
Sent from my GT-S5570 using XDA Premium 4 mobile app
Click to expand...
Click to collapse
I can see where your code is going wrong.
you have included com.example.arpit.Extra in the new intent.
it should be com.example.arpit.STARTINGPOINT
Here is the corrected code for your class.
Code:
package com.example.arpit;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.app.AlertDialog;
import android.content.Intent;
public class New extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
Thread timer = new Thread(){
public void run(){
try{
sleep(5000); //time to display splash screen in millisecond
}
catch (InterruptedException e){
e.printStackTrace();
}
finally{
Intent openStartingPoint = new Intent("com.example.arpit.STARTINGPOINT");
startActivity(openStartingPoint);
}
}
};
timer.start();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
Hope this helps u.

a-ssassi-n said:
I can see where your code is going wrong.
you have included com.example.arpit.Extra in the new intent.
it should be com.example.arpit.STARTINGPOINT
Here is the corrected code for your class.
Code:
package com.example.arpit;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.app.AlertDialog;
import android.content.Intent;
public class New extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
Thread timer = new Thread(){
public void run(){
try{
sleep(5000); //time to display splash screen in millisecond
}
catch (InterruptedException e){
e.printStackTrace();
}
finally{
Intent openStartingPoint = new Intent("com.example.arpit.STARTINGPOINT");
startActivity(openStartingPoint);
}
}
};
timer.start();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
Hope this helps u.
Click to expand...
Click to collapse
I thought it was a name of activity.thanks
Edit-Same error
Code:
/ActivityManager( 1087): START {act=com.example.arpit.STARTINGPOINT u=0} from pid 3386
W/dalvikvm( 3386): threadid=11: thread exiting with uncaught exception (group=0x40aba300)
E/AndroidRuntime( 3386): FATAL EXCEPTION: Thread-153
E/AndroidRuntime( 3386): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.example.arpit.STARTINGPOINT }
E/AndroidRuntime( 3386): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1545)
E/AndroidRuntime( 3386): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1416)
E/AndroidRuntime( 3386): at android.app.Activity.startActivityForResult(Activity.java:3351)
E/AndroidRuntime( 3386): at android.app.Activity.startActivityForResult(Activity.java:3312)
E/AndroidRuntime( 3386): at android.app.Activity.startActivity(Activity.java:3522)
E/AndroidRuntime( 3386): at android.app.Activity.startActivity(Activity.java:3490)
E/AndroidRuntime( 3386): at com.example.arpit.New$100000000.run(New.java:30)
Sent from my GT-S5570 using XDA Premium 4 mobile app

arpitkh96 said:
I thought it was a name of activity.thanks
Edit-Same error
Code:
/ActivityManager( 1087): START {act=com.example.arpit.STARTINGPOINT u=0} from pid 3386
W/dalvikvm( 3386): threadid=11: thread exiting with uncaught exception (group=0x40aba300)
E/AndroidRuntime( 3386): FATAL EXCEPTION: Thread-153
E/AndroidRuntime( 3386): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.example.arpit.STARTINGPOINT }
E/AndroidRuntime( 3386): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1545)
E/AndroidRuntime( 3386): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1416)
E/AndroidRuntime( 3386): at android.app.Activity.startActivityForResult(Activity.java:3351)
E/AndroidRuntime( 3386): at android.app.Activity.startActivityForResult(Activity.java:3312)
E/AndroidRuntime( 3386): at android.app.Activity.startActivity(Activity.java:3522)
E/AndroidRuntime( 3386): at android.app.Activity.startActivity(Activity.java:3490)
E/AndroidRuntime( 3386): at com.example.arpit.New$100000000.run(New.java:30)
Sent from my GT-S5570 using XDA Premium 4 mobile app
Click to expand...
Click to collapse
Still getting Error.??
Upload your project file as a zip.
i will take a look at that after my exams are over(after 3days)
Thankyou.

a-ssassi-n said:
Still getting Error.??
Upload your project file as a zip.
i will take a look at that after my exams are over(after 3days)
Thankyou.
Click to expand...
Click to collapse
Problem solved by
New.this,Extra.class rather than "com.example.Arpit.STARTINGPOINT"
Sent from my GT-S5570 using XDA Premium 4 mobile app

Great :good:

Related

No Activity found to handle Intent - Error

Hey guys I have already made few apps and doing exactly the same this time though I am getting errors. Please check my logcat below
Code:
05-04 07:35:41.888: E/AndroidRuntime(1066): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.droidacid.count.COUNT }
This is my java code of main class
Code:
package com.droidacid.count;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class mainMenu extends Activity {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
Button count = (Button) findViewById(R.id.count);
try{
bapticalc.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("com.droidacid.count.COUNT"));
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
this is my count class code
Code:
package com.droidacid.count;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class system extends Activity{
Button system;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.apticalc);
system = (Button) findViewById(R.id.system);
system.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("com.droidacid.count.SYSTEM"));
}
});
}
}
And atlast this is my android manifest code
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.droidacid.count"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".mainMenu"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".count"
android:label="@string/app_name"
>
<intent-filter>
<action android:name="com.example.sweet_memories.COUNT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
I am really sorry for such a long question guys but really wanted to state everything happening with me...Also I would really appreciate if someone would help me on how to check logcat properly for errors?
So, from your mainMenu you are sending an intent to start the "count", is that the activity that you have named system?
Code:
public class system extends Activity
and in the "system" activity you are trying to start itself? And you also have a button named system?
I think you should rename the class "system" to "count", eclipse will offer you to change the compilation unit to count automatically. And I shouldn't name a button system, maybe mBtnSystem or something like that.
thanks problem solved
coolbud012 said:
thanks problem solved
Click to expand...
Click to collapse
Great. Please add [solved] to the thread title.

Browser not working! Please help :(

Hi, I was trying to make a browser. But obviously, its not working. Please help me out. I will be providing all the codes here:
Thanks in advance ...
manifest:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.browser"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-premission android:name="android.content.permissions.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.browser.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.browser.ta"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.TA" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.class:
Code:
package com.example.browser;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
EditText search = (EditText) findViewById(R.id.editText1);
WebView wb = (WebView) findViewById(R.id.webView1);
Button back = (Button) findViewById(R.id.button2);
Button forward = (Button) findViewById(R.id.button1);
Button Bsearch = (Button) findViewById(R.id.dd);
String s = search.getText().toString();
ta t = new ta();
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wb.getSettings().setBuiltInZoomControls(true);
wb.getSettings().setJavaScriptEnabled(true);
wb.getSettings().setLoadWithOverviewMode(true);
wb.getSettings().setSavePassword(true);
wb.getSettings().setAllowFileAccess(true);
back.setOnClickListener(this);
forward.setOnClickListener(this);
Bsearch.setOnClickListener(this);
wb.setWebViewClient(t);
wb.loadUrl("http://www.google.com");
}
[user=439709]@override[/user]
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.dd: // search
ProgressDialog d = ProgressDialog.show(this, "loading",
"Please wait");
wb.loadUrl("http://" + s);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(search.getWindowToken(), 0);
break;
case R.id.button2: // back
if (wb.canGoBack())
wb.goBack();
break;
case R.id.button1: // forward
if (wb.canGoForward())
wb.goForward();
break;
}
}
}
ta.class:
Code:
package com.example.browser;
import android.app.ProgressDialog;
import android.content.Context;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class ta extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView v, String url) {
v.loadUrl(url);
return true;
}
}
Logcat?
nikwen said:
Logcat?
Click to expand...
Click to collapse
Sorry, I completely forgot, about that!!
Here it is:
Code:
07-14 16:12:46.367: E/AndroidRuntime(287): FATAL EXCEPTION: main
07-14 16:12:46.367: E/AndroidRuntime(287): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.browser/com.example.browser.MainActivity}: java.lang.NullPointerException
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-14 16:12:46.367: E/AndroidRuntime(287): at android.os.Handler.dispatchMessage(Handler.java:99)
07-14 16:12:46.367: E/AndroidRuntime(287): at android.os.Looper.loop(Looper.java:123)
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-14 16:12:46.367: E/AndroidRuntime(287): at java.lang.reflect.Method.invokeNative(Native Method)
07-14 16:12:46.367: E/AndroidRuntime(287): at java.lang.reflect.Method.invoke(Method.java:521)
07-14 16:12:46.367: E/AndroidRuntime(287): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-14 16:12:46.367: E/AndroidRuntime(287): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-14 16:12:46.367: E/AndroidRuntime(287): at dalvik.system.NativeStart.main(Native Method)
07-14 16:12:46.367: E/AndroidRuntime(287): Caused by: java.lang.NullPointerException
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.Activity.findViewById(Activity.java:1637)
07-14 16:12:46.367: E/AndroidRuntime(287): at com.example.browser.MainActivity.<init>(MainActivity.java:17)
07-14 16:12:46.367: E/AndroidRuntime(287): at java.lang.Class.newInstanceImpl(Native Method)
07-14 16:12:46.367: E/AndroidRuntime(287): at java.lang.Class.newInstance(Class.java:1429)
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
07-14 16:12:46.367: E/AndroidRuntime(287): ... 11 more
Read This http://forum.xda-developers.com/showthread.php?t=2325164
then look at your logcat
Code:
07-14 16:12:46.367: E/AndroidRuntime(287): Caused by: java.lang.NullPointerException
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.Activity.findViewById(Activity.java:1637)
07-14 16:12:46.367: E/AndroidRuntime(287): at com.example.browser.MainActivity.<init>(MainActivity.java:17)
then count from the top, and your error is your edittext
I looked at the edit-text. But i still cannot find any wrong. However, I modified one of my buttons with this:
Code:
case R.id.dd: // search
wb.loadUrl("http://" + search.getText().toString());
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(search.getWindowToken(), 0);
break;
Still. no help...
Code:
07-14 16:12:46.367: E/AndroidRuntime(287): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.browser/com.example.browser.MainActivity}: java.lang.NullPointerException
What is this about??
I think, there is something wrong with the manifest, Please take a look at it!
read nikwens debugging guide I linked again.
then here
07-14 16:12:46.367: E/AndroidRuntime(287): at com.example.browser.MainActivity.<init>(MainActivity.java:17
thats the name of your app, and the line you have the problem at.
nullpointers could be a million things, look for your app and the line it errors on.
also intent.action.TA isnt a thing. take that out.
out of ideas said:
read nikwens debugging guide I linked again.
then here
07-14 16:12:46.367: E/AndroidRuntime(287): at com.example.browser.MainActivity.<init>(MainActivity.java:17
thats the name of your app, and the line you have the problem at.
nullpointers could be a million things, look for your app and the line it errors on.
also intent.action.TA isnt a thing. take that out.
Click to expand...
Click to collapse
Hey, thanks for linking it.
It even tells you that the method which fails is findViewById().
nikwen said:
Hey, thanks for linking it.
It even tells you that the method which fails is findViewById().
Click to expand...
Click to collapse
Yeah, you were right, there were couple of wrong ids, in that code. But I have edited all of them now.. Still the app is crashing and I am getting the same error, for "findByView".
I am also pasting, the new code and the UI xml.
activity_main.xml:
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" >
<EditText
android:id="@+id/editText1"
android:layout_width="291dp"
android:layout_height="wrap_content"
android:layout_x="0dp"
android:layout_y="4dp"
android:hint="Enter Search!" />
<WebView
android:id="@+id/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignLeft="@+id/editText1"
android:layout_alignParentBottom="true"
android:layout_below="@+id/back" />
<Button
android:id="@+id/s"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignTop="@+id/back"
android:text="Search" />
<Button
android:id="@+id/dd"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_toRightOf="@+id/s"
android:text="Forward" />
<Button
android:id="@+id/back"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/dd"
android:layout_alignBottom="@+id/dd"
android:layout_toRightOf="@+id/dd"
android:text="Back" />
</RelativeLayout>
MainActivity:
Code:
package com.example.browser;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
EditText search = (EditText) findViewById(R.id.editText1);
WebView wb = (WebView) findViewById(R.id.webView1);
Button back = (Button) findViewById(R.id.s);
Button forward = (Button) findViewById(R.id.back);
Button Bsearch = (Button) findViewById(R.id.dd);
ta t = new ta();
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
back.setOnClickListener(this);
forward.setOnClickListener(this);
Bsearch.setOnClickListener(this);
wb.loadUrl("http://www.google.com");
wb.setWebViewClient(t);
}
[user=439709]@override[/user]
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.dd: // search
wb.loadUrl("http://" + search.getText().toString());
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(search.getWindowToken(), 0);
break;
case R.id.back: // back
if (wb.canGoBack())
wb.goBack();
break;
case R.id.s: // forward
if (wb.canGoForward())
wb.goForward();
break;
}
}
}
Please help me out! I know I am dumb. But I am learning it all by myself, without a mentor at the age of 16. Its little complex for me. I have spent, a lot of time finding the error. But its not working.
It doesn't like trying to find the view where you are declaring your variables. The findviewbyid should be moved in to your oncreate.
This works:
Code:
public class MainActivity extends Activity implements OnClickListener {
EditText search;
WebView wb;
Button back;
Button forward;
Button Bsearch;
ta t = new ta();
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = (EditText) findViewById(R.id.editText1);
wb = (WebView) findViewById(R.id.webView1);
back = (Button) findViewById(R.id.s);
forward = (Button) findViewById(R.id.back);
Bsearch = (Button) findViewById(R.id.dd);
back.setOnClickListener(this);
forward.setOnClickListener(this);
Bsearch.setOnClickListener(this);
wb.loadUrl("http://www.google.com");
wb.setWebViewClient(t);
}
After looking in to the reason why it would crash, my only educated guess is because you are trying to find the view without the view being set. View is set in the oncreate method.
zalez said:
It doesn't like trying to find the view where you are declaring your variables. The findviewbyid should be moved in to your oncreate.
This works:
Code:
public class MainActivity extends Activity implements OnClickListener {
EditText search;
WebView wb;
Button back;
Button forward;
Button Bsearch;
ta t = new ta();
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = (EditText) findViewById(R.id.editText1);
wb = (WebView) findViewById(R.id.webView1);
back = (Button) findViewById(R.id.s);
forward = (Button) findViewById(R.id.back);
Bsearch = (Button) findViewById(R.id.dd);
back.setOnClickListener(this);
forward.setOnClickListener(this);
Bsearch.setOnClickListener(this);
wb.loadUrl("http://www.google.com");
wb.setWebViewClient(t);
}
After looking in to the reason why it would crash, my only educated guess is because you are trying to find the view without the view being set. View is set in the oncreate method.
Click to expand...
Click to collapse
Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = (EditText) findViewById(R.id.editText1);
wb = (WebView) findViewById(R.id.webView1);
back = (Button) findViewById(R.id.s);
forward = (Button) findViewById(R.id.back);
Bsearch = (Button) findViewById(R.id.dd);
back.setOnClickListener(this);
forward.setOnClickListener(this);
Bsearch.setOnClickListener(this);
wb.loadUrl("http://www.google.com");
wb.setWebViewClient(t);
}
I modified my code, with this.. But, its still crashing
Post your entire MainActivity.class. I copied all of your code and changed what I posted back and do not get a crash.
This is working for me:
Code:
package com.example.browser;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
EditText search;
WebView wb;
Button back;
Button forward;
Button Bsearch;
ta t = new ta();
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = (EditText) findViewById(R.id.editText1);
wb = (WebView) findViewById(R.id.webView1);
back = (Button) findViewById(R.id.s);
forward = (Button) findViewById(R.id.back);
Bsearch = (Button) findViewById(R.id.dd);
back.setOnClickListener(this);
forward.setOnClickListener(this);
Bsearch.setOnClickListener(this);
wb.loadUrl("http://www.google.com");
wb.setWebViewClient(t);
}
[user=439709]@override[/user]
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.dd: // search
wb.loadUrl("http://" + search.getText().toString());
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(search.getWindowToken(), 0);
break;
case R.id.back: // back
if (wb.canGoBack())
wb.goBack();
break;
case R.id.s: // forward
if (wb.canGoForward())
wb.goForward();
break;
}
}
}
hiphop12ism said:
Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = (EditText) findViewById(R.id.editText1);
wb = (WebView) findViewById(R.id.webView1);
back = (Button) findViewById(R.id.s);
forward = (Button) findViewById(R.id.back);
Bsearch = (Button) findViewById(R.id.dd);
back.setOnClickListener(this);
forward.setOnClickListener(this);
Bsearch.setOnClickListener(this);
wb.loadUrl("http://www.google.com");
wb.setWebViewClient(t);
}
I modified my code, with this.. But, its still crashing
Click to expand...
Click to collapse
It is still crashing. However, keep that code as it is right. The setContentView method needs to be called before getting the views.
In your xml there are some errors though:
You always use @+id/...
Use that just for android:id="@+id/myId".
Everywhere else do it without the plus, e.g. android:layout_below="@id/asdf".
The plus tells the compiler to create a new id. However, you do not want it to create a new id in android:layout_below but to use an already existing id.
Are all ids in the xml you load with setContentView? Is the logcat still the same? Could you please highlight the line which makes it crash?
nikwen said:
It is still crashing. However, keep that code as it is right. The setContentView method needs to be called before getting the views.
In your xml there are some errors though:
You always use @+id/...
Use that just for android:id="@+id/myId".
Everywhere else do it without the plus, e.g. android:layout_below="@id/asdf".
The plus tells the compiler to create a new id. However, you do not want it to create a new id in android:layout_below but to use an already existing id.
Are all ids in the xml you load with setContentView? Is the logcat still the same? Could you please highlight the line which makes it crash?
Click to expand...
Click to collapse
Actually, I fixed it. I made a new project. I thought of another way of making the browser.
I realised, there were lots of mistakes in the xml file.
here are my new codes. (Thank you everbody its over finally)
the UI
Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<EditText
android:id="@+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="enter url" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="100"
android:orientation="horizontal" >
<Button
android:id="@+id/s"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="search" />
<Button
android:id="@+id/back"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="back" />
<Button
android:id="@+id/forward"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_weight="35"
android:text="forward" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<WebView
android:layout_width="match_parent"
android:layout_height="308dp"
android:id="@+id/wd" />
</LinearLayout>
</LinearLayout>
MainActivity:
Code:
package com.example.asd;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
EditText et;
Button search, back, forward;
WebView wb;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText1);
search = (Button) findViewById(R.id.s);
back = (Button) findViewById(R.id.back);
forward = (Button) findViewById(R.id.forward);
wb = (WebView) findViewById(R.id.wd);
search.setOnClickListener(this);
wb.getSettings().setJavaScriptEnabled(true);
wb.getSettings().setAllowFileAccess(true);
wb.getSettings().setBuiltInZoomControls(true);
}
[user=439709]@override[/user]
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.s:
wb.loadUrl(et.getText().toString());
wb.setWebViewClient(new callb());
break;
}
}
private class callb extends WebViewClient {
[user=439709]@override[/user]
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
wb.loadUrl(url);
return true;
}
}
}
But can you tell me, how can I make it more advanced. Like, when hit a editText on a website itslf.. Nothing Happens
You have to request focus on the webview:
wb.requestFocus(View.FOCUS_DOWN);

[GUIDE][UP] How to easly Implement J.W. ViewPagerIndicator + transitions [SAMPLE APP]

IF YOU MAKE USE OF THIS GUIDE AND YOU WILL MAKE PUBLIC YOUR APPLICATION, PLEASE THANK THE OP AND GIVE ME & ENRICOCID CREDITS/MENTION . THANK YOU
1) Set Up Jake Wharton ViewPagerIndicator
{
"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"
}
​
IF YOU WANNA DOWNLOAD MY SAMPLE APP GO HERE:
http://forum.xda-developers.com/showpost.php?p=45742129&postcount=4​
SITE>>>http://viewpagerindicator.com/<<<SITE​
1 - Download JakeWharton ViewPagerIndicator:
​
Download from here: JakeWharton ViewPagerIndicator download
Or from the website: http://viewpagerindicator.com/
2 - OPEN ECLIPSE
First you need to extract "library" folder from the zip and save it in your documents folder, like the picture below:
Now drag & drop "library" folder to your Documents directory:
- Import downloaded ViewPagerIndicator Library to your workspace:
GO TO FILE > NEW > OTHER > ANDROID > ANDROID PROJECT FROM EXISTING CODE:
- Click next button and browse directory (1) to select the downloaded ViewPagerIndicator Library (2):
(1) CLICK BROWSE...
(2) AND SELECT "LIBRARY" FOLDER, GO TO Libraries > My Documents > Library, click OK.
Now give a name to this project (for example "ViewPagerIndicator") and check "Copy project into workspace", like the picture:
Click "Finish"
If you like my work don't Forget To Hit Thanks, five star
:good: or offer me a beer :good:
​
Make a donation​
2) How to load VievPagerIndicator to Your Project​
- Create a new Android Application Project:
- Give a name to your project (for example "ViewPagerTest"), like the picture below:
​
- Go next and click finish to create the project
​
- Now navigate to your project properties:
- Go to Android and Click "Add" to load the library into your project:
​
You will receive an error:
To fix this error you have two options:
- 1) delete the libs folder of your project:
- 2) [RECOMENDED]The best way is to copy the android-support-v4.jar from sdk/extras/android/support/v4 to your workspace/ViewPagerIndicator/libs folder, without deleting libs folder of your project!!!
If you have other errors like this:
go to ViewPagerIndicator properties and change the "Project Build Target". This must be equal to that of the ViewPagerTest project:
---------- Post added at 08:28 PM ---------- Previous post was at 08:27 PM ----------​
3) Create Layouts ​
Blue = Add
Red = Delete
- Now go to res > layout
and edit activity_main.xml deleting the entire code:
Code:
[COLOR="red"]<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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>[/COLOR]
Copy & paste the code below to your activity_main.xml
Code:
[COLOR="Blue"]<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.viewpagerindicator.TitlePageIndicator
android:id="@+id/indicator"
android:padding="10dip"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:background="#000000"
android:textColor="#2FB3E3"
app:footerColor="#2FB3E3"
app:footerLineHeight="1dp"
app:footerIndicatorHeight="3dp"
app:footerIndicatorStyle="underline"
app:selectedColor="#FFFFFF"
app:selectedBold="true"
/>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
</LinearLayout>[/COLOR]
Now create new .xml files in your layout folder (I will create 3 layouts for example). Go to New > other
and select "Android XML file":
​
Give a name to your xml file (for example "layout1") and select linear layout, click finish. See the picture:
Create two other layouts and call them "layout2" and "layout3":
4)Implement ViewPager using fragments ​
Blue = Add
Red = Delete
Now go to src > com.example.viewpagertest and edit MainActivity.java
Delete the content marked in red:
Code:
[COLOR="Blue"]package com.example.viewpagertest;[/COLOR]
[COLOR="Red"]import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}[/COLOR]
and add the following code:
Code:
[COLOR="blue"]import com.viewpagerindicator.PageIndicator;
import com.viewpagerindicator.TitlePageIndicator;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import com.example.viewpagertest.R;
public class MainActivity extends FragmentActivity {
FragmentAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;
int Number = 0;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new FragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TitlePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}[/COLOR]
The result:
Code:
package com.example.viewpagertest;
import com.viewpagerindicator.PageIndicator;
import com.viewpagerindicator.TitlePageIndicator;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import com.example.viewpagertest.R;
public class MainActivity extends FragmentActivity {
FragmentAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;
int Number = 0;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new FragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TitlePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Now you have to create three fragments into src > com.example.viewpagertest folder:
- go to new > other:
and create three classes named "FirstActivity", "SecondActivity" and "ThirdActivity" like the picture below:
Now edit FirstActivity.java in src > com.example.viewpagertest folder and delete the red code:
Code:
[COLOR="Blue"]package com.example.viewpagertest;[/COLOR]
[COLOR="Red"]public class FragmentAdapter {
}[/COLOR]
and add the following code:
Code:
package com.example.viewpagertest;
[COLOR="Blue"]import com.example.viewpagertest.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FirstActivity extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.layout1, null);
return v;
}
}
[/COLOR]
For the SecondActivity class:
Code:
package com.example.viewpagertest;
import com.example.viewpagertest.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class SecondActivity extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.layout2, null);
return v;
}
}
For the ThirdActivity class:
Code:
package com.example.viewpagertest;
import com.example.viewpagertest.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ThirdActivity extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.layout3, null);
return v;
}
}
Now we need to create a new class called "FragmentAdapter.java" into src > com.example.viewpagertest folder:
- go to new > other:
and create a new class called "FragmentAdapter" like the pictures:
click finish.
Now edit the FragmentAdapter.java in src > com.example.viewpagertest folder and delete the red code:
Code:
[COLOR="Blue"]package com.example.viewpagertest;[/COLOR]
[COLOR="Red"]public class FragmentAdapter {
}[/COLOR]
and add the following code:
Code:
package com.example.viewpagertest;
[COLOR="blue"]import com.viewpagerindicator.IconPagerAdapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatPagerAdapter;
public class FragmentAdapter extends FragmentStatPagerAdapter implements IconPagerAdapter{
public FragmentAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
[user=439709]@override[/user]
public int getIconResId(int index) {
// TODO Auto-generated method stub
return 0;
}
[user=439709]@override[/user]
public Fragment getItem(int position)
{
// TODO Auto-generated method stub
Fragment fragment = new FirstActivity();
switch(position){
case 0:
fragment = new FirstActivity();
break;
case 1:
fragment = new SecondActivity();
break;
case 2:
fragment = new ThirdActivity();
break;
}
return fragment;
}
[user=439709]@override[/user]
public int getCount() {
// TODO Auto-generated method stub
return 3;
}
[user=439709]@override[/user]
public CharSequence getPageTitle(int position){
String title = "";
switch(position){
case 0:
title = "First";
break;
case 1:
title = "Second";
break;
case 2:
title = "Third";
break;
}
return title;
}
}[/COLOR]
Save the entire project! Enjoy your App!!!
SAMPLE APP:
>>>DOWNLOAD<<<​
JAKE WHARTON VIEW PAGER INDICATOR GITHUB:
https://github.com/JakeWharton/Android-ViewPagerIndicator​
CREDITS:
- me
- enricocid
- Jake Warthon
Thanks to Xda!
ivn888 said:
CREDITS:
- me
- enricocid
- Jake Warthon
Thanks to Xda!
Click to expand...
Click to collapse
grandi ,ottimo lavoro
Awesome!! I badly needed this.. Thanks for the guide
Suppose I want to add pics and some strings for each layout, how do I do that?? Can you give an example for this also..?? thanks
rakz992 said:
Awesome!! I badly needed this.. Thanks for the guide
Suppose I want to add pics and some strings for each layout, how do I do that?? Can you give an example for this also..?? thanks
Click to expand...
Click to collapse
You can use the ImageView to display images in your Application.There are many different configuration options and many screens from different devices that you should take into account. I write a little guide using my viewer app.
EXAMPLE:
First to use imageview you have to add resources, in Eclipse navigate to res/values/strings.xml.
Edit the strings.xml
This is the content of string.xml:
Code:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ViewPagerTest</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
</resources>
Add the following string:
Code:
[COLOR="Blue"]<string name="content">image</string>[/COLOR]
Like this:
Code:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ViewPagerTest</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
[COLOR="blue"]<string name="content">image</string>[/COLOR]
</resources>
Now you have to add a picture in the appropriate project folder, as you would have noticed there are 5 folders that contain the image resources of the project :
res/drawable-hdpi
res/drawable-ldpi
res/drawable-mdpi
res/drawable-xhdpi
res/drawable-xxhdpi
You can copy the images you want to put in you’re application in any one of these folders. Android SDK will automatically recognize any images you put on any one of these folders as drawable resources. Refer to official Android’s Drawable Resource and Screen Support to understand of how image works in Android.
Inside these folder there are default project .pngs. Now i use them to show you on how to add pict. The pictures are named ic_launcher.png
Now open layout1.xml
This is the blank layout:
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
and add the following code:
Code:
[COLOR="Blue"]<ImageView
android:id="@+id/image"
android:contentDescription="@string/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />[/COLOR]
Like this:
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
[COLOR="blue"]<ImageView
android:id="@+id/image"
android:contentDescription="@string/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />[/COLOR]
</LinearLayout>
Now you may open the Graphical layout editor to preview your UI:
--------------------------------------------------------------------------------------------------------------
1) Resources: string.xml, <string name="content">image</string>
2) Your_image
3) Use imageview to image to your layout:
<ImageView
android:id="@+id/image"
android:contentDescription="@string/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/Your_image" />[/COLOR]
@ivn888: We cannot see your pictures. You ran out of bandwidth.
nikwen said:
@ivn888: We cannot see your pictures. You ran out of bandwidth.
Click to expand...
Click to collapse
we are working to fix this problem... thanks
bro another help here
i want to add Zoom-out page transformer animation for slide from one layout to other..
should i replace mAdapter with this
pager.setPageTransformer(true, new ZoomOutPageTransformer());
can you help me on how to do it ?
thank you
rakz992 said:
bro another help here
i want to add Zoom-out page transformer animation for slide from one layout to other..
should i replace mAdapter with this
pager.setPageTransformer(true, new ZoomOutPageTransformer());
can you help me on how to do it ?
thank you
Click to expand...
Click to collapse
Tomorrow i will release a short guide on how to add this animation...
ivn888 said:
Tomorrow i will release a short guide on how to add this animation...
Click to expand...
Click to collapse
:highfive:
ivn888 said:
Tomorrow i will release a short guide on how to add this animation...
Click to expand...
Click to collapse
Thanks a lot
Customize the Animation with PageTransformer - How to add Zoom-out page transformer
Reference here: http://developer.android.com/training/animation/screen-slide.html#pagetransformer
- What you need:
- NineOldAndroids library:
>>>Download here<<<
Site>>>http://nineoldandroids.com/<<<Site
- ZoomOutPageTransformer.java
>>>Download here<<<​
1) First you need to extract "library" folder from the zip and save it in your documents folder, like the picture below:
2) Now drag & drop "library" folder to your Documents directory,i will rename it "library_1":
3) Import downloaded NineOld Library to your workspace:
GO TO FILE > NEW > OTHER > ANDROID > ANDROID PROJECT FROM EXISTING CODE
4) Click next button and browse directory to select the downloaded Library:
(1) CLICK BROWSE...
(2) AND SELECT "LIBRARY" FOLDER, GO TO Libraries > My Documents > Library_1, click OK.
5) Now give a name to this project (for example "Library_1 or "NineOld") and check "Copy project into workspace"
follow the first post to understand "how import libs": http://forum.xda-developers.com/showpost.php?p=45742000&postcount=1
EXAMPLE APP:
Copy the ZoomOutPageTransformer.java to your src/com.example.viewpagertest/ folder or create a class named ZoomOutPageTransformer:
Code:
package com.example.viewpagertest;
import android.support.v4.view.ViewPager.PageTransformer;
import android.view.View;
[COLOR="green"]import com.nineoldandroids.view.ViewHelper;[/COLOR]
public class ZoomOutPageTransformer implements PageTransformer {
private static float MIN_SCALE = 0.85f;
private static float MIN_ALPHA = 0.5f;
public void transformPage(View view, float position) {
int pageWidth = view.getWidth();
int pageHeight = view.getHeight();
if (position < -1) { // [-Infinity,-1)
// This page is way off-screen to the left.
[COLOR="green"]ViewHelper[/COLOR].setAlpha(view, 0);
} else if (position <= 1) { // [-1,1]
// Modify the default slide transition to shrink the page as well
float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
float vertMargin = pageHeight * (1 - scaleFactor) / 2;
float horzMargin = pageWidth * (1 - scaleFactor) / 2;
if (position < 0) {
[COLOR="green"]ViewHelper[/COLOR].setTranslationX(view, horzMargin - vertMargin / 2);
} else {
[COLOR="green"]ViewHelper[/COLOR].setTranslationX(view, -horzMargin + vertMargin / 2);
}
// Scale the page down (between MIN_SCALE and 1)
[COLOR="green"]ViewHelper[/COLOR].setScaleX(view, scaleFactor);
[COLOR="green"]ViewHelper[/COLOR].setScaleY(view, scaleFactor);
// Fade the page relative to its size.
[COLOR="green"]ViewHelper[/COLOR].setAlpha(view, MIN_ALPHA +
(scaleFactor - MIN_SCALE) /
(1 - MIN_SCALE) * (1 - MIN_ALPHA));
} else { // (1,+Infinity]
// This page is way off-screen to the right.
[COLOR="green"]ViewHelper[/COLOR].setAlpha(view, 0);
}
}
}
If you have deleted the "libs" folder of your project, go to workspace/ViewPagerTest/ make a new folder called "libs" and put the android-support-v4.jar (you will find it in sdk/extras/android/support/v4 folder), copy the same file (android-support-v4.jar) in workspace/ViewPagerIndicator/libs folder.
Now go to library_1 options and check the correct project build target and "Is library":
Load the library into your project.
THE CODE​
blue = add
red = delete
Now i will make an xml file called "colors" in res/values folder:
Code:
[COLOR="Blue"]<?xml version="1.0" encoding="UTF-8"?>
<resources>
<color name="red">#F75D59</color>
<color name="blue">#0000FF</color>
<color name="orange">#dc5a1e</color>
</resources>[/COLOR]
add the following code to layout1:
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
[COLOR="blue"]android:background="@color/red"[/COLOR]>
</LinearLayout>
layout2:
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
[COLOR="blue"]android:background="@color/blue" >[/COLOR]
</LinearLayout>
layout3:
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
[COLOR="blue"]android:background="@color/orange">[/COLOR]
</LinearLayout>
Now open the MainActivity.java:
Code:
package com.example.viewpagertest;
import com.viewpagerindicator.PageIndicator;
import com.viewpagerindicator.TitlePageIndicator;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import com.example.viewpagertest.R;
public class MainActivity extends FragmentActivity {
FragmentAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;
int Number = 0;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new FragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TitlePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
and add the blue lines like this:
Code:
package com.example.viewpagertest;
import com.viewpagerindicator.PageIndicator;
import com.viewpagerindicator.TitlePageIndicator;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import com.example.viewpagertest.R;
public class MainActivity extends FragmentActivity {
FragmentAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;
int Number = 0;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new FragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TitlePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
[COLOR="blue"]mPager.setPageTransformer(true, new ZoomOutPageTransformer ());[/COLOR]
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
ZoomOutPageTransformer example app - ViewPagerTest+zoomout.apk
>>>DOWNLOAD ZoomOutPageTransformer example app here <<<​​
If you wanna try other animations please go here: http://developer.android.com/training/animation/screen-slide.html
or use other libs like transitionviewpager and JazzyViewPager
Using DepthPageTransformer
Create a class called DepthPageTransformer in src/.../ folder and add the following:
Code:
package com.example.viewpagertest;
import android.support.v4.view.ViewPager.PageTransformer;
import android.view.View;
//import com.nineoldandroids.view.ViewHelper;
public class DepthPageTransformer implements PageTransformer {
private static float MIN_SCALE = 0.75f;
public void transformPage(View view, float position) {
int pageWidth = view.getWidth();
if (position < -1) { // [-Infinity,-1)
// This page is way off-screen to the left.
view.setAlpha(0);
} else if (position <= 0) { // [-1,0]
// Use the default slide transition when moving to the left page
view.setAlpha(1);
view.setTranslationX(0);
view.setScaleX(1);
view.setScaleY(1);
} else if (position <= 1) { // (0,1]
// Fade the page out.
view.setAlpha(1 - position);
// Counteract the default slide transition
view.setTranslationX(pageWidth * -position);
// Scale the page down (between MIN_SCALE and 1)
float scaleFactor = MIN_SCALE
+ (1 - MIN_SCALE) * (1 - Math.abs(position));
view.setScaleX(scaleFactor);
view.setScaleY(scaleFactor);
} else { // (1,+Infinity]
// This page is way off-screen to the right.
view.setAlpha(0);
}
}
}
In your MainActivity.java add the blue code:
Code:
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
...
[COLOR="Blue"] mPager.setPageTransformer(true, new DepthPageTransformer ());[/COLOR]
...
...
}
How to use addPreferencesFromResource(R.xml.preferences); in these fragments with action bar sherlock? I tried to make work, but... But implented ABS in my app.
ivn888 said:
4)Implement ViewPager using fragments code:
[package com.example.viewpagertest;
[import com.viewpagerindicator.IconPagerAdapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatPagerAdapter;
public class FragmentAdapter extends FragmentStatPagerAdapter implements IconPagerAdapter{
Click to expand...
Click to collapse
its FragmentStatePagerAdapter (instead of FragmentStatPagerAdapter) and Override (instead of override)
i think u made these two small mistakes. bt the tutorial is awesome.. was looking for this

[Q] Error receiving Intent from IntentService

I'm trying to make an app that displays and image which will be downloaded in background in an IntentService class. When the IntentService finishes to download it sends the intent to be catched by a BroadcastReceiver in the MainActivity but I'm getting this error:
Code:
07-17 14:27:21.003 19189-19189/com.example.matt95.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.matt95.myapplication, PID: 19189
java.lang.RuntimeException: Error receiving broadcast Intent { act=TRANSACTION_DONE flg=0x10 (has extras) } in [email protected]
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java)
at android.os.Handler.handleCallback(Handler.java)
at android.os.Handler.dispatchMessage(Handler.java)
at android.os.Looper.loop(Looper.java)
at android.app.ActivityThread.main(ActivityThread.java)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.matt95.myapplication.MyActivity$1.onReceive(MyActivity.java:74)
************at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java)
************at android.os.Handler.handleCallback(Handler.java)
************at android.os.Handler.dispatchMessage(Handler.java)
************at android.os.Looper.loop(Looper.java)
************at android.app.ActivityThread.main(ActivityThread.java)
************at java.lang.reflect.Method.invokeNative(Native Method)
************at java.lang.reflect.Method.invoke(Method.java)
This is MainActivity class:
Code:
package com.example.matt95.myapplication;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
public class MyActivity extends Activity {
ProgressDialog pd;
// Custom BroadcastReceiver for catching and showing images
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
@Override
protected void onStart() {
super.onStart();
Intent i = new Intent(this, ImageIntentService.class);
i.putExtra("url", "http://samsung-wallpapers.com/uploads/allimg/130527/1-13052F02118.jpg");
startService(i);
pd = ProgressDialog.show(this, "Fetching image", "Go intent service go!");
}
@Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ImageIntentService.TRANSACTION_DONE);
registerReceiver(imageReceiver, intentFilter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(imageReceiver);
}
private BroadcastReceiver imageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String location = intent.getExtras().getString("imageLocation");
if (location == null || location.length() == 0) {
String failedString = "Failed to download image";
Toast.makeText(context, failedString, Toast.LENGTH_LONG).show();
}
File imageFile = new File(location);
if (!imageFile.exists()) {
pd.dismiss();
String downloadFail = "Unable to download the image";
Toast.makeText(context, downloadFail, Toast.LENGTH_LONG).show();
return;
}
Bitmap image = BitmapFactory.decodeFile(location);
ImageView iv = (ImageView) findViewById(R.id.show_image);
iv.setImageBitmap(image);
pd.dismiss();
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is the IntentService class:
Code:
package com.example.matt95.myapplication;
import android.app.IntentService;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageIntentService extends IntentService {
private File cacheDir;
private static final String CACHE_FOLDER = "/myapp/image_cache/";
public static String TRANSACTION_DONE = "com.example.matt95.myapplication.ImageIntentService.TRANSACTION_DONE";
//Constructor method
public ImageIntentService() {
super("ImageIntentService");
}
@Override
public void onCreate() {
super.onCreate();
String tmpLocation = Environment.getExternalStorageDirectory().getPath() + CACHE_FOLDER;
cacheDir = new File(tmpLocation);
if (!cacheDir.exists())
cacheDir.mkdirs();
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent.hasExtra("url")) {
String remoteUrl = intent.getExtras().getString("url");
String imageLocation;
String fileName = remoteUrl.substring(remoteUrl.lastIndexOf(File.separator) + 1);
File tmpImage = new File(cacheDir + "/" + fileName);
if (tmpImage.exists()) {
imageLocation = tmpImage.getAbsolutePath();
notifyFinished(imageLocation, remoteUrl);
stopSelf();
return;
}
try {
URL url = new URL(remoteUrl);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
if (httpCon.getResponseCode() != 200)
throw new Exception("Failed to connect");
InputStream is = httpCon.getInputStream();
FileOutputStream fos = new FileOutputStream(tmpImage);
writeStream(is, fos);
fos.flush();
fos.close();
is.close();
imageLocation = tmpImage.getAbsolutePath();
notifyFinished(imageLocation, remoteUrl);
} catch (Exception e) {
Log.e("Service", "Failed!", e);
}
}
}
private void writeStream(InputStream is, OutputStream fos) throws Exception {
byte buffer[] = new byte[80000];
int read = is.read(buffer);
while (read != -1) {
fos.write(buffer, 0, read);
read = is.read(buffer);
}
}
private void notifyFinished(String imageLocation, String remoteUrl) {
Intent i = new Intent(TRANSACTION_DONE);
i.putExtra("imageLocation", imageLocation);
i.putExtra("url", remoteUrl);
ImageIntentService.this.sendBroadcast(i);
}
}
And this is the Manifest file:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.matt95.myapplication" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MyActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".ImageIntentService" />
</application>
</manifest>
What am I doing wrong?
Code:
Caused by: java.lang.NullPointerException
at com.example.matt95.myapplication.MyActivity$1.onReceive(MyActivity.java:74)
tells you there, you are asking an object that is of type "x" that is NULL to do something on line 74
Why not just use the picasso library or similar to download the image asynchronously in the background?
Sent from my HTC One using Tapatalk
deanwray said:
Code:
Caused by: java.lang.NullPointerException
at com.example.matt95.myapplication.MyActivity$1.onReceive(MyActivity.java:74)
tells you there, you are asking an object that is of type "x" that is NULL to do something on line 74
Click to expand...
Click to collapse
Thanks, I knew that but I'lll take a closer look at the code again :good:
Jonny said:
Why not just use the picasso library or similar to download the image asynchronously in the background?
Sent from my HTC One using Tapatalk
Click to expand...
Click to collapse
I'm a beginner in Android application so I don't have the proper knowledge right now, thanks for the suggestion though, I'll definitely try to take a look at that library :good:
matt95 said:
Thanks, I knew that but I'lll take a closer look at the code again :good:
I'm a beginner in Android application so I don't have the proper knowledge right now, thanks for the suggestion though, I'll definitely try to take a look at that library :good:
Click to expand...
Click to collapse
Better use asynctask for loading images
Sent from my Moto G using XDA Premium 4 mobile app
arpitkh96 said:
Better use asynctask for loading images
Sent from my Moto G using XDA Premium 4 mobile app
Click to expand...
Click to collapse
Yeah but I also need to download it and then load it, and it's not good to download that amount of data on the main thread
matt95 said:
Yeah but I also need to download it and then load it, and it's not good to download that amount of data on the main thread
Click to expand...
Click to collapse
AsyncTask runs in the background on a separate thread via the doInBackground method.
Sent from my HTC One using Tapatalk
Also, when there is a possibility that one of the objects included in the intent is null you can trap the error with a try/catch around the sendBroadcast() to prevent the exception from crashing the entire app.

[Tutorial] Learn to use WebSockets on Android with OkHttp

Hello,
I create that post to present you a tutorial aiming to learn you to use WebSockets on Android with OkHttp. Like you should know, WebSocket is a computer communications protocol, providing full-duplex communication channels over a single TCP connection. It is supported in HTML 5. Since the version 3.5 of the OkHttp library, you can also use WebSockets connection in your Android applications. In this tutorial, you are going to learn how to create a simple chat application with the Echo WebSocket Server which is available at the following address : http://www.websocket.org/echo.html .
Note that you can also discover this tutorial in video on Youtube :
First step is to add the OkHttp dependency in your Gradle build file
Code:
compile 'com.squareup.okhttp3:okhttp:3.6.0'
Don’t forget to add the Internet permission in your Android manifest since the application will use the network to create a WebSocket connection to the Echo WebSocket server. For this tutorial, we will need a simple layout with a Button to start the connection and the exchange with the server and a TextView which will be used as a console output for the messages received from the server :
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.websocket.MainActivity">
<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Start !"
android:layout_marginTop="40dp"
android:textSize="17sp"/>
<TextView
android:id="@+id/output"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/start"
android:layout_centerHorizontal="true"
android:textSize="16sp"
android:layout_marginTop="30dp"/>
</RelativeLayout>
Then, we can write the Java code of the application. The main part will be the method used to create the connection to the WebSocket connection and the WebSocketListener object used to exchange with the server :
Code:
private final class EchoWebSocketListener extends WebSocketListener {
private static final int NORMAL_CLOSURE_STATUS = 1000;
@Override
public void onOpen(WebSocket webSocket, Response response) {
webSocket.send("Hello, it's SSaurel !");
webSocket.send("What's up ?");
webSocket.send(ByteString.decodeHex("deadbeef"));
webSocket.close(NORMAL_CLOSURE_STATUS, "Goodbye !");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
output("Receiving : " + text);
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
output("Receiving bytes : " + bytes.hex());
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
webSocket.close(NORMAL_CLOSURE_STATUS, null);
output("Closing : " + code + " / " + reason);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
output("Error : " + t.getMessage());
}
}
We send messages to the server in the onOpen method. The messages received from the Echo WebSocket server are displayed inside the onMessage method. Note that you can send text or hexadecimal messages. Lastly, we close the connection by using the close method of the WebSocket object. To create the WebSocket connection with OkHttp, we need to build a Request object with the URL of the Echo WebSocket server in parameter, then calling the newWebSocket method of the OkHttpClient object.
The code will have the following form :
Code:
package com.ssaurel.websocket;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;
public class MainActivity extends AppCompatActivity {
private Button start;
private TextView output;
private OkHttpClient client;
private final class EchoWebSocketListener extends WebSocketListener {
private static final int NORMAL_CLOSURE_STATUS = 1000;
@Override
public void onOpen(WebSocket webSocket, Response response) {
webSocket.send("Hello, it's SSaurel !");
webSocket.send("What's up ?");
webSocket.send(ByteString.decodeHex("deadbeef"));
webSocket.close(NORMAL_CLOSURE_STATUS, "Goodbye !");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
output("Receiving : " + text);
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
output("Receiving bytes : " + bytes.hex());
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
webSocket.close(NORMAL_CLOSURE_STATUS, null);
output("Closing : " + code + " / " + reason);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
output("Error : " + t.getMessage());
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.start);
output = (TextView) findViewById(R.id.output);
client = new OkHttpClient();
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
start();
}
});
}
private void start() {
Request request = new Request.Builder().url("ws://echo.websocket.org").build();
EchoWebSocketListener listener = new EchoWebSocketListener();
WebSocket ws = client.newWebSocket(request, listener);
client.dispatcher().executorService().shutdown();
}
private void output(final String txt) {
runOnUiThread(new Runnable() {
@Override
public void run() {
output.setText(output.getText().toString() + "\n\n" + txt);
}
});
}
}
Finally, you have just to run your application and enjoy the result :
{
"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 and give me your feedbacks.
Thanks.
Sylvain
Hi want to fetch data on my Android app from bitfinex websocket api. Can you explain how to do it here? In detail would be great and if you don't have time, some general advice would be appreciated too.
Thank you

Categories

Resources