Save Files to Mobile Memory

Keywords: Android Java xml Apache


MainActivity.java

package com.example;

import java.util.Map;
import com.example.service.loginService;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.util.Log;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {
    private static final String TAG = "MainActivity"; //Logs are typically called "MainActivity"
    private EditText et_username;
    private EditText et_password;
    private CheckBox cb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_username = (EditText)this.findViewById(R.id.et_username);
        et_password = (EditText)this.findViewById(R.id.et_password);
        cb = (CheckBox) findViewById(R.id.cb_remember_pwd);
        //Check for saved accounts and passwords if they are echoed
        Map<String,String> map = loginService.getSavedUserInfo(this);
        if(map!=null){
            et_password.setText(map.get("password"));
            et_username.setText(map.get("username"));
        }
    }
      public void login(View view){
          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 or password cannot be empty", 1).show(); 
          }else{
              //Determine whether to save the password
              if(cb.isChecked()){  //If checked, remember the password
                  Log.i(TAG, "Need to save username password"); //Journal
                  boolean result = loginService.saveUserInfo(this,username, password);
                  if(result){
                      Toast.makeText(this, "Successful saving of user information", 0).show();
                  }
              }
              //Log in and send a message to the server to verify the success of the server
              if("1477996221".equals(username)&&"666666".equals(password)){
                  Toast.makeText(this, "Successful landing", 1).show();
              }
              else{
                  Toast.makeText(this, "Logon failure, account or password error",1).show();
              }
          }
          }
}

/res/layout/activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.MainActivity" >

  <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Account number"
        />
<EditText
       android:id="@+id/et_username"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />    
<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Password"
        />
<EditText
        android:inputType="textPassword" //Password Format
        android:id="@+id/et_password"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        /> 

<RelativeLayout         //Using Relative Layout in Linear Layout
       android:layout_width="wrap_content"
       android:layout_height="wrap_content">
<CheckBox
       android:id="@+id/cb_remember_pwd"
       android:checked="true"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Keep passwords in mind"
       />
<Button
       android:onClick="login"
       android:layout_alignParentRight="true"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Sign in"
       />
</RelativeLayout>

</LinearLayout>

loginSrvice.java Right-click on the original package to create a new package (com.example.service)
Right-click the new package to create a new class (loginSrvice)

package com.example.service;    //New package name

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.net.ContentHandler;
import java.text.BreakIterator;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.entity.InputStreamEntity;

import android.content.Context;

public class loginService {
    /*
     ***Business Method of Keeping Account Password***
     * content context
     * username Account number
     * password Password
     */
    public static boolean saveUserInfo(Context context, String username, String password){
        try {
            File file = new File(context.getFilesDir(),"Info.txt"); //context.getFilesDir() helps us return a directory / date/date / package name / files "Info. txt" file name
            FileOutputStream fos = new FileOutputStream(file);// Create output stream objects
            fos.write((username+"##"+password).getBytes());// Write information to a file
            fos.close();  //Close the output stream object
            return true;   //true saved successfully
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;//false save failed
        }
    }
    /*
     * Get saved data
     */
    public static Map<String, String> getSavedUserInfo(Context context){
        File file = new File(context.getFilesDir(),"Info.txt");
        try{
        FileInputStream fis = new FileInputStream(file);
        BufferedReader br = new BufferedReader(new InputStreamReader(fis));
        String str = br.readLine();//Read a line from this cache
        String[] infos = str.split("##");//The split() method is used to split a string into an array of strings.
        Map<String, String> map = new HashMap<String, String>();// Map is an interface and HashMap is its implementation class. This is a new object.
        map.put("username", infos[0]);
        map.put("password", infos[1]);
        return map;
    }catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
    }
}

Introduce the value of the inputtype of xml.
Android:inputType="none"
android:inputType="text"
android:inputType= "textCapCharacters" in capital letters
android:inputType= "textCapWords" initials capitalized
android:inputType= "textCapSentences" is capitalized only with the first letter
android:inputType= "textAutoCorrect" auto-complete
android:inputType= "textAutoComplete" auto-complete
android:inputType= "textMultiLine" multi-line input
android:inputType= "textImeMultiLine" input method with multiple lines (if supported)
android:inputType= "textNoSuggestions" is not prompted
android:inputType= "textUri" web site
android:inputType= "textEmailAddress" e-mail address
android:inputType= "textEmailSubject" mail topic
android:inputType= "textShortMessage" short message
android:inputType= "textLong Message" long message
android:inputType= "textPersonName" person name
android:inputType= "textPostalAddress" address
android:inputType= "textPassword" password
android:inputType= "textVisiblePassword" visible password
android:inputType= "textWeb EditText" as the text of a web form
android:inputType= "textFilter" text filtering
android:inputType= "textPhonetic" Pinyin Input
android:password= "true" setting can only enter a password
android:textColor = font color " ff8c00"
android:textSize= "20dip" size
android:capitalize = characters written in capital letters
android:textAlign="center" EditText does not have this attribute, but TextView has the background color of the selected Chinese word android:textColorHighlight=" cccccc cc", which defaults to blue.
android:textColorHint=" ffff00" sets the color of the prompt text, which defaults to gray.
android:textScaleX= "1.5" controls the spacing between words
android:typeface= "monospace" font, normal, sans, serif, monospace
android:background="@null" spatial background, not here, refers to transparency.
android:layout_weight="1" weight, which controls the position between controls, is useful in controlling the size of the display of controls.
Through the layout xml file of EditText, the related attributes are implemented:
1. The password box property android:password= "true" allows the content displayed by EditText to be asterisked automatically, and the content will become * in 1 second when input.
2. Pure numeric android:numeric= "true" allows the input method to automatically change to a digital input keyboard, while allowing only 0-9 digital input.
3. Only android:capitalize = "cwj1987" is allowed, so only input cwj1987 is allowed. Generally, for password verification, the following are some extended style attributes
android:editable = "false" setting EditText is not editable
android:singleLine= "true" forcibly entered content on a single line
android:ellipsize="end" automatically hides tail overflow data, usually when text content is too long to be displayed in all lines

Posted by Rony on Sat, 08 Jun 2019 16:18:38 -0700