SD卡的四种操作
准备工作
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Button writejson;
private Button readjson;
private Button urlpic;
private Button readpic;
private TextView showjson;
private ImageView showpic;
private String json = "http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=10&page=1";
private String picurl="http://www.qubaobei.com/ios/cf/uploadfile/132/9/8289.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String externalStorageState = Environment.getExternalStorageState();
final File externalStorageDirectory = Environment.getExternalStorageDirectory();
File externalStoragePublicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
writejson = (Button) findViewById(R.id.writejson);
readjson = (Button) findViewById(R.id.readjson);
urlpic = (Button) findViewById(R.id.urlpic);
readpic = (Button) findViewById(R.id.readpic);
showjson = (TextView) findViewById(R.id.showjson);
showpic = (ImageView) findViewById(R.id.showpic);
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},100);
布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<Button
android:id="@+id/writejson"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="写入json串"/>
<Button
android:id="@+id/readjson"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="读取json串"/>
<Button
android:id="@+id/readpic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="从SD卡中读取一张图片"/>
<Button
android:id="@+id/urlpic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="从网上下载一张图片"/>
<TextView
android:id="@+id/showjson"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="这里是显示读取的json字符串的"
android:textColor="#000"
android:layout_marginTop="20dp"/>
<ImageView
android:id="@+id/showpic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher"
android:layout_marginTop="10dp"/>
</LinearLayout>
写入json
writejson.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (externalStorageState.equals(Environment.MEDIA_MOUNTED)){
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(externalStorageDirectory,"json.txt"));
fos.write(json.getBytes());
} catch (Exception e) {
e.printStackTrace();
}finally {
if (fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Log.i(TAG, "onClick: 写入成功");
}
}
});
读取json
readjson.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (externalStorageState.equals(Environment.MEDIA_MOUNTED)){
FileInputStream is = null;
StringBuffer sb = new StringBuffer();
try {
is = new FileInputStream(new File(externalStorageDirectory,"json.txt"));
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes))!=-1){
sb.append(new String(bytes,0,len));
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Log.i(TAG, "onClick: 读取成功");
showjson.setText(sb.toString());
}
}
});
从网上下载一张图片到SD卡中
urlpic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new MyTask().execute(picurl);
}
});
异步
package com.example.weekhomework1013;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
class MyTask extends AsyncTask<String,String,String> {
@Override
protected String doInBackground(String... strings) {
FileOutputStream fos = null;
InputStream is = null;
HttpURLConnection connection = null;
try {
URL url = new URL(strings[0]);
connection= (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5*1000);
connection.setReadTimeout(5*1000);
if (connection.getResponseCode() == 200){
is = connection.getInputStream();
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File externalStorageDirectory = Environment.getExternalStorageDirectory();
fos = new FileOutputStream(new File(externalStorageDirectory,"wangbolup.jpg"));
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes))!=-1){
fos.write(bytes,0,len);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (fos!=null){
try {
fos.close();
} catch (IOException e) {
}
}
if (is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection!=null){
connection.disconnect();
}
}
return null;
}
}
从SD卡中读取图片
readpic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bitmap bitmap = null;
if (externalStorageState.equals(Environment.MEDIA_MOUNTED)){
File file = new File(externalStorageDirectory, "wangbolup.jpg");
bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
}
showpic.setImageBitmap(bitmap);
}
});
登录保存密码
布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main2Activity">
<TextView
android:id="@+id/heand"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登录界面"
android:textSize="30sp"
android:textColor="#000"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"/>
<EditText
android:id="@+id/username"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="200dp"
android:hint="请输入用户名"/>
<EditText
android:id="@+id/pwd"
android:layout_width="300dp"
android:layout_below="@+id/username"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:hint="请输入密码"/>
<CheckBox
android:id="@+id/remember"
android:layout_below="@+id/pwd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="记住密码"
android:layout_marginLeft="56dp"
android:layout_marginTop="10dp"/>
<Button
android:id="@+id/login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登录"
android:layout_toRightOf="@+id/remember"
android:layout_below="@+id/pwd"
android:layout_marginLeft="125dp"/>
</RelativeLayout>
代码
package com.example.app2;
import android.content.SharedPreferences;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class Main2Activity extends AppCompatActivity {
private TextView heand;
private EditText username;
private EditText pwd;
private CheckBox remember;
private Button login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
heand = (TextView) findViewById(R.id.heand);
username = (EditText) findViewById(R.id.username);
pwd = (EditText) findViewById(R.id.pwd);
remember = (CheckBox) findViewById(R.id.remember);
login = (Button) findViewById(R.id.login);
final String externalStorageState = Environment.getExternalStorageState();
final File externalStorageDirectory = Environment.getExternalStorageDirectory();
SharedPreferences user = getSharedPreferences("user", MODE_PRIVATE);
String username_read = user.getString("username", "");
String password_read = user.getString("password", "");
boolean remember_read = user.getBoolean("remember", false);
username.setText(username_read);
pwd.setText(password_read);
remember.setChecked(remember_read);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (externalStorageState.equals(Environment.MEDIA_MOUNTED)){
try {
if (Main2Activity.this.remember.isChecked()){
Editable name = Main2Activity.this.username.getText();
Editable password = pwd.getText();
SharedPreferences user = getSharedPreferences("user", MODE_PRIVATE);
SharedPreferences.Editor edit = user.edit();
edit.putString("username",name.toString());
edit.putString("password",password.toString());
edit.putBoolean("remember",true);
edit.commit();
}else{
SharedPreferences user1 = getSharedPreferences("user", MODE_PRIVATE);
SharedPreferences.Editor edit = user1.edit();
edit.clear();
edit.commit();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
}
页面跳转 读写SD卡 ListView展示数据
布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".fragment.DageFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="主界面"
android:layout_centerHorizontal="true"
android:textSize="30sp"
android:layout_marginTop="20dp"/>
<Button
android:id="@+id/writeSD"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="150dp"
android:text="存入SD卡"/>
<Button
android:id="@+id/readSD"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="250dp"
android:text="读取SD卡"/>
<Button
android:id="@+id/rli"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="350dp"
android:text="日历"/>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main2Activity">
<android.support.design.widget.TabLayout
android:id="@+id/tl"
android:layout_width="match_parent"
android:layout_height="50dp">
</android.support.design.widget.TabLayout>
<LinearLayout
android:id="@+id/ll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/tl"
android:layout_above="@+id/footer"
android:orientation="vertical">
</LinearLayout>
<RadioGroup
android:id="@+id/footer"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<RadioButton
android:id="@+id/dage"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:button="@null"
android:text="大哥吃肉"
android:gravity="center"/>
<RadioButton
android:id="@+id/erdi"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:button="@null"
android:text="二弟吃面"
android:gravity="center"/>
<RadioButton
android:id="@+id/sandi"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:button="@null"
android:text="三弟喝汤"
android:gravity="center"/>
<RadioButton
android:id="@+id/sidi"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:button="@null"
android:text="四弟刷碗"
android:gravity="center"/>
</RadioGroup>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
tools:context=".fragment.ErdiFragment">
<ListView
android:id="@+id/lviewid"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>
</FrameLayout>
网络请求
package com.example.app3;
import android.util.Log;
import com.bumptech.glide.load.resource.bytes.ByteBufferRewinder;
import com.google.gson.Gson;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class Httputils {
private static final String TAG = "Httputils";
public static String geturl(String s){
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
URL url = new URL(s);
Log.i(TAG, "geturl: "+s);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setRequestMethod("GET");
connection.connect();
if (connection.getResponseCode() == 200){
is = connection.getInputStream();
baos = new ByteArrayOutputStream();
int len = 0;
byte[] bytes = new byte[1024];
while ((len = is.read(bytes))!=-1){
baos.write(bytes,0,len);
}
Log.i(TAG, "geturl: "+baos.toString());
String s1 = baos.toString();
return s1;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Fragment跳转
package com.example.app3;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import com.example.app3.fragment.DageFragment;
import com.example.app3.fragment.ErdiFragment;
import com.example.app3.fragment.SandiFragment;
import com.example.app3.fragment.SidiFragment;
public class Main2Activity extends AppCompatActivity {
private TabLayout tl;
private LinearLayout ll;
private RadioButton dage;
private RadioButton erdi;
private RadioButton sandi;
private RadioButton sidi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
tl = (TabLayout) findViewById(R.id.tl);
ll = (LinearLayout) findViewById(R.id.ll);
dage = (RadioButton) findViewById(R.id.dage);
erdi = (RadioButton) findViewById(R.id.erdi);
sandi = (RadioButton) findViewById(R.id.sandi);
sidi = (RadioButton) findViewById(R.id.sidi);
final FragmentManager supportFragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
final DageFragment dageFragment = new DageFragment();
final ErdiFragment erdiFragment = new ErdiFragment();
final SandiFragment sandiFragment = new SandiFragment();
final SidiFragment sidiFragment = new SidiFragment();
fragmentTransaction.add(R.id.ll,dageFragment);
fragmentTransaction.add(R.id.ll,erdiFragment);
fragmentTransaction.add(R.id.ll,sandiFragment);
fragmentTransaction.add(R.id.ll,sidiFragment);
fragmentTransaction.show(dageFragment);
fragmentTransaction.hide(erdiFragment);
fragmentTransaction.hide(sandiFragment);
fragmentTransaction.hide(sidiFragment);
fragmentTransaction.commit();
dage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager supportFragmentManager1 = getSupportFragmentManager();
FragmentTransaction fragmentTransaction1 = supportFragmentManager1.beginTransaction();
fragmentTransaction1.show(dageFragment);
fragmentTransaction1.hide(erdiFragment);
fragmentTransaction1.hide(sandiFragment);
fragmentTransaction1.hide(sidiFragment);
fragmentTransaction1.commit();
}
});
erdi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager supportFragmentManager1 = getSupportFragmentManager();
FragmentTransaction fragmentTransaction1 = supportFragmentManager1.beginTransaction();
fragmentTransaction1.show(erdiFragment);
fragmentTransaction1.hide(dageFragment);
fragmentTransaction1.hide(sandiFragment);
fragmentTransaction1.hide(sidiFragment);
fragmentTransaction1.commit();
}
});
sandi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager supportFragmentManager1 = getSupportFragmentManager();
FragmentTransaction fragmentTransaction1 = supportFragmentManager1.beginTransaction();
fragmentTransaction1.show(sandiFragment);
fragmentTransaction1.hide(dageFragment);
fragmentTransaction1.hide(erdiFragment);
fragmentTransaction1.hide(sidiFragment);
fragmentTransaction1.commit();
}
});
sidi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager supportFragmentManager1 = getSupportFragmentManager();
FragmentTransaction fragmentTransaction1 = supportFragmentManager1.beginTransaction();
fragmentTransaction1.show(sidiFragment);
fragmentTransaction1.hide(dageFragment);
fragmentTransaction1.hide(erdiFragment);
fragmentTransaction1.hide(sandiFragment);
fragmentTransaction1.commit();
}
});
}
}
创建一个公共的List
package com.example.app3;
import java.util.ArrayList;
import java.util.List;
public class Together {
public static List<JavaBean> totallist = new ArrayList<>();
}
主页
package com.example.app3.fragment;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.example.app3.Httputils;
import com.example.app3.JavaBean;
import com.example.app3.R;
import com.example.app3.Together;
import com.google.gson.Gson;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
public class DageFragment extends Fragment {
private static final String TAG = "DageFragment";
private Button writeSD;
private Button readSD;
private Button rli;
private String url="http://api.yunzhancn.cn/api/app.interface.php?siteid=78703&act=column&ctype=4";
private String s;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View inflate = inflater.inflate(R.layout.fragment_dage, container, false);
writeSD = (Button) inflate.findViewById(R.id.writeSD);
readSD = (Button) inflate.findViewById(R.id.readSD);
rli = (Button) inflate.findViewById(R.id.rli);
final String externalStorageState = Environment.getExternalStorageState();
final File externalStorageDirectory = Environment.getExternalStorageDirectory();
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},100);
new Thread(new Runnable() {
@Override
public void run() {
String geturl = Httputils.geturl(url);
List<JavaBean> javaBeans = JSON.parseArray(geturl, JavaBean.class);
Together.totallist.addAll(javaBeans);
s = javaBeans.toString();
Log.i(TAG, "run: "+s);
}
}).start();
writeSD.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (externalStorageState.equals(Environment.MEDIA_MOUNTED)){
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(externalStorageDirectory,"json2.txt"));
fos.write(s.getBytes());
} catch (Exception e) {
e.printStackTrace();
}finally {
if (fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Log.i(TAG, "onClick: 写入成功");
}
}
});
readSD.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (externalStorageState.equals(Environment.MEDIA_MOUNTED)){
FileInputStream is = null;
StringBuffer sb = null;
try {
is = new FileInputStream(new File(externalStorageDirectory,"json2.txt"));
sb = new StringBuffer();
int len = 0;
byte[] bytes = new byte[1024];
while((len = is.read(bytes))!=-1){
sb.append(new String(bytes,0,len));
}
Toast.makeText(getActivity(), sb.toString(), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
return inflate;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
}else{
getActivity().finish();
Toast.makeText(getActivity(), "未获取授权", Toast.LENGTH_SHORT).show();
}
}
}
适配器
package com.example.app3;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.List;
public class MyAdapter extends BaseAdapter {
private Context context;
private LayoutInflater layoutInflater;
public MyAdapter(Context context) {
this.context = context;
layoutInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return Together.totallist.size();
}
@Override
public Object getItem(int position) {
return Together.totallist.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null){
holder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.layout_item,null);
holder.pic = convertView.findViewById(R.id.pic);
holder.msg = convertView.findViewById(R.id.msg);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.msg.setText(Together.totallist.get(position).getName());
Glide.with(context).load(Together.totallist.get(position).getThumb()).into(holder.pic);
return convertView;
}
static class ViewHolder{
private ImageView pic;
private TextView msg;
}
}
ListView展示页面
package com.example.app3.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.example.app3.MyAdapter;
import com.example.app3.R;
public class ErdiFragment extends Fragment {
private ListView lviewid;
public ErdiFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View inflate = inflater.inflate(R.layout.fragment_erdi, container, false);
lviewid = (ListView) inflate.findViewById(R.id.lviewid);
MyAdapter myAdapter = new MyAdapter(getActivity());
lviewid.setAdapter(myAdapter);
return inflate;
}
}