i m trying to make custom android app from android Developer site with android studio but my app doesnt run in emulator its shows error
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo
Here is My Main Activity
package firstapp.boysjoys.com.waste;
import android.app.Activity;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Created by Varun on 12/24/14.
*/
public class MainActivity extends Activity {
public static final int MEDIA_TYPE_IMAGE = 1;
private Camera mcamera;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mcamera = getcam();
cam mcam = new cam(this, mcamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camPre);
preview.addView(mcam);
}
public static Camera getcam() {
Camera c = null;
try {
c = Camera.open();
}
catch (Exception e){
e.getMessage();
}
return c;
}
private Camera.PictureCallback mpicturecallback = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile=getOutPutMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile==null){
android.util.Log.d("Error","Problem");
return;
}
try {
FileOutputStream fos=new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
//CREATE A FILE URI FOR SAVING AN IMAGE OR VIDEO
private static Uri getOutPutMediaFileUri(int type){
return Uri.fromFile(getOutPutMediaFile(type));
}
private static File getOutPutMediaFile(int type){
File mediaStorage=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"MyCameraApp");
if (!mediaStorage.exists()){
if (!mediaStorage.mkdirs()) {
android.util.Log.d("Mycamera", "Failed Error");
return null;
}
}
File mediaName;
if (type==MEDIA_TYPE_IMAGE) {
mediaName = new File(mediaStorage.getPath()+File.separator+"Rim_"+".jpg");
}
else {
return null;
}
return mediaName;
}
//Button Listener to the capture button
Button btn= (Button) findViewById(R.id.Capture);
public void clickPic(View view){
mcamera.takePicture(null,null,mpicturecallback);
}
}
And camera preview activity
package firstapp.boysjoys.com.waste;
import android.content.Context;
import android.hardware.Camera;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.IOException;
public class cam extends SurfaceView implements SurfaceHolder.Callback{
private SurfaceHolder mholder;
private Camera mcamera;
public cam(Context context,Camera camera){
super(context);
mholder=getHolder();
mholder.addCallback(this);
mholder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
/**
* This is called immediately after the surface is first created.
* Implementations of this should start up whatever rendering code
* they desire. Note that only one thread can ever draw into
* a {#link android.view.Surface}, so you should not draw into the Surface here
* if your normal rendering will be in another thread.
*
* #param holder The SurfaceHolder whose surface is being created.
*/
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
mcamera.setPreviewDisplay(holder);
mcamera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* This is called immediately after any structural changes (format or
* size) have been made to the surface. You should at this point update
* the imagery in the surface. This method is always called at least
* once, after {#link #surfaceCreated}.
*
* #param holder The SurfaceHolder whose surface has changed.
* #param format The new PixelFormat of the surface.
* #param width The new width of the surface.
* #param height The new height of the surface.
*/
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (mholder.getSurface()==null) {
return;
}
mcamera.stopPreview();
//Start Preview WIth New Setting
try {
mcamera.setPreviewDisplay(mholder);
mcamera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* This is called immediately before a surface is being destroyed. After
* returning from this call, you should no longer try to access this
* surface. If you have a rendering thread that directly accesses
* the surface, you must ensure that thread is no longer touching the
* Surface before returning from this function.
*
* #param holder The SurfaceHolder whose surface is being destroyed.
*/
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mholder.getSurface()!=null){
mholder.getSurface().release();
mcamera=null;
}
}
}
This Is Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="firstapp.boysjoys.com.waste" >
<uses-permission android:name="android.permission.CAMERA" ></uses-permission>
<uses-permission android:name="android.permission.write_external_storage"></uses-permission>
<uses-feature android:name="android.hardware.camera2.full" android:required="false">
</uses-feature>
<uses-feature android:name="android.hardware.Camera" android:required="false"></uses-feature>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity android:name=".MainActivity"
android:label="#string/app_name"
android:screenOrientation="landscape"
>
<intent-filter>
<action android:name="android.intent.action.MAIN">
</action>
<category android:name="android.intent.category.LAUNCHER">
</category>
</intent-filter>
</activity>
</application>
</manifest>
And Here Is Complete LogCat From Android Studio
12-26 15:26:46.284 610-610/firstapp.boysjoys.com.waste D/dalvikvm﹕ Not late-enabling CheckJNI (already on)
12-26 15:26:48.244 610-615/firstapp.boysjoys.com.waste I/dalvikvm﹕ threadid=3: reacting to signal 3
12-26 15:26:48.434 610-615/firstapp.boysjoys.com.waste I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
12-26 15:26:48.683 610-615/firstapp.boysjoys.com.waste I/dalvikvm﹕ threadid=3: reacting to signal 3
12-26 15:26:48.754 610-610/firstapp.boysjoys.com.waste D/AndroidRuntime﹕ Shutting down VM
12-26 15:26:48.754 610-610/firstapp.boysjoys.com.waste W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
12-26 15:26:48.786 610-615/firstapp.boysjoys.com.waste I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
12-26 15:26:48.822 610-610/firstapp.boysjoys.com.waste E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{firstapp.boysjoys.com.waste/firstapp.boysjoys.com.waste.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1880)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1794)
at firstapp.boysjoys.com.waste.MainActivity.<init>(MainActivity.java:102)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1319)
at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1871)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
12-26 15:26:49.154 610-615/firstapp.boysjoys.com.waste I/dalvikvm﹕ threadid=3: reacting to signal 3
12-26 15:26:49.234 610-615/firstapp.boysjoys.com.waste I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
12-26 15:26:49.654 610-615/firstapp.boysjoys.com.waste I/dalvikvm﹕ threadid=3: reacting to signal 3
12-26 15:26:49.734 610-615/firstapp.boysjoys.com.waste I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
12-26 15:27:18.314 610-610/firstapp.boysjoys.com.waste I/Process﹕ Sending signal. PID: 610 SIG: 9
i dont understand from where its throwing RuntimeException
at this line it says in error log
Caused by: java.lang.NullPointerException at android.app.Activity.findViewById(Activity.java:1794)
says it return null its button id in xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/camPre"
android:layout_weight="1"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/click"
android:text="Capture"
android:layout_gravity="center"
/>
</FrameLayout>
</LinearLayout>
i tried to debug app but still can get why its throwing null pointer exception
it can be because of button id or this line according to error log line no 102
in main activity
if (!mediaStorage.exists()){
if (!mediaStorage.mkdirs()) {
android.util.Log.d("Mycamera", "Failed Error");
return null;
}
}
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1794)
at firstapp.boysjoys.com.waste.MainActivity.<init>(MainActivity.java:102)
You're calling findViewById() too early, in activity <init> phase that includes e.g. member variable initialization.
You can only call activity methods like findViewById() in onCreate() or later in the activity lifecycle.
Move the findViewById() call to onCreate() to get rid of the NPE. Put it after setContentView() so that it can actually return a non-null value.
Related
Note: I'm using the YouTube Android Player API
Expected behavior:
The activity remains in portrait mode when the video is not fullscreen (Enforced by AndroidManifest ok).
The activity is set to landscape orientation when the video enters fullscreen mode (ok).
The activity returns to portrait orientation when the user exits fullscreen mode (ExceptionInInitializerError occurs here).
See the problem in action here
YouTubeFailureRecoveryActivity.java (This is included in the library under sample/src/com/examples/youtubeapidemo)
Main Activity
package test.testapp;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
public class MainActivity extends YouTubeFailureRecoveryActivity implements YouTubePlayer.OnFullscreenListener {
static final String API_KEY = "PLACE YOUTUBE DATA API KEY HERE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
youTubeView.initialize(API_KEY, this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
youTubePlayer.setOnFullscreenListener(this);
youTubePlayer.setFullscreenControlFlags(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_SYSTEM_UI);
if(!wasRestored){
youTubePlayer.cueVideo("wKJ9KzGQq0w");
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView) findViewById(R.id.youtube_view);
}
#Override
public void onFullscreen(boolean isFullscreen) {
if(isFullscreen){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}else if(!isFullscreen){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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="match_parent"
tools:context="test.testapp.MainActivity">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</com.google.android.youtube.player.YouTubePlayerView>
</LinearLayout>
Stack trace
06-10 09:47:09.205 2646-2646/test.testapp E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.ExceptionInInitializerError
at android.support.v7.widget.RecyclerView.onSaveInstanceState(SourceFile:201)
at android.view.View.dispatchSaveInstanceState(View.java:11839)
at android.view.ViewGroup.dispatchFreezeSelfOnly(ViewGroup.java:2576)
at android.support.v7.widget.RecyclerView.dispatchSaveInstanceState(SourceFile:220)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.View.saveHierarchyState(View.java:11822)
at com.android.internal.policy.impl.PhoneWindow.saveHierarchyState(PhoneWindow.java:1566)
at android.app.Activity.onSaveInstanceState(Activity.java:1188)
at com.google.android.youtube.player.YouTubeBaseActivity.onSaveInstanceState(Unknown Source)
at android.app.Activity.performSaveInstanceState(Activity.java:1137)
at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1215)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3486)
at android.app.ActivityThread.access$700(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1201)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NoClassDefFoundError: rt
at rs.<clinit>(SourceFile:17)
at android.support.v7.widget.RecyclerView.onSaveInstanceState(SourceFile:201)
at android.view.View.dispatchSaveInstanceState(View.java:11839)
at android.view.ViewGroup.dispatchFreezeSelfOnly(ViewGroup.java:2576)
at android.support.v7.widget.RecyclerView.dispatchSaveInstanceState(SourceFile:220)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.View.saveHierarchyState(View.java:11822)
at com.android.internal.policy.impl.PhoneWindow.saveHierarchyState(PhoneWindow.java:1566)
at android.app.Activity.onSaveInstanceState(Activity.java:1188)
at com.google.android.youtube.player.YouTubeBaseActivity.onSaveInstanceState(Unknown Source)
at android.app.Activity.performSaveInstanceState(Activity.java:1137)
at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1215)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3486)
at android.app.ActivityThread.access$700(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1201)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Looks like the application is crashing when restarting because of a configuration change
https://developer.android.com/guide/topics/resources/runtime-changes.html
You can disable the automatic activity recreation for orientation changes, and handle it yourself.
To do that, add
android:configChanges="orientation|screenLayout|screenSize"
With orientation alone it probably works, but the other ones I think were triggered also on some devices.
You can then override onConfigurationChanged() to do stuff on an orientation change if you need it, like showing / hiding views, etc.. as Android will not recreate your layouts automatically (that's what it does when restarts the activity on an orientation change)
So you can do:
#Override
public void onConfigurationChanged(final Configuration newConfiguration) {
Log.wtf(
"Orientation",
newConfiguration.orientation == Configuration.ORIENTATION_PORTRAIT
? "portrait"
: "landscape"
);
}
I'm developing an android app with a splash screen. I want another activity which is a tab swiper to be started soon after the splash screen and next go to the main activity.
When I run the following code, my splash screen works fine but then the app stops without showing the tabswiper or the main activity. How should I change my code to get it working? Any suggestions would be highly valued.
My main activity: MainActivity.java
package lk.sidadiya.sidadiya;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = new Intent(MainActivity.this, WelcomeScreen.class);
startActivity(i);
// close this activity
finish();
}
My tabswiper: WelcomeScreen.java
package lk.sidadiya.sidadiya;
import lk.sidadiya.tabswipe.adapter.TabsPagerAdapter;
import lk.sidadiya.sidadiya.R;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class WelcomeScreen extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Top Rated", "Games", "Movies" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
My splash screen: SplashScreen.java
package lk.sidadiya.sidadiya;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class SplashScreen extends Activity {
// Splash screen timer
private static int SPLASH_TIME_OUT = 3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="lk.sidadiya.sidadiya"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<!-- Splash screen -->
<activity
android:name="lk.sidadiya.sidadiya.SplashScreen"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.Black.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Welcome screen -->
<activity
android:name="lk.sidadiya.sidadiya.WelcomeScreen"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.Black" >
<intent-filter>
<action android:name="lk.sidadiya.sidadiya.WelcomeScreen" />
<!-- <category android:name="android.intent.category.DEFAULT" /> -->
</intent-filter>
</activity>
<!-- Main activity -->
<activity
android:name="lk.sidadiya.sidadiya.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.LAUNCHER" />
</intent-filter>
</activity>
-->
</application>
</manifest>
logcat:
04-20 12:09:21.327: I/Process(1684): Sending signal. PID: 1684 SIG: 9
04-20 12:27:56.267: D/dalvikvm(1755): GC_FOR_ALLOC freed 54K, 5% free 2808K/2948K, paused 300ms, total 303ms
04-20 12:27:57.737: D/gralloc_goldfish(1755): Emulator without GPU emulation detected.
04-20 12:28:01.567: D/dalvikvm(1755): GC_FOR_ALLOC freed 9K, 3% free 3311K/3404K, paused 230ms, total 231ms
04-20 12:28:02.997: I/Choreographer(1755): Skipped 38 frames! The application may be doing too much work on its main thread.
04-20 12:28:04.037: D/AndroidRuntime(1755): Shutting down VM
04-20 12:28:04.037: W/dalvikvm(1755): threadid=1: thread exiting with uncaught exception (group=0xb2ad3ba8)
04-20 12:28:04.187: E/AndroidRuntime(1755): FATAL EXCEPTION: main
04-20 12:28:04.187: E/AndroidRuntime(1755): Process: lk.sidadiya.sidadiya, PID: 1755
04-20 12:28:04.187: E/AndroidRuntime(1755): java.lang.RuntimeException: Unable to start activity ComponentInfo{lk.sidadiya.sidadiya/lk.sidadiya.sidadiya.WelcomeScreen}: java.lang.NullPointerException
04-20 12:28:04.187: E/AndroidRuntime(1755): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-20 12:28:04.187: E/AndroidRuntime(1755): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-20 12:28:04.187: E/AndroidRuntime(1755): at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-20 12:28:04.187: E/AndroidRuntime(1755): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-20 12:28:04.187: E/AndroidRuntime(1755): at android.os.Handler.dispatchMessage(Handler.java:102)
04-20 12:28:04.187: E/AndroidRuntime(1755): at android.os.Looper.loop(Looper.java:136)
04-20 12:28:04.187: E/AndroidRuntime(1755): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-20 12:28:04.187: E/AndroidRuntime(1755): at java.lang.reflect.Method.invokeNative(Native Method)
04-20 12:28:04.187: E/AndroidRuntime(1755): at java.lang.reflect.Method.invoke(Method.java:515)
04-20 12:28:04.187: E/AndroidRuntime(1755): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-20 12:28:04.187: E/AndroidRuntime(1755): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-20 12:28:04.187: E/AndroidRuntime(1755): at dalvik.system.NativeStart.main(Native Method)
04-20 12:28:04.187: E/AndroidRuntime(1755): Caused by: java.lang.NullPointerException
04-20 12:28:04.187: E/AndroidRuntime(1755): at lk.sidadiya.sidadiya.WelcomeScreen.onCreate(WelcomeScreen.java:34)
04-20 12:28:04.187: E/AndroidRuntime(1755): at android.app.Activity.performCreate(Activity.java:5231)
04-20 12:28:04.187: E/AndroidRuntime(1755): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-20 12:28:04.187: E/AndroidRuntime(1755): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-20 12:28:04.187: E/AndroidRuntime(1755): ... 11 more
activity_main.xml:
<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>
I'm trying to implement drive storage into my app, and I'm having a bit of an issue getting it to run. It compiles fine (no errors), but there's some class files getting lost somewhere. The error when launching my app is as follows:
01-24 18:40:09.747 1038-8218/? I/ActivityManager﹕ Start proc net.rymate.notes for activity net.rymate.notes/.activities.NotesListActivity: pid=6099 uid=10102 gids={50102, 3003}
01-24 18:40:09.748 1038-1103/? D/WifiStateMachine﹕ handleMessage: X
01-24 18:40:09.772 6099-6105/? D/dalvikvm﹕ Debugger has detached; object registry had 1 entries
01-24 18:40:09.814 6099-6099/? I/dalvikvm﹕ Failed resolving Lnet/rymate/notes/storage/GoogleDriveStorage; interface 1582 'Lcom/google/android/gms/common/api/GoogleApiClient$ConnectionCallbacks;'
01-24 18:40:09.815 6099-6099/? W/dalvikvm﹕ Link of class 'Lnet/rymate/notes/storage/GoogleDriveStorage;' failed
01-24 18:40:09.815 6099-6099/? E/dalvikvm﹕ Could not find class 'net.rymate.notes.storage.GoogleDriveStorage', referenced from method net.rymate.notes.activities.NotesListActivity.onCreate
01-24 18:40:09.815 6099-6099/? W/dalvikvm﹕ VFY: unable to resolve new-instance 1949 (Lnet/rymate/notes/storage/GoogleDriveStorage;) in Lnet/rymate/notes/activities/NotesListActivity;
01-24 18:40:09.815 6099-6099/? D/dalvikvm﹕ VFY: replacing opcode 0x22 at 0x0092
01-24 18:40:09.837 6099-6099/? I/dalvikvm﹕ Failed resolving Lnet/rymate/notes/storage/GoogleDriveStorage; interface 1582 'Lcom/google/android/gms/common/api/GoogleApiClient$ConnectionCallbacks;'
01-24 18:40:09.838 6099-6099/? W/dalvikvm﹕ Link of class 'Lnet/rymate/notes/storage/GoogleDriveStorage;' failed
01-24 18:40:09.839 6099-6099/? D/dalvikvm﹕ DexOpt: unable to opt direct call 0x3162 at 0x94 in Lnet/rymate/notes/activities/NotesListActivity;.onCreate
01-24 18:40:09.905 1038-8218/? D/dalvikvm﹕ GC_EXPLICIT freed 1503K, 23% free 26687K/34552K, paused 4ms+10ms, total 111ms
01-24 18:40:09.910 6099-6099/? D/AndroidRuntime﹕ Shutting down VM
01-24 18:40:09.910 6099-6099/? W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41616d40)
01-24 18:40:09.912 6099-6099/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: net.rymate.notes, PID: 6099
java.lang.NoClassDefFoundError: net.rymate.notes.storage.GoogleDriveStorage
at net.rymate.notes.activities.NotesListActivity.onCreate(NotesListActivity.java:122)
at android.app.Activity.performCreate(Activity.java:5248)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2173)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5102)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:126)
at dalvik.system.NativeStart.main(Native Method)
This is the source for the problem class (my main activity just creates a new instance of this class, it doesn't do anything with it):
package net.rymate.notes.storage;
import android.app.Activity;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.drive.Drive;
/**
* Created by Ryan on 24/01/14.
*/
public class GoogleDriveStorage implements
ConnectionCallbacks,
OnConnectionFailedListener {
private static final String TAG = "GoogleDriveStorage";
/**
* Extra for account name.
*/
protected static final String EXTRA_ACCOUNT_NAME = "account_name";
/**
* Request code for auto Google Play Services error resolution.
*/
protected static final int REQUEST_CODE_RESOLUTION = 1;
/**
* Next available request code.
*/
protected static final int NEXT_AVAILABLE_REQUEST_CODE = 2;
private final Activity activity;
/**
* Google API client.
*/
private GoogleApiClient mGoogleApiClient;
public GoogleDriveStorage(Activity a) {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(a.getApplication())
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
mGoogleApiClient.connect();
this.activity = a;
}
/**
* Called when {#code mGoogleApiClient} is connected.
*/
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "GoogleApiClient connected");
}
/**
* Called when {#code mGoogleApiClient} is disconnected.
*/
#Override
public void onDisconnected() {
Log.i(TAG, "GoogleApiClient disconnected");
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// show the localized error dialog.
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), activity, 0).show();
return;
}
try {
result.startResolutionForResult(activity, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
}
And my build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.6.+'
}
}
apply plugin: 'android'
repositories {
mavenCentral()
mavenLocal()
}
android {
compileSdkVersion 19
buildToolsVersion "19.0.0"
defaultConfig {
minSdkVersion 14
targetSdkVersion 19
}
}
dependencies {
compile project(':libs:ShowcaseView')
// Google Play Services
compile 'com.google.android.gms:play-services:4.1.32'
}
Help will be appreciated!
EDIT: adding manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.rymate.notes"
android:versionCode="7"
android:versionName="1.3" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" android:hardwareAccelerated="true">
<activity android:name="net.rymate.notes.activities.NotesListActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name="net.rymate.notes.activities.NoteViewActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:windowSoftInputMode="adjustResize" />
<activity
android:name="net.rymate.notes.activities.NoteEditActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:windowSoftInputMode="stateVisible|adjustResize" />
</application>
</manifest>
In the project properties under Java Build Path -> Order and Export make sure that "Android Private Libraries" and "Android Dependencies" are checked. Then clean and try again.
I'm new to android development. This is a camera app and it has no compilation errors. But when is run it on the emulator it won't work. It gives "unfortunately preview has stopped". Then I test it on a phone which has "android 2.3.6" os, then also gives an error "The application Preview (process com.example.preview) has stopped unexpectedly. Please try again"
MainActivity.java
package com.rrd.perview;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
//import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
public class MainActivity extends Activity {
private static final String TAG = "CameraDemo";
Camera camera;
Preview preview;
Button buttonClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preview = new Preview(this);
((FrameLayout) findViewById(R.id.preview)).addView(preview);
buttonClick = (Button) findViewById(R.id.buttonClick);
buttonClick.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
preview.camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
});
Log.d(TAG, "onCreate'd");
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
// TODO Auto-generated method stub
Log.d(TAG,"onShutter'd");
}
};
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
Log.d(TAG, "onPictureTaken - raw");
}
};
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
FileOutputStream outStream = null;
try{
outStream = new FileOutputStream(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
}
Log.d(TAG, "onPictureTaken - jpeg");
}
};
}
Preview.java
package com.rrd.perview;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
//import android.R.color;
//import android.R.string;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.CameraInfo;
import android.os.Build;
//import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
class Preview extends SurfaceView implements SurfaceHolder.Callback{
private static final String TAG = "Preview";
SurfaceHolder mHolder;
public Camera camera;
//#SuppressWarnings("deprecation")
Preview (Context context){
super(context);
mHolder = getHolder();
mHolder.addCallback(this);
//mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
Camera.open(CameraInfo.CAMERA_FACING_BACK);
try {
camera.setPreviewDisplay(holder);
camera.setPreviewCallback(new PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera camera) {
// TODO Auto-generated method stub
FileOutputStream outStream = null;
try{
outStream = new FileOutputStream(String.format("/sdcard/%d.jpg",System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d(TAG,"onPreviewFrame - wrote bytes: "+ data.length);
} catch(FileNotFoundException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}finally{
}
Preview.this.invalidate();
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
camera = null;
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// TODO Auto-generated method stub
Camera.Parameters parameters = camera.getParameters();
parameters.setPreviewSize(w, h);
camera.setParameters(parameters);
camera.startPreview();
}
public void drow(Canvas canvas){
super.draw(canvas);
Paint p = new Paint(Color.RED);
Log.d(TAG, "drow");
canvas.drawText("Preview",canvas.getWidth()/2,canvas.getHeight()/2, p);
}
}
activity_main.xml
<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" >
<FrameLayout android:id="#+id/preview"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</FrameLayout>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/buttonClick"
android:text="Click" android:layout_gravity="center">
</Button>
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rrd.perview"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.CAMERA"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.rrd.perview.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>
</application>
</manifest>
LogCat
11-20 05:02:23.974: D/CameraDemo(1075): onCreate'd
11-20 05:02:24.804: D/AndroidRuntime(1075): Shutting down VM
11-20 05:02:24.804: W/dalvikvm(1075): threadid=1: thread exiting with uncaught exception (group=0xb1b0ab90)
11-20 05:02:24.884: E/AndroidRuntime(1075): FATAL EXCEPTION: main
11-20 05:02:24.884: E/AndroidRuntime(1075): Process: com.rrd.perview, PID: 1075
11-20 05:02:24.884: E/AndroidRuntime(1075): java.lang.NullPointerException
11-20 05:02:24.884: E/AndroidRuntime(1075): at com.rrd.perview.Preview.surfaceCreated(Preview.java:43)
11-20 05:02:24.884: E/AndroidRuntime(1075): at android.view.SurfaceView.updateWindow(SurfaceView.java:572)
11-20 05:02:24.884: E/AndroidRuntime(1075): at android.view.SurfaceView.access$000(SurfaceView.java:86)
11-20 05:02:24.884: E/AndroidRuntime(1075): at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:175)
11-20 05:02:24.884: E/AndroidRuntime(1075): at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:847)
11-20 05:02:24.884: E/AndroidRuntime(1075): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1869)
11-20 05:02:24.884: E/AndroidRuntime(1075): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:998)
11-20 05:02:24.884: E/AndroidRuntime(1075): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5582)
11-20 05:02:24.884: E/AndroidRuntime(1075): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
11-20 05:02:24.884: E/AndroidRuntime(1075): at android.view.Choreographer.doCallbacks(Choreographer.java:562)
11-20 05:02:24.884: E/AndroidRuntime(1075): at android.view.Choreographer.doFrame(Choreographer.java:532)
11-20 05:02:24.884: E/AndroidRuntime(1075): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
11-20 05:02:24.884: E/AndroidRuntime(1075): at android.os.Handler.handleCallback(Handler.java:733)
11-20 05:02:24.884: E/AndroidRuntime(1075): at android.os.Handler.dispatchMessage(Handler.java:95)
11-20 05:02:24.884: E/AndroidRuntime(1075): at android.os.Looper.loop(Looper.java:137)
11-20 05:02:24.884: E/AndroidRuntime(1075): at android.app.ActivityThread.main(ActivityThread.java:4998)
11-20 05:02:24.884: E/AndroidRuntime(1075): at java.lang.reflect.Method.invokeNative(Native Method)
11-20 05:02:24.884: E/AndroidRuntime(1075): at java.lang.reflect.Method.invoke(Method.java:515)
11-20 05:02:24.884: E/AndroidRuntime(1075): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
11-20 05:02:24.884: E/AndroidRuntime(1075): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
11-20 05:02:24.884: E/AndroidRuntime(1075): at dalvik.system.NativeStart.main(Native Method)
11-20 05:03:03.864: I/Process(1075): Sending signal. PID: 1075 SIG: 9
What is your question? What have you tried so far?
Couple of points to keep in mind:
when using camera, you need to declare "android.permission.CAMERA" in your manifest - haven't seen that in yours
you have java.lang.NullPointerException, please check which line is causing
in your surfaceCreated(), you are doing this:
Camera.open(CameraInfo.CAMERA_FACING_BACK);
and then you're using camera object, which is not initialised! Change the above to:
camera = Camera.open(CameraInfo.CAMERA_FACING_BACK);
and check for RuntimeException, which you might get if opening camera fails.
Please check Android Training class regarding camera controlling:
http://developer.android.com/training/camera/cameradirect.html
I created splash screen to my android project, if i run it splash screen appears for a while and displays force close message, what should i do to navigate to the next page? any suggestions?
public class LoadingScreen extends Activity implements LoadingTaskFinishedListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Show the splash screen
setContentView(R.layout.activity_loading_screen);
// Find the progress bar
ProgressBar progressBar = (ProgressBar) findViewById(R.id.Progressbar);
// Start your loading
new LoadingTask(progressBar, null).execute("www.google.co.uk"); // Pass in whatever you need a url is just an example we don't use it in this tutorial
}
// This is the callback for when your async task has finished
public void onTaskFinished() {
completeSplash();
}
private void completeSplash(){
startApp();
finish(); // Don't forget to finish this Splash Activity so the user can't return to it!
}
private void startApp() {
Intent intent = new Intent(LoadingScreen.this, Rebuix.class);
startActivity(intent);
}
}
My manifest file
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:icon="#drawable/rebuix"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".LoadingScreen"
android:label="#string/title_activity_loading_screen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Rebuix"
android:label="#string/title_activity_rebuix" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.rebuix.com.Rebuix" />
</activity>
<activity
android:name=".Login"
android:label="#string/title_activity_login" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.rebuix.com.Rebuix" />
</activity>
Logcat
11-23 13:13:03.798: I/Tutorial(459): Starting task with url: www.google.co.uk
11-23 13:13:14.156: D/AndroidRuntime(459): Shutting down VM
11-23 13:13:14.156: W/dalvikvm(459): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
11-23 13:13:14.166: E/AndroidRuntime(459): FATAL EXCEPTION: main
11-23 13:13:14.166: E/AndroidRuntime(459): java.lang.NullPointerException
11-23 13:13:14.166: E/AndroidRuntime(459): at com.rebuix.com.LoadingTask.onPostExecute(LoadingTask.java:68)
11-23 13:13:14.166: E/AndroidRuntime(459): at com.rebuix.com.LoadingTask.onPostExecute(LoadingTask.java:1)
11-23 13:13:14.166: E/AndroidRuntime(459): at android.os.AsyncTask.finish(AsyncTask.java:417)
11-23 13:13:14.166: E/AndroidRuntime(459): at android.os.AsyncTask.access$300(AsyncTask.java:127)
11-23 13:13:14.166: E/AndroidRuntime(459): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
11-23 13:13:14.166: E/AndroidRuntime(459): at android.os.Handler.dispatchMessage(Handler.java:99)
11-23 13:13:14.166: E/AndroidRuntime(459): at android.os.Looper.loop(Looper.java:123)
11-23 13:13:14.166: E/AndroidRuntime(459): at android.app.ActivityThread.main(ActivityThread.java:4627)
11-23 13:13:14.166: E/AndroidRuntime(459): at java.lang.reflect.Method.invokeNative(Native Method)
11-23 13:13:14.166: E/AndroidRuntime(459): at java.lang.reflect.Method.invoke(Method.java:521)
11-23 13:13:14.166: E/AndroidRuntime(459): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-23 13:13:14.166: E/AndroidRuntime(459): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-23 13:13:14.166: E/AndroidRuntime(459): at dalvik.system.NativeStart.main(Native Method)
LoadingTask class
public class LoadingTask extends AsyncTask<String, Integer, Integer> {
public interface LoadingTaskFinishedListener {
void onTaskFinished(); // If you want to pass something back to the listener add a param to this method
}
// This is the progress bar you want to update while the task is in progress
private final ProgressBar progressBar;
// This is the listener that will be told when this task is finished
private final LoadingTaskFinishedListener finishedListener;
/**
* A Loading task that will load some resources that are necessary for the app to start
* #param progressBar - the progress bar you want to update while the task is in progress
* #param finishedListener - the listener that will be told when this task is finished
*/
public LoadingTask(ProgressBar progressBar, LoadingTaskFinishedListener finishedListener) {
this.progressBar = progressBar;
this.finishedListener = finishedListener;
}
#Override
protected Integer doInBackground(String... params) {
Log.i("Tutorial", "Starting task with url: "+params[0]);
if(resourcesDontAlreadyExist()){
downloadResources();
}
// Perhaps you want to return something to your post execute
return 1234;
}
private boolean resourcesDontAlreadyExist() {
// Here you would query your app's internal state to see if this download had been performed before
// Perhaps once checked save this in a shared preference for speed of access next time
return true; // returning true so we show the splash every time
}
private void downloadResources() {
// We are just imitating some process thats takes a bit of time (loading of resources / downloading)
int count = 10;
for (int i = 0; i < count; i++) {
// Update the progress bar after every step
int progress = (int) ((i / (float) count) * 100);
publishProgress(progress);
// Do some long loading things
try { Thread.sleep(1000); } catch (InterruptedException ignore) {}
}
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]); // This is ran on the UI thread so it is ok to update our progress bar ( a UI view ) here
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
finishedListener.onTaskFinished(); // Tell whoever was listening we have finished
}
}
change
new LoadingTask(progressBar, null).execute("www.google.co.uk");
to
new LoadingTask(progressBar, this).execute("www.google.co.uk");
I think the second param should be a LoadingTaskFinishedListener.