Android Studio3 在listview上显示解析的json数据

我还没学android,以下代码均借鉴于网络,部分来自书籍(五一假光干这事了,app开发到了一个little阶段,先写一篇博客祭奠我那逝去的三天),以下代码均在Android Studio3.4实现,demo是不可能发的,我还要拿它来参加比赛(虽然距离完成还差了一大截)。

首先,也是最重要的是,新手碰到红字就把鼠标放到红字前面快捷键alt+enter,如果是import class就确定,create就算了

解析本地json数据:

首先要说明的一点是,我解析的是本地的json数据,以后会升级成服务器,不知道json的可以去百度,我需要的json数据比较简单,所以我的代码解析的也是这种格式的,网上有解析复杂格式的方法,这里我还是不说明了(因为之前使用有数组名字的json数据,导致后面的读取有点复杂,就直接去了数组名)

 

[
{
"title": "balabalabalabalabalabalabalabalabalabalabalabalabalabala",
"summary": "balabalabalabalabalabalabalabalabalabalabalabalabalabala",
"url": "balabalabalabalabalabalabalabalabalabalabalabalabalabala"
}
]

格式就是上面这样了,数组不断重复

 

 

 

召唤:真:分割线

---------------------------------------------------------------------------------------------------------------------------------------------------

本地的json一般都保存在assests文件夹下面,这个百度能找到正确答案,我就不写了,我的文件名字是test,格式是json,assests文件夹下面显示的名字也是test,如果你显示的是test.json,那下面的代码就改改

    // 解析Json数据
    jiexiJson jiexiJ = new jiexiJson();
    String str = jiexiJ.getJson();
    Gson gson = new Gson();
    //这个Bean是json返回的实体类
    List<Bean> shops = gson.fromJson(str, new TypeToken<List<Bean>>() {}.getType());

这段代码随你放哪里,新手还是放MainActivity.java,代码非常简单,对不对,但是你放上去肯定是不能运行的,网上好多人写的文章代码残缺,对于我这种新人来说十分不友好,所以,,,,,,,,下面就一个一个说了

jiexiJson是我定义的一个public类,jiexiJ.getJson()是我的在那个类里面定义的一个方法,Gson是官方的,进file->project structure导入,搜索gson试试,不行的话去百度gson,Bean还是自定义的一个实体类,其它红色的就自己去alt+enter

首先是jiexiJson:

public class jiexiJson {
    public String getJson() {
        //将json数据变成字符串
        StringBuilder stringBuilder = new StringBuilder();
        try {
            //获取assets资源管理器
            InputStream is = jiexiJson.this.getClass().getClassLoader().getResourceAsStream("assets/" + "test");
            InputStreamReader streamReader = new InputStreamReader(is);
            BufferedReader bf = new BufferedReader(streamReader);
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
}

解析本地json数据花了我一天时间

获取assests资源管理器那里,网上好多人写了一个函数,函数里面有个变量叫做context,但是又没有写这么用的,百度了好久,终于在简书里发现了原来这个context的实参就是:代码所在类名(比如MainActivity).this

但是,找到了又怎么样,好多人用AssetManager assetManager = context.getAssets();获取assests资源管理器,但是呢?空指针!愣是没在网上找到一个写了这个问题的人,大佬可以在评论区里面留言解答一下,最后用的就是我注释下面的一行代码,不过这好像是指定路径,但是app里面就不行了,反正最后还是从网络获取数据,管他呢

try catch我就不写了,百度能找到用法,选中你的代码快捷键crtl+alt+t,我也不知道那段代码为什么要写在try catch里面,写在外面还会报红线

以上可以单独写一篇博客

Bean这个实体类呢,是用Gsonformat创造出来的,用法自己去百度,简单来说就是能根据你的json数据格式创造出它的实体类,不论你的json数据多么复杂

 

 

 

 

 

大空白分割术

有了shops这个变量我们能干嘛呢?我去百度了一下,没找到答案,我严重怀疑那群写解析本都json数据的家伙是不是互相copy的,自行摸索了好久:

    // 数据传输
    Getall getall = new Getall();
    // 标题
    ArrayList<String> title = getall.TitleToString(shops);
    private String[] title_LIST = title.toArray(new String[title.size()]) ;

    // 内容简介
    ArrayList<String> summary = getall.SummarryToString(shops);
    private String[] summary_LIST = summary.toArray(new String[summary.size()]);

    // 网址
    ArrayList<String> url = getall.UrlToString(shops);
    private String[] url_LIST = url.toArray(new String[url.size()]);

终于,我得到以上的代码段,Getall是我定义的类,剩下的不能import的变量的红字函数全是我在这个类下面写的函数

public class Getall {

    //数据传输
    public ArrayList<String> TitleToString(List<Bean> shops){
        ArrayList<String> titles = new ArrayList<>();
        String temp = "x";
        try {
            int i = 0;
            while(i < shops.size())
            {
                i++;
                temp = shops.get(i).getTitle();
                titles.add(temp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return titles;
    }

    public ArrayList<String> SummarryToString(List<Bean> shops){
        ArrayList<String> summary = new ArrayList<>();
        String temp = "x";
        try {
            int i = 0;
            while(i < shops.size())
            {
                i++;
                temp = shops.get(i).getSummary();
                summary.add(temp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return summary;
    }

    public ArrayList<String> UrlToString(List<Bean> shops){
        ArrayList<String> url = new ArrayList<>();
        String temp = "x";
        try {
            int i = 0;
            while(i < shops.size())
            {
                i++;
                temp = shops.get(i).getUrl();
                url.add(temp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }
}

OK,以上就是解析本地json的详细过程了

 

 

 

 

传输数据到ListView

16:30了,不想写了,自己看代码,下周考试,我干嘛花三天搞这个app

    private List<News> newsList=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initNews();                 //初始化数据
        NewsAdapter adapter=new NewsAdapter(MainActivity.this,R.layout.news_item, newsList);

        ListView listview = (ListView) findViewById(R.id.LIST);
        listview.setAdapter(adapter);
    }

    private void initNews(){
        for(int j = 0; j < title.size(); j++)
        {
            News a = new News(summary_LIST[j],title_LIST[j]);
            newsList.add(a);
        }
    }

放MainActivity.java里面

 

News是仿照《第一行代码》写的类

public class News {
    private String summary;
    private String title;
    public News(String summary,String title){
        this.summary=summary;
        this.title=title;
    }
    public String getSummary(){
        return summary;
    }
    public String getTitles(){
        return title;
    }
}

 

 

LIST解释(在activity_main.xml里面):

<android.support.constraint.ConstraintLayout 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=".MainActivity">

    <HorizontalScrollView
        android:id="@+id/horizontalScrollView"
        android:layout_width="411dp"
        android:layout_height="wrap_content"
        android:background="#459B93"
        android:scrollbars="none"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/searchView4">

        <LinearLayout
            android:id="@+id/horizontalScrollViewItemContainer"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:orientation="horizontal" />
    </HorizontalScrollView>

    <TextView
        android:id="@+id/testTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="TextView_Test"
        android:textSize="36sp"
        tools:layout_editor_absoluteX="88dp"
        tools:layout_editor_absoluteY="230dp"
        app:layout_constraintTop_toBottomOf="@id/LIST"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"/>

    <SearchView
        android:id="@+id/searchView4"
        android:layout_width="411dp"
        android:layout_height="56dp"
        android:iconifiedByDefault="false"
        android:queryHint="搜索内容"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ListView
        android:id="@+id/LIST"
        android:layout_width="413dp"
        android:layout_height="618dp"
        app:layout_constraintLeft_toLeftOf="@id/horizontalScrollView"
        app:layout_constraintTop_toBottomOf="@id/horizontalScrollView"
        />

</android.support.constraint.ConstraintLayout>

新手别copy上去,自己在design里面拖动一个ListView就好了,记得它的id是LIST,覆盖整个屏幕,再点击那个魔法棒(百度了ConstraintLayout的人可以在代码里固定它的位置,大佬也可以直接在design里面将它固定住)

 

NewsAdapter:

public class NewsAdapter extends ArrayAdapter<News> {
    private int resourceId;
    public NewsAdapter(Context context, int textViewResourceId, List<News> objects){
        super(context,textViewResourceId,objects);
        resourceId=textViewResourceId;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        News news=getItem(position);           //获取当前项的实例
        View view= LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
        TextView newsTitle=(TextView) view.findViewById(R.id.titles);
        TextView newsSummary=(TextView) view.findViewById(R.id.summary);
        newsTitle.setText(news.getTitles());
        newsSummary.setText(news.getSummary());
        return view;
    }
}

 

 

news_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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">

    <TextView
        android:id="@+id/titles"
        android:layout_width="411dp"
        android:layout_height="30dp"
        android:layout_gravity="center_vertical"
        tools:layout_editor_absoluteY="16dp" />

    <TextView
        android:id="@+id/summary"
        android:layout_width="411dp"
        android:layout_height="70dp"
        app:layout_constraintTop_toBottomOf="@id/titles"
        android:layout_gravity="center_vertical"
        tools:layout_editor_absoluteY="94dp" />
</android.support.constraint.ConstraintLayout>

这个新手可以copy上去,记得在layout下面新建一个xml文件

 

 

到这里,我们居然在listview的每个item上面显示了两行textview数据,新手是不是很神奇,在listview插入图片的方法你可以看看《第一行代码》,也可以自行百度。

到这里就结束了,听说评论给积分

 

 

下面附赠两段代码,网上找的

listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                Bundle bundle = new Bundle();
                bundle.putString("url_LIST", url_LIST[arg2]);
                Intent intent = new Intent();
                intent.putExtras(bundle);
                intent.setClass(testURL.this, Article.class);
                Log.i("url:", url_LIST[arg2]);
                startActivity(intent);
            }
        });

关键字:MainActivity.java      onCreate

 

 

 

public class Article extends Activity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_article);

        Bundle bundle=getIntent().getExtras();
        String url=bundle.getString("url_LIST");
        TextView tv=(TextView) findViewById(R.id.url);
        tv.setText(url);
    }
}

 

 

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/url"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="哈哈哈啊哈哈" />
</android.support.constraint.ConstraintLayout>

 

 

不解释,我源代码几乎发给你们了,几十分钟搞定我三天的时间,想想都很爽,接下来我要搞点击item进入url的网络链接,好烦,代码不给了,心理不平衡

  • 6
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
好的,我可以为你提供一些解析 JSON 数据并在 Android Studio显示天气预报和生活指数的基本步骤: 1. 首先,你需要获取天气数据的 API 接口,例如和风天气提供的天气预报 API:https://dev.heweather.com/docs/api/weather 2. 然后,你需要使用 Android 中提供的网络请求库,比如 Volley 或 OkHttp,来获取天气数据。你可以使用以下代码来发送 GET 请求并获取 JSON 数据: ``` String url = "your_weather_api_url_here"; JsonObjectRequest jsonObjectRequest = new JsonObjectRequest (Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // 处理 JSON 数据 } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // 处理错误 } }); // 将请求添加到请求队列中 RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(jsonObjectRequest); ``` 3. 接下来,你需要解析 JSON 数据并将它转换为 Java 对象。你可以使用 Gson 这个库来实现 JSON 数据和 Java 对象之间的转换。以下是一个使用 Gson 解析 JSON 数据的示例代码: ```java Gson gson = new Gson(); WeatherData weatherData = gson.fromJson(response.toString(), WeatherData.class); ``` 其中,WeatherData 是一个 POJO 类,它包含了从 JSON 数据解析出来的天气信息。 4. 最后,你需要将天气信息显示在你的应用程序界面上。你可以使用 RecyclerView 或 ListView显示每天的天气预报信息,使用 TextView 显示当前天气信息和生活指数信息。以下是一个示例布局文件: ```xml <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/current_weather" android:layout_width="match_parent" android:layout_height="wrap_content" /> <RecyclerView android:id="@+id/daily_forecast" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/life_index" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> ``` 以上就是在 Android Studio解析 JSON 数据显示天气预报和生活指数的基本步骤。希望对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值