Android 实现用户收藏新闻以及查看新闻(简易新闻 六)

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/21490.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

关于世界杯的一篇文章-ChatGPT

世界杯是国际足球的最高荣誉&#xff0c;每四年举办一届&#xff0c;是世界上最受欢迎的体育赛事之一。自1930年首届世界杯在乌拉圭举办以来&#xff0c;已经举办了20届。 由国际足联&#xff08;FIFA&#xff09;主办&#xff0c;每届比赛都会在举办国举行&#xff0c;由32支…

2021最近的新闻大事10条简短 今天的新闻大事10条汇总

每天精选2021最近的新闻大事10-12条&#xff0c;365资讯简报 汇总近期、今天的新闻大事。每一条热点新闻大事件都比较简短&#xff0c;可以用作新闻大事件摘抄素材&#xff01; 【365资讯简报】每天一分钟&#xff0c;知晓天下事&#xff01;2021年1月12日 星期二 农历十一月廿…

收藏|最全的LIMS实验室信息管理系统介绍

实验室信息管理系统(LIMS)&#xff0c;就是指通过计算机网络技术对实验的各种信息进行管理的计算机软、硬件系统。也就是将计算机网络技术与现代的管理思想有机结合&#xff0c;利用数据处理技术、海量数据存储技术、宽带传输网络技术、自动化仪器分析技术&#xff0c;来对实验…

使用大型语言模(LLM)构建系统(四):链式提示

今天我学习了DeepLearning.AI的 Building Systems with LLM 的在线课程&#xff0c;我想和大家一起分享一下该门课程的一些主要内容。 下面是我们访问大型语言模(LLM)的主要代码&#xff1a; import openai#您的openai的api key openai.api_key YOUR-OPENAI-API-KEY def get_…

AIGC - 生产力新工具 Bito AI

文章目录 Bito AI 是什么Bito AI 能干啥官网免费的吗&#xff1f;如何使用 Bito方式一&#xff1a;方式二&#xff1a;在这里插入图片描述方式三 Bito AI 是什么 Bito AI是继Github Copilot、Cursor、CodeWhisperer等AI智能编程产品之后发了一大AI编程工具 。 Bito是一款建立…

ChatGPT背后的技术

ChatGPT背后的技术InstructGPT&#xff0c;论文标题为 Training language models to follow instructions with human feedback。 语言模型(Language model)的原理是给一段文本&#xff0c;让它去预测后面下面的词是什么。在预训练中它的训练数据是没有标签的&#xff0c;是自…

揭密ChatGPT背后团队鲜为人知的小秘密

ChatGPT引领的人工智能技术浪潮还在持续火爆&#xff0c;可是做出这款产品的OpenAI公司&#xff0c;熬得住多年的冷板凳&#xff0c;最终一飞冲天&#xff0c;他们是怎么做到的呢&#xff1f; 因此&#xff0c;我对这家企业的组织建设产生了浓厚的兴趣。我找啊找&#xff0c;最…

一点就分享系列(实践篇6——上篇)【迟到补发_详解yolov8】Yolo-high_level系列融入YOLOv8 旨在研究和兼容使用【3月份开始持续补更】

一点就分享系列&#xff08;实践篇5-补更篇&#xff09;[迟到补发]—Yolo系列算法开源项目融入V8旨在研究和兼容使用[持续更新] 题外话 [最近一直在研究开放多模态泛化模型的应用事情&#xff0c;所以这部分内容会更新慢一些&#xff0c;文章和GITGUB更新并不同步&#xff0c;g…

基于OpenAI的gpt-3.5模型API实现个人助手服务

引言 网上有不少OpenAI的API资料&#xff0c;实测下来&#xff0c;可能是环境因素踩了不少坑&#xff0c;这里分享一下我实践成功的技术路线。出于篇幅考虑&#xff0c;本文不会对开发前的部分工作&#xff0c;例如openai账号注册&#xff0c;外网访问权限获取&#xff0c;java…

人人都可实测体验的ChatGPT来了

来源&#xff1a;量子位 所有人都能上手微软Bing了&#xff01; 今天&#xff0c;微软突然官宣全面开放BingChat&#xff1a; 无需任何等待。只需注册一个账户&#xff0c;首页即可体验。 更关键的是&#xff0c;还有一大堆堪称“家底”的新功能来袭&#xff01; 支持100种语言…

最快下载微软必应Bing搜索背景图片的方法

1.打开谷歌Chrome浏览器。 2.打开https://cn.bing.com/或https://cn.bing.com/ 3.CtrlShiftI 4.CtrlO 5.输入 jpg 6.点击链接 7.鼠标右键图片&#xff0c;选择最后两个菜单都能下载&#xff0c;个人偏好第三个 8.另存为即可 第4步 还可以使用CtrlF &#xff0c;在Eleme…

分享:企业内部通信 〖局域网QQ〗Bing(必应)1.0 正式发布,包括:聊天、视频、语音、电话、截屏、涂鸦、文件传输 等

分享&#xff1a;企业内部通信 〖局域网QQ〗Bing&#xff08;必应&#xff09;1.0 正式发布,包括&#xff1a;聊天、视频、语音、电话、截屏、涂鸦、文件传输 等 局域网QQ Bing&#xff08;必应&#xff09;1.0 正式发布 Bing&#xff08;必应&#xff09;是一款优秀的企业局…

【IDEA插件】 EasyCode

Easycode是idea的一个插件&#xff0c;可以直接对数据的表生成 entity,controller,service,dao,mapper,无需任何编码&#xff0c;简单而强大。 1、安装(EasyCode) img 我这里的话是已经那装好了。 建议大家再安装一个插件&#xff0c;Lombok。Lombok能通过注解的方式&#x…

IDEA集成chatGTP让你编码如虎添翼

如果您 还没有chatGTP账号,请移步以下文章中注册章节: ​​​​​​独立部署基于apiKey或accessToken的GPT聊天工具_云台095的博客-CSDN博客 IDEA集成chatGTP让你编码如虎添翼 第一步,打开您的IDEA, 打开首选项(Preference) -> 插件(Plugin) 在插件市场搜索 c…

Docker容器编排

Docker容器编排 简介为什么需要 Compose?安装docker-compose常用命令使用步骤小案例总结 简介 Compose&#xff08;容器编排&#xff09; 是 Docker 公司推出的一个工具软件&#xff0c;可以管理多个 Docker 容器组成一个应用。你需要定义一个 YAML 格式的配置文件docker-com…

云编排技术:探索您的选择

最近 IT 行业有很多围绕云编排的议论&#xff0c;而且许多人想知道云编排到底是怎么回事。本文将探索云编排的概念&#xff0c;以及它将如何融入云计算的大发展趋势中。我将分析各种编排工具并介绍它们之间的区别&#xff0c;使您能够更好地了解有哪些可用的选择。 首先&#x…

终于有本书讲清了ChatGPT和AIGC的前世今生!(文末送书)

AIGC的各大门派是谁&#xff1f;典型技术都有什么&#xff1f; AIGC为什么在绘画领域先破圈&#xff1f;ChatGPT的有哪些局限性&#xff1f; 为何科技企业争相推出大模型&#xff1f; 人类的创新能力会被AIGC取代吗…… 诸如此类的这些话题呈现爆发性增长&#xff0c;频频被科技…

ChatGPT等AIGC如何移动边缘部署?南洋理工最新《 在移动网络中释放边云生成AI的力量:AIGC服务》综述其技术体系...

人工智能生成内容(AIGC)是一种使用人工智能算法创造性地生成、操作和修改有价值和多样化数据的自动化方法。本文重点研究了ChatGPT和Dall-E等AIGC应用在移动边缘网络(mobile AIGC networks)中的部署&#xff0c;这些应用在维护用户隐私的同时&#xff0c;提供个性化和定制化的实…

【ChatGPTAIGC研讨社】“iPhone时刻”:未来已来

文章目录 前言一、ChaGPT&AIGC研讨社简介二、ChatGPT&AIGC研讨社的优势1.丰富充实的资料库Github开源&#xff1a;[ChatGPT_Project](https://github.com/shawshany/ChatGPT_Project)飞书资料库 2.重量级嘉宾3.工作机会4.投资资源 总结 前言 去年年末&#xff0c;Chat…