SharedPreferences存储&SD卡存储
记住密码登录
布局文件
<?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=".LoginActivity"
android:orientation="vertical"
android:gravity="center">
<EditText
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:id="@+id/pwd"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<RelativeLayout
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:layout_alignParentLeft="true"
android:id="@+id/remember"
android:text="记住密码"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_alignParentRight="true"
android:id="@+id/login"
android:text="登录"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
</LinearLayout>
Activity
public class MainActivity extends AppCompatActivity {
private SharedPreferences sharedPreferences;
private EditText username;
private EditText password;
private CheckBox cb;
private Button login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name1 = (EditText) findViewById(R.id.username);
pwd1 = (EditText) findViewById(R.id.password);
cb=(CheckBox)findViewById(R.id.cb_remember);
login=(Button)findViewById(R.id.login);
//TODO 读取
sharedPreferences=getSharedPreferences("work",MODE_PRIVATE);
boolean ischeck= sharedPreferences.getBoolean("ischeck",false);
if(ischeck){
String username1=sharedPreferences.getString("name","");
String password1=sharedPreferences.getString("pwd","");
username.setText(username1);
password.setText(password1);
cb.setChecked(true);
}
//TODO 写数据
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name2=username.getText().toString().trim();
String pwd2=password.getText().toString().trim();
if("czp".equals(username2)&&"123456".equals(password2)){
if(cb.isChecked()){
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putBoolean("ischeck",true);
edit.putString("username",name2);
edit.putString("password",pwd2);
edit.commit();
}
else{
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putBoolean("ischeck",false);
edit.commit();
}
}
}
});
}
}
向SD卡中读写Bitmap图片和json字符串
SD卡权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
布局文件:
<?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="50dp"
android:text="写入JSON串"
android:onClick="click"
/>
<Button
android:id="@+id/readJson"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="读取JSON串"
android:onClick="click"
/>
<Button
android:id="@+id/writeImg"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="写入图片"
android:onClick="click"
/>
<Button
android:id="@+id/readImg"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="读取图片"
android:onClick="click"
/>
<TextView
android:id="@+id/showjson"
android:layout_marginTop="20dp"
android:layout_width="300dp"
android:layout_height="50dp"
/>
<ImageView
android:id="@+id/showImg"
android:layout_marginTop="20dp"
android:layout_width="200dp"
android:layout_height="200dp" />
</LinearLayout>
外部方法及Activity:
public class FileUtils {
//方法1:向SD卡中写json串
public static void write_json(String json) {
//判断是否挂载
ifEnvironment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
}
File file=Environment.getExternalStorageDirectory();
FileOutputStream out=null;
try {
out= new FileOutputStream(new File(file,"json.txt"));
out.write(json.getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
//方法2:从SD卡中读取json串
public static String read_json() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File file = Environment.getExternalStorageDirectory();
FileInputStream inputStream = null;
StringBuffer sb=new StringBuffer();
try {
inputStream=new FileInputStream(new File(file,"json.txt"));
byte[] b=new byte[1024];
int len=0;
while((len=inputStream.read(b))!=-1){
sb.append(new String(b,0,len));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}else{
return "";
}
}
//方法3:从SD卡中读取一张图片
public static Bitmap read_bitmap(String filename) {
Bitmap bitmap=null;
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File file=Environment.getExternalStorageDirectory();
File file1 = new File(file, filename);
bitmap= BitmapFactory.decodeFile(file1.getAbsolutePath());
}
return bitmap;
}
//方法4:网络下载一张图片存储到SD卡中
public static void write_bitmap(String url) {
new MyTask().execute(url);
}
static class MyTask extends AsyncTask<String,String,String> {
@Override
protected String doInBackground(String... strings) {
FileOutputStream out=null;
InputStream inputStream=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){
inputStream = connection.getInputStream();
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File file = Environment.getExternalStorageDirectory();
out = new FileOutputStream(new File(file,"xxx.jpg"));
byte[] bytes=new byte[1024];
int len=0;
while((len=inputStream.read(bytes))!=-1){
out.write(bytes,0,len);
}
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//关流
if(out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(connection!=null){
connection.disconnect();
}
}
return null;
}
}
}
private void checkAccess(String access,int code){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int hasAccess = ContextCompat.checkSelfPermission(getApplication(), access);
Log.e("PERMISION_CODE", hasAccess + "***");
if (hasAccess == PackageManager.PERMISSION_GRANTED) {
if (code == 1) {
write_json("json");
}else if(code == 2){
read_json();
}
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, code);
}
}else{
if (code == 1) {
write_json("json");
}else if(code == 2){
read_json();
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if(requestCode==1) {
if (permissions[0].equals(Manifest.permission.READ_EXTERNAL_STORAGE) && grantResults[0] == PackageManager.PERMISSION_GRANTED)
write_json("json");
} else {
finish();
}
}else if(requestCode == 2){
if (permissions[0].equals(Manifest.permission.READ_EXTERNAL_STORAGE) && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
read_json();
} else {
finish();
}
}
}
package com.example.app3;
import android.os.Bundle;
import android.os.FileUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private Button writeJson;
private Button readJson;
private Button writeImg;
private Button readImg;
private TextView showjson;
private ImageView showImg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
writeJson = (Button) findViewById(R.id.writeJson);
readJson = (Button) findViewById(R.id.readJson);
writeImg = (Button) findViewById(R.id.writeImg);
readImg = (Button) findViewById(R.id.readImg);
showjson = (TextView) findViewById(R.id.showjson);
showImg = (ImageView) findViewById(R.id.showImg);
}
public void click(View view) {
switch (view.getId()){
case R.id.writeJson:
FileUtils.write_json("json");
break;
case R.id.readJson:
FileUtils.read_json("json");
break;
case R.id.writeImg:
FileUtils.read_bitmap("czp");
break;
case R.id.readImg:
FileUtils.write_bitmap("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=10&page=1");
break;
}
}
}
七月第二周周考
Activity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private RadioGroup radioGroup;
private RadioButton one;
private RadioButton two;
private RadioButton three;
private ViewPager viewPage;
private Button button;
private TextView textView;
private Timer timer;
private Timer timer1;
private List<Fragment> list = new ArrayList<>();
private int index = 0;
private int num = 5;
private Handler handler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1:
viewPage.setCurrentItem(index);
index++;
if (index == list.size()) {
index = 0;
//实现一个倒计时
timer1 = new Timer();
timer1.schedule(new TimerTask() {
@Override
public void run() {
Message message = new Message();
message.what = 2;
handler.sendMessage(message);
}
}, 0, 1000);
}
break;
case 2:
textView.setText("倒计时:"+(num--));
if (num == 0){
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
timer1.cancel();
//在SD卡设置一个标记 用来判断引导页
SharedPreferences flag = getSharedPreferences("flag", MODE_PRIVATE);
SharedPreferences.Editor edit = flag.edit();
edit.putBoolean("isCome",true);
edit.commit();
finish();
}
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences flag = getSharedPreferences("flag", MODE_PRIVATE);
boolean isCome = flag.getBoolean("isCome", false);
if (isCome){
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
this.finish();
}
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
viewPage = (ViewPager) findViewById(R.id.viewPage);
button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView);
button.setOnClickListener(this);
one = (RadioButton) findViewById(R.id.one);
one.setChecked(true);
one.setOnClickListener(this);
two = (RadioButton) findViewById(R.id.two);
two.setOnClickListener(this);
three = (RadioButton) findViewById(R.id.three);
three.setOnClickListener(this);
radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
radioGroup.setOnClickListener(this);
//把Fragment添加进集合
for (int i = 1; i < 4; i++) {
ContentFragment contentFragment = new ContentFragment();
Bundle bundle = new Bundle();
bundle.putString("key", i + "");
contentFragment.setArguments(bundle);
list.add(contentFragment);
}
//把Fragment加到ViewPage
viewPage.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
@Override
public int getCount() {
return list.size();
}
@NonNull
@Override
public Fragment getItem(int position) {
return list.get(position);
}
});
//让Fragment实现轮播效果
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
handler.sendEmptyMessage(1);
}
}, 0, 1000);
//给Fragment设置页面监听
viewPage.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
//把选择器和Fragment页面绑定
@Override
public void onPageSelected(int position) {
if (position == 0){
one.setChecked(true);
}else if (position == 1){
two.setChecked(true);
}else {
three.setChecked(true);
}
//如果到达第三个页面停止Timer,中断轮播
if (position == list.size() - 1) {
button.setVisibility(View.VISIBLE);
textView.setVisibility(View.VISIBLE);
timer.cancel();
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
//跳转按钮的点击事件
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
timer1.cancel();
startActivity(intent);
SharedPreferences flag = getSharedPreferences("flag", MODE_PRIVATE);
SharedPreferences.Editor edit = flag.edit();
edit.putBoolean("isCome",true);
edit.commit();
this.finish();
break;
}
}
}
适配器
```java
public class MyAdapter extends BaseAdapter {
private Context context;
private List<FoodBean> lists;
private LayoutInflater layoutInflater;
public MyAdapter(Context context, List<FoodBean> lists) {
this.context = context;
this.lists = lists;
layoutInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return lists.size();
}
@Override
public Object getItem(int position) {
return lists.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null){
holder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.layout_listview_item,null);
holder.textView_title = convertView.findViewById(R.id.title_id);
holder.imageView_icon = convertView.findViewById(R.id.icon_id);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
//设置数据
holder.textView_title.setText(lists.get(position).getName());
//设置图片
RequestOptions options = new RequestOptions();
options.circleCrop();//圆形图片
Glide.with(context).load(lists.get(position).getThumb()).apply(options).into(holder.imageView_icon);
return convertView;
}
static class ViewHolder{
private TextView textView_title;
private ImageView imageView_icon;
}
}
异步任务
public class MyAsyncTask extends AsyncTask<String, Void, String> {
private Context context;
private ListView listView;
public MyAsyncTask(Context context, ListView listView) {
this.context = context;
this.listView = listView;
}
@Override
protected String doInBackground(String... strings) {
//网络请求Json字符串
String jsonString = HttpUtils.getJsonFromUrl(strings[0]);
Log.i("MyAsyncTask", "doInBackground: "+jsonString);
if (!(jsonString.isEmpty())){
return jsonString;
}
return null;
}
@Override
protected void onPostExecute(String jsonString) {
super.onPostExecute(jsonString);
if (!(jsonString.isEmpty())){
//解析
// FoodBean foodBean = new Gson().fromJson(jsonString, FoodBean.class);
List<FoodBean> list = JSON.parseArray(jsonString, FoodBean.class);
//创建适配器
MyAdapter adapter = new MyAdapter(context,list);
//设置适配器
listView.setAdapter(adapter);
}
}
}
Fragment
/**
* A simple {@link Fragment} subclass.
*/
public class Fragment_item extends Fragment {
private Button buttonWrite;
private Button buttonRead;
private Button buttonTime;
SharedPreferences.Editor editor;
SharedPreferences sharedPreferences;
String s;
public Fragment_item() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View inflate = inflater.inflate(R.layout.fragment_fragment_item, container, false);
buttonRead = inflate.findViewById(R.id.buttonRead);
buttonWrite = inflate.findViewById(R.id.buttonWrite);
buttonTime = inflate.findViewById(R.id.buttonTime);
OkGo.<String>get("http://api.yunzhancn.cn/api/app.interface.php?siteid=78703&act=column&ctype=4").execute(new StringCallback() {
@Override
public void onSuccess(Response<String> response) {
Toast.makeText(getActivity(), response.body(), Toast.LENGTH_SHORT).show();
sharedPreferences = getActivity().getSharedPreferences("one", MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putString("json", response.body());
editor.commit();
}
});
}
});
buttonRead.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String string = sharedPreferences.getString("json","");
Toast.makeText(getActivity(), string, Toast.LENGTH_SHORT).show();
}
});
return inflate;
}
}
略