Android configuration file sharing and JSON data generation and parsing

Source: Internet
Author: User
<span id="Label3"></p><p><p><span style="font-size:18px"><span style="font-size:18px">first of all, I'm talking about a "</span> <span style="font-size:18px">Android profile sharing and JSON data generation and parsing "the overall process, the data in the specific database according to the Reader's own project to arrange, if you do not understand also please forgive me, after all, i said, I am just a novice. In fact, about the data in the database you just need to know that they are all objects, and then have their own properties on the line, our key is the JSON data generation and Parsing. </span><br></span></p></p><p><p><span style="font-size:18px">In view of their own is a novice blogger, feel that their blog visits a few may be because of their own knowledge is scarce, after all, I have said, I am not suitable for programming, but there is no way ah, I would like to read a doctor of literature, I am afraid to be the eyes of the people, so later things can be said later, the present still This is also a matter of no means. well, don't say more, do the right thing.</span></p></p><p><p><span style="font-size:18px">first, the profile sharing:</span></p></p><p><p><span style="font-size:18px">First Code Snippet:</span></p></p><p><p></p></p><pre code_snippet_id="1745553" snippet_file_name="blog_20160705_1_1316534" name="code" class="html">Profile sharing function private void shareconfiguration () {//Get configuration data.//this is the name of the configuration file, which is the JSON type of STR ing fileName = "configurationdata" + system.currenttimemillis () + ". json";//this is to fetch data from the database for writing to the configuration file, followed by String con figuration = Mdbmanager.getdatabaseasjson (); Create the temporal file within the private application folder,//writes the data read from the database to the configuration file Tmpsharingfile = Utils.wri Tetosdfile (fileName, configuration); if (tmpsharingfile = = Null) {//if There is no data in the configuration file, an error message is prompted Toast.maketext (this, getString (r.string.error_sharing_co nfiguration), toast.length_short). Show (); Return }//popup a sharing dialog Intent shareintent = new Intent (); Shareintent.setaction (intent.action_send);//put profile data in the shared data stream Shareintent.putextra (intent.extra_stream, Uri.fromfile (tmpsharingfile));//this is the share dialog title Shareintent.putextra (android.content.Intent.EXTRA_SUBJECT, getString ( r.string.share_configuration)); Shareintent.settyPE ("application/json");//this is the type of the specified share file, we can choose any binary data type, in order to support a variety of sharing interface Shareintent.settype ("application/ Octet-stream ")///for sharing the profile successfully, delete the locally staged profile Startactivityforresult (intent.createchooser (shareintent, getresources () . GetText (r.string.send_to)), sharing_result_code); }</pre><br><br><p><p></p></p><pre><pre></pre></pre><span style="font-size:18px"><span style="font-size:18px">second Code snippet:</span></span><p><p></p></p><p><p></p></p><pre code_snippet_id="1745553" snippet_file_name="blog_20160705_10_7317252" name="code" class="html"><pre code_snippet_id="1745553" snippet_file_name="blog_20160705_10_7317252" name="code" class="html"><span style= "font-size:18px;" > @Override protected void onactivityresult (int requestcode, int resultcode, Intent Data) { Super.onactivityresult (requestcode, resultcode, data); if (requestcode = = Sharing_result_code) { if (tmpsharingfile! = Null) { tmpsharingfile.delete (); } } }</span></pre></pre><span style="font-size:18px"><span style="font-size:18px"><br>Third Code snippet:</span></span><p><p></p></p><p><p></p></p><pre code_snippet_id="1745553" snippet_file_name="blog_20160705_11_6238239" name="code" class="html"><span style= "font-size:18px;" >/** * Get The database as a JSON format. * * @return JSON containing the Database. */public synchronized String getdatabaseasjson () {jsonobject objjson = new Jsonobject (); Try {//is used to store all devices Entries. Jsonarray jsondevices = new Jsonarray (); list<device> devices = getalldeviceslist ();//query All Device data from the database into the list for (int i = 0; i < devices.size (); I++) {//traversal of the resulting device data list device device = Devices.get (i); Jsonobject Devicejson = new Jsonobject ();//put All of the Device's property information in the form of a key-value pair Devicejson (jsonobject type), At the receiving end, the corresponding value (value) devicejson.put (key_device_id, Device.getdeviceid ()) is obtained based on the key (key); Devicejson.put (key_device_name, Device.getname ()); Devicejson.put (key_device_associated,1); Devicejson.put (key_device_hash, Device.getdevicehash ()); Devicejson.put (key_device_appearance, Device.getAppearance ()); Devicejson.put (key_device_model_low, Device.getmodellow ()); Devicejson.put (key_device_model_high, Device.getmodelhigh ()); Devicejson.put (key_device_num_groups, device.getnumgroups ()); An array (int) that stores the ID of the group that each device belongs to, such as {jsonarray} jsongroups = new Jsonarray (); int[] groups = Device.getgroups (); for (int j = 0; J < groups.length; j + +) {jsongroups.put (groups[j]); } devicejson.put (key_device_groups, jsongroups); Devicejson.put (key_device_auth_code, Device.getauthcode ()); Jsondevices.put (devicejson); }//stores All Device entry jsondevices (jsonarray types) in the Objjson (jsonobject Type) objjson.put (key_devices_list, jsondevices); Store all packet data jsonarray jsonareas = new Jsonarray (); list<area> areas = Getallarealist (); for (int i = 0; i < areas.siZe (); I++) {area area = Areas.get (i);//store Each packet of data to Areajson and add Areajson to Jsonareas jsonobject area Json = new Jsonobject (); Areajson.put (key_area_name, Area.getname ()); Areajson.put (key_area_id, Area.getareaid ()); Jsonareas.put (areajson); }//stores All Area entry Jsonareas (jsonarray types) in Objjson (jsonobject type) objjson.put (key_areas_list, jsonareas); } catch (Exception E) {return null; }//returns Objjson as a string, used to generate a local JSON file, see the first code snippet return objjson.tostring (); }</span></pre><span style="font-size:18px"><span style="font-size:18px">Fourth Code snippet:</span></span><p><p></p></p><p><p></p></p><pre code_snippet_id="1745553" snippet_file_name="blog_20160705_12_8331790" name="code" class="html"><span style= "font-size:18px;" >/** * Method to the Write text characters to file on SD Card. * * @param filename * @param text * @return */static public File writetosdfile (string filename, string Text) {//gets The root directory of the external storage media file root = android.os.Environment.getExternalStorageDirectory ();//gets The absolute path to the root directory and creates a new file under the path File dir = new file (root.getabsolutepath ()); Dir.mkdirs ();//specifies The name of the new file filename File = new (dir, filename); Try {//specify output file FileOutputStream f = new FileOutputStream (file);//print Data tool class PrintWriter PW = new PRINTWR ITER (f);//writes text to file pw.println (text);//writes all data of the output buffer once, then closes the file output stream Pw.flush (); Pw.close (); F.close (); } catch (Exception E) {e.printstacktrace (); Return null; }//returns a file object for subsequent operations, see Tmpsharingfile return in the first code snippet; }</span></pre><span style="font-size:18px"><span style="font-size:18px">well, after a series of actions above, we have successfully generated a JSON file locally from the device and area data in the database and shared it by invoking a third-party interface. So how do we accept and parse the JSON file? Don't worry, we'll talk in code Next. </span></span><p><p></p></p><p><p><span style="font-size:18px">Section Five:</span></p></p><p><p></p></p><pre code_snippet_id="1745553" snippet_file_name="blog_20160705_5_8066318" name="code" class="html"><pre code_snippet_id="1745553" snippet_file_name="blog_20160705_5_8066318" name="code" class="html">Select the JSON file to import into the database private void Pickfiletoimport () {//open system's file management function Intent Intent = new Intent (intent.action_get_ CONTENT); Intent.settype ("file/*"); Intent.settype ("application/json"); Startactivityforresult (intent, pickfile_result_code); }</pre></pre><p><p></p></p><span style="font-size:18px"><span style="font-size:18px">Sixth Code snippet:</span></span><p><p></p></p><p><p></p></p><pre code_snippet_id="1745553" snippet_file_name="blog_20160705_16_6805837" name="code" class="html"><span style= "font-size:18px;" > @Override protected void onactivityresult (int requestcode, int resultcode, Intent Data) {super.onactivityr Esult (requestcode, resultcode, data); if (requestcode = = Pickfile_result_code && ResultCode = = Activity.result_ok) {//new Activity successfully closes and returns data if ( data = = NULL | | Data.getdata () = Null) {//if The returned data is empty, an error message is given Toast.maketext (getapplicationcontext (), getString (r.string.er ror_opening_file), toast.length_short). Show (); Return }//gets the file path (full file Name) uri uri = data.getdata () as stored in data according to the obtained data parameter; Create a new file with the path to the data store the Document object File File = new file (uri.getpath ()); Check the extension of the File. APP only Accept. JSON extensions. If (! Utils.getfileextension (file). equalsignorecase (". json")) {//if The file type is Not. JSON, give the error message, see seventh code snippet Toast.maketext (this, getString (r.string.invalid_file_extension), toast.length_shor T). Show (); No Continue. Return }//start reading a file ... Start reading file data//why use StringBuilder instead of StringBuffer can refer to my other blog http://blog.csdn.net/songkai320/article/details/51823246 Final StringBuilder json = new StringBuilder (); Try {//reads the file data and puts it into the buffer bufferedreader br = new BufferedReader (new filereader (file)); String line; While (line = Br.readline ()) = Null) {//reads data from the buffer and stores it in a JSON object Json.append (line); } br.close (); } catch (ioexception e) {toast.maketext (getapplicationcontext (), getString (r.string.error_openi ng_file), toast.length_short). Show (); Return }//end reading File//Confirm replacing Database.//convert json (stringbuilder Type) to string format mimp Ortedjson = json.tostring (); If (meditmode) {//if in edit modification mode, overwrites the current data with the imported data, see eighth code snippet for details Confirmreplacingdatabase (mimportedjson); } else {//if in new mode, the data is imported directly into the local database dialogmaterial infodialog = new Dialogmaterial (this, Getstrin G (r.string.import_notify_title), getString (r.string.import_notify)); Infodialog.addcancelbutton ("ok"); Infodialog.show (); }}}</span></pre><span style="font-size:18px"><span style="font-size:18px">Seventh Code snippet:</span></span><p><p></p></p><p><p></p></p><pre code_snippet_id="1745553" snippet_file_name="blog_20160705_17_535592" name="code" class="html"><pre code_snippet_id="1745553" snippet_file_name="blog_20160705_17_535592" name="code" class="html"><span style= "font-size:18px;" >/** * Get the extension of a file. * * @param file * @return Extension. * /static public String getfileextension (file file) { String name = File.getname (); Try { return name.substring (name.lastindexof (".")); } Catch (Exception e) { return ""; } } </span></pre></pre><span style="font-size:18px"><span style="font-size:18px"><br>Eighth Code snippet:</span></span><p><p></p></p><p><p></p></p><pre code_snippet_id="1745553" snippet_file_name="blog_20160705_18_2629143" name="code" class="html"><span style= "font-size:18px;" >private void confirmreplacingdatabase (final String json) {//pops up a dialog asking if you want to overwrite the current data, click "yes" to start importing JSON data Alertdialog.bui Lder builder = new Alertdialog.builder (this); Builder.setmessage (getString (r.string.confirm_replacing_db)); Builder.setcancelable (false); Builder.setpositivebutton (getString (r.string.yes), new Dialoginterface.onclicklistener () {public void OnClick ( Dialoginterface dialog, int id) {new Thread (new Runnable () {@Override public void Run () {//overwrites the original data, see Nineth code snippet ReplaceDatabase (json), for details; }}). Start (); } }); Builder.setnegativebutton (getString (r.string.no), new Dialoginterface.onclicklistener () {public void OnClick (D Ialoginterface dialog, int Id) {dialog.cancel (); } }); Alertdialog alert = builder.create (); Alert.show (); }</span> </pre><span style="font-size:18px"><span style="font-size:18px"><br>Nineth Code snippet:</span></span><p><p></p></p><p><p></p></p><pre code_snippet_id="1745553" snippet_file_name="blog_20160705_19_2770847" name="code" class="html"><span style= "font-size:18px;" >private void ReplaceDatabase (string Json) {//first Get the device list from the JSON string, which is also a key place for JSON file parsing, Given that this property is too many, we choose to use the <span style= "font-family:arial, Helvetica, sans-serif;" >area parsing as an example, see tenth code snippet </span> list<device> devices = Mdbmanager.getlistdevicesbyjson (json, mplace.ge TId ());//ditto, except for area list data list<area> areas = Mdbmanager.getlistareasbyjson (json, Mplace.getid ()); if (devices = = NULL | | areas = = Null) {runonuithread (new Runnable () {public void Run () {///if from J The data that is taken in the son string is null, then the error message is given Toast.maketext (detailplaceactivity.this, r.string.error_importing_db, Toa St. Length_short). Show (); } }); } else {//first Remove all current device data to facilitate the import of new data in place of Mdbmanager.removealldevicesbyplaceid (mplace.getid ( )); Then delete all the current area data to facilitate the import of new data to replace Mdbmanager.removeareaofplacewithid (mplace.getid ()); for (int i = 0; I < devices.size (); I++) {//adds device data one by one parsed from the JSON string to the local database Mdbmanager.createorupdatedevice (devices.get (i)); } for (int i = 0; i < areas.size (); I++) {//) Add the resolved area data one by one from the JSON string to the local database mdbmanager.create Orupdatearea (areas.get (i)); } runonuithread (new Runnable () {public void run () {///pop-up data import successful prompt information toast.ma Ketext (detailplaceactivity.this, r.string.db_imported, toast.length_short). show (); }});//update Database Mdevicemanager.refreshinfo (); }}</span></pre><span style="font-size:18px"><span style="font-size:18px">Tenth Code Snippet:</span></span><p><p></p></p><p><p></p></p><pre code_snippet_id="1745553" snippet_file_name="blog_20160705_20_9183579" name="code" class="html"><span style= "font-size:18px;" >/** * Create A list of area objects from JSON. * @param json JSON string containing the description of the Areas. * @param placeid the place ID to the Areas. * @return A List of area Objects. */public synchronized list<area> getlistareasbyjson (String json, int placeid) {list<area> areas = New Arraylist<> (); Try {//generate a Jsonobject object through a JSON string, in fact, the process of generating a JSON file is roughly the opposite jsonobject jsonobj = new Jsonobject (json);//key key_are As_list gets the data to the area list Jsonarray jsonarray Jsonarray = Jsonobj.getjsonarray (key_areas_list); For (int Areasindex = 0; Areasindex < jsonarray.length (), areasindex++) {area area = new Area ();//from JSON Each time a set of data is fetched to the new Area object and added to the areas (list<area> Type) in the array based on the properties of the area, String areaname = Jsonarray.getjsonobject ( areasindex). getString (key_area_name); Area.setname (areaname); int areaid = JsonarrAy.getjsonobject (areasindex). getInt (key_area_id); Area.setareaid (areaid); Area.setplaceid (placeid); Areas.add (area); }} catch (jsonexception e) {return null; }//returns all area data for insertion into the local database, see Nineth code snippet return areas; }</span></pre><span style="font-size:18px"><span style="font-size:18px"><br>well, Here's How to get the "android profile sharing and JSON data generation and parsing" process Complete. Thank you for Reading.<br><br><br><br><br><br></span></span><br><p><p></p></p><p><p>Android configuration file sharing and JSON data generation and parsing</p></p></span>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.