External Storage Tutorial In Android Studio With Example

文章推薦指數: 80 %
投票人數:10人

In this tutorial we gonna study about storage of data/files in android external storage or you can say the secondary memory/SD card of your phone. Togglenavigation FREEResources ContactUs JAVAForAndroid AndroidStudio DesignAndroidUI AndroidMaterialDesign AndroidProgramming AndroidDatabase CreateAndroidApp AndroidDatabaseTutorials XMLinAndroid LinearLayout RelativeLayout TableLayout FrameLayout AbsoluteLayout AdapterTutorial BaseAdapter SimpleAdapter CustomSimpleAdapter ArrayAdapter CustomArrayAdapter ListView GridView Fragment ScrollView&HorizontalScrollView SpinnerTutorial CustomSpinnerTutorial TextView EditText Button ImageViewTutorial scaleTypeInImageView ImageButton CheckBox Switch(On/Off) ToggleButton RadioButton&RadioGroup RatingBar WebView AutoCompleteTextView MultiAutoCompleteTextView ProgressBar TimePicker DatePicker CalendarView AnalogClock,DigitalClockAndTextClock SeekBar ExpandableListView SimpleExpandableListAdapterWithExampleInAndroidStudio BaseExpandableListAdapterWithExampleInAndroidStudio ExpandableListAdapterTutorialWithExampleInAndroidStudio Chronometer ZoomControls CheckedTextView VideoView TabHost SearchView SlidingDrawer TextSwitcher ViewSwitcher ImageSwitcher ViewFlipper AdapterViewFlipper ViewAnimator ViewStub IncludeMergeTag Gallery CountDownTimer AlertDialog CustomAlertDialog ProgressDialog HTMLinAndroid IntentinAndroid SharedPreferenceinAndroid ToastinAndroid InternalStorage ExternalStorage SQLiteinAndroid JSONParsing AsyncTask SplashScreen FloatingLabels ToolBar TabLayout PercentRelativeLayout PercentFrameLayout RecyclerView PullToRefreshSwipeRefreshLayout CardView ViewPager CamerainAndroid ExternalStorageTutorialInAndroidStudioWithExampleInthistutorialwegonnastudyaboutstorageofdata/filesinandroidexternalstorageoryoucansaythesecondarymemory/SDcardofyourphone.Thedataisstoredinafilespecifiedbytheuseritselfandusercanaccessthesefile.ThesefilesareonlyaccessibletilltheapplicationexitsoryouhaveSDcardmountedonyourdevice. ImportantNote:Itisnecessarytoaddexternalstoragethepermissiontoreadandwrite.ForthatyouneedtoaddpermissioninandroidManifestfile. OpenAndroidManifest.xmlfileandaddpermissionstoitjustafterthepackagename. ExternalStorageAvailabilityInAndroidStudio ToavoidcrashingappitisrequiredtocheckbeforewhetherstorageSDcardisavailableforread&writeoperations.getExternalStorageState()methodisusedtodeterminethestateofthestoragemediai.eSDcardismounted,isitreadable,itiswritableetc..allthiskindofinformation. booleanisAvailable=false; booleanisWritable=false; booleanisReadable=false; Stringstate=Environment.getExternalStorageState(); if(Environment.MEDIA_MOUNTED.equals(state)){ //Readandwriteoperationpossible isAvailable=true; isWritable=true; isReadable=true; }elseif(Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){ //Readoperationpossible isAvailable=true; isWritable=false; isReadable=true; }else{ //SDcardnotmounted isAvailable=false; isWritable=false; isReadable=false;} Methodsto StoreDataInAndroid: getExternalStorageDirectory()–OlderwaytoaccessexternalstorageinAPI Levellessthan7.Itisabsolutenowandnotrecommended.ItdirectlygetthereferencetotherootdirectoryofyourexternalstorageorSDCard. getExternalFilesDir(Stringtype)– Itisrecommendedwaytoenableustocreateprivatefilesspecifictoappandfilesareremovedasappisuninstalled.Exampleisappprivatedata. getExternalStoragePublicDirectory(): Thisis currentrecommendedwaythatenableustokeepfilespublicandarenotdeletedwiththeappuninstallation.Exampleimagesclickedbythecameraexistsevenweuninstallthecameraapp. ExternalStorageExampleInAndroidStudio Belowistheexampletoshowhowusercanuseexternalmemoryfordatastorage.Herewearecreatingtwoactivities,thefirstactivitycontaintheformthatwillstoredatainfileandsecondisusedtoloaddatawhichissaved. DownloadCode Step1:CreateanewprojectandnameitExternalStorageExample. Step2:Openres->layout->activity_main.xml(or)main.xmlandaddfollowingcode: Inthiscodesimplyaddtextview,edittextandbuttonforonclickfunctionality. Step3:Opensrc->package->MainActivity.java InthisstepweopenMainActivityandaddthefunctionsdefinedoverbuttonsonclick.ThesavePrivateandsavePublicfunctiongetthedatafromedittextandsaveitinbyteformatinfile.Alsotoastisusedtodisplaythepathwherefileisstoredwithfilename.Thenextfunctionusesintenttomovetothenextactivityassociatedwithit. ImportantNote:ThereisadifferencewhileretrievingdatawithdifferentAPIlevel.ThepermissionconcepthaschangedsinceAPI23.BeforeAPIlevel23theuserwasaskedduringinstallation,afterAPIlevel23theuserisaskedduringruntime.SoanadditionalruntimepermissionisaddedintheapplicationoperatingovertheAPIlevelabove23. packagecom.example.externalstorageexample; importandroid.Manifest; importandroid.content.Intent; importandroid.os.Environment; importandroid.support.v4.app.ActivityCompat; importandroid.support.v7.app.AppCompatActivity; importandroid.os.Bundle; importandroid.view.View; importandroid.widget.EditText; importandroid.widget.Toast; importjava.io.File; importjava.io.FileOutputStream; importjava.io.IOException; publicclassMainActivityextendsAppCompatActivity{ EditTexteditText; privateintSTORAGE_PERMISSION_CODE=23; @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText=(EditText)findViewById(R.id.editText2); } publicvoidnext(Viewview){ Intentintent=newIntent(MainActivity.this,Main2Activity.class); startActivity(intent); } publicvoidsavePublic(Viewview){ //Permissiontoaccessexternalstorage ActivityCompat.requestPermissions(this,newString[]{Manifest.permission.READ_EXTERNAL_STORAGE},STORAGE_PERMISSION_CODE); Stringinfo=editText.getText().toString(); Filefolder=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_ALARMS);//FolderName FilemyFile=newFile(folder,"myData1.txt");//Filename writeData(myFile,info); editText.setText(""); } publicvoidsavePrivate(Viewview){ Stringinfo=editText.getText().toString(); Filefolder=getExternalFilesDir("AbhiAndroid");//FolderName FilemyFile=newFile(folder,"myData2.txt");//Filename writeData(myFile,info); editText.setText(""); } privatevoidwriteData(FilemyFile,Stringdata){ FileOutputStreamfileOutputStream=null; try{ fileOutputStream=newFileOutputStream(myFile); fileOutputStream.write(data.getBytes()); Toast.makeText(this,"Done"+myFile.getAbsolutePath(),Toast.LENGTH_SHORT).show(); }catch(Exceptione){ e.printStackTrace(); }finally{ if(fileOutputStream!=null){ try{ fileOutputStream.close(); }catch(IOExceptione){ e.printStackTrace(); } } } } } Step4:Openres->layout->activity_main2.xml(or)main2.xmlandaddfollowingcode: Inthisactivitythelayoutisjustsimilarwiththemain.xml. Step5:Opensrc->package->MainActivity2.java InthisstepweopenMainActivity2andaddthefunctionsdefinedoverbutton’sonclick.ThegetPrivateandgetPublicfunctionretrievethedatafromthefile,addittothebufferandfurthersetthetextoverthetextview’s.The backfunctioncontainintenttomovebacktomainactivity. packagecom.example.externalstorageexample; importandroid.content.Intent; importandroid.os.Environment; importandroid.support.v7.app.AppCompatActivity; importandroid.os.Bundle; importandroid.view.View; importandroid.widget.TextView; importjava.io.*; publicclassMain2ActivityextendsAppCompatActivity{ TextViewshowText; @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); showText=(TextView)findViewById(R.id.getText); } publicvoidback(Viewview){ Intentintent=newIntent(Main2Activity.this,MainActivity.class); startActivity(intent); } publicvoidgetPublic(Viewview){ Filefolder=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_ALARMS);//FolderName FilemyFile=newFile(folder,"myData1.txt");//Filename Stringtext=getdata(myFile); if(text!=null){ showText.setText(text); }else{ showText.setText("NoData"); } } publicvoidgetPrivate(Viewview){ Filefolder=getExternalFilesDir("AbhiAndroid");//FolderName FilemyFile=newFile(folder,"myData2.txt");//Filename Stringtext=getdata(myFile); if(text!=null){ showText.setText(text); }else{ showText.setText("NoData"); } } privateStringgetdata(Filemyfile){ FileInputStreamfileInputStream=null; try{ fileInputStream=newFileInputStream(myfile); inti=-1; StringBufferbuffer=newStringBuffer(); while((i=fileInputStream.read())!=-1){ buffer.append((char)i); } returnbuffer.toString(); }catch(Exceptione){ e.printStackTrace(); }finally{ if(fileInputStream!=null){ try{ fileInputStream.close(); }catch(IOExceptione){ e.printStackTrace(); } } } returnnull; } } Output: Nowruntheappandyouwillseeformonthescreen.Adddatainthefieldandsaveit.Furtherclicknexttomovetonextactivityandgetdatathatissavedbeforeaspublicorprivate. DOWNLOADTHISFREE eBook! ThisfreeeBookwillhelpyoumasterthelearningofAndroidAppDevelopmentinAndroidStudio! Name Email Subscribe&DownloadeBookNow>> 3thoughtson“ExternalStorageTutorialInAndroidStudioWithExample” Iwanttojoinyourgroup.whatwillbedotomepleasereplymesir Reply GetingErrorinSave_as_public notsavedataintoExternalStorage sosolvethiserrorassoon Plzdoneedfullasabove Reply Howtosaveandgetaudiodataorvideodata???ifumakeatutorialonthatthenthatwillbeuseful.. Reply LeaveaReplyCancelreplyYouremailaddresswillnotbepublished.Requiredfieldsaremarked*CommentName* Email* Website Savemyname,email,andwebsiteinthisbrowserforthenexttimeIcomment. DOWNLOADTHISFREE eBook! ThisfreeeBookwillhelpyoumasterthelearningofAndroidAppDevelopmentinAndroidStudio! Name Email Subscribe&DownloadeBookNow>> PremiumProjectSourceCode: FoodOrderingAndroidAppProjectSourceCode EcommerceStoreAndroidAppProjectSourceCode ConvertWebsiteIntoAndroidAppProjectSourceCode QuizGameAndroidAppProjectSourceCode RadioStreamingAndroidAppSourceCode CityGuideAndroidAppProjectSourceCode QRBarcodeAndroidAppProjectSourceCode DOWNLOADTHISFREE eBook! ThisfreeeBookwillhelpyoumasterthelearningofAndroidAppDevelopmentinAndroidStudio! Name Email Subscribe&DownloadeBookNow>>



請為這篇文章評分?