Activity
public class Main2Activity extends AppCompatActivity {
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
pager.setCurrentItem(0);
return true;
case R.id.navigation_video:
pager.setCurrentItem(1);
return true;
case R.id.navigation_my:
pager.setCurrentItem(2);
return true;
}
return false;
}
};
private ViewPager pager;
private BottomNavigationView navigation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
pager = findViewById(R.id.pager);
pager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem(int i) {
switch (i){
case 0:
return new FragmentOne();
case 1:
return new BlankFragment();
case 2:
return new BlankFragment();
}
return null;
}
@Override
public int getCount() {
return 3;
}
});
navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int i, float v, int i1) {
}
@Override
public void onPageSelected(int i) {
switch (i){
case 0:
navigation.setSelectedItemId(R.id.navigation_home);
break;
case 1:
navigation.setSelectedItemId(R.id.navigation_video);
break;
case 2:
navigation.setSelectedItemId(R.id.navigation_my);
break;
}
}
@Override
public void onPageScrollStateChanged(int i) {
}
});
}
}
Fragment
public class FragmentOne extends Fragment {
private ListView news;
private NewsAdapter adapter;
private UserDao newsDao;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
newsDao = new UserDao(getActivity());
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_one, container, false);
}
private String apiUrl = "https://api.expoon.com/AppNews/getNewsList/type/1/p/1";
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
news = view.findViewById(R.id.listview);
adapter = new NewsAdapter(getActivity());
news.setAdapter(adapter);
news.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
newsDao.del(adapter.getItem(position).getNews_id());
adapter.delData(position);
return true;
}
});
initData();
}
@SuppressLint("StaticFieldLeak")
private void initData() {
if(!hasNetwork()) {
List<NewsResponse.Data> result = newsDao.query();
adapter.setDatas(result);
return ;
}
//集合更好。
new AsyncTask<String, Void, List<NewsResponse.Data>>() {
@Override
protected List<NewsResponse.Data> doInBackground(String... strings) {//
NewsResponse result = null;
try {
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
if (isMobileNetwork()) {
urlConnection.setConnectTimeout(15000);
urlConnection.setReadTimeout(15000);
} else {
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
}
int responseCode = urlConnection.getResponseCode();
if (responseCode == 200) {
String strResult = stream2String(urlConnection.getInputStream());
result = new Gson().fromJson(strResult, NewsResponse.class);
}
} catch (Exception e) {
e.printStackTrace();
}
//网络请求成功,解析成功,服务端返回成功
if(result != null && result.isSuccess()) {
newsDao.addAll(result.getData());
return result.getData();
}
return null;
}
@Override
protected void onPostExecute(List<NewsResponse.Data> data) {
if(data != null) {
adapter.setDatas(data);
} else {
Toast.makeText(getActivity(), "请求失败", Toast.LENGTH_SHORT).show();
}
}
}.execute(apiUrl);
}
//是否是手机网络
private boolean isMobileNetwork() {
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.getType() == TYPE_MOBILE;
}
private boolean hasNetwork() {
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isAvailable();
}
private String stream2String(InputStream inputStream) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
InputStreamReader isr = new InputStreamReader(inputStream);
BufferedReader br = new BufferedReader(isr);
for (String tmp = br.readLine(); tmp != null; tmp = br.readLine()) {
stringBuilder.append(tmp);
}
return stringBuilder.toString();
}
}
Bean
public class NewsResponse {
private final int SUCCESS = 1;
private int status;
private String info;
private List<Data> data;
public boolean isSuccess(){
return status == SUCCESS;
}
public int getStatus() {
return status;
}
public String getInfo() {
return info;
}
public List<Data> getData() {
return data;
}
public static class Data{
private String news_id;
private String news_title;
private String news_summary;
public String getNews_id() {
return news_id;
}
public String getNews_title() {
return news_title;
}
public String getNews_summary() {
return news_summary;
}
public Data(String news_id, String news_title, String news_summary) {
this.news_id = news_id;
this.news_title = news_title;
this.news_summary = news_summary;
}
}
}
适配器
public class NewsAdapter extends BaseAdapter {
private Context context;
private List<NewsResponse.Data> datas;
public NewsAdapter(Context context) {
this.context = context;
datas = new ArrayList<>();
}
public void setDatas(List<NewsResponse.Data> datas) {
this.datas = datas;
notifyDataSetInvalidated();
}
public void addData(NewsResponse.Data data){
datas.add(data);
notifyDataSetInvalidated();
}
public void delData(int position){
datas.remove(position);
notifyDataSetInvalidated();
}
@Override
public int getCount() {
return datas.size();
}
@Override
public NewsResponse.Data getItem(int position) {
return datas.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null){
convertView = LayoutInflater.from(context).inflate(R.layout.item,parent,false);
holder = new ViewHolder(convertView);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.bindData(getItem(position));
return convertView;
}
class ViewHolder{
TextView title,summary;
public ViewHolder(View convertView){
title = convertView.findViewById(R.id.title);
summary = convertView.findViewById(R.id.summary);
convertView.setTag(this);
}
public void bindData(NewsResponse.Data item) {
title.setText(item.getNews_title());
summary.setText(item.getNews_summary());
}
}
}
Sqlite
public class Sqlite extends SQLiteOpenHelper {
private static final String DB_NAME ="news.db";
private static final int DB_VERSION =1;
public Sqlite(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE news(_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"title TEXT," +
"summary TEXT," +
"id TEXT UNIQUE)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
UserDao
public class UserDao {
private SQLiteDatabase db;
public UserDao(Context context){
db = new Sqlite(context).getWritableDatabase();
}
//查询
public List<NewsResponse.Data> query(){
List<NewsResponse.Data> result = new ArrayList<>();
Cursor cursor = db.query("news",null,null,null,null,null,null);
if (cursor != null){
while (cursor.moveToNext()){
String id = cursor.getString(cursor.getColumnIndex("id"));
String title = cursor.getString(cursor.getColumnIndex("title"));
String summary = cursor.getString(cursor.getColumnIndex("summ,ary"));
result.add(new NewsResponse.Data(id,title,summary));
}
cursor.close();
}
return result;
}
//添加
public void add(NewsResponse.Data data){
ContentValues values = new ContentValues();
values.put("id",data.getNews_id());
values.put("title",data.getNews_title());
values.put("summary",data.getNews_summary());
db.insert("news",null,values);
}
public void addAll(List<NewsResponse.Data> datas){
for (NewsResponse.Data data:datas){
add(data);
}
}
//删除
public void del(String id){
db.delete("news","id=?",new String[]{id});
}
}
解析数据 https://api.expoon.com/AppNews/getNewsList/type/1/p/1
导入两个权限