Android 02 file storage

Keywords: Android xml encoding

1. test

1. From the perspective of code visibility. Black box test, test code invisible through documents. Automated tests are tested by scripting. White box test, programmers write code to test.
2. Granularity from test. Unit test, integration test, system test.
3. From the level of violence. Pressure test, smoke test (test to hang).
4. You can use monkey 1000 in Android to test 1000 random points. Monkey - P com.my.android pro1 1000, tested in the current application.

2.Android unit test

1. Write the test class extends AndroidTestCase, and test in this class.
2. Right click the prepared method - > run as - > Android juint test to test. This is an error that will be reported, [2019-10-12 18:37:06 - android-pro-1] android-pro-1 does not specify a android.test.Instrumentation test runner Instrumentation or does not declare uses library android.test.runner in its Android manifest.xml, indicating that you need to select to add Instrumentation in the Android manifest.xml file, and then Name to select the test class android.test to use. Instrumentationtestrunner, Target package select the package com.my.android pro1 of the class to be tested.
3. The < instrumentation Android: name = "Android. Test. Instrumentationtestrunner" Android: targetpackage = "com. My. Android pro1" >
4. Then add < uses library Android: name = "Android. Test. Runner" / > under the application tag to indicate the class library to be introduced into the test.

3. Log processing

1. You can use Logcat to view and filter logs. Use tag to filter.
2. Actually in the project, android.util.Log class is used for log output, and the tag and log information are passed in. In Logcat, tag can be used for filtering. Generally, the passed in tag is the current class name.
3. In the actual production, the log class will be encapsulated to control whether to use the log or not, so as to ensure that the log is not needed after going online.

//A simple tool class for log processing. After the project goes online, you can modify the flag and use the relationship log.
public class LogUtils {

	private static boolean flag = true;
	
	public static void logD(String tag,String msg){
		if(flag)
			Log.d(tag, msg);
	}
}

4. Implementation of Android simple login

	<EditText
        android:id="@+id/ed_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="enter one user name" />

    <EditText 
        android:id="@+id/ed_password"
        android:layout_below="@id/ed_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:hint="Please input a password" />
    
    <CheckBox 
        android:id="@+id/cb_isSave"
        android:layout_below="@id/ed_password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save information"/>
    
    <Button 
        android:id="@+id/bnt_login"
        android:layout_below="@id/ed_password"
        android:layout_alignParentRight="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Land"
        />
//Login to see the logical implementation
public class MainActivity extends Activity {
	
	//Components used
    private EditText et_username;
	private EditText et_password;
	private CheckBox cb_isSave;
	private Button btn_login;

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Loading page
        setContentView(R.layout.activity_main);
        
        //Get components that need action
        et_username = (EditText) findViewById(R.id.ed_username);
        et_password = (EditText) findViewById(R.id.ed_password);
        cb_isSave = (CheckBox) findViewById(R.id.cb_isSave);
        btn_login = (Button) findViewById(R.id.bnt_login);
        
        //Bind click event for button
        btn_login.setOnClickListener(new MyListener());
        
        //If user information is saved for display
        String[] infos = Utils.read();
        if(infos != null){
        	et_username.setText(infos[0]);
        	et_password.setText(infos[1]);
        }
    }
	
	//Click event through inner class
	class MyListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			//Get the user name and password entered
			String username = et_username.getText().toString().trim();
			String password = et_password.getText().toString().trim();
			
			//Determine the user name and password entered
			if(TextUtils.isEmpty(username) || TextUtils.isEmpty(password)){
				Toast.makeText(MainActivity.this, "User name or password is empty", Toast.LENGTH_SHORT).show();
			}else {
				//Determine whether to save the information
				boolean checked = cb_isSave.isChecked();
				if(checked){
					boolean info = Utils.saveInfo(username,password);
					if(info){
						Log.d("MainActivity", "User information saved successfully");
					}
				}
				
				Log.d("MainActivity", "User login 11");
			}
		}
	}
}
//Tool class for saving and reading information
public class Utils {

	public static boolean saveInfo(String username, String password) {
		String info = username + "---" + password;
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(new File("data/data/com.my.androidPro03/info.txt"));
			fos.write(info.getBytes());
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}finally {
			if(fos != null){
				try {
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}

	public static String[] read() {
		FileInputStream fis = null;
		BufferedReader br = null;
		try {
			fis = new FileInputStream(new File("data/data/com.my.androidPro03/info.txt"));
			br = new BufferedReader(new InputStreamReader(fis));
			String string = br.readLine();
			String[] split = string.split("---");
			return split;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	public static String[] readByContext(Context context) {
		FileInputStream fis = null;
		BufferedReader br = null;
		try {
			fis = context.openFileInput("info2.txt");
			br = new BufferedReader(new InputStreamReader(fis));
			String string = br.readLine();
			String[] split = string.split("---");
			return split;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	public static boolean saveInfoByContext(Context context,String username, String password) {
		String info = username + "---" + password;
		FileOutputStream fos = null;
		try {
			fos = context.openFileOutput("info2.txt", Context.MODE_PRIVATE);
			fos.write(info.getBytes());
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}finally {
			if(fos != null){
				try {
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}

5. The role of Context in Android

1: global information related to the application can be obtained.
2: you can access the private resources and classes of the current application.
3: you can also make system level calls, such as opening another activation policy and broadcasting.
4:getFilesDir(), the operation is data/data / package name / files directory.
5:openFileInput and openFileOutPut, respectively, get the input stream and output stream. The bottom layer uses getFilesDir().

6. Code implementation of saving files in sd card

//When the sd card is overloaded, save the file on the sd card
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "info.txt");
    try {
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write("Save information".getBytes());
        fileOutputStream.close();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
//Get sd card space information
File file = Environment.getExternalStorageDirectory();
long totalSpace = file.getTotalSpace(); //Total space
long freeSpace = file.getFreeSpace(); //Free space

//Convert byte units
String totalSize = Formatter.formatFileSize(this, totalSpace);
String freeSize = Formatter.formatFileSize(this, freeSpace);
Log.d("MainActivity", totalSize);
Log.d("MainActivity", freeSize);

7. Units in Android

1: indicates that the space size uses DP, android:width="100dp".
2: use sp for text size, android:textSize="15sp".

8. Document authority

1: first is the file or directory.
2: next are the current user, the same group user and other users, each accounting for three.
3: every three bits are r, w and x permissions, with weights of 4, 2 and 1. You can use chmod weight file name to modify the permissions of the file.

9. File mode when using openFileOutPut to manipulate files

1: mode "private, weight 660, the original file will be overwritten when the file is modified.
2: mode "append, with a weight of 660. When modifying a file, the file will be appended.
3: mode? World? Readable, weight 664, all users can read the file.
4: mode > world > writeable, weight 662, all users can write files.

10. Use SharedPreferences to save configuration information

1:SharedPreferences is a lightweight api for saving information.
2: there are 6 types of data that can be saved, int long float Boolean string set < string >.
3: common methods include: sp.edit();edit.putString("username", username);edit.commit(); to save data.
4: sp.getBoolean("isSave", false) can be used for getting. The second parameter is the value returned when the object is not found.
5: the data saved by SharedPreferences is in the data/data / package name / shared_prefs / file name.
6: the format of data saving is xml, such as
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<boolean name="isSave" value="true" />
<string name="password">1234</string>
<string name="username">1234</string>
</map>
//Using SharedPreferences to save information
public class MainActivity extends Activity implements OnClickListener{

    private EditText et_username;
	private EditText et_password;
	private CheckBox cb_isSave;
	private Button btn_login;
	private SharedPreferences sp;

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        et_username = (EditText) findViewById(R.id.et_username);
        et_password = (EditText) findViewById(R.id.et_password);
        
        cb_isSave = (CheckBox) findViewById(R.id.cb_isSave);
        btn_login = (Button) findViewById(R.id.btn_login);
        
        //Set click event interface i for button
        btn_login.setOnClickListener(this);
        //SharedPreferences is a lightweight api for saving information. There are 6 types of data that can be saved.
        //int long float boolean String Set<String>
        //Get SharedPreferences. The first parameter is the file name of the data to be saved. The second parameter is the saved mode.
        sp = getSharedPreferences("info", MODE_PRIVATE);
        
        //If the previous operation has saved the data, then the obtained value is true, and the data needs to be written to the input box automatically.
        boolean isSave = sp.getBoolean("isSave", false);
        if(isSave){
        	String username = sp.getString("username", "");
        	String password = sp.getString("password", "");
        	et_username.setText(username);
        	et_password.setText(password);
        	
        	cb_isSave.setChecked(true);
        }
    }
	
	@Override
	public void onClick(View v) {
		//Get user input data
		String username = et_username.getText().toString().trim();
		String password = et_password.getText().toString().trim();
		
		if(TextUtils.isEmpty(username) || TextUtils.isEmpty(password)){
			Toast.makeText(this, "User name and password are empty", Toast.LENGTH_SHORT).show();
		}else{
			boolean checked = cb_isSave.isChecked();
			Editor edit = sp.edit();
			//Saving data through Editor
			if(checked){
				edit.putString("username", username);
				edit.putString("password", password);
			}
			
			edit.putBoolean("isSave", checked);
			//Write saved data to file
			edit.commit();
		}
	}
}

11. xml serialization of objects

public void saveInfo(View v){
    //Gets the serialized object of xml.
    XmlSerializer serializer = Xml.newSerializer();
    try {
        //Set the output stream and encoding for serialization
        serializer.setOutput(openFileOutput("info.xml", MODE_PRIVATE), "utf-8");

        serializer.startDocument("utf-8", true);

        serializer.startTag(null, "List");
        for(SMS sms : list){
            serializer.startTag(null, "sms");

            serializer.startTag(null, "from");
            serializer.text(sms.from);
            serializer.endTag(null, "from");

            serializer.startTag(null, "content");
            serializer.text(sms.content);
            serializer.endTag(null, "content");

            serializer.startTag(null, "time");
            serializer.text(sms.time);
            serializer.endTag(null, "time");

            serializer.endTag(null, "sms");
        }
        serializer.endTag(null, "List");

        serializer.endDocument();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

12. xml parsing of objects

public void parseInfo(View v){
    XmlPullParser parser = Xml.newPullParser();
    List<SMS> list = null;
    SMS sms = null;
    try {
        parser.setInput(openFileInput("info.xml"), "utf-8");

        int eventType = parser.getEventType();
        while(eventType != XmlPullParser.END_DOCUMENT){
            if(eventType == XmlPullParser.START_TAG){
                if("List".equals(parser.getName())){
                    list = new ArrayList<SMS>();
                }else if("sms".equals(parser.getName())){
                    sms = new SMS();
                }else if("from".equals(parser.getName())){
                    sms.from = parser.nextText();

                }else if("content".equals(parser.getName())){
                    sms.content = parser.nextText();
                }else if("time".equals(parser.getName())){
                    sms.time = parser.nextText();
                }
            }else if(eventType == XmlPullParser.END_TAG){
                if("sms".equals(parser.getName())){
                    list.add(sms);
                }
            }

            eventType = parser.next();
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 

    for(SMS s : list){
        System.out.println(s);
    }
}

Posted by shamilton on Sun, 27 Oct 2019 00:32:10 -0700