效果图:
由于gif过大,所以我只录制了一部分,但是等你自己写完后运行一下就知道效果了:
关于全局变量的获取,请看:
在修改代码之前的思考
1. 手机号的获取方式
不论是点击侧滑栏的编辑资料,个人收藏还是,点击收藏新闻,都需要判断是否登录,理论上一个新安装的app是没有登陆的,所以我们唯一需要存储的地方就是在登录活动模块了。在本项目中,也就是在LoginActivity.java。
2. 手机号的使用地方
手机号需要使用的地方包括侧滑栏的按钮点击事件,以及网页新闻的收藏。
明白了这两点,我们就可以开始修改了。
第一步,修改LoginActivity.java
package com.example.frametest.UserMode;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.frametest.R;
import com.example.frametest.tools.DBOpenHelper;
import com.example.frametest.tools.MyApplication;
import com.mob.MobSDK;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
String APPKEY = "2b85a17d997b2";
String APPSECRET = "bc386e05d6171e915f1195858a9d017b";
String phoneNums;
// 手机号输入框
private EditText inputPhoneEt;
private static final int UPDATE_INSERT = 0;
// 验证码输入框
private EditText inputCodeEt;
// 获取验证码按钮
private Button requestCodeBtn;
// 注册按钮
private Button commitBtn;
private Button shareBtn;
//倒计时显示 可以手动更改。
int i = 50;
String inputText;
@SuppressLint("HandlerLeak")
private Handler userHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
String user_phone,user_name,user_pasw;
switch (msg.what){
case UPDATE_INSERT:
User user = (User) msg.obj;
user_phone = user.getUser_phone();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputPhoneEt = (EditText) findViewById(R.id.login_input_phone_et);
inputCodeEt = (EditText) findViewById(R.id.login_input_code_et);
requestCodeBtn = (Button) findViewById(R.id.login_request_code_btn);
commitBtn = (Button) findViewById(R.id.login_commit_btn);
// 初始化sdk
MobSDK.init(this,APPKEY,APPSECRET);
}
@Override
protected void onStart() {
super.onStart();
requestCodeBtn.setOnClickListener(this);
commitBtn.setOnClickListener(this);
//启动短信验证SDK
EventHandler eventHandler = new EventHandler(){
@Override
public void afterEvent(int event, int result, Object data) {
Message msg = new Message();
msg.arg1 = event;
msg.arg2 = result;
msg.obj = data;
handler.sendMessage(msg);
}
};
//注册回调监听接口
SMSSDK.registerEventHandler(eventHandler);
}
@Override
public void onClick(View v) {
//取出输入的手机号
phoneNums = inputPhoneEt.getText().toString();
switch (v.getId()) {
case R.id.login_request_code_btn:
// 1. 判断手机号是不是11位并且看格式是否合理
if (!judgePhoneNums(phoneNums)) {
return;
} // 2. 通过sdk发送短信验证
SMSSDK.getVerificationCode("86", phoneNums);
// 3. 把按钮变成不可点击,并且显示倒计时(正在获取)
requestCodeBtn.setClickable(false);
requestCodeBtn.setText("重新发送(" + i + ")");
new Thread(new Runnable() {
@Override
public void run() {
for (; i > 0; i--) {
handler.sendEmptyMessage(-9);
if (i <= 0) {
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
handler.sendEmptyMessage(-8);
}
}).start();
break;
case R.id.login_commit_btn:
//将收到的验证码和手机号提交再次核对
SMSSDK.submitVerificationCode("86", phoneNums, inputCodeEt
.getText().toString());
new Thread(new Runnable() {
@Override
public void run() {
Connection conn = null;
conn = (Connection) DBOpenHelper.getConn();
String sql = "insert into user_info(user_phone) values(?)";
int i = 0;
String id=null;
String user_name=null;
String user_phone=null;
String user_pasw=null;
PreparedStatement pstmt;
try {
User user = new User();
pstmt = (PreparedStatement) conn.prepareStatement(sql);
pstmt.setString(1,phoneNums);
i = pstmt.executeUpdate();
user.setUser_phone(user_phone);
Message message = new Message();
message.what = UPDATE_INSERT;
message.obj = user;
userHandler.sendMessage(message);
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}).start();
break;
}
}
@SuppressLint("HandlerLeak")
Handler handler = new Handler(){
public void handleMessage(Message msg) {
if (msg.what == -9) {
requestCodeBtn.setText("重新发送(" + i + ")");
} else if (msg.what == -8) {
requestCodeBtn.setText("获取验证码");
requestCodeBtn.setClickable(true);
i = 30;
} else {
int event = msg.arg1;
int result = msg.arg2;
Object data = msg.obj;
Log.e("event", "event=" + event);
if (result == SMSSDK.RESULT_COMPLETE) {
// 短信注册成功后,返回MainActivity,然后提示
if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {// 提交验证码成功
Toast.makeText(getApplicationContext(), "提交验证码成功",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putString("userName",phoneNums);
intent.putExtras(bundle);
MyApplication.getInstance().setMoublefhoneUser(inputPhoneEt.getText().toString());
finish();
} else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
Toast.makeText(getApplicationContext(), "正在获取验证码",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(LoginActivity.this,"验证码不正确",Toast.LENGTH_SHORT).show();
((Throwable) data).printStackTrace();
}
}
}
}
};
/**
* 判断手机号码是否合理
*
* @param phoneNums
*/
private boolean judgePhoneNums(String phoneNums) {
if (isMatchLength(phoneNums, 11)
&& isMobileNO(phoneNums)) {
return true;
}
Toast.makeText(this, "手机号码输入有误!",Toast.LENGTH_SHORT).show();
return false;
}
/**
* 验证手机格式
*/
private boolean isMobileNO(String mobileNums) {
/*
* 移动:134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
* 联通:130、131、132、152、155、156、185、186 电信:133、153、180、189、(1349卫通)
* 总结起来就是第一位必定为1,第二位必定为3或5或8,其他位置的可以为0-9
*/
String telRegex = "[1][358]\\d{9}";// "[1]"代表第1位为数字1,"[358]"代表第二位可以为3、5、8中的一个,"\\d{9}"代表后面是可以是0~9的数字,有9位。
if (TextUtils.isEmpty(mobileNums))
return false;
else
return mobileNums.matches(telRegex);
}
/**
* 判断一个字符串的位数
* @param str
* @param length
* @return
*/
private boolean isMatchLength(String str, int length) {
if (str.isEmpty()) {
return false;
} else {
return str.length() == length ? true : false;
}
}
@Override
protected void onDestroy() {
//反注册回调监听接口
SMSSDK.unregisterAllEventHandler();
//存储手机号
inputText = inputPhoneEt.getText().toString();
save(inputText);
System.out.println("活动毁灭之后是否传值"+MyApplication.getInstance().getMoublefhoneUser());
System.out.println("活动毁灭之前是否传值"+inputText);
super.onDestroy();
}
public void save(String inputText) {
FileOutputStream out = null;
BufferedWriter writer = null;
try {
out = openFileOutput("data",Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(inputText);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null){
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
第二步,修改MainActivity.java
package com.example.frametest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.frametest.UserMode.LoginActivity;
import com.example.frametest.UserMode.User;
import com.example.frametest.UserMode.UserFavoriteActivity;
import com.example.frametest.UserMode.User_DataActivity;
import com.example.frametest.tools.DBOpenHelper;
import com.example.frametest.tools.MyApplication;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity {
private android.support.v7.widget.Toolbar toolbar;
private DrawerLayout mDrawerLayout;
private NavigationView navigationView;
private TabLayout tabLayout;
private ViewPager viewPager;
private List<String> list;
private TextView tvhuoqu,tvName;
String phonenumber,userName;
private static final int USER_LOOK_NAME = 0;
@SuppressLint("HandlerLeak")
private Handler userFeedHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
String admin_title,admin_url,user_name;
switch (msg.what){
case USER_LOOK_NAME:
User user = (User) msg.obj;
user_name =user.getUser_name();
tvName = (TextView) findViewById(R.id.text_username);
tvName.setText(user_name);
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); //获取抽屉布局
navigationView = (NavigationView) findViewById(R.id.nav_design);//获取菜单控件实例
View v = navigationView.getHeaderView(0);
CircleImageView circleImageView =(CircleImageView) v.findViewById(R.id.icon_image);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
viewPager = (ViewPager) findViewById(R.id.viewPager);
list = new ArrayList<>();
tvhuoqu = (TextView) findViewById(R.id.text_huoqu);
}
@Override
protected void onStart() {
super.onStart();
/* toolbar.setLogo(R.drawable.icon);//设置图片logo,你可以添加自己的图片*/
toolbar.setTitle("简易新闻");
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar !=null){
//通过HomeAsUp来让导航按钮显示出来
actionBar.setDisplayHomeAsUpEnabled(true);
//设置Indicator来添加一个点击图标
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_24dp);
}
navigationView.setCheckedItem(R.id.nav_call);//设置第一个默认选中
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
//设置菜单项的监听事件
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
mDrawerLayout.closeDrawers();
switch (menuItem.getItemId()) {
case R.id.nav_call:
phonenumber = MyApplication.getMoublefhoneUser();
//通过判断手机号是否存在,来决定是进入编辑资料页面还是进入登陆页面
if (phonenumber != null){
Intent unIntent = new Intent(MainActivity.this,User_DataActivity.class);
startActivity(unIntent);
} else {
Intent exitIntent = new Intent(MainActivity.this,LoginActivity.class);
startActivity(exitIntent);
}
break;
case R.id.nav_friends:
//
break;
case R.id.nav_location:
Toast.makeText(MainActivity.this, "你点击了发布新闻,下步实现", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_favorite:
phonenumber = MyApplication.getMoublefhoneUser();
if (phonenumber != null){
Intent userFavIntent = new Intent(MainActivity.this,UserFavoriteActivity.class);
startActivity(userFavIntent);
} else {
Intent exitIntent = new Intent(MainActivity.this,LoginActivity.class);
startActivity(exitIntent);
}
break;
case R.id.nav_settings:
Toast.makeText(MainActivity.this,"需要做出登出功能,可扩展夜间模式,离线模式等,检查更新",Toast.LENGTH_LONG).show();
break;
case R.id.nav_exit:
Intent intent = new Intent(MainActivity.this,LoginActivity.class);
startActivity(intent);
break;
default:
}
return true;
}
});
list.add("头条");
list.add("社会");
list.add("国内");
list.add("国际");
list.add("娱乐");
list.add("体育");
list.add("军事");
list.add("科技");
list.add("财经");
/* viewPager.setOffscreenPageLimit(1);*/
viewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
//得到当前页的标题,也就是设置当前页面显示的标题是tabLayout对应标题
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return list.get(position);
}
@Override
public Fragment getItem(int position) {
NewsFragment newsFragment = new NewsFragment();
//判断所选的标题,进行传值显示
Bundle bundle = new Bundle();
if (list.get(position).equals("头条")){
bundle.putString("name","top");
}else if (list.get(position).equals("社会")){
bundle.putString("name","shehui");
}else if (list.get(position).equals("国内")){
bundle.putString("name","guonei");
}else if (list.get(position).equals("国际")){
bundle.putString("name","guoji");
}else if (list.get(position).equals("娱乐")){
bundle.putString("name","yule");
}else if (list.get(position).equals("体育")){
bundle.putString("name","tiyu");
}else if (list.get(position).equals("军事")){
bundle.putString("name","junshi");
}else if (list.get(position).equals("科技")){
bundle.putString("name","keji");
}else if (list.get(position).equals("财经")){
bundle.putString("name","caijing");
}else if (list.get(position).equals("时尚")){
bundle.putString("name","shishang");
}
newsFragment.setArguments(bundle);
return newsFragment;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
NewsFragment newsFragment = (NewsFragment) super.instantiateItem(container, position);
return newsFragment;
}
@Override
public int getItemPosition(@NonNull Object object) {
return FragmentStatePagerAdapter.POSITION_NONE;
}
@Override
public int getCount() {
return list.size();
}
});
//TabLayout要与ViewPAger关联显示
tabLayout.setupWithViewPager(viewPager);
String inputText = load();
if (!TextUtils.isEmpty(inputText)){
System.out.println("________)))))))");
System.out.println("________)))))))");
System.out.println(phonenumber);
phonenumber =inputText;
MyApplication.setMoublefhoneUser(phonenumber);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//获取toolbar菜单项
getMenuInflater().inflate(R.menu.toolbar,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
//R.id.home修改导航按钮的点击事件为打开侧滑栏
case android.R.id.home:
if (MyApplication.getInstance().getMoublefhoneUser() != null){
phonenumber = MyApplication.getInstance().getMoublefhoneUser();
}
mDrawerLayout.openDrawer(GravityCompat.START); //打开侧滑栏
tvhuoqu = (TextView) findViewById(R.id.text_huoqu);
tvhuoqu.setText(phonenumber);
//用户开启侧滑栏时,查询数据库对应手机号的用户名,并显示在侧滑栏头部
new Thread(new Runnable() {
@Override
public void run() {
Connection conn = null;
conn = (Connection) DBOpenHelper.getConn();
String sql = "select user_name from user_info where user_phone ='"+phonenumber+"'";
Statement pstmt;
try {
pstmt = (Statement) conn.createStatement();
ResultSet rs = pstmt.executeQuery(sql);
while (rs.next()){
User user = new User();
user.setUser_name(rs.getString(1));
Message msg = new Message();
msg.what=USER_LOOK_NAME;
msg.obj = user;
userFeedHandler.sendMessage(msg);
}
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}).start();
break;
case R.id.userFeedback:
final EditText ed =new EditText(MainActivity.this);
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setTitle("用户反馈");
dialog.setView(ed);
dialog.setCancelable(false);
dialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//添加点击事件
}
});
dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.show();
break;
case R.id.userExit:
Toast.makeText(this,"ni click 退出",Toast.LENGTH_SHORT).show();
break;
default:
}
return true;
}
public String load() {
FileInputStream in = null;
BufferedReader reader = null;
StringBuilder content = new StringBuilder();
try {
in = openFileInput("data");
System.out.println("是否读到文件内容"+in);
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null){
content.append(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content.toString();
}
}
第三步,修改User_DataActivity.java
package com.example.frametest.UserMode;
import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.frametest.R;
import com.example.frametest.tools.DBOpenHelper;
import com.example.frametest.tools.MyApplication;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class User_DataActivity extends AppCompatActivity {
private ImageView imageView_user;
public static final int CHOOSE_USER_TOUX =11;
public static final int USER_SETTINGS_NAME =12;
public static final int USER_UPDATE_NAME =13;
private TextView tv_user_photo,tv_nc,tv_nc_fb;
String user_setting_phone;
String input_userName;
@SuppressLint("HandlerLeak")
private Handler userSettingsHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
String admin_title,admin_url;
switch (msg.what){
case USER_SETTINGS_NAME:
Toast.makeText(User_DataActivity.this,"用户名为空或不存在!",Toast.LENGTH_SHORT).show();
break;
case USER_UPDATE_NAME:
tv_nc_fb.setText(input_userName);
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user__data);
user_setting_phone = MyApplication.getMoublefhoneUser();
Toolbar uToolbar = (Toolbar) findViewById(R.id.userData_toolbar);
tv_user_photo = (TextView)findViewById(R.id.tv_user_photo);
imageView_user = (ImageView)findViewById(R.id.imageView_user);
tv_nc = (TextView)findViewById(R.id.tv_nc);
tv_nc_fb = (TextView) findViewById(R.id.tv_nc_fb);
uToolbar.setTitle("个人信息");
setSupportActionBar(uToolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.ic_chevron_left);
}
}
@Override
protected void onStart() {
super.onStart();
tv_user_photo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(User_DataActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE) !=PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(User_DataActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
}else {
openAlbum();
}
}
});
tv_nc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final EditText editText =new EditText(User_DataActivity.this);
AlertDialog.Builder alog = new AlertDialog.Builder(User_DataActivity.this);
alog.setTitle("输入用户名");
alog.setView(editText);
alog.setCancelable(false);
alog.setPositiveButton("提交", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
new Thread(new Runnable() {
@Override
public void run() {
input_userName = editText.getText().toString();
if ("".equals(input_userName) || input_userName == null) {
Message msg = new Message();
msg.what =USER_SETTINGS_NAME;
userSettingsHandler.sendMessage(msg);
} else {
Connection conn = null;
conn = (Connection) DBOpenHelper.getConn();
String sql = "update user_info set user_name='"+input_userName+"' where user_phone='"+user_setting_phone+"'";
int i = 0;
PreparedStatement pstmt;
try {
pstmt = (PreparedStatement) conn.prepareStatement(sql);
i = pstmt.executeUpdate();
pstmt.close();
conn.close();
Message msg = new Message();
msg.what = USER_UPDATE_NAME;
userSettingsHandler.sendMessage(msg);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}).start();
}
});
alog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
alog.show();
}
});
}
private void openAlbum() {
Intent mIntent = new Intent("android.intent.action.GET_CONTENT");
mIntent.setType("image/*");
startActivityForResult(mIntent,CHOOSE_USER_TOUX);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case 1:
if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
openAlbum();
}else {
Toast.makeText(this,"you denied the permission",Toast.LENGTH_SHORT).show();
}
break;
default:
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
switch (requestCode){
case CHOOSE_USER_TOUX:
if (resultCode == RESULT_OK) {
if (Build.VERSION.SDK_INT >= 19){
handleImageOnKiKat(data);
}else {
handleImageBeforeKiKat(data);
}
}
break;
}
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private void handleImageOnKiKat(Intent data) {
String imagePath = null;
Uri uri = data.getData();
if (DocumentsContract.isDocumentUri(this,uri)){
String docId = DocumentsContract.getDocumentId(uri);
if ("com.android.providers.media.documents".equals(uri.getAuthority())){
String id = docId.split(":")[1];
String selection = MediaStore.Images.Media._ID + "=" + id;
imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
}else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())){
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));
imagePath = getImagePath(contentUri,null);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())){
//如或是content类型的URI就使用普通方法处理
imagePath = getImagePath(uri,null);
} else if ("file".equalsIgnoreCase(uri.getScheme())){
//如果是file类型的直接获取图片路径就行
imagePath = uri.getPath();
}
diplayImage(imagePath); //根据路径显示图片
}
private void handleImageBeforeKiKat(Intent data) {
Uri uri = data.getData();
String imagePath = getImagePath(uri,null);
diplayImage(imagePath);
}
private String getImagePath(Uri uri, String selection) {
String path = null;
//通过Uri和selection来获取真实的图片路径
Cursor cursor = getContentResolver().query(uri,null,selection,null,null);
if (cursor != null){
if (cursor.moveToFirst()){
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();
}
return path;
}
private void diplayImage(String imagePath) {
if (imagePath != null){
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
imageView_user.setImageBitmap(bitmap);
int a =10;
} else {
Toast.makeText(this,"failed to get image",Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
User_DataActivity.this.finish();
break;
}
return true;
}
@Override
protected void onDestroy() {
super.onDestroy();
Intent intent = new Intent();
finish();
}
}
第四步,修改UserFavoriteActivity.java
package com.example.frametest.UserMode;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.example.frametest.R;
import com.example.frametest.WebActivity;
import com.example.frametest.json.NewsBean;
import com.example.frametest.tools.DBOpenHelper;
import com.example.frametest.tools.MyApplication;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class UserFavoriteActivity extends AppCompatActivity {
private ListView listView;
private List<NewsBean.ResultBean.DataBean> newList = new ArrayList<>();
NewsBean.ResultBean.DataBean dataBean;
String phone_userfavorite;
private static final int NewsFav_List = 6;
private TextView textView;
@SuppressLint("HandlerLeak")
private Handler newsFavHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case NewsFav_List:
NewsInfoAdapter adapter = new NewsInfoAdapter(UserFavoriteActivity.this,R.layout.item_layout_news,newList);
Log.d("传入数据后", String.valueOf(newList.size()));
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_favorite);
initNews();
listView = (ListView) findViewById(R.id.list_news);
phone_userfavorite = MyApplication.getMoublefhoneUser();
System.out.println("收藏页面是否传值"+phone_userfavorite);
Toolbar toolbar = (Toolbar) findViewById(R.id.userFavorite_toolbar);
toolbar.setTitle("我的收藏");
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.ic_chevron_left);
}
}
private void initNews() {
new Thread(new Runnable() {
@Override
public void run() {
Connection conn = null;
conn = (Connection) DBOpenHelper.getConn();
String sql = "select title,url from news_info where uniquekey in( select news_id from user_collect where user_phone = ?)";
PreparedStatement pstmt;
try {
String num = phone_userfavorite;
System.out.println("^^^^^^^^^");
System.out.println("^^^^^^^^^");
System.out.println("huoqu手机号内容是"+num);
pstmt = (PreparedStatement) conn.prepareStatement(sql);
pstmt.setString(1,num);
ResultSet rs = pstmt.executeQuery();
while (rs.next()){
rs.getString(1);
NewsBean.ResultBean.DataBean dataBean = new NewsBean.ResultBean.DataBean();
dataBean.setTitle(rs.getString(1));
dataBean.setUrl(rs.getString(2));
newList.add(dataBean);
}
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
Message msg = new Message();
msg.what=NewsFav_List;
newsFavHandler.sendMessage(msg);
}
}).start();
}
@SuppressLint("MissingSuperCall")
@Override
protected void onStart() {
super.onStart();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
NewsBean.ResultBean.DataBean dataBean = newList.get(position);
String url = dataBean.getUrl();
Intent intent = new Intent(UserFavoriteActivity.this,WebActivity.class);
intent.putExtra("url",url);
startActivity(intent);
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
UserFavoriteActivity.this.finish();
break;
}
return true;
}
}
到此,本篇关于手机号使用的优化已经完成。
下篇将会实现用户反馈,用户两种退出方式。
关于新闻的获取功能,界面框架搭建,手机号获取等等请看简易新闻导航篇
。