Android - unable to play song on splash screen - java

im trying to put sound when splash screen open up, but the song.start() returns me nullpointerexception. Why is this happen? im using min api 11.
code :
public class Splash extends Activity{
MediaPlayer song;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.bg);
song = MediaPlayer.create(Splash.this, R.raw.splashmusic);
song.start();
Thread timer = new Thread(){//create thread to execute one class to another class within a time
public void run(){
try{
sleep(5000);//5 seconds of pausing
} catch (InterruptedException e){
e.printStackTrace();
}finally{
Intent openMain = new Intent("com.example.hapshare.DashboardActivity");
startActivity(openMain);
}
}
};
timer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
song.release();
finish();
}
Logcat :
11-19 09:42:02.631: E/AndroidRuntime(20289): FATAL EXCEPTION: main
11-19 09:42:02.631: E/AndroidRuntime(20289): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.hapshare/com.example.hapshare.Splash}: java.lang.NullPointerException
11-19 09:42:02.631: E/AndroidRuntime(20289): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2517)
11-19 09:42:02.631: E/AndroidRuntime(20289): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2574)
11-19 09:42:02.631: E/AndroidRuntime(20289): at android.app.ActivityThread.access$600(ActivityThread.java:162)
11-19 09:42:02.631: E/AndroidRuntime(20289): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1413)
11-19 09:42:02.631: E/AndroidRuntime(20289): at android.os.Handler.dispatchMessage(Handler.java:99)
11-19 09:42:02.631: E/AndroidRuntime(20289): at android.os.Looper.loop(Looper.java:158)
11-19 09:42:02.631: E/AndroidRuntime(20289): at android.app.ActivityThread.main(ActivityThread.java:5789)
11-19 09:42:02.631: E/AndroidRuntime(20289): at java.lang.reflect.Method.invokeNative(Native Method)

Looks like your MediaPlayer is not created correctly (from the docs for MediaPlayer create()):
Returns
a MediaPlayer object, or null if creation failed
so check your R.raw.splashmusic
From the docs again:
In this case, a "raw" resource is a file that the system does not try to parse in any particular way. However, the content of this resource should not be raw audio. It should be a properly encoded and formatted media file in one of the supported formats.
You can also create MediaPlayer object this way:
try {
AssetFileDescriptor afd = this.getResources().openRawResourceFd(R.raw.splashmusic);
song = new MediaPlayer();
song.reset();
song.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
song.setAudioStreamType(AudioManager.STREAM_MUSIC);
song.prepare(); // might take long! (for buffering, etc)
song.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Remember though, that prepare() might take long, so it's not good idea to create MediaPlayer on your UI thread. You have 2 choices here:
create another thread and spawn MP there
use prepareAsync(), and when preparation is finished, onPrepared() method of the MediaPlayer.OnPreparedListener, configured through setOnPreparedListener() is called.
Please read more about MediaPlayer here
Also, when creating intent, instead of:
Intent openMain = new Intent("com.example.hapshare.DashboardActivity");
do this:
Intent openMain = new Intent(this, DashboardActivity.class);

You have the wrong media type, check the media types available developer.android.com/guide/appendix/media-formats.html as this would cause MediaPlayer.create to return null.

Related

App crashes when I call a constructor in an Activity

I am new to android studio and I am trying to build a Notepad app.
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String title = findViewById(R.id.textView3).toString();
String note_content = findViewById(R.id.textView).toString();
FileOutputStream outputStream;
try
{
outputStream = openFileOutput(title, Context.MODE_PRIVATE);
outputStream.write(note_content.getBytes());
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
MainActivity mainActivity = new MainActivity(title);
}
});
This is the button a user clicks to save the note. Once the code saves the note, it should send the Title to MainActivity so that it can be sent to Recycleview Adapter - this will display it in viewholder as a text.
Presently, when I run the code, it crashes - however, when I remove the constructor, the app works fine.
( MainActivity mainActivity = new MainActivity(title);)
Error:
10-02 02:39:13.822 27279-27279/? D/AndroidRuntime: Shutting down VM
10-02 02:39:13.824 27279-27279/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.quicknote, PID: 27279
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.quicknote/com.example.quicknote.MainActivity}: java.lang.InstantiationException: java.lang.Class<com.example.quicknote.MainActivity> has no zero argument constructor
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2337)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.InstantiationException: java.lang.Class<com.example.quicknote.MainActivity> has no zero argument constructor
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1090)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5443) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 
10-02 02:39:20.081 27279-27279/com.example.quicknote I/Process: Sending signal. PID: 27279 SIG: 9
As per the error message:
java.lang.InstantiationException: java.lang.Class has no zero argument constructor
A zero argument constructor is required for the Android system to instantiate an Activity. You should never be manually calling an Activity constructor yourself since only the system can properly create an Activity.
The Parcelables and Bundles documentation details the correct way of sending information to an Activity using the extras Bundle.
Unable to instantiate activity. Because you can't start an activity like this. You have to use intent to start activity. To sent "title" use intent extra.
Intent intent=new Intent(CurrentActivity.this, NewActivty.this);
intent.putExtra("title", title);
startActivty(intent);
Is your Activity in your AndroidManifest.xml?
If it is, you have to retrieve the title from your extras from onCreate() of MainActivity instead from the constructor.
Something like that:
//that code instead of your MainActivity mainActivity = new MainActivity(title); line
Intent intent = new Intent(YourActualActivity.this, MainActivity.class);
intent.putExtra("title", title);
startActivity(intent);
//That code in the onCreate method of your MainActivity
Bundle extras = getIntent().getExtras();
if (extras != null) {
String title = extras.getString("title");
}

Keep getting a NullPointerException for MediaPlayer [duplicate]

This question already exists:
MediaPlayer NullPointerException in local method [duplicate]
Closed 7 years ago.
There is an annoying bug in my code somewhere and I can't sleep because of it!
I kind of get why I might be getting it - I think something to do with onCreate method I think.
This is what I have:
public class PredefinedUserPlayer extends Activity {
MediaPlayer mediaPlayer;
String names;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.userdefplayer);
names = "http://X.X.X.X/musikz/musikz01.mp3";
mediaPlayer = new MediaPlayer();
}
public void playSelectedFile() {
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(PredefinedUserPlayer.this, Uri.parse(names));
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
}
The playSelectedFile() method is being called in another class and here is that bit of code here:
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PredefinedUserPlayer predefinedUserPlayer = new PredefinedUserPlayer()
predefinedUserPlayer.playSelectedFile();
}
});
I can't really have the MediaPlayer stuff in the above class which is why I have had to instantiate the PredefinedUserPlayer class. This is the actual stack trace (maybe someone can help me debug and fix this annoying bug):
java.lang.NullPointerException
at android.content.ContextWrapper.getContentResolver(ContextWrapper.java:99)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:882)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:859)
at lukasz.musik.PredefinedUserPlayer.playSelectedFile(PredefinedUserPlayer.java:86)
at lukasz.musik.CustomMusicAdapter$ViewHolder$1.onClick(CustomMusicAdapter.java:85)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
You can't new activity by hand like this:
PredefinedUserPlayer predefinedUserPlayer = new PredefinedUserPlayer()
You can use Broadcast to achieve it,Like this:
**First,Register a BroadcastReceiver in PredefinedUserPlayer Activity:
public static String ACTION_PLAY = "ACTION_PLAY_FILE";
private final BroadcastReceiver mPlayFileReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (ACTION_PLAY.equals(action)) {
playSelectedFile();
}
}
};
IntentFilter intentFilter = new IntentFilter(ACTION_PLAY);
LocalBroadcastManager.getInstance(this).registerReceiver(mPlayFileReceiver,intentFilter);
Second,Send Broadcast with action ACTION_PLAY to inform the receiver to be invoked:
LocalBroadcastReceiver.getInstance(this).sendBroadcastSync(new Intent(PredefinedUserPlayer.ACTION_PLAY));

Camera NullPointerException

Im working off the Android camera tutorial, SDK 11. For some reason I'm getting a Null Pointer within handleCameraPhoto(). The only thing I see is "Failure delivering result ResultInfo{who=null, request=100, result=-1, data=null} to activity", but I can't sort out why.
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
///Toast.makeText(this, "File Uri"+fileUri.toString(), Toast.LENGTH_LONG).show();
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
handleCameraPhoto(data);
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
finish();
} else {
// Image capture failed, advise user
finish();
Toast.makeText(this, "Image capture failed, quiting", Toast.LENGTH_LONG).show();
}
}
}
/**
*
* #param intent
*/
private void handleCameraPhoto(Intent data) {
Toast.makeText(this, "Image saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
}
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "Shindiggy");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("Shindiggy", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
Error Cat
11-19 11:39:06.782: W/dalvikvm(7719): threadid=1: thread exiting with uncaught exception (group=0x41549700)
11-19 11:39:06.782: E/AndroidRuntime(7719): FATAL EXCEPTION: main
11-19 11:39:06.782: E/AndroidRuntime(7719): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=null} to activity {com.shindiggy.shindiggy/com.shindiggy.shindiggy.CameraActivity}: java.lang.NullPointerException
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.app.ActivityThread.deliverResults(ActivityThread.java:3367)
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3410)
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.app.ActivityThread.access$1100(ActivityThread.java:141)
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304)
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.os.Handler.dispatchMessage(Handler.java:99)
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.os.Looper.loop(Looper.java:137)
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-19 11:39:06.782: E/AndroidRuntime(7719): at java.lang.reflect.Method.invokeNative(Native Method)
11-19 11:39:06.782: E/AndroidRuntime(7719): at java.lang.reflect.Method.invoke(Method.java:525)
11-19 11:39:06.782: E/AndroidRuntime(7719): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-19 11:39:06.782: E/AndroidRuntime(7719): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-19 11:39:06.782: E/AndroidRuntime(7719): at dalvik.system.NativeStart.main(Native Method)
11-19 11:39:06.782: E/AndroidRuntime(7719): Caused by: java.lang.NullPointerException
11-19 11:39:06.782: E/AndroidRuntime(7719): at com.shindiggy.shindiggy.CameraActivity.handleCameraPhoto(CameraActivity.java:68)
11-19 11:39:06.782: E/AndroidRuntime(7719): at com.shindiggy.shindiggy.CameraActivity.onActivityResult(CameraActivity.java:51)
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.app.Activity.dispatchActivityResult(Activity.java:5322)
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.app.ActivityThread.deliverResults(ActivityThread.java:3363)
11-19 11:39:06.782: E/AndroidRuntime(7719): ... 11 more
It seems that handleCameraPhoto(asdf) is being called with an argument in your code (but you haven't shown us this part), and the problem is that the object asdf was not allocated with new. That means that there's no physical object in the program's memory.
So when the instructions of the method are executed, more especifically data.getData(), the crash happens because the name data doesn't refer to a valid object in your program's memory.
NullPointerException errors happen when we try to access members of an object that was not allocated properly. Make sure you allocate the object when calling handleCameraPhoto().
Sometimes when the phone is plugged into a USB cord, access to Camera files is blocked for security reasons. Also, check for null data when coming back to activity from Camera.
Thanks for the input guys, its helped me think of what I needed to look for.
Whenever you save an image by passing EXTRAOUTPUT with camera intent
the data parameter inside the onActivityResult always return null. So,
instead of using data to retrieve the image , use the filepath to
retrieve the Bitmap.
See onActivityResult returns null data for an Image Capture
So with that said, updated handleCameraPhoto to get the fileUri, and the app is back to working.
/**
*
* #param intent
*/
private void handleCameraPhoto(Intent data) {
Toast.makeText(this, "Image saved to:\n" +
this.fileUri, Toast.LENGTH_LONG).show();
}

GoogleMap Android API V2 Capture Error

I try #Tarsem answer already but have fatal error occur can I know why?
#Tarsem answer:
https://stackoverflow.com/a/18308611/2398886
<--- these are my error codes in eclipse: --->
08-21 18:52:23.399: W/dalvikvm(29376): threadid=1: thread exiting with uncaught exception (group=0x40018578)
08-21 18:52:23.409: E/AndroidRuntime(29376): FATAL EXCEPTION: main
08-21 18:52:23.409: E/AndroidRuntime(29376): java.lang.NoClassDefFoundError: com.example.testing01.MainActivity2$6
08-21 18:52:23.409: E/AndroidRuntime(29376): at com.example.testing01.MainActivity2.CaptureMapScreen(MainActivity2.java:410)
08-21 18:52:23.409: E/AndroidRuntime(29376): at com.example.testing01.MainActivity2$3.onClick(MainActivity2.java:182)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.view.View.performClick(View.java:2485)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.view.View$PerformClick.run(View.java:9080)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.os.Handler.handleCallback(Handler.java:587)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.os.Handler.dispatchMessage(Handler.java:92)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.os.Looper.loop(Looper.java:130)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.app.ActivityThread.main(ActivityThread.java:3687)
08-21 18:52:23.409: E/AndroidRuntime(29376): at java.lang.reflect.Method.invokeNative(Native Method)
08-21 18:52:23.409: E/AndroidRuntime(29376): at java.lang.reflect.Method.invoke(Method.java:507)
08-21 18:52:23.409: E/AndroidRuntime(29376): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:867)
08-21 18:52:23.409: E/AndroidRuntime(29376): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
08-21 18:52:23.409: E/AndroidRuntime(29376): at dalvik.system.NativeStart.main(Native Method)
<--- these are my error codes in eclipse: --->
and these are my coding, is it my coding any bug?
public void CaptureMapScreen()
{
SnapshotReadyCallback callback = new SnapshotReadyCallback() {
Bitmap bitmap;
#Override
public void onSnapshotReady(Bitmap snapshot) {
// TODO Auto-generated method stub
bitmap = snapshot;
try {
FileOutputStream out = new FileOutputStream("/mnt/sdcard/"
+ "MyMapScreen" + System.currentTimeMillis()
+ ".png");
// above "/mnt ..... png" => is a storage path (where image will be stored) + name of image you can customize as per your Requirement
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
};
map.snapshot(callback);
// myMap is object of GoogleMap +> GoogleMap myMap;
// which is initialized in onCreate() =>
// myMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_pass_home_call)).getMap();
}
my Stop Button function:
//End Button Function
Button timerStopButton = (Button) findViewById(R.id.btnTimerStop);
timerStopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
String latitude3=Double.toString(latitude1);
String latitude4=Double.toString(latitude2);
String longitude3=Double.toString(longitude1);
String longitude4=Double.toString(longitude2);
String Kcalories=String.format("%.2f", calories);
Intent intent = new Intent(view.getContext(),NewDataActivity.class);
intent.putExtra("lat1", latitude3);
intent.putExtra("lat2", latitude4);
intent.putExtra("long1", longitude3);
intent.putExtra("long2", longitude4);
intent.putExtra("timer", timerStop1);
intent.putExtra("distance", distance2 + " m");
intent.putExtra("Ccalories", Kcalories + " kcal");
Toast.makeText(getApplicationContext(), "Calories (kcal):" + Kcalories, Toast.LENGTH_LONG).show();
startActivity(intent);
try {
CaptureMapScreen();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
//kill task timer and other
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
}
});
Is it my coding have any bug or my logic any probelm?
can anyone help me? thanks :)
Note Your code to Capture Map Screen is Correct and if still you have confusion than
Please Make sure Each Step Below:-
Below are the steps to capture screen shot of Google Map V2 with example
Step 1. open Android Sdk Manager (Window > Android Sdk Manager) then Expand Extras now update/install Google Play Services to Revision 10 ignore this step if already installed
Read Notes here https://developers.google.com/maps/documentation/android/releases#august_2013
Step 2. Restart Eclipse
Step 3. import com.google.android.gms.maps.GoogleMap.SnapshotReadyCallback;
Step 4. Make Method to Capture/Store Screen/image of Map like below
public void CaptureMapScreen()
{
SnapshotReadyCallback callback = new SnapshotReadyCallback() {
Bitmap bitmap;
#Override
public void onSnapshotReady(Bitmap snapshot) {
// TODO Auto-generated method stub
bitmap = snapshot;
try {
FileOutputStream out = new FileOutputStream("/mnt/sdcard/"
+ "MyMapScreen" + System.currentTimeMillis()
+ ".png");
// above "/mnt ..... png" => is a storage path (where image will be stored) + name of image you can customize as per your Requirement
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
};
myMap.snapshot(callback);
// myMap is object of GoogleMap +> GoogleMap myMap;
// which is initialized in onCreate() =>
// myMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_pass_home_call)).getMap();
}
Step 5. Now call this CaptureMapScreen() method where you want to capture the image
in my case i am calling this method on Button click in my onCreate() which is working fine
like:
Button btnCap = (Button) findViewById(R.id.btnTakeScreenshot);
btnCap.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
CaptureMapScreen();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
});
Check Doc here and here

FileInputStream in Another class?

I'm loading a file that has been saved by another class via the FileOutputstream method. Anyway, I want to load that file in another class, but it either gives me syntax errors or crashes my App.
The only tutorials I could find where they saved and loaded the file in the same class, but I want to load it up in another class and couldn't find how to solve the problem of loading into another class.
Thanks
My Code:
public class LogIn extends Activity implements OnClickListener {
EditText eTuser;
EditText eTpassword;
CheckBox StaySignedIn;
Button bSubmit;
String user;
String pass;
FileOutputStream fos;
FileInputStream fis = null;
String FILENAME = "userandpass";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
eTuser = (EditText) findViewById(R.id.eTuser);
eTpassword = (EditText) findViewById(R.id.eTpassword);
StaySignedIn = (CheckBox) findViewById(R.id.Cbstay);
bSubmit = (Button) findViewById(R.id.bLogIn);
bSubmit.setOnClickListener(this);
File file = getBaseContext().getFileStreamPath(FILENAME);
if (file.exists()) {
Intent i = new Intent(LogIn.this, ChatService.class);
startActivity(i);
}
// if if file exist close bracket
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // end of catch bracket
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // end of catch
} // create ends here
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bLogIn:
String user = eTuser.getText().toString();
String pass = eTpassword.getText().toString();
Bundle userandpass = new Bundle();
userandpass.putString("user", user);
userandpass.putString("pass", pass);
Intent login = new Intent(LogIn.this, logincheck.class);
login.putExtra("pass", user);
login.putExtra("user", pass);
startActivity(login);
if (StaySignedIn.isChecked())
;
String userstaysignedin = eTuser.getText().toString();
String passstaysignedin = eTpassword.getText().toString();
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(userstaysignedin.getBytes());
fos.write(passstaysignedin.getBytes());
fos.close();
} catch (IOException e) {
// end of try bracket, before the Catch IOExceptions e.
e.printStackTrace();
} // end of catch bracket
} // switch and case ends here
}// Click ends here
}// main class ends here
Class B( Class that loads the data.)
public class ChatService extends Activity {
String collected = null;
FileInputStream fis = null;
String FILENAME;
TextView userandpass;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.chatservice);
userandpass = (TextView) findViewById(R.id.textView1);
try {
fis = openFileInput(FILENAME);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] dataArray = null;
try {
dataArray = new byte[fis.available()];
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while (fis.read(dataArray) != -1)
;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
{
// while statement
}
userandpass.setText(collected);
}// create ends here
}// class ends here
LogCat:
03-03 21:03:34.725: E/AndroidRuntime(279): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gta5news.bananaphone/com.gta5news.bananaphone.ChatService}: java.lang.NullPointerException
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.os.Handler.dispatchMessage(Handler.java:99)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.os.Looper.loop(Looper.java:123)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.main(ActivityThread.java:4627)
03-03 21:03:34.725: E/AndroidRuntime(279): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 21:03:34.725: E/AndroidRuntime(279): at java.lang.reflect.Method.invoke(Method.java:521)
03-03 21:03:34.725: E/AndroidRuntime(279): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-03 21:03:34.725: E/AndroidRuntime(279): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-03 21:03:34.725: E/AndroidRuntime(279): at dalvik.system.NativeStart.main(Native Method)
03-03 21:03:34.725: E/AndroidRuntime(279): Caused by: java.lang.NullPointerException
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ContextImpl.makeFilename(ContextImpl.java:1599)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ContextImpl.openFileInput(ContextImpl.java:399)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.content.ContextWrapper.openFileInput(ContextWrapper.java:152)
03-03 21:03:34.725: E/AndroidRuntime(279): at com.gta5news.bananaphone.ChatService.onCreate(ChatService.java:25)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
03-03 21:03:34.725: E/AndroidRuntime(279): ... 11 more
The FILENAME string in the ChatService class is null. So you get a NullPointerException when you try to load a file using fis = openFileInput(FILENAME).
Also, your read loop throws away the data:
while (fis.read(dataArray) != -1)
;
It needs to collect the data and set the value of your collected String.
The stack trace tells you everything you need to know.
The error is a NullPointerException (meaning that you pass a null reference to a method expecting a non null reference, or that you call a method on a null reference).
The error occurs inside some android code (ContextWrapper.openFileInput()), which is called by your ChatService.onCreate() method, on line 25.
The line 25 is the following line:
fis = openFileInput(FILENAME);
So the error is clear: FILENAME is null. You haven't initialized it before this method is called.
I'm not sure about your program flow and if your two classes are running in the same thread, but it looks like you have a program flow issue. You are trying to open the file and getting a NullPointerException. Make sure the file is created and you have the correct reference to it before attempting to read.
If they are running in separate threads then you might try something like this:
try {
int waitTries=1;
fis = openFileInput(FILENAME);
while(fis.available()<EXPECTEDSIZE && waitTries++<10)
Tread.sleep(50);
}
If you know how large the file should be (EXPECTEDSIZE is some constant you will set), then this may be what you are looking for.

Categories