Android does not create a directory sdcard - java

I have already read many similar questions, but I could not find a solution to the problem.
At first glance, I'm doing everything right, but the directory creation does not work for API 17 and low.
Manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
...
Cod
// скачиваем файл
public void downloadWallpaper(String url, String name) {
final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
SharedPreferences preferenceManager = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
String Download_ID = "PREF_DOWNLOAD_ID";
// проверяем наличие подключения
if (activeNetwork != null && activeNetwork.isConnected()) {
for (int z = 0; z < 1; z++) {
// проверяем был ли уже загружен файл
File file = new File(Environment.getExternalStorageDirectory() + "/LiveWallpapers/" + name);
if (!file.exists()) {
// загружаем файл, т.к. его нет
Uri downloadUri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(downloadUri);
// назначаем имя для файла
request.setDestinationInExternalPublicDir("LiveWallpapers", name);
// сохраняем request id
SharedPreferences.Editor PrefEdit = preferenceManager.edit();
long id = downloadManager.enqueue(request);
PrefEdit.putLong(Download_ID, id);
PrefEdit.apply();
} else {
// такой файл уже есть
break;
}
for (int p = 0; p < 30; p++) {
// проверяем был ли уже загружен файл
if (!file.exists()) {
// ожидаем загрузки файла
try {Thread.sleep(1000);} catch (InterruptedException e) {}
} else {
// файл загрузился
try {Thread.sleep(1000);} catch (InterruptedException e) {}
break;
}
}
}
}
}
For API 18 and high its work (/storage/sdcard/LiveWallpapers/...)
For API 17 and low its not work (/mnt/sdcard/LiveWallpapers/...)
I also tried to create a directory manually
File folder = new File(Environment.getExternalStorageDirectory() + "/LiveWallpapers");
if (!folder.exists()) {
folder.mkdirs();
}
if (folder.exists()) {
...
}
The application downloads a file from the Internet and creates a directory LiveWallpapers. For API 14, 15, 16, 17 can not create directory.
LogCat
03-15 15:41:15.411 2059-2059/com.developer.skyline.livewallpapers E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Unable to create directory: /mnt/sdcard/LiveWallpapers
at android.app.DownloadManager$Request.setDestinationInExternalPublicDir(DownloadManager.java:496)
at com.developer.skyline.livewallpapers.LiveWallpaperService$GifEngine.downloadWallpaper(LiveWallpaperService.java:379)
at com.developer.skyline.livewallpapers.LiveWallpaperService$GifEngine.<init>(LiveWallpaperService.java:206)
at com.developer.skyline.livewallpapers.LiveWallpaperService.onCreateEngine(LiveWallpaperService.java:41)
at android.service.wallpaper.WallpaperService$IWallpaperEngineWrapper.executeMessage(WallpaperService.java:1012)
at com.android.internal.os.HandlerCaller$MyHandler.handleMessage(HandlerCaller.java:61)
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)

Related

Picking an image from gallery gives error Android N

I am having trouble with retrieving the Uri from an intent in Android N.
As far as I know on Android 24 and above to get an external Uri you need FileProvider declared in Manifest. That's all done and it works with the camera, but when I try to get an image from the gallery I get an error in onActivityResult data.getData();
These are a few samples of my code:
public void getPictureFromGallery(){
picUriCar = null;
try {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, PIC_SELECT);
} catch (ActivityNotFoundException e) {
Toast.makeText(MainActivity.this, getResources().getString(R.string.text_error_no_gallery_app),
Toast.LENGTH_SHORT).show();
}
}
And onActivityResult:
else if(requestCode == PIC_SELECT){
picUriCar = data.getData();
if (picUriCar != null){
performCrop();
}
}
As far as I know data.getData() returns a Uri and this works ok on Marshmallow, but on a Nougat phone i get this error:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=5, result=-1, data=Intent {
dat=content://com.android.externalstorage.documents/document/4996-1EFF:DCIM/100ANDRO/DSC_0004.JPG
flg=0x1 }} to activity
{com.company.example/com.company.example.MainActivity}:
java.lang.SecurityException: Uid 10246 does not have permission to uri
0 #
content://com.android.externalstorage.documents/document/4996-1EFF%3ADCIM%2F100ANDRO%2FDSC_0004.JPG
at android.app.ActivityThread.deliverResults(ActivityThread.java:4267)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4310)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1628)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6361)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
Caused by: java.lang.SecurityException: Uid 10246 does not have permission to uri 0 #
content://com.android.externalstorage.documents/document/4996-1EFF%3ADCIM%2F100ANDRO%2FDSC_0004.JPG
at android.os.Parcel.readException(Parcel.java:1683)
at android.os.Parcel.readException(Parcel.java:1636)
at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:3213)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1525)
at android.app.Activity.startActivityForResult(Activity.java:4235)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
at android.app.Activity.startActivityForResult(Activity.java:4194)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:754)
at com.company.example.MainActivity.performCrop(MainActivity.java:1654)
at com.company.example.MainActivity.onActivityResult(MainActivity.java:1534)
at android.app.Activity.dispatchActivityResult(Activity.java:6928)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4263)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4310) 
at android.app.ActivityThread.-wrap20(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1628) 
at android.os.Handler.dispatchMessage(Handler.java:110) 
at android.os.Looper.loop(Looper.java:203) 
at android.app.ActivityThread.main(ActivityThread.java:6361) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
My question is:
How do I pass data.getData() uri to picUriCar without any errors?
Use this code to create new intent to choose image:
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType(image/*);
startActivityForResult(Intent.createChooser(intent, ""), Constants.SELECT_PICTURE);
Use this code in onActivityResult:
if (resultCode == Activity.RESULT_OK) {
if (requestCode == Constants.SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
try {
if (isNewGooglePhotosUri(selectedImageUri)) {
resultFile = getPhotoFile(selectedImageUri);
} else {
resultFile = getFilePathForGallery(selectedImageUri);
}
if (resultFile == null) {
//error
return;
}
} catch (Exception e) {
e.printStackTrace();
//error
return;
}
}
}
}
Also here is some usefull function that i use in my code:
private File getFilePathForGallery(Uri contentUri) {
String path = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
path = cursor.getString(column_index);
}
cursor.close();
return new File(path);
}
public static boolean isNewGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.contentprovider".equals(uri.getAuthority());
}
private File getPhotoFile(Uri selectedImageUri) {
try {
InputStream is = mActivityInstance.getContentResolver().openInputStream(selectedImageUri);
if (is != null) {
Bitmap pictureBitmap = BitmapFactory.decodeStream(is);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
pictureBitmap.compress(Bitmap.CompressFormat.JPEG, 80, bytes);
File output = new File(FileManager.getImageCacheDir(mActivityInstance), System.currentTimeMillis() + ".jpg");
output.createNewFile();
FileOutputStream fo = new FileOutputStream(output);
fo.write(bytes.toByteArray());
fo.close();
return output;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Functions from FileManager class:
private static File getCacheDir(Context context) {
File cacheDir = context.getExternalFilesDir(null);
if (cacheDir != null) {
if (!cacheDir.exists())
cacheDir.mkdirs();
} else {
cacheDir = context.getCacheDir();
}
return cacheDir;
}
public static File getImageCacheDir(Context context) {
File imageCacheDir = new File(getCacheDir(context), "cache_folder");
if (!imageCacheDir.exists())
imageCacheDir.mkdirs();
return imageCacheDir;
}
Also you need to create new xml file in your xml folder:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external_files"
path="." />
</paths>
and then add new provider to manifest file:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/your_xml_file" />
</provider>
I did a few checks and as always the solution was simpler that I expected. This is my performCrop function. I have two options when clicking on a View. Either get the image from the gallery or capture it with the camera. I remembered that the gallery option problem occurred only after I fixed the camera problem. So the issue might be somewhere within the crop code. So this is what I did:
public void performCrop(boolean cameraShot){
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//indicate image type and Uri
//cropIntent.setDataAndType(picUri, "image");
cropIntent.setDataAndType(picUriCar, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 2);
cropIntent.putExtra("aspectY", 1);
//indicate output X and Y
cropIntent.putExtra("outputX", 1024);
cropIntent.putExtra("outputY", 512);
cropIntent.putExtra("scale", true);
cropIntent.putExtra("return-data", false);
Uri uri;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N || !cameraShot) {
uri = Uri.fromFile(croppedFileCar);
}else{
String authority = "com.company.example.provider";
uri = FileProvider.getUriForFile(
MainActivity.this,
authority,
croppedFileCar);
cropIntent.setClipData(ClipData.newRawUri( "", uri ) );
cropIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
Please notice - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N ||
!cameraShot)
So basically the logic behind it is that if the image is not provided by the camera (which is determined in onActivityResult) or API is below 24, execute the line:
uri = Uri.fromFile(croppedFileCar);
Otherwise use the FileProvider. Before I did these changes the app crashed when picking an image from the gallery. I have no idea why it works now, but if someone knows the answer, I would be happy to hear it.

Java - Android - Main thread exception uploading by FTP

I'm developing a very simple app in which you press a button, the camera is launched, you take a photo and this photo is stored in the SD card and then uploaded to my FTP. I'm using simpleFTP library to connect to my FTP but I don't know why I'm getting the error below when uploading the file.
This is the relevant part of the code from the main class:
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
photoFile = null;
try {
photoFile = createImageFile();
Log.v("photoFile", photoFile.toString());
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
//The image is already stored in the phone, let's open it up from there
File imgFile = photoFile;
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
mImageView.setImageBitmap(myBitmap);
}
new UploadFTP<File>().doInBackground(imgFile);
}
}
And this is the class that handle's the AsycnTask:
class UploadFTP<File> extends AsyncTask<File, Void, Void> {
#Override
protected Void doInBackground(File... params) {
File file = params[0];
try
{
SimpleFTP ftp = new SimpleFTP();
// Connect to an FTP server on port 21.
ftp.connect("ftp.myurl", 21, "myuser", "mypass");
// Set binary mode.
ftp.bin();
// Change to a new working directory on the FTP server.
ftp.cwd("www/xxx");
// Upload files.
ftp.stor(new java.io.File(String.valueOf(file)));
ftp.disconnect();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
}
And here the error:
FATAL EXCEPTION: main
Process: com.ignistudios.photosharing, PID: 22214
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.ignistudios.photosharing/com.ignistudios.photosharing.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3607)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3650)
at android.app.ActivityThread.access$1400(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1370)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5294)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:110)
at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
at libcore.io.IoBridge.connect(IoBridge.java:122)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:163)
at java.net.Socket.startupSocket(Socket.java:590)
at java.net.Socket.tryAllAddresses(Socket.java:128)
at java.net.Socket.<init>(Socket.java:178)
at java.net.Socket.<init>(Socket.java:150)
at org.jibble.simpleftp.SimpleFTP.connect(SimpleFTP.java:68)
at com.ignistudios.photosharing.UploadFTP.doInBackground(UploadFTP.java:26)
at com.ignistudios.photosharing.MainActivity.onActivityResult(MainActivity.java:139)
at android.app.Activity.dispatchActivityResult(Activity.java:6192)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3603)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3650) 
at android.app.ActivityThread.access$1400(ActivityThread.java:154) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1370) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5294) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 
You are using your AsyncTask the wrong way. Call execute on it and it automatically call doInBackground() on a different thread, where network operations are allowed.
UploadFTP uploadFTP = new UploadFTP();
uploadFTP.execute();

Receive/Read emails in android

I am new to android.I want to build an app to receive & read emails from my own app.I prepared my code with help of these links & some blogs.
Retrieving all unread emails using javamail with POP3 protocol
https://buddhimawijeweera.wordpress.com/2011/02/09/sendreceiveemailsjava/
https://metoojava.wordpress.com/2010/03/21/java-code-to-receive-mail-using-javamailapi/
I have been working nearly for two weeks,but still app doesn't display the received emails.Please help me to find errors.Or else do you know a code to connect Gmail app with my app to receive emails ? Your any help for the app is greatly appreciated.
MailReaderActivity.java (Main Activity)
public class MailReaderActivity extends Activity{
Folder inbox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
public MailReaderActivity(){
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store;
store = session.getStore("imaps");
store.connect("imap.gmail.com","<user#gmail.com>","<password>");
inbox = store.getFolder("Inbox");
System.out.println("No of Unread Messages : " + inbox.getUnreadMessageCount());
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.CONTENT_INFO);
inbox.fetch(messages, fp);
try {
printAllMessages(messages);
inbox.close(true);
store.close();
} catch (Exception ex) {
System.out.println("Exception arise at the time of read mail");
ex.printStackTrace();
}
} catch (NoSuchProviderException e) {
e.printStackTrace();
System.exit(1);
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
}
}
public void printAllMessages(Message[] msgs) throws Exception
{
for (int i = 0; i < msgs.length; i++)
{
System.out.println("MESSAGE #" + (i + 1) + ":");
printEnvelope(msgs[i]);
}
}
public void printEnvelope(Message message) throws Exception
{
Address[] a;
// FROM
if ((a = message.getFrom()) != null)
{
for (int j = 0; j < 2; j++)
{
System.out.println("FROM: " + a[j].toString());
}
}
// TO
if ((a = message.getRecipients(Message.RecipientType.TO)) != null)
{
for (int j = 0; j < 2; j++)
{
System.out.println("TO: " + a[j].toString());
}
}
String subject = message.getSubject();
Date receivedDate = message.getReceivedDate();
String content = message.getContent().toString();
System.out.println("Subject : " + subject);
System.out.println("Received Date : " + receivedDate.toString());
System.out.println("Content : " + content);
getContent(message);
}
public void getContent(Message msg)
{
try
{
String contentType = msg.getContentType();
System.out.println("Content Type : " + contentType);
Multipart mp = (Multipart) msg.getContent();
int count = mp.getCount();
for (int i = 0; i < count; i++)
{
dumpPart(mp.getBodyPart(i));
}
}
catch (Exception ex)
{
System.out.println("Exception arise at get Content");
ex.printStackTrace();
}
}
public void dumpPart(Part p) throws Exception
{
// Dump input stream ..
InputStream is = p.getInputStream();
// If "is" is not already buffered, wrap a BufferedInputStream
// around it.
if (!(is instanceof BufferedInputStream))
{
is = new BufferedInputStream(is);
}
int c;
System.out.println("Message : ");
while ((c = is.read()) != -1)
{
System.out.write(c);
}
}
public static void main(String args[])
{
new MailReaderActivity();
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MailReaderActivity"
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>
Logcat
//01-19 13:09:00.554 8487-8487/com.example.dell.frfr E/Trace﹕ error opening trace file: No such file or directory (2)
01-19 13:09:00.812 8487-8487/com.example.dell.frfr E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.dell.frfr/com.example.dell.frfr.MailReaderActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2277)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.access$600(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5370)
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:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1128)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getByName(InetAddress.java:289)
at java.net.InetSocketAddress.<init>(InetSocketAddress.java:105)
at java.net.InetSocketAddress.<init>(InetSocketAddress.java:90)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:321)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237)
at com.sun.mail.iap.Protocol.<init>(Protocol.java:116)
at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:115)
at com.sun.mail.imap.IMAPStore.newIMAPProtocol(IMAPStore.java:685)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:636)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at com.example.dell.frfr.MailReaderActivity.<init>(MailReaderActivity.java:53)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1319)
at android.app.Instrumentation.newActivity(Instrumentation.java:1123)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2268)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2403)
            at android.app.ActivityThread.access$600(ActivityThread.java:165)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
            at android.os.Handler.dispatchMessage(Handler.java:107)
            at android.os.Looper.loop(Looper.java:194)
            at android.app.ActivityThread.main(ActivityThread.java:5370)
            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:833)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
            at dalvik.system.NativeStart.main(Native Method)
//
I don't know if you have already fixed this error or not, but it may help people with a similar issue if i still answer it.
In your LogCat. It says Caused by: android.os.NetworkOnMainThreadException
Android by default will not let any networking on the same thread as the rest of the application. So, to fix this we just have to simply create a new thread to run it in.
Replace:
public static void main(String args[])
{
new MailReaderActivity();
}
with this:
public static void main(String args[])
{
Thread thread = new Thread() {
#Override
public void run() {
new MailReaderActivity();
}
};
thread.start();
}
You should execute network threads asynchronously using AsyncTask. For further information read the docs.

Android - java.lang.RuntimeException:App is crashing as soon as it launches

I am trying to send GPS coordinates to server in android, but my app is crashing as soon as i run it, i am new to android so i'm not getting how to resolve this
Here is my logcat file
01-23 14:03:40.220: E/AndroidRuntime(880): FATAL EXCEPTION: main
01-23 14:03:40.220: E/AndroidRuntime(880): Process: com.example.server2, PID: 880
01-23 14:03:40.220: E/AndroidRuntime(880): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.server2/com.example.server2.MainActivity}: java.lang.IllegalArgumentException: invalid provider: null
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
01-23 14:03:40.220: E/AndroidRuntime(880):at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.ActivityThread.access$800(ActivityThread.java:135)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.os.Handler.dispatchMessage(Handler.java:102)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.os.Looper.loop(Looper.java:136)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.ActivityThread.main(ActivityThread.java:5017)
01-23 14:03:40.220: E/AndroidRuntime(880): at java.lang.reflect.Method.invokeNative(Native Method)
01-23 14:03:40.220: E/AndroidRuntime(880): at java.lang.reflect.Method.invoke(Method.java:515)
01-23 14:03:40.220: E/AndroidRuntime(880): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-23 14:03:40.220: E/AndroidRuntime(880): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-23 14:03:40.220: E/AndroidRuntime(880): at dalvik.system.NativeStart.main(Native Method)
01-23 14:03:40.220: E/AndroidRuntime(880): Caused by: java.lang.IllegalArgumentException: invalid provider: null
01-23 14:03:40.220: E/AndroidRuntime(880): at android.location.LocationManager.checkProvider(LocationManager.java:1623)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.location.LocationManager.getLastKnownLocation(LocationManager.java:1167)
01-23 14:03:40.220: E/AndroidRuntime(880): at com.example.server2.MainActivity.onCreate(MainActivity.java:71)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.Activity.performCreate(Activity.java:5231)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
And here is my MainActivity.java:
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
String lat,lng;
EditText etResponse;
TextView tvIsConnected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// get reference to the views
etResponse = (EditText) findViewById(R.id.etResponse);
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
}
else{
tvIsConnected.setText("You are NOT conncted");
}
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute("http://182.18.144.140:80");
}
public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
#Override
public void onLocationChanged(Location location) {
lat = Double.toString(location.getLatitude());
lng = Double.toString (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://182.18.144.140:80");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
// nameValuePairs.add(new BasicNameValuePair("android", editText1.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("LAT", lat));
nameValuePairs.add(new BasicNameValuePair("LON", lng));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
try {
httpclient.execute(httppost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
Log.i("HTTP Failed", e.toString());
}
return null;
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
etResponse.setText(result);
}
}
}
And my manifest.xml is like this
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.server2"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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" >
<activity
android:name="com.example.server2.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>
provider is null. You declare it here
private String provider;
but you never initialize it properly.
This line is returning null
provider = locationManager.getBestProvider(criteria, false);
which is causing your initial exception at this line
Location location = locationManager.getLastKnownLocation(provider);
you can see that by stepping back through the stacktrace.
Debug that and see why provider is null.
i can see a couple things that might have a problem here:
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
provider is null at this point, and also you need to set the permissions to get fine or coarse user location.

Application code used to work but now crashes

Thing is my application used to run PERFECTLY but then i wanted to change packages names and classes names so i created another project and copy pasted my code and did the changes there. no error in eclipse but app crashes now !! here's whats my app is about:
public class LocationMobileUser implements LocationListener {
Context gContext;
boolean gps_enabled=false;
boolean network_enabled=false;
public LocationMobileUser(Context gContext){
this.gContext = gContext;
}
public static final String URL =
"http://www.ip2phrase.com/ip2phrase.asp?template=%20%3CISP%3E";
public void XML (View view) {
GetXMLTask task = new GetXMLTask();
task.execute(new String[] { URL });
}
public class GetXMLTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String output = null;
for (String url : urls) {
output = getOutputFromUrl(url);
}
return output;
}
public String getOutputFromUrl(String url) {
StringBuffer output = new StringBuffer("");
int x =1;
try {
InputStream stream = getHttpConnection(url);
LineNumberReader lnr = new LineNumberReader(new InputStreamReader(stream));
String line = "";
int lineNo;
for (lineNo = 1; lineNo < 90; lineNo++) {
if (lineNo == x) {
line = lnr.readLine();
//output.append(line);
Pattern p = Pattern.compile(">(.*?)<");
Matcher m = p.matcher(line);
if (m.find()) {
output.append(m.group(1)); // => "isp"
}
} else
lnr.readLine();
}
} catch (IOException e1) {
e1.printStackTrace();
}
return output.toString();
}
// Makes HttpURLConnection and returns InputStream
public InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
public String getSimOperator() {
TelephonyManager telephonyManager = (TelephonyManager)gContext.getSystemService(Context.TELEPHONY_SERVICE);
String operator = telephonyManager.getSimOperatorName();
return operator;
}
public GsmCellLocation getCellLocation() {
//String Context=Context.Telephony_SERVICE;
TelephonyManager telephonyManager = (TelephonyManager)gContext.getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation CellLocation = (GsmCellLocation)telephonyManager.getCellLocation();
return CellLocation;
}
public Location getLocation(){
String provider = null;
LocationManager locationManager;
Location gps_loc=null;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)gContext.getSystemService(context);
gps_loc=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try{gps_enabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
try{network_enabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
if(gps_enabled && gps_loc != null){
provider = LocationManager.GPS_PROVIDER;
}
else{
provider = LocationManager.NETWORK_PROVIDER;
}
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 1, this);
return location;
}
public String getProvider(Location location){
String provider = null;
LocationManager locationManager;
Location gps_loc=null;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)gContext.getSystemService(context);
gps_loc=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try{gps_enabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
try{network_enabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
if(gps_enabled && gps_loc != null ){
provider = LocationManager.GPS_PROVIDER;
}
else{
provider = LocationManager.NETWORK_PROVIDER;
}
return provider;
}
public String CellLacLocation(GsmCellLocation CellLocation){
String cidlacString;
if (CellLocation != null) {
int cid = CellLocation.getCid();
int lac = CellLocation.getLac();
cidlacString = "CellID:" + cid + "\nLAC:" + lac;}
else {
cidlacString="No Cell Location Available";
}
return cidlacString;
}
public String updateWithNewLocation(Location location) {
String latLongString;
if (location != null){
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Latitude:" + lat + "\nLongitude:" + lng;
}else{
latLongString = "No Location available";
}
return latLongString;
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
this app will be exported into a JAR file and then included into another app as a library using build path; and here's what i wrote in this new app:
public class LocationTheApp extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationMobileUser LMU = new LocationMobileUser (this);
Location location = LMU.getLocation();
GsmCellLocation CellLocation = LMU.getCellLocation();
String URL = LocationMobileUser.URL;
LocationMobileUser.GetXMLTask xmlp = LMU.new GetXMLTask();
String Provider = LMU.getProvider(location);
String isp = xmlp.getOutputFromUrl(URL);
String latLongString = LMU.updateWithNewLocation(location);
String cidlacString = LMU.CellLacLocation(CellLocation);
String operator = LMU.getSimOperator();
TextView myLocationText = (TextView)findViewById(R.id.myLocationText);
myLocationText.setText("Your current GPS position is:\n" + latLongString);
TextView myprovider = (TextView)findViewById(R.id.myprovider);
myprovider.setText("\nYour GPS position is provided by:\n" + Provider);
TextView myCellLocation = (TextView)findViewById(R.id.mycelllocation);
myCellLocation.setText("\nYour current Cell position is:\n" + cidlacString);
TextView myOperator = (TextView)findViewById(R.id.myoperator);
myOperator.setText("\nYour GSM operator is:\n" + operator);
TextView myispText = (TextView)findViewById(R.id.myispText);
myispText.setText("\nYour current ISP is:\n" + isp);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Code contains no errors !!
if its any use here's my Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.locationmobileuser"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.locationtheapp.LocationTheApp"
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>
Tried to toggle the package name in the Manifest between locationmobileuser and locationtheapp but still app crashes !!
As i said used to work like a charm in my previous projects !!
LOG:
06-18 05:36:54.502: E/Trace(992): error opening trace file: No such file or directory (2)
06-18 05:36:54.852: D/dalvikvm(992): newInstance failed: no <init>()
06-18 05:36:54.862: D/AndroidRuntime(992): Shutting down VM
06-18 05:36:54.862: W/dalvikvm(992): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
06-18 05:36:55.002: E/AndroidRuntime(992): FATAL EXCEPTION: main
06-18 05:36:55.002: E/AndroidRuntime(992): java.lang.RuntimeException: Unable toinstantiate activity ComponentInfo{com.example.locationmobileuser/com.example.locationmobileuser.LocationMobileUser}: java.lang.InstantiationException: can't instantiate class com.example.locationmobileuser.LocationMobileUser; no empty constructor
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.os.Handler.dispatchMessage(Handler.java:99)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.os.Looper.loop(Looper.java:137)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.ActivityThread.main(ActivityThread.java:5041)
06-18 05:36:55.002: E/AndroidRuntime(992): at java.lang.reflect.Method.invokeNative(Native Method)
06-18 05:36:55.002: E/AndroidRuntime(992): at java.lang.reflect.Method.invoke(Method.java:511)
06-18 05:36:55.002: E/AndroidRuntime(992): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-18 05:36:55.002: E/AndroidRuntime(992): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-18 05:36:55.002: E/AndroidRuntime(992): at dalvik.system.NativeStart.main(Native Method)
06-18 05:36:55.002: E/AndroidRuntime(992): Caused by: java.lang.InstantiationException: can't instantiate class com.example.locationmobileuser.LocationMobileUser; no empty constructor
06-18 05:36:55.002: E/AndroidRuntime(992): at java.lang.Class.newInstanceImpl(Native Method)
06-18 05:36:55.002: E/AndroidRuntime(992): at java.lang.Class.newInstance(Class.java:1319)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
06-18 05:36:55.002: E/AndroidRuntime(992): ... 11 more
Any help would be really appreciated !!
see the package name of menifest
package="com.example.locationmobileuser
and activity package name both should be same change this package
<activity
android:name="com.example.locationtheapp.LocationTheApp"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
you need to add empty constructor in your locationmobileuser class.
public LocationMobileUser(){
}
don't need to do all these things , just go to old project and right click on the project ->> refactor to rename project name or package name

Categories