private List<Bean.DataBean> lists;
private Context context;
private ListView listview;
private MyAdapter adapter;
public MyAsyncTask(List<Bean.DataBean> lists, Context context, MyAdapter adapter) {
this.lists = lists;
this.context = context;
this.adapter = adapter;
}
@Override
protected String doInBackground(String... strings) {
Log.i("TAG", "doInBackground: 数据为"+new HttpUtils().instance(strings[0]));
return new HttpUtils().instance(strings[0]);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Gson gson = new Gson();
Bean bean = gson.fromJson(s, Bean.class);
List<Bean.DataBean> list = bean.getData();
lists.addAll(list);
Log.i("TAG", "onPostExecute: "+list);
adapter.notifyDataSetChanged();
}
}
<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"
android:orientation="vertical"
tools:context=".MainActivity">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="400dp"></ListView>
<RelativeLayout
android:id="@+id/xianshi"
android:layout_width="match_parent"
android:layout_height="200dp"></RelativeLayout>
</LinearLayout>
public String instance(String path){
ByteArrayOutputStream baos = null;
try {
URL url = new URL(path);
Log.i("TAG", "instance: "+path);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if(urlConnection.getResponseCode()==200){
InputStream inputStream = urlConnection.getInputStream();
baos = new ByteArrayOutputStream();
int len;
byte[] b=new byte[1024];
while((len=inputStream.read(b))!=-1){
baos.write(b,0,len);
}
Log.i("TAG", "instance: "+baos.toString());
return baos.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
private ListView listView;
private List<Bean.DataBean> lists = new ArrayList<>();
private MyAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
adapter = new MyAdapter(this, lists);
listView.setAdapter(adapter);
new MyAsyncTask(lists, this, adapter).execute("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=30&page=1");
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FragmentManager supportFragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
BlankFragment blankFragment = new BlankFragment();
fragmentTransaction.replace(R.id.xianshi,blankFragment);
Bundle bundle = new Bundle();
bundle.putString("key",lists.get(position).getId());
blankFragment.setArguments(bundle);
fragmentTransaction.commit();
}
});
}
}