垃圾分类APP(五)新闻功能的实现
准备工作
需要垃圾分类新闻的接口
前往天行数据,注册账号,申请接口
前往个人中心,找到我的密钥,那个就是你用来调用接口的密钥,每人每天可以免费调用接口100次
加入约束
要用到 OKhttp3 所以前往 build.gradle 添加依赖
implementation 'com.squareup.okhttp3:okhttp:4.4.0'
implementation 'com.squareup.okio:okio:2.4.3'
新建类来使用Okhttp
一、新建一个API包来放和api相关的类
二、在API包下新建一个 OkhttpUntils 类
package com.example.goodrubish.API;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
public class OkhttpUntils {
public static void OkHttpPost(String url, String json, Callback callback){
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=utf-8"),json);
Request request = new Request.Builder().url(url).post(body).build();
client.newCall(request).enqueue(callback);
}
public static void OkHttpGet(String url, Callback callback){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(callback);
}
}
三、在API包下新建一个 Okhttp_work 类
package com.example.goodrubish.API;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
public class Okhttp_work {
public static void OkHttpGet(String url, Callback callback){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(callback);
}
}
网络配置
需要手机的网络等权限,所以前往 AndroidManifest.xml 添加
<uses-permission android:name="android.permission.INTERNET" /> <!--网络-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" /> <!--录音-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <!--文件读写-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" /> <!--相机-->
android:networkSecurityConfig="@xml/network_config"
android:requestLegacyExternalStorage="true"
具体详情看垃圾分类APP(三)
处理接口传递过来的数据
浅看一下接收的数据
新建新闻列表
新建一个 news_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/garbage_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:singleLine="true"
android:ellipsize="end"
android:text="标题"
android:textSize="18dp"
android:textColor="@color/black"
android:textStyle="bold"
android:layout_marginTop="10dp"/>
<TextView
android:id="@+id/garbage_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="内容详情" />
<ImageView
android:layout_marginTop="10dp"
android:id="@+id/garbage_picUrl"
android:layout_width="250dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:scaleType="fitXY"/>
</LinearLayout>
一、新建 News_list 类处理接收的数据
package com.example.goodrubish.Garbage;
import com.example.goodrubish.Fragment.NewsFragment;
import org.json.JSONException;
import org.json.JSONObject;
public class News_list {
private String title;
private String description;
private String url;
private String pictureUrl;
public News_list(JSONObject the_news_JSON) throws JSONException {
title=the_news_JSON.getString("title");
description=the_news_JSON.getString("description");
url=the_news_JSON.getString("url");
pictureUrl =the_news_JSON.getString("picUrl");
}
public String getTitle(){
return title;
}
public String getDescription(){
return description;
}
public String getpicUrl(){return pictureUrl;}
public String getUrl(){return url;}
}
二、再建一个新闻适配器 News_adapter 类
package com.example.goodrubish.Garbage;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.goodrubish.R;
import java.util.List;
public class News_adapter extends ArrayAdapter {
private int resourceId;
public News_adapter(Context context, int textViewResourceId, List<News_list> objects){
super(context,textViewResourceId,objects);
resourceId=textViewResourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
News_list news_list= (News_list) getItem(position);
View view= LayoutInflater.from(getContext()).inflate(resourceId, parent,false);
TextView garbageTitle=(TextView)view.findViewById(R.id.garbage_title);
TextView garbageDescription=(TextView)view.findViewById(R.id.garbage_description);
ImageView garbagePicUrl= (ImageView) view.findViewById(R.id.garbage_picUrl);
String url = news_list.getpicUrl();
Glide.with(parent).load(url).into(garbagePicUrl);
garbageTitle.setText(news_list.getTitle());
garbageDescription.setText(news_list.getDescription());
return view;
}
}
实现新闻功能
一、先到NewsFragment添加要用到的属性
private Button button;
public static JSONObject News_JSON;
//接口地址加密钥
String url_garbagenews="http://api.tianapi.com/lajifenleinews/index?key=******************************&num=";
//星号位置为你们自己的密钥,把数据换上去就行了
同之前一样在 NewsFragment 中加入下面代码
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
button = getActivity().findViewById(R.id.bt_news);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
intn_search();
}
});
}
public void intn_search() {
View view = getActivity().getWindow().peekDecorView();
if (view != null) {//这里是网络访问的代码,获取服务
InputMethodManager inputmanger = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
initData_search();
}
Handler handler_search=new Handler(new Handler.Callback() {//首先通过handler发送信息
@Override
public boolean handleMessage(@NonNull Message msg) {
switch (msg.what){
case 0:
Toast.makeText(getActivity(),"网络错误",Toast.LENGTH_LONG).show();
break;
case 1:
String json=(String)msg.obj;
try{
News_JSON=new JSONObject(json);
Intent intent=new Intent();
intent.setClass(getActivity(), News.class);
startActivity(intent); //进行页面跳转
break;
}catch (JSONException e){
e.printStackTrace();
}
default:
throw new IllegalStateException("Unexpected value: " + msg.what);
}
return false;
}
});
private void initData_search(){
Okhttp_work.OkHttpGet(url_garbagenews+10, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String content=response.body().string();
Message message=new Message();
message.what=1;
message.obj=content;
handler_search.sendMessageDelayed(message,1000);
}
});
}
上面页面跳转到另外一个页面,记得创建这个Activity
新闻页面布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".News"
android:orientation="vertical">
<ListView
android:id="@+id/news_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
新闻的Java代码
package com.example.goodrubish;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.example.goodrubish.Fragment.NewsFragment;
import com.example.goodrubish.Garbage.News_adapter;
import com.example.goodrubish.Garbage.News_list;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class News extends AppCompatActivity {
private ListView newsList_View;
public static int News_id;
private JSONObject news_result= NewsFragment.News_JSON; //用于接收NewsFragment中的搜索结果
private List<News_list> newsList=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
ActionBar actionbar=getSupportActionBar();
if(actionbar!=null){
actionbar.hide();
}
try {
init_news_list();
} catch (JSONException e) {
e.printStackTrace();
}
News_adapter adapter=new News_adapter(News.this, R.layout.news_item, newsList);
ListView listView=findViewById(R.id.news_listview);
listView.setAdapter(adapter);
newsList_View=findViewById(R.id.news_listview);
newsList_View.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
News_id=i;
String path = "https://www.baidu.com";
try {
path=make_the_String("url");
} catch (JSONException e) {
e.printStackTrace();
}
Uri uri = Uri.parse(path);
Intent intent=new Intent(Intent.ACTION_VIEW,uri);
startActivity(intent);
}
});
}
private void init_news_list() throws JSONException {
JSONArray newslist=news_result.getJSONArray("newslist");
for(int i=0;i<newslist.length();i++){
News_list the_garbage=new News_list(make_the_JSON(i));
newsList.add(the_garbage);
}
}
private JSONObject make_the_JSON(int i) throws JSONException { //用于将JSON转换为字符串数组
JSONArray newslist=news_result.getJSONArray("newslist");
String[] name=new String[newslist.length()];
String newslistString=new String();
JSONObject the_garbage_JSON = new JSONObject(); //具体某一项的json ,可以通过getstring获得其中具体的项
newslistString=newslist.getString(i);
the_garbage_JSON=new JSONObject(newslistString);
// name[i]=the_garbage_JSON.getString("name");
return the_garbage_JSON;
}
private String make_the_String(String need) throws JSONException { //用于将JSON转换为字符串数组
JSONArray newslist=news_result.getJSONArray("newslist");
// String[] name=new String[newslist.length()];
String newslistString=new String();
JSONObject the_garbage_JSON=new JSONObject(); //具体某一项的json ,可以通过getstring获得其中具体的项
newslistString=newslist.getString(News_id);
the_garbage_JSON=new JSONObject(newslistString);
// name[i]=the_garbage_JSON.getString("name");
return the_garbage_JSON.getString(need);
}
}