Activity getting destroyed when starting another activity for file viewing - java

I'm performing file viewing operation as follows:
private void openFile(File file, String format) {
try {
if (file.exists()) {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
String mimeType = "*/*";
if (format.length() > 0) {
mimeType = MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(format);
if (mimeType == null)
mimeType = "*/*";
} else
mimeType = "*/*";
intent.setDataAndType(path, mimeType);
try {
startActivity(intent);
} catch (Exception e) {
Toast.makeText(LoginSuccessActivity.this,
constants.Error_NoCompatibleApp, Toast.LENGTH_SHORT)
.show();
e.printStackTrace();
}
} else {
Toast.makeText(LoginSuccessActivity.this,
constants.Error_DocNotFound, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
This is working fine, as I get app chooser pop-up for the filetypes which has multiple apps related to it(for eg. kingsoft office and polaris office for word file) OR directly file is opened for the filetypes which has only one app related to it(HTMLViewer for html file).
What I don't understand is my main activity is getting destroyed in few moments after calling file viewer activity. I've checked this by placing logs in onPause(), onStop() and onDestroy(). So, after file viewing is done, when I press back key, instead of taking back to app, it navigated to main menu.
I tried with startActivityForResult(intent, 1); instead of startActivity(intent); hoping that it'll preserve my main activity as it'll be waiting for result, but to no avail.
Please note that I've added android:configChanges="orientation|screenSize" in manifest file and
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
in java file.
Am I doing anything wrong?
Any help appreciated.
Sometimes, mind you, "Sometimes", I get follwing messages on log:
file:// Uri exposed through Intent.getData()
java.lang.Throwable: file:// Uri exposed through Intent.getData()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:1597)
at android.net.Uri.checkFileUriExposed(Uri.java:2338)
at android.content.Intent.prepareToLeaveProcess(Intent.java:7194)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1418)
at android.app.Activity.startActivityForResult(Activity.java:3423)
at android.app.Activity.startActivityForResult(Activity.java:3384)
at android.app.Activity.startActivity(Activity.java:3626)
at android.app.Activity.startActivity(Activity.java:3594)
at com.android.internal.app.ResolverActivity.onIntentSelected(ResolverActivity.java:407)
at com.android.internal.app.ResolverActivity.startSelected(ResolverActivity.java:299)
at com.android.internal.app.ResolverActivity.onButtonClick(ResolverActivity.java:289)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3809)
at android.view.View.performClick(View.java:4424)
at android.view.View$PerformClick.run(View.java:18383)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4998)
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:777)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
at dalvik.system.NativeStart.main(Native Method)

Add these lines to your Intent and try to Start Activity,
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setType(Your_MimeType);
I m using this code in my App
String MimeType = URLConnection.guessContentTypeFromName(myFile.getAbsolutePath());
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setType(MimeType);
Uri uri_path = Uri.fromFile(myFile);
intent.setDataAndType(uri_path, MimeType);
try
{
_context.startActivity(intent);
}
catch(ActivityNotFoundException e)
{
Toast.makeText(_context,"Activity Not Found..", Toast.LENGTH_SHORT).show();
}
Refer this link also for better understanding
Hope it will help you.

Activity can get destroyed any time. If someone has some data to retain one can do as follows:
class MyActivity {
private String mMyString;
public void onSaveInstanceState(Bundle b) {
b.putString("MYDATA", mMyString);
super.onSaveInstanceState(b);
}
public void onCreate(Bundle savedState) {
super.onCreate(savedState)
if(savedState != null) {
mMyString = savedState.getString("MYDATA");
}
}
You can this way create your own subclass private static class State implements Serializable and save it in onSaveInstanceState()

Related

easiest way to play mp3 from storage

I'm a newbie. I just want to play mp3 in my app.
I've read the documentation and I browsed through many websites including this one.
The steps should be
MediaPlayer.setDataSource(String) or (context, Uri)
.prepare();
.start();
My file is in /storage/emulated/0/New Folder/ztz3.mp3 ..
if i use External.getExternalDirectory().getPath() the result is /storage/emulated/0/
but it just won't play.
I've browsed many sites.. trying many things but it just didn't work.
I've used permission to read external storage.
and the sites I'm browsing has too many different answers which only confused me more.
some use AudioManager.STREAM.. some use MediaPlayer.create.
and I followed that too.. but it just won't play.
public class MainActivity extends AppCompatActivity {
Button buttonPlay;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonPlay = (Button) findViewById(R.id.buttonPlay);
// String filePath = Environment.getExternalStorageDirectory()+
// "/New Folder/ztz_3_adding.mp3";
// String filePath = "/storage/emulated/0/New Folder/ztz_3_adding.mp3";
Log.e("Dir", Environment.getExternalStorageDirectory().toString());
Log.e("Directory", Environment.getExternalStorageDirectory().getPath());
mediaPlayer = new MediaPlayer();
//mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
// mediaPlayer.setDataSource("/storage/emulated/0/New Folder/ztz_3_adding.mp3");
// mediaPlayer.setDataSource("file://storage/emulated/0/New Folder/ztz_3_adding.mp3");
mediaPlayer.setDataSource(getApplicationContext(),
Uri.parse(Environment.getExternalStorageDirectory().getPath()+
"/New Folder/ztz_3_adding.mp3"));
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
//mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
buttonPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.start();
}
});
}
}
I think the problem is in the prepare() method.. but I don't know how to fix it.
I've read and tried a site that said to use static MediaPlayer.create or something.
I just want a simple media player that use a string value that I can change anytime to play mp3 files based on the layout.
thanks for the help before...
the log...
02-25 22:10:08.546 17345-17345/com.echo.tesmediaplayer E/Dir:
/storage/emulated/0 02-25 22:10:08.548
17345-17345/com.echo.tesmediaplayer E/Directory: /storage/emulated/0
02-25 22:10:08.563 17345-17345/? E/MediaPlayer: prepareAsync called in
state 1 02-25 22:10:08.564 17345-17345/? E/AndroidRuntime: FATAL
EXCEPTION: main
Process: com.echo.tesmediaplayer, PID: 17345
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.echo.tesmediaplayer/com.echo.tesmediaplayer.MainActivity}:java.lang.IllegalStateException
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2440)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2500)at
android.app.ActivityThread.access$900(ActivityThread.java:163)at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1362)at
android.os.Handler.dispatchMessage(Handler.java:102) at
android.os.Looper.loop(Looper.java:148) at
android.app.ActivityThread.main(ActivityThread.java:5585) at
java.lang.reflect.Method.invoke(Native Method) at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
Caused by: java.lang.IllegalStateExceptionat
android.media.MediaPlayer._prepare(Native Method) at
android.media.MediaPlayer.prepare(MediaPlayer.java:1158) at
com.echo.tesmediaplayer.MainActivity.onCreate(MainActivity.java:48)
at android.app.Activity.performCreate(Activity.java:6279) at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2393)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2500)
at android.app.ActivityThread.access$900(ActivityThread.java:163) at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1362)
at android.os.Handler.dispatchMessage(Handler.java:102) at
android.os.Looper.loop(Looper.java:148) at
android.app.ActivityThread.main(ActivityThread.java:5585) at
java.lang.reflect.Method.invoke(Native Method) at
.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
Do you have the permissions set correctly?
You need:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
See: https://developer.android.com/guide/topics/media/mediaplayer.html#manifest

IllegalArgumentException In An AsyncTask On Rotate

I have successfully sent an email in the background and displayed a progress dialog to the user as said email is sent. However when the user flips the screen while the dialog is up I get an IllegalArgumentException. I have tried using a WeakReference object and it doesn't seem to be fixing the problem. This is my AsyncTask class.
private class SendMailTask extends AsyncTask<Mail, String, EmailStatusResponce> {
private final WeakReference<ProgressDialog> weakReference;
public SendMailTask() {
ProgressDialog progressDialog = new ProgressDialog(SendReportActivity.this);
progressDialog.setMessage("Sending...");
progressDialog.setCancelable(false);
progressDialog.show();
weakReference = new WeakReference<>(progressDialog);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected EmailStatusResponce doInBackground(Mail... mail) {
return mail[0].send();
}
#Override
protected void onPostExecute(EmailStatusResponce result) {
super.onPostExecute(result);
if (result != null && weakReference != null) {
weakReference.get().dismiss(); // This is where the exception is thrown.
if (result.isSuccess()) {
Intent intent = new Intent(SendReportActivity.this, MainActivity.class);
startActivity(intent);
}
else {}
}
}
This is the exception
java.lang.IllegalArgumentException: View=com.android.internal.policy.PhoneWindow$DecorView{688d3e2 V.E...... R......D 0,0-1026,348} not attached to window manager
Thanks in advance for any and all help.
EDIT: More logcat
--------- beginning of crash
12-11 16:22:40.154 1976-1976/com.blazapps.allenfamilymedicine E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.blazapps.allenfamilymedicine, PID: 1976
java.lang.IllegalArgumentException: View=com.android.internal.policy.PhoneWindow$DecorView{f89e667 V.E...... R......D 0,0-760,232} not attached to window manager
at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:424)
at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:350)
at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:116)
at android.app.Dialog.dismissDialog(Dialog.java:362)
at android.app.Dialog.dismiss(Dialog.java:345)
at com.blazapps.allenfamilymedicine.SendReportActivity$SendMailTask.onPostExecute(SendReportActivity.java:168)
at com.blazapps.allenfamilymedicine.SendReportActivity$SendMailTask.onPostExecute(SendReportActivity.java:138)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I still do no know why the exception is being thrown but because I save lots of information in EmailStatusResponse I can just surround the exception with a try catch and if the task was complete I get the result I expected.
try {
weakReference.get().dismiss();
} catch (Exception e) {}
If anyone can figure a better solution I would really appreciate it. I hate just catching exceptions. There is usually a better way.

DownloadImage when login

I've created an app where the user registers with his credentials and also uploads a profile picture. While logging the user enters his username,password and name of the image which he has uploaded. Till now the user is successfully able to register with his credentials along with his profile pic. I've stored the credentials of the user in the MySql while the image of the user is getting stored in the folder in the same server. Now when I'm trying to login, it gives me a NullPointerException and my app crashes. I don't know why this is happening, I've checked my code, I didn't find any error. I'm uploading it here. Please provide me with the answer. Thank you.
Login.java
public void onClick(View view) {
switch (view.getId()) {
case R.id.bLogin:
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
String name1=etimagen.getText().toString();
User user = new User(username, password,name1);
DownloadImage di=new DownloadImage(etimagen.getText().toString());
di.execute();
authenticate(user);
break;
case R.id.tvRegisterLink:
Intent registerIntent = new Intent(Login.this, Register.class);
startActivity(registerIntent);
break;
}
}
private void authenticate(User user) {
ServerRequests serverRequest = new ServerRequests(this);
serverRequest.fetchUserDataAsyncTask(user, new GetUserCallback() {
#Override
public void done(User returnedUser) {
if (returnedUser == null) {
showErrorMessage();
} else {
logUserIn(returnedUser);
}
}
});
}
private void showErrorMessage() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(Login.this);
dialogBuilder.setMessage("Incorrect user details");
dialogBuilder.setPositiveButton("Ok", null);
dialogBuilder.show();
}
private void logUserIn(User returnedUser) {
userLocalStore.storeUserData(returnedUser);
userLocalStore.setUserLoggedIn(true);
startActivity(new Intent(this, MainActivity.class));
}
public class DownloadImage extends AsyncTask<Void, Void, Bitmap>
{
String name1;
public DownloadImage(String name1)
{
this.name1=name1;
}
#Override
protected Bitmap doInBackground(Void... arg0) {
String url=SERVER_ADDRESS + "pictures1/" + name1 + ".JPG";
try
{
URLConnection connection=new URL(url).openConnection();
connection.setConnectTimeout(1000*30);
connection.setReadTimeout(1000*30);
return BitmapFactory.decodeStream((InputStream) connection.getContent(),null,null);
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
public void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if(bitmap!=null)
{
MainActivity main=new MainActivity();
main.bitmap=bitmap;
main.image();
}
}
}
MainActivity.java
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.bLogout:
userLocalStore.clearUserData();
userLocalStore.setUserLoggedIn(false);
Intent loginIntent = new Intent(this, Login.class);
startActivity(loginIntent);
break;
}
}
#Override
protected void onStart() {
super.onStart();
if (authenticate() == true) {
displayUserDetails();
}
}
private boolean authenticate() {
if (userLocalStore.getLoggedInUser() == null) {
Intent intent = new Intent(this, Login.class);
startActivity(intent);
return false;
}
return true;
}
private void displayUserDetails() {
User user = userLocalStore.getLoggedInUser();
etUsername.setText(user.username);
etName.setText(user.name);
etAge.setText(user.age + "");
}
public Bitmap image() {
image2.setImageBitmap(bitmap);
return bitmap;
}
}
Error Log
09-05 15:39:34.179: E/AndroidRuntime(4236): FATAL EXCEPTION: main
09-05 15:39:34.179: E/AndroidRuntime(4236): Process: com.example.loginregister, PID: 4236
09-05 15:39:34.179: E/AndroidRuntime(4236): java.lang.NullPointerException
09-05 15:39:34.179: E/AndroidRuntime(4236): at com.example.loginregister.MainActivity.image(MainActivity.java:86)
09-05 15:39:34.179: E/AndroidRuntime(4236): at com.example.loginregister.Login$DownloadImage.onPostExecute(Login.java:132)
09-05 15:39:34.179: E/AndroidRuntime(4236): at com.example.loginregister.Login$DownloadImage.onPostExecute(Login.java:1)
09-05 15:39:34.179: E/AndroidRuntime(4236): at android.os.AsyncTask.finish(AsyncTask.java:632)
09-05 15:39:34.179: E/AndroidRuntime(4236): at android.os.AsyncTask.access$600(AsyncTask.java:177)
09-05 15:39:34.179: E/AndroidRuntime(4236): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
Replace your code with,
public Bitmap image() {
if(bitmap!=null)
image2.setImageBitmap(bitmap);
return bitmap;
}
Your bitmap object in null, that's why it is giving you NullPointerExcepition at line ,
image2.setImageBitmap(bitmap);
Let me know if it works for you...
And mark it as an answer so that it would be useful to others...
Firstly i assume you are a beginner for Android Development.
You are trying to download the user image and display it on MainActivity.
There is two issues with the architecture.
First
The below piece of code initiates two async request. There is no guarantee that the image request will complete after login or vice versa. I suggest you to place the image request inside MainActivity after ensuring the user has successfully logged in. Meaning, place it after authenticate(user) success.
User user = new User(username, password,name1);
DownloadImage di=new DownloadImage(etimagen.getText().toString());
di.execute();
authenticate(user);
Second
The below piece of code creates a new instance of MainActivity and tries to assigns the retrieved bitmap to ImageView. One must know that onCreate gets executed just before the activity is displayed. It wont be called when new MainActivity() is done. So there is no chance of image2 being set with a value. Which is why you are getting the error.
public void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if(bitmap!=null)
{
MainActivity main=new MainActivity();
main.bitmap=bitmap;
main.image();
}
}
I assume since you want to set the image somewhere on MainActivity, you should make the image request inside MainActivity probably in onCreate.
Also this startActivity(new Intent(this, MainActivity.class)); in method login will start a new activity. This is completly different MainActivity instance from the one you are creating in onPostExecute.
Pass the image url via bundle extra to activity, retrieve it in onCreate, make the image call and display it on the imageView.
Hope this helps :) ::)

Application Crash when using CAMERA - Android

I've written an application which should take a picture and then show it on the screen for modifications.
When trying it on the eclipse emulator the camera won't work, so I'm trying it on my Galaxy Nexus Smart Phone.
Nevertheless when running it on my SP the application will crash saying that it unfortunally stopped working.
When executing the app this is what exactly happens:
I click on the camera button and the camera interface gets opened
After taking the picture it gives me the choice to discard it or open it
If I click on discard the application returns to normal usage
If I click on open the application crashes as mentioned above
I googled a little and found out that you need permissions to use hardware devices check here, so I created the file /etc/udev/rules.d/51-android.rules and this is its content:
SUBSYSTEM=="USB", ATTR{IDVENDOR}=="18d1", MODE="0666, "GROUP="plugdev"
SUBSYSTEM=="USB", ATTR{IDVENDOR}=="04e8", MODE="0666, "GROUP="plugdev"
SUBSYSTEM=="USB", ATTR{IDVENDOR}=="0bb4", MODE="0666, "GROUP="plugdev"
But still I won't be able to use camera.
Here are the permissions I declared in my manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
Here is the code I use to launch the camera intent:
//create new Intent
Intent cameraIntent = new Intent( android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
//get something back from the activity we are starting
startActivityForResult( cameraIntent, CAMERA_PICTURE_REQUEST );
And this is the code for processing the result:
public void onActivityResult( int requestCode, int resultCode, Intent imageReturnedIntent )
{
if( resultCode == RESULT_OK )
{
if( requestCode == GALLERY_PICTURE_REQUEST )
{
selectedImageUri = imageReturnedIntent.getData();
Log.d( TAG, selectedImageUri );
Intent intent = new Intent( DVAHLUI_SuperviseActivity.this, DVAHLUI_SelectImageContentActivity.class );
intent.setData( selectedImageUri );
startActivity( intent );
}
if( requestCode == CAMERA_PICTURE_REQUEST )
{
selectedImageUri = imageReturnedIntent.getData();
Log.d( TAG, selectedImageUri );
Intent intent = new Intent( DVAHLUI_SuperviseActivity.this, DVAHLUI_SelectImageContentActivity.class );
intent.setData( selectedImageUri );
startActivity( intent );
}
}
}
This is the getPath() function causing the Java Null pointer exception:
public String getPath( Uri uri )
{
String[] filePathColumn = { android.provider.MediaStore.Images.Media.DATA };
LINE 343 --> Cursor cursor = getContentResolver().query( uri, filePathColumn, null, null, null );
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndexOrThrow( filePathColumn[0] );
String filePath = cursor.getString( columnIndex );
cursor.close();
return filePath;
}
Can you please tell me what's going wrong?
FOGOT TO POST LOGCAT:
E/AndroidRuntime(27859): FATAL EXCEPTION: main
E/AndroidRuntime(27859): java.lang.RuntimeException: Failure delivering result ResultInfo{who=supervise, request=1, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.DVA_HLUI/com.DVA_HLUI.DVAHLUI_TabModeActivity}: java.lang.NullPointerException
E/AndroidRuntime(27859): at android.app.ActivityThread.deliverResults(ActivityThread.java:3141)
E/AndroidRuntime(27859): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3184)
E/AndroidRuntime(27859): at android.app.ActivityThread.access$1100(ActivityThread.java:130)
E/AndroidRuntime(27859): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1243)
E/AndroidRuntime(27859): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(27859): at android.os.Looper.loop(Looper.java:137) E/AndroidRuntime(27859): at android.app.ActivityThread.main(ActivityThread.java:4745)
E/AndroidRuntime(27859): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(27859): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(27859): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
E/AndroidRuntime(27859): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime(27859): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(27859): Caused by: java.lang.NullPointerException
E/AndroidRuntime(27859): at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1094)
E/AndroidRuntime(27859): at android.content.ContentResolver.query(ContentResolver.java:354)
E/AndroidRuntime(27859): at android.content.ContentResolver.query(ContentResolver.java:313)
E/AndroidRuntime(27859): at com.DVA_HLUI.DVAHLUI_SuperviseActivity.getPath(DVAHLUI_SuperviseActivity.java:343)
E/AndroidRuntime(27859): at com.DVA_HLUI.DVAHLUI_SuperviseActivity.onActivityResult(DVAHLUI_SuperviseActivity.java:312)
E/AndroidRuntime(27859): at android.app.ActivityGroup.dispatchActivityResult(ActivityGroup.java:122)
E/AndroidRuntime(27859): at android.app.ActivityThread.deliverResults(ActivityThread.java:3137)
E/AndroidRuntime(27859): ... 11 more
It sounds and looks like your not allowing the system to update itself that a new media file has been created. Thats why your method is failing. You can either manully create the image file path so you have the images location on the file tree or you can call for the media service to run an update. I always create my own filepath as older phones take longer to update using the media service and so your method in that case would fail.
Apparently this crash is due to a known Samsung problem: it seems like you need to create a Uri before calling the camera intent, in this way when running the onActivityResult method
the content provider will allready have allocated the place where to save the resource.
For further information check the following:
My Android camera Uri is returning a null value, but the Samsung fix is in place, help?
Android: startActivityForResult always null and force close my app
wordpress link
Android Samsung: Camera app won't return intent.getData()
and many more by googling...
P.S. as soon as possible I'll post the solution that worked for me.
I know it is late to answer it but asap i found the answer i replied for it so please atleast review it .
AndroidCameraUtil could be nice and easy solution for each and every device below is the code snippet you can use with the library
private void setupCameraIntentHelper() {
mCameraIntentHelper = new CameraIntentHelper(this, new CameraIntentHelperCallback() {
#Override
public void onPhotoUriFound(Date dateCameraIntentStarted, Uri photoUri, int rotateXDegrees) {
messageView.setText(getString(R.string.activity_camera_intent_photo_uri_found) + photoUri.toString());
Bitmap photo = BitmapHelper.readBitmap(CameraIntentActivity.this, photoUri);
if (photo != null) {
photo = BitmapHelper.shrinkBitmap(photo, 300, rotateXDegrees);
ImageView imageView = (ImageView) findViewById(de.ecotastic.android.camerautil.sample.R.id.activity_camera_intent_image_view);
imageView.setImageBitmap(photo);
}
}
#Override
public void deletePhotoWithUri(Uri photoUri) {
BitmapHelper.deleteImageWithUriIfExists(photoUri, CameraIntentActivity.this);
}
#Override
public void onSdCardNotMounted() {
Toast.makeText(getApplicationContext(), getString(R.string.error_sd_card_not_mounted), Toast.LENGTH_LONG).show();
}
#Override
public void onCanceled() {
Toast.makeText(getApplicationContext(), getString(R.string.warning_camera_intent_canceled), Toast.LENGTH_LONG).show();
}
#Override
public void onCouldNotTakePhoto() {
Toast.makeText(getApplicationContext(), getString(R.string.error_could_not_take_photo), Toast.LENGTH_LONG).show();
}
#Override
public void onPhotoUriNotFound() {
messageView.setText(getString(R.string.activity_camera_intent_photo_uri_not_found));
}
#Override
public void logException(Exception e) {
Toast.makeText(getApplicationContext(), getString(R.string.error_sth_went_wrong), Toast.LENGTH_LONG).show();
Log.d(getClass().getName(), e.getMessage());
}
});
}
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
mCameraIntentHelper.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mCameraIntentHelper.onRestoreInstanceState(savedInstanceState);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
mCameraIntentHelper.onActivityResult(requestCode, resultCode, intent);
}
}

TCP socket on Android 4.0.3

I am working on a project in which I have a TCP connection with a server via Android.
I am using the following code:
public class MyService extends Service {
private static final String TAG = "MyService";
MediaPlayer player;
Socket s;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
player = MediaPlayer.create(this, R.raw.braincandy);
player.setLooping(false); // Set looping
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
try {
s = new Socket("192.168.1.54", 64000);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am running the connection as a service.
The real problem is I can make a connection with my Android phone (2.3.7) and with the emulator (2.3.3) but when I want to test in on my tablet (4.0.3), my app always crashes when I want to start the connection.
Can someone help me with this?
Here is the logcat log:
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start service
com.gunther.servicetcp.MyService#412b0a98 with Intent
{ cmp=com.gunther.servicetcp/.MyService }: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2376)
at android.app.ActivityThread.access$1900(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
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: android.os.NetworkOnMainThreadException
0at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
at libcore.io.IoBridge.connect(IoBridge.java:112)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.Socket.startupSocket(Socket.java:566)
at java.net.Socket.tryAllAddresses(Socket.java:127)
at java.net.Socket.<init>(Socket.java:177)
at java.net.Socket.<init>(Socket.java:149)
at com.gunther.servicetcp.MyService.onStart(MyService.java:53)
at android.app.Service.onStartCommand(Service.java:438)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2359)
: ... 10 more
You shouldn't do network operations on the main thread. This will lead to your app being unresponsive. Before Honeycomb you could get away with it, but Honeycomb and newer Android versions will check and throw the exception you're getting. See also this page of the Android Developers API
Services's onStart() method runs on the main thread, (yes, services seem to run on the main thread of the application.) so you should fork another thread in the onStart() method and do everything you need to do in that thread.

Categories

Resources