Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Application data in Android SDK

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail the example analysis of application data in Android SDK. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

Introduction

In a broad sense, there are five main types of data storage options in Android applications: saving data in the application's shared preferences, in internal storage (dedicated to the application itself), in external storage (exposed to devices), in databases, and in Web resources that can be accessed through the device's Internet connection. Due to space constraints, we cannot discuss these options in detail, but we will summarize the basic features of each solution to help you figure out how to solve storage problems when you need to use persistent data.

1. Sharing preference

Sharing preferences allow you to save basic data types in the form of key-value pairs. The sharing preference file of an application is generally regarded as the simplest data storage option, but it essentially imposes a certain degree of restriction on the storage object. You can use it to store basic types of numbers (such as integers, long numbers, and floating point numbers), Boolean values, and text strings. We need to assign a name to each value we save so that we can retrieve it while the application is running. Since people are likely to use sharing preferences in their own apps, we use it as the focus of the explanation and express it in a more detailed way (compared to other options). To help you consolidate the necessary knowledge.

You can try this code in your main Activity class and test it later when you run the application examples in this series of tutorials. Ideally, sharing preferences should match the user configuration options in the application, just like selecting appearance settings. You will recall that we once created a simple button that will display "Ouch" text on the screen when the user clicks it. Now let's assume that we want the user to continue to display the word "Ouch" on the button after one click, and that the state remains the same while the application is running. This means that the initial text on the button exists only before the user clicks.

Let's add shared preference content to the application. Before the starting position of the class and the onCreate method, we choose a name for the sharing preference:

Public static final String MY_APP_PREFS = "MyAppPrefs"

With the "public static" modifier, we can access this variable in any class within the application, so we just need to save the preference name string here. We use uppercase because the variable is a constant, and that's why the "final" modifier exists. Every time you retrieve or set a data entry in your application preferences, you must use the same name.

Step two

Now let's write shared preference content. In our onClick method, below the button "Ouch" text settings section, try to retrieve this sharing preference by name:

SharedPreferences thePrefs = getSharedPreferences (MY_APP_PREFS, 0)

You need to add an import to the "android.conent.SharedPreferences" class. Hover over the "SharedPreferences" text and use the Eclipse prompt to complete the import. The * item parameter is the preference name we defined, and the second item is our basic mode as the default option.

Now we need to specify an editor for the sharing preferences to set the values in it:

SharedPreferences.Editor prefsEd = thePrefs.edit ()

Now we can write values to the sharing preferences:

PrefsEd.putBoolean ("btnPressed", true)

We use the Boolean type here because the current state is divided into only two types-the user has or has not pressed the button. The editor provides a number of different types, from which we can choose to save this set of shared preferences, each with its own name and value parameters. *, we need to submit the editing result:

PrefsEd.commit ()

Step three

Now let's use the saved values to detect what the button should display after the user runs the application. Add sharing preferences after existing code in onCreate:

SharedPreferences thePrefs = getSharedPreferences (MY_APP_PREFS, 0)

This time we don't have to use the editor because we only need to get one value:

Boolean pressed = thePrefs.getBoolean ("btnPressed", false)

Now we retrieve the value using the name that has been set and read the result in the variable. If the value has not been set, the second parameter, the default value, is returned, which represents a negative meaning. Now let's use this value:

If (pressed) theButton.setText ("Ouch")

If the user presses the button after the application is running, the button directly displays the word "Ouch". In subsequent articles in this series, you will see how we do this while the application is running. This simple example is a good illustration of the use of shared preferences. You will find that sharing preferences play an important role in helping applications cater to user preferences through their look and feel.

two。 Private internal files

You can save the file in the internal and external storage of the user's device. If you save the file in internal storage, the Android system treats it as private data that belongs exclusively to the current application. Such files are basically part of the application, and we cannot access them directly outside the application. In addition, if the application is removed, these files will be emptied at the same time.

You can use the following output routine to create a file in the memory store:

FileOutputStream fileOut = openFileOutput ("my_file", Context.MODE_PRIVATE)

You need to import and add the "java.io.FileOutputStream" class. We provide the file name and mode, and choosing private mode means that the file will only be used by the application. If you add this code to Activity now, for example, in the onClick method, Eclipse will pop up an error prompt. This is because when we do input / output operations, the application may encounter some errors that need to be dealt with. If your input / output operations fail to resolve such errors, Eclipse will prompt an exception and the application will stop running. To ensure that the application works properly in this case, we need to encapsulate our input / output code in a block of try code:

Try {FileOutputStream fileOut = openFileOutput ("my_file", Context.MODE_PRIVATE);} catch (IOException ioe) {Log.e ("APP_TAG", "IOException", ioe);}

If the input / output operation causes an exception, the above code in the catch block is executed, thus writing the error message to the log. In the future, you will often use the Log class in the application (import 'android.util.Log'), which records what happens when the code is executed. We can define a class variable for the string tag, that is, the * parameter in the above code. In this way, if an error occurs, you can view the exception information in Android LogCat.

Step two

Now going back to the try block, after creating the file output routine, you can try to write the following code to the file:

String fileContent = "my data file content"; fileOut.write (fileContent.getBytes ())

After writing all necessary content to the data file, end with the following code:

FileOut.close ()

Step three

When you need to retrieve the contents of an internal file, you can do so through the following process:

Try {FileInputStream fileIn = openFileInput ("my_file"); / / read the file} catch (IOException ioe) {Log.e ("APP_TAG", "IOException", ioe);}

In the try block, use the buffer reader to read the contents of the file:

InputStreamReader streamIn = new InputStreamReader (fileIn); BufferedReader fileRead = new BufferedReader (streamIn); StringBuilder fileBuild = new StringBuilder (""); String fileLine=fileRead.readLine (); while (filelinear null) {fileBuild.append (fileLine+ "\ n"); fileLine=fileRead.readLine ();} String fileText = fileBuild.toString (); streamIn.close ()

Don't be intimidated by the large number of different objects involved, which is actually a standard Java input / output operation. The while loop is executed once on every line in the file. When the execution is complete, the "fileText" variable will save the contents of the file as a string for us to use directly.

3. Public external file

As long as the user device supports it, our application can also save the file in external storage. There are many kinds of external storage, including SD cards, other portable media or memory storage mechanisms that cannot be removed by the user but are identified as external types by the system. When we save the file in external storage, its contents will be fully exposed and no one can prevent users or other applications from accessing it in any way.

Before we try to save the data in external storage, we must first check whether the corresponding storage mechanism is available-it is definitely a good habit to avoid unexpected situations as much as possible:

String extStorageState = Environment.getExternalStorageState ()

The system will return the information as a string, which can be analyzed and compared with the external storage status field in the Environment class:

If (Environment.MEDIA_MOUNTED.equals (extStorageState)) {/ / ok to go ahead and read/ write to external storage} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals (extStorageState)) {/ / can only read} else {/ / cannot read or write}

Even if external storage does exist on the device, we cannot presuppose that the application can write data to it.

Step two

After confirming that we can indeed write data to external storage, you then need to retrieve the directory to specify the location where the file is saved. The following application settings point to level 8 and higher API:

File myFile = new File (getExternalFilesDir (null), "MyFile.txt")

In this way, you can write and read the file. But don't forget to add the following to the project's manifest file only:

As the applications we develop become more complex, you may want to share your saved files with other applications. In this case, you can use all kinds of common items in the public directory, such as pictures and music files.

4. Database

As our application involves more and more complex structural data, sharing preferences or internal / external files may no longer meet the actual needs, it is time to consider using database scenarios. Android enables developers to create and access SQLite databases within the application. When we create a set of databases, it will serve the relevant applications simply as a private component service.

There are a variety of ways to use SQLite database in Android applications. It is recommended that you use classes that extend SQLiteOpenHelper to achieve this requirement. In this class, we need to define database properties and create various class variables (including the database list name we defined and its SQL creation string). The specific code is as follows:

Private static final String NOTE_TABLE_CREATE = "CREATE TABLE Note (noteID INTEGER PRIMARY KEY AUTOINCREMENT," + "noteTxt TEXT);"

The example here involves a very simple set of tables with two columns, one for ID and the other for text; both columns are used to record user comments. In the SQLiteOpenHelper class, you can override the onCreate method to create your own database. In other parts of the application, such as the Activity class, you can access the database through SQLiteOpenHelper, insert new records using the WritableDatabase method, query existing records using the getReadableDatabase method, and then display the results in the application UI.

When iterating over the query results, our application will use the Cursor class, which in turn references each row in the result set.

5. Internet data

Many applications will use Internet data resources, and some applications are even basically composed of a set of interfaces and a large number of Web data sources. You can use the Internet connection on the user's device to store and retrieve data from Web. As long as the network connection is valid, this mechanism will work properly. To achieve this, we need to add the "android.permission.INTERNET" permission to our manifest file.

If we want our application to be able to obtain data from the Internet, we must ensure that this process is separated from the application's main UI thread. With AsyncTask, you can obtain data from the Web source through the background process, write the result to UI after the data download is completed, and * * allow UI to perform its functions normally.

You can also add an internal AsyncTask class to the Activity class and create an AsyncTask instance in the Activity when you need to get the data. By introducing doInBackground and onPostExecute into AsyncTask, you can retrieve the data obtained in Activity and write it to the user interface.

Obtaining Web data is a moderately difficult task in application development. Everyone will try it after they have mastered the knowledge of Android development. However, you may soon find that such a data acquisition mechanism is very suitable for many applications, because it can effectively make use of the connection resources of user devices. Both Java and Android provide tools for processing returned structured data such as JSON feed.

This is the end of this article on "sample analysis of application data in Android SDK". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report