Android 实现用户收藏新闻以及查看新闻(简易新闻 六)
效果图:
因为录制的gif过长无法上传,所以这里分为两段,一段是用户未登录状态下收藏新闻需登录,用户登录后可以收藏:
第二段用户未登录查看收藏,以及登录后查看收藏,以及即时收藏查看:
本次实现分为两个功能实现
1. 用户收藏新闻
1.1用户未登陆状态下收藏新闻流程
1.2用户已登陆状态下收藏新闻流程
2. 用户查看新闻
2.1用户未登录状态下查看新闻
2.2用户登陆状态下查看新闻
首先第一步,新建用户收藏数据表user_collect
表中有三个字段,id,user_phone,news_id,其中user_phone为外键,关联user_info表中的user_phone,news_id关联news_info表中的uniqukey,关联这个特殊key,是因为每个新闻的key都不同,方便查询如下图:
其他两张表的字段设置请看:连接数据库,实现下拉刷新(简易新闻 三)
与App实现第三方Mob短信验证登录以及手机号显示和修改用户名(简易新闻 五)
。
第二步,实现用户判断为未登录状态下收藏过程
修改WebActivity.class
package com.example.frametest;import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.net.http.SslError;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.SearchView;
import android.widget.Toast;import com.example.frametest.UserMode.LoginActivity;
import com.example.frametest.tools.DBOpenHelper;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;public class WebActivity extends AppCompatActivity {private WebView webView;private Toolbar toolbar,ltoolBar;String url,user_phonenumber,uniqukey;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_web);//获取传递的路径webView = (WebView) findViewById(R.id.webView);toolbar = (Toolbar) findViewById(R.id.toolbar_webview);ltoolBar = (Toolbar) findViewById(R.id.toolbar_webcomment);findViewById(R.id.toolbar_webcomment).bringToFront();}@Overrideprotected void onStart() {super.onStart();url = getIntent().getStringExtra("url");uniqukey = getIntent().getStringExtra("uniqukey");//在写这一步的时候,要看一下NewsFragment.class类中,是否在lsitview的点击事件中将uniqukey的值获取并且传值进来,否则,在下面的用户收藏,即使点击了收藏,但是也不会存进user_collect数据表中System.out.println("新闻");//显示JavaScript页面WebSettings settings = webView.getSettings();webView.setWebViewClient(new WebViewClient(){@Overridepublic void onPageFinished(WebView view, String url) {super.onPageFinished(view,url );view.loadUrl("javascript:function setTop(){document.querySelector('body > div.top-wrap.gg-item.J-gg-item').style.display=\"none\";}setTop();");}public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error){//handler.cancel(); 默认的处理方式,WebView变成空白页handler.proceed();//handleMessage(Message msg); 其他处理}});settings.setJavaScriptEnabled(true);settings.setSupportZoom(true); //支持缩放,默认为true。是下面那个的前提。settings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false,则该WebView不可缩放settings.setJavaScriptCanOpenWindowsAutomatically(true);settings.setUseWideViewPort(true);settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);settings.setLoadWithOverviewMode(true);/*settings.setDisplayZoomControls(false);*/webView.loadUrl(url);setSupportActionBar(ltoolBar);toolbar.setTitle("简易新闻");setSupportActionBar(toolbar);ltoolBar.inflateMenu(R.menu.tool_webbottom);ltoolBar.setTitle("感谢观看");ltoolBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {@Overridepublic boolean onMenuItemClick(MenuItem menuItem) {switch (menuItem.getItemId()){case R.id.news_share:Intent intent = new Intent(Intent.ACTION_SEND);intent.putExtra(Intent.EXTRA_SUBJECT,url);intent.setType("text/plain");intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);startActivity(Intent.createChooser(intent,getTitle()));break;case R.id.news_collect://下一步实现点击收藏功能,以及用户查看收藏功能if (user_phonenumber != null){Toast.makeText(WebActivity.this,"收藏成功",Toast.LENGTH_SHORT).show();new Thread(new Runnable() {@Overridepublic void run() {Connection conn = null;conn = (Connection) DBOpenHelper.getConn();String uniquekey = getIntent().getStringExtra("uniquekey");String sql = "insert into user_collect(user_phone,news_id) values(?,?) ";int i = 0;PreparedStatement pstmt;try {pstmt = (PreparedStatement) conn.prepareStatement(sql);pstmt.setString(1,user_phonenumber);pstmt.setString(2,uniquekey);i = pstmt.executeUpdate();pstmt.close();conn.close();} catch (SQLException e) {e.printStackTrace();}}}).start();} else {Intent exitIntent = new Intent(WebActivity.this,LoginActivity.class);startActivityForResult(exitIntent,4);}break;}return true;}});ActionBar actionBar = getSupportActionBar();if (actionBar != null){actionBar.setDisplayHomeAsUpEnabled(true);actionBar.setHomeAsUpIndicator(R.drawable.ic_chevron_left);}}@Overrideprotected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {switch (requestCode){case 4:if (resultCode == RESULT_OK){String returnedData = data.getStringExtra("data_return");user_phonenumber =returnedData;if (returnedData != null){}else {Toast.makeText(this,"登陆失败",Toast.LENGTH_SHORT).show();}}break;default:}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.toolbar_webview,menu);SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);SearchView searchView = (SearchView) menu.findItem(R.id.news_search).getActionView();searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {@Overridepublic boolean onQueryTextSubmit(String query) {Toast.makeText(WebActivity.this,query,Toast.LENGTH_SHORT).show();return false;}@Overridepublic boolean onQueryTextChange(String newText) {return false;}});return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {switch (item.getItemId()){case android.R.id.home:Intent returnIntent = new Intent();WebActivity.this.finish();break;case R.id.news_setting:Toast.makeText(this,"夜间模式",Toast.LENGTH_SHORT).show();break;case R.id.news_feedback:break;default:break;}return true;}
}
修改LonginAcitivity.class
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.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(){@Overridepublic 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;}}};@Overrideprotected 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);// 初始化sdkMobSDK.init(this,APPKEY,APPSECRET);}@Overrideprotected void onStart() {super.onStart();requestCodeBtn.setOnClickListener(this);commitBtn.setOnClickListener(this);//启动短信验证SDKEventHandler eventHandler = new EventHandler(){@Overridepublic 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);}@Overridepublic 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() {@Overridepublic 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() {@Overridepublic 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();intent.putExtra("data_return",inputPhoneEt.getText().toString());setResult(RESULT_OK,intent);Bundle bundle = new Bundle();bundle.putString("userName",phoneNums);intent.putExtras(bundle);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;elsereturn 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;}}@Overrideprotected void onDestroy() {//反注册回调监听接口SMSSDK.unregisterAllEventHandler();//存储手机号inputText = inputPhoneEt.getText().toString();save(inputText);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();}}}}
}
效果图:
注意收藏成功后返回到主界面在另点一个新闻收藏依然要重新登陆,但是当你退出程序再次点开程序,任意点一个新闻收藏却会发现收藏成功,此时点开滑动侧滑栏也会发现头部有你自己上次登陆的手机号与修改过的用户名,这是因为LonginActivity启用了本地保存,但是WebActivity获取到的手机号并未传值给主界面,所以问题就是手机号作为全局变量来使用,并实现这个实时的跟新与获取
第三步,实现用户在登陆了一次之后,下次收藏不用继续登陆,退出app在启动后,也不用登陆,除非换号
这一步说这么多,感觉还是讲不明白,但是等我们实现后,你就知道我的意思了,一次登录,只要没有卸载,永久可用!
关于如何实现存储和实时更新和取出全局变量
请看博客Android实现存储和实时更新和取出全局变量
首先新建一个自己的Application类
package com.example.frametest.tools;import android.app.Application;
import android.content.Context;public class MyApplication extends Application {private static Context context;private static MyApplication instance;private static String moublefhoneUser;@Overridepublic void onCreate() {context = getApplicationContext();super.onCreate();instance = this;}public static MyApplication getInstance(){return instance;}public static Context getContext() {return context;}public static void setMoublefhoneUser(String moublefhoneUser) {MyApplication.moublefhoneUser = moublefhoneUser;}public static String getMoublefhoneUser() {return moublefhoneUser;}}
修改AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.frametest"><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><!-- mob发送短信权限 --><uses-permission android:name="android.permission.READ_CONTACTS" /><uses-permission android:name="android.permission.READ_PHONE_STATE" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.RECEIVE_SMS" /><uses-permission android:name="android.permission.READ_SMS" /><uses-permission android:name="android.permission.GET_TASKS" /><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /><applicationandroid:name=".tools.MyApplication"android:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><activity android:name=".WebActivity" /><activity android:name=".UserMode.LoginActivity" /><activity android:name=".UserMode.User_DataActivity"></activity></application></manifest>
修改WebActivity.class
package com.example.frametest;import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.net.http.SslError;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.SearchView;
import android.widget.Toast;import com.example.frametest.UserMode.LoginActivity;
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 WebActivity extends AppCompatActivity {private WebView webView;private Toolbar toolbar,ltoolBar;String url,user_phonenumber,uniquekey;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_web);//获取传递的路径webView = (WebView) findViewById(R.id.webView);toolbar = (Toolbar) findViewById(R.id.toolbar_webview);ltoolBar = (Toolbar) findViewById(R.id.toolbar_webcomment);findViewById(R.id.toolbar_webcomment).bringToFront();}@Overrideprotected void onStart() {super.onStart();url = getIntent().getStringExtra("url");uniquekey = getIntent().getStringExtra("uniquekey");System.out.println("新闻");//显示JavaScript页面WebSettings settings = webView.getSettings();webView.setWebViewClient(new WebViewClient(){@Overridepublic void onPageFinished(WebView view, String url) {super.onPageFinished(view,url );view.loadUrl("javascript:function setTop(){document.querySelector('body > div.top-wrap.gg-item.J-gg-item').style.display=\"none\";}setTop();");}public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error){//handler.cancel(); 默认的处理方式,WebView变成空白页handler.proceed();//handleMessage(Message msg); 其他处理}});settings.setJavaScriptEnabled(true);settings.setSupportZoom(true); //支持缩放,默认为true。是下面那个的前提。settings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false,则该WebView不可缩放settings.setJavaScriptCanOpenWindowsAutomatically(true);settings.setUseWideViewPort(true);settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);settings.setLoadWithOverviewMode(true);/*settings.setDisplayZoomControls(false);*/webView.loadUrl(url);setSupportActionBar(ltoolBar);toolbar.setTitle("简易新闻");setSupportActionBar(toolbar);ltoolBar.inflateMenu(R.menu.tool_webbottom);ltoolBar.setTitle("感谢观看");ltoolBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {@Overridepublic boolean onMenuItemClick(MenuItem menuItem) {switch (menuItem.getItemId()){case R.id.news_share:Intent intent = new Intent(Intent.ACTION_SEND);intent.putExtra(Intent.EXTRA_SUBJECT,url);intent.setType("text/plain");intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);startActivity(Intent.createChooser(intent,getTitle()));break;case R.id.news_collect://下一步实现点击收藏功能,以及用户查看收藏功能user_phonenumber = MyApplication.getInstance().getMoublefhoneUser();if (user_phonenumber != null){Toast.makeText(WebActivity.this,"收藏成功",Toast.LENGTH_SHORT).show();new Thread(new Runnable() {@Overridepublic void run() {Connection conn = null;conn = (Connection) DBOpenHelper.getConn();String uniquekey = getIntent().getStringExtra("uniquekey");String sql = "insert into user_collect(user_phone,news_id) values(?,?) ";int i = 0;PreparedStatement pstmt;try {pstmt = (PreparedStatement) conn.prepareStatement(sql);pstmt.setString(1,user_phonenumber);pstmt.setString(2,uniquekey);i = pstmt.executeUpdate();pstmt.close();conn.close();} catch (SQLException e) {e.printStackTrace();}}}).start();} else {Intent exitIntent = new Intent(WebActivity.this,LoginActivity.class);startActivityForResult(exitIntent,4);}break;}return true;}});ActionBar actionBar = getSupportActionBar();if (actionBar != null){actionBar.setDisplayHomeAsUpEnabled(true);actionBar.setHomeAsUpIndicator(R.drawable.ic_chevron_left);}}@Overrideprotected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {switch (requestCode){case 4:if (resultCode == RESULT_OK){String returnedData = data.getStringExtra("data_return");user_phonenumber =returnedData;if (returnedData != null){}else {Toast.makeText(this,"登陆失败",Toast.LENGTH_SHORT).show();}}break;default:}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.toolbar_webview,menu);SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);SearchView searchView = (SearchView) menu.findItem(R.id.news_search).getActionView();searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {@Overridepublic boolean onQueryTextSubmit(String query) {Toast.makeText(WebActivity.this,query,Toast.LENGTH_SHORT).show();return false;}@Overridepublic boolean onQueryTextChange(String newText) {return false;}});return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {switch (item.getItemId()){case android.R.id.home:Intent returnIntent = new Intent();WebActivity.this.finish();break;case R.id.news_setting:Toast.makeText(this,"夜间模式",Toast.LENGTH_SHORT).show();break;case R.id.news_feedback:break;default:break;}return true;}
}
修改LoginActivity.class
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(){@Overridepublic 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;}}};@Overrideprotected 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);// 初始化sdkMobSDK.init(this,APPKEY,APPSECRET);}@Overrideprotected void onStart() {super.onStart();requestCodeBtn.setOnClickListener(this);commitBtn.setOnClickListener(this);//启动短信验证SDKEventHandler eventHandler = new EventHandler(){@Overridepublic 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);}@Overridepublic 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() {@Overridepublic 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() {@Overridepublic 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();intent.putExtra("data_return",inputPhoneEt.getText().toString());setResult(RESULT_OK,intent);Bundle bundle = new Bundle();bundle.putString("userName",phoneNums);intent.putExtras(bundle);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;elsereturn 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;}}@Overrideprotected void onDestroy() {//反注册回调监听接口SMSSDK.unregisterAllEventHandler();//存储手机号inputText = inputPhoneEt.getText().toString();save(inputText);if (inputText != null){MyApplication.getInstance().setMoublefhoneUser(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.class
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.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(){@Overridepublic 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;}}};@Overrideprotected 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);}@Overrideprotected 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() {//设置菜单项的监听事件@Overridepublic boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {mDrawerLayout.closeDrawers();switch (menuItem.getItemId()) {case R.id.nav_call://通过判断手机号是否存在,来决定是进入编辑资料页面还是进入登陆页面if (phonenumber != null){Intent unIntent = new Intent(MainActivity.this,User_DataActivity.class);unIntent.putExtra("user_settings",phonenumber);startActivityForResult(unIntent,3);} else {Intent exitIntent = new Intent(MainActivity.this,LoginActivity.class);startActivityForResult(exitIntent,2);}break;case R.id.nav_friends:Toast.makeText(MainActivity.this, "你点击了好友", Toast.LENGTH_SHORT).show();break;case R.id.nav_location:Toast.makeText(MainActivity.this, "你点击了发布新闻,下步实现", Toast.LENGTH_SHORT).show();break;case R.id.nav_favorite:Toast.makeText(MainActivity.this, "你点击了个人收藏,下步实现", Toast.LENGTH_SHORT).show();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);startActivityForResult(intent,1);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@Overridepublic CharSequence getPageTitle(int position) {return list.get(position);}@Overridepublic 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@Overridepublic Object instantiateItem(@NonNull ViewGroup container, int position) {NewsFragment newsFragment = (NewsFragment) super.instantiateItem(container, position);return newsFragment;}@Overridepublic int getItemPosition(@NonNull Object object) {return FragmentStatePagerAdapter.POSITION_NONE;}@Overridepublic 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);}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {//获取toolbar菜单项getMenuInflater().inflate(R.menu.toolbar,menu);return true;}@Overridepublic 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() {@Overridepublic 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() {@Overridepublic void onClick(DialogInterface dialog, int which) {//添加点击事件}});dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic 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;}@Overrideprotected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {switch (requestCode){case 1:if (resultCode == RESULT_OK){String returnedData = data.getStringExtra("data_return");phonenumber = returnedData;View v = navigationView.getHeaderView(0);tvhuoqu = (TextView) v.findViewById(R.id.text_huoqu);tvhuoqu.setText(phonenumber);System.out.println("*********");System.out.println("*********");System.out.println("手机号获取到的内容+"+phonenumber);}break;case 2:if(resultCode == RESULT_OK){String returnedData = data.getStringExtra("data_return");phonenumber = returnedData;}break;case 3:if (requestCode == RESULT_OK){String retutnName = data.getStringExtra("return_name");userName = retutnName;}break;default:}}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();}
}
此时效果如下:
此时只差一个用户查看收藏新闻的功能了。
第三步,实现用户查看个人收藏功能
效果图:
项目结构图
修改 MainActivity.class
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(){@Overridepublic 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;}}};@Overrideprotected 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);}@Overrideprotected 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() {//设置菜单项的监听事件@Overridepublic boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {mDrawerLayout.closeDrawers();switch (menuItem.getItemId()) {case R.id.nav_call://通过判断手机号是否存在,来决定是进入编辑资料页面还是进入登陆页面if (phonenumber != null){Intent unIntent = new Intent(MainActivity.this,User_DataActivity.class);unIntent.putExtra("user_settings",phonenumber);startActivityForResult(unIntent,3);} else {Intent exitIntent = new Intent(MainActivity.this,LoginActivity.class);startActivityForResult(exitIntent,2);}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:if (phonenumber != null){Intent userFavIntent = new Intent(MainActivity.this,UserFavoriteActivity.class);userFavIntent.putExtra("test_user",phonenumber);startActivity(userFavIntent);} else {Intent exitIntent = new Intent(MainActivity.this,LoginActivity.class);startActivityForResult(exitIntent,2);}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);startActivityForResult(intent,1);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@Overridepublic CharSequence getPageTitle(int position) {return list.get(position);}@Overridepublic 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@Overridepublic Object instantiateItem(@NonNull ViewGroup container, int position) {NewsFragment newsFragment = (NewsFragment) super.instantiateItem(container, position);return newsFragment;}@Overridepublic int getItemPosition(@NonNull Object object) {return FragmentStatePagerAdapter.POSITION_NONE;}@Overridepublic 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);}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {//获取toolbar菜单项getMenuInflater().inflate(R.menu.toolbar,menu);return true;}@Overridepublic 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() {@Overridepublic 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() {@Overridepublic void onClick(DialogInterface dialog, int which) {//添加点击事件}});dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic 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;}@Overrideprotected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {switch (requestCode){case 1:if (resultCode == RESULT_OK){String returnedData = data.getStringExtra("data_return");phonenumber = returnedData;View v = navigationView.getHeaderView(0);tvhuoqu = (TextView) v.findViewById(R.id.text_huoqu);tvhuoqu.setText(phonenumber);System.out.println("*********");System.out.println("*********");System.out.println("手机号获取到的内容+"+phonenumber);}break;case 2:if(resultCode == RESULT_OK){String returnedData = data.getStringExtra("data_return");phonenumber = returnedData;}break;case 3:if (requestCode == RESULT_OK){String retutnName = data.getStringExtra("return_name");userName = retutnName;}break;default:}}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();}
}
添加用户收藏活动
新一个空白的Activity,包括UserFavoriteActivity.class与activity_user_favorite.xml
新建UserFavoriteActivity.class
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 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(){@Overridepublic 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;}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_user_favorite);initNews();listView = (ListView) findViewById(R.id.list_news);phone_userfavorite = getIntent().getStringExtra("test_user");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() {@Overridepublic 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")@Overrideprotected void onStart() {super.onStart();listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {@Overridepublic 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);}});}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {switch (item.getItemId()){case android.R.id.home:UserFavoriteActivity.this.finish();break;}return true;}
}
修改activity_user_favorite.xml布局文件:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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=".UserMode.UserFavoriteActivity"><LinearLayoutandroid:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"><android.support.v7.widget.Toolbarandroid:id="@+id/userFavorite_toolbar"android:layout_width="match_parent"android:layout_height="?attr/actionBarSize"android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"android:background="?attr/colorPrimary"app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/><ListViewandroid:id="@+id/list_news"android:layout_width="match_parent"android:layout_height="match_parent"></ListView></LinearLayout></android.support.design.widget.CoordinatorLayout>
新建ListView的适配器与子布局文件
新建NewsInfoAdapter.java适配器
package com.example.frametest.UserMode;import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;import com.example.frametest.R;
import com.example.frametest.json.NewsBean;import java.util.List;public class NewsInfoAdapter extends ArrayAdapter<NewsBean.ResultBean.DataBean> {private int resourceId;public NewsInfoAdapter(Context context, int textViewResourceId, List<NewsBean.ResultBean.DataBean> objects){super(context, textViewResourceId, objects);resourceId = textViewResourceId;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {NewsBean.ResultBean.DataBean dataBean = getItem(position);View view =null;if (convertView == null){view = LayoutInflater.from(getContext()).inflate(resourceId, parent,false);} else {view = convertView;}TextView newsName = (TextView) view.findViewById(R.id.title_news);newsName.setText(dataBean.getTitle());return view;}public class ViewHoder{private TextView newsName;}
}
修改item_layout_news.xml布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_marginTop="10dp"android:layout_marginBottom="10dp"><TextViewandroid:id="@+id/title_news"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textStyle="bold"android:layout_toLeftOf="@id/image"android:layout_marginTop="8dp"android:layout_marginLeft="10dp"android:layout_marginBottom="8dp"android:text="Title"android:textSize="18sp"/>
</RelativeLayout>
到此,本篇功能用户收藏,用户查看收藏,都已实现。
欢迎讨论
关于之前的博客,可以看 制作简易新闻App导航篇
看到这里很多细心的朋友应该发现了一个问题就是,代码有点冗余了,可以做的一个优化就是将每次输入手机号登录后返回的onAcctivityResult替换成我们的全局变量,这样每次运行的逻辑也很清楚,关于这一步,后面将会在导航篇里对其优化。
针对上面说的优化已经完成,具体请看:
关于手机号获取的优化(改为全局变量存储与获取与更新)
项目GitHub地址:https://github.com/ziruiliu1/MyBlog