这是一段我自己写的 读取自己服务器上的数据写入listview的代码
package com.jinesc.xbook; import android.os.Handler; import android.os.Message; import androidx.appcompat.app.AppCompatActivity; //原 import android.support.v7.app.AppCompatActivity; 替换 import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; public class xBookType extends AppCompatActivity implements View.OnClickListener { public static final int SHOW_RESPONSE=0;//用于更新操作 private Button sendRequest; private String str; private ArrayList<String> list = new ArrayList<String>(); //private TextView responseText; //用于处理和发送消息的Hander //用于处理和发送消息的Hander private Handler handler=new Handler(){ public void handleMessage(Message msg){ //如果返现msg.what=SHOW_RESPONSE,则进行制定操作,如想进行其他操作,则在子线程里将SHOW_RESPONSE改变 switch (msg.what){ case SHOW_RESPONSE: String response=(String)msg.obj; //进行UI操作,将结果显示到界面上 //responseText.setText(pJsonStr(response)); //将字符读如全局变量中 str=pJsonStr(response); //将内容加到list view中 使用了list ListView listView = (ListView) findViewById(R.id.listview);//在视图中找到ListView ArrayAdapter<String> adapter = new ArrayAdapter<String>(xBookType.this,android.R.layout.simple_list_item_1,list);//新建并配置ArrayAapeter listView.setAdapter(adapter); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_x_book_type); sendRequest=(Button)findViewById(R.id.send_request); sendRequest.setOnClickListener(this); sendRequestWithHttpURLConnection(); //读取了数据 final ListView listView = (ListView) findViewById(R.id.listview);//在视图中找到ListView listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { //启动监听 list view @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //监听单击事件 String title=list.get(position).toString(); //获取点击的item的字符 Toast.makeText(xBookType.this, "点击>>"+title+"---"+id, Toast.LENGTH_SHORT).show(); } }); } @Override public void onClick(View v) {//触发按钮 if(v.getId()==R.id.send_request){ sendRequestWithHttpURLConnection(); } } private void sendRequestWithHttpURLConnection(){ //开启线程来发起网络请求 new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection=null; try{ URL url=new URL(" 已经隐藏了 "); connection=(HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); InputStream in=connection.getInputStream(); //下面对获取到的输入流进行读取 BufferedReader bufr=new BufferedReader(new InputStreamReader(in)); StringBuilder response=new StringBuilder(); String line=null; while((line=bufr.readLine())!=null){ response.append(line); } Message message=new Message(); message.what=SHOW_RESPONSE; //将服务器返回的数据存放到Message中 message.obj=response.toString(); handler.sendMessage(message); }catch(Exception e){ e.printStackTrace(); }finally { if(connection!=null){ connection.disconnect(); } } } }).start(); } private String pJsonStr(String jsonStr) { String result = ""; try{ // 解析JSON字符 JSONArray jsonArray = new JSONArray(jsonStr); list.clear(); //清除list的值 for (int i = 0; i < jsonArray.length(); i++) { // JSON数组里面的具体-JSON对象 JSONObject jsonObject = jsonArray.getJSONObject(i); String lx = jsonObject.optString("lx", null); //int sl = jsonObject.optInt("sl", 0); //整形 String sl = jsonObject.optString("sl", null); result=String.format("%s%s.[%s]\n",result,lx,sl); //data[i]=String.format("%s",lx); list.add(lx);//加入list 为了能显示listview } } catch (Exception e) { e.printStackTrace(); } return result; } }
XML
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" android:background="@mipmap/bg" android:gravity="center_horizontal" > <Button android:id="@+id/send_request" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="刷新图书类型" /> <ListView android:id="@+id/listview" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
返回的JSON字符
[{"lx":"Ebook","sl":"110"}, {"lx":"三国","sl":"528"}, {"lx":"仙侠","sl":"712"}, {"lx":"全集","sl":"23409"}, {"lx":"历史","sl":"92"}, {"lx":"古龙全集","sl":"46"}, {"lx":"末日","sl":"102"}, {"lx":"网络小说合集","sl":"2162"}, {"lx":"翠微居全本","sl":"320"}, {"lx":"血红","sl":"11"}, {"lx":"西游","sl":"72"}, {"lx":"超能","sl":"29"}, {"lx":"都市","sl":"1307"}, {"lx":"重生","sl":"1262"}]
发表评论