gpt4 book ai didi

java - 从数组填充 ListView

转载 作者:行者123 更新时间:2023-12-01 10:16:14 26 4
gpt4 key购买 nike

我想使用循环填充我的 ListView ,我最近尝试通过多次调用 SQL 中的数据来以非常低效的方式填充它。当我意识到效率有多低时,我开始使用数组从服务器一次性提取数据。我无法更改代码以使其正常工作。

我需要做的是找到一种循环访问下面的 JSONArrays 数组的方法(这对我来说不是困难的部分),但要做到这一点,我需要让我的 GetSocietyDataASyncTask 返回上面的数组并找到一种方法将其传递给 SocietySearch.java 中的 OnCreate/done 方法(我的代码中的许多 Society 对象可以被忽略,并以某种方式替换为 List Society)

现在我相信我已经包含了所有相关代码,但如果您需要查看其他内容,请随时询问我。

Java 从我的数据库接收的数据如下所示:

[{"society_id":1,"name":"TestName1","email":"Test@email1","description":"TestDes1"},
{"society_id":2,"name":"TestName2","email":"Test@email2","description":"TestDes2"}]

SocietySearch 类:

public class SocietySearch extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_society_search);


Society society = new Society(-1, null, null, null);
ServerRequests serverRequest1 = new ServerRequests(SocietySearch.this);
serverRequest1.GetSocietyDataAsyncTask(society, new GetSocietyCallback() {
@Override
public void done(final Society returnedSociety) {
ListView lv = (ListView) findViewById(R.id.ListView);
List<ListViewItem> items = new ArrayList<>();
items.add(new ListViewItem() {{
ThumbnailResource = R.drawable.test;
Title = returnedSociety.socName;
Subtitle = returnedSociety.socDes;
}});
CustomListViewAdapter adapter = new CustomListViewAdapter(SocietySearch.this, items);
lv.setAdapter(adapter);
}
});
}


class ListViewItem {
public int ThumbnailResource;
public String Title;
public String Subtitle;
}

ServerRequests 类的相关部分:

public class getSocietyDataAsyncTask extends AsyncTask<Void, Void, Society> {
Society society;
GetSocietyCallback societyCallback;

public getSocietyDataAsyncTask(Society society, GetSocietyCallback societyCallback) {
this.society = society;
this.societyCallback = societyCallback;
}

@Override
protected Society doInBackground(Void... params) {
BufferedReader reader = null;
Society returnedSociety = null;
List<Society> societies = new ArrayList<>();
try {
URL url = new URL(SERVER_ADDRESS + "/getsocietydata.php");

HttpURLConnection con = (HttpURLConnection) url.openConnection();

con.setConnectTimeout(CONNECTION_TIMEOUT);
con.setReadTimeout(CONNECTION_TIMEOUT);

con.setRequestMethod("POST");

con.setDoOutput(true);

StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

String line;
while ((line = reader.readLine()) != null) { //Read until there is something available
sb.append(line + "\n"); //Read and save line by line
}
line = sb.toString(); //Saving complete data received in string

//Check values received in Logcat
Log.i("custom_check", "The values received in the store part are as follows:");
Log.i("custom_check", line);


JSONArray ja = new JSONArray(line);
if (ja != null && ja.length() == 0) {
returnedSociety = null;
} else {
for (int i = 0; i <ja.length(); i++) {
JSONObject json = ja.optJSONObject(i);
//Storing each Json in a variable
int society_id = json.getInt("society_id");
String socName = json.getString("name");
String socEmail = json.getString("email");
String socDes = json.getString("description");
returnedSociety = new Society(society_id, socName, socEmail, socDes);
societies.add(returnedSociety);
}
return returnedSociety;
}


} catch (Exception e) {
e.printStackTrace();
Log.d("Sample", "Error has occurred!\n" + e.toString());

}


finally {

if (reader != null) {
try {
reader.close(); //Closing the
} catch (IOException e) {
e.printStackTrace();
}
}

}
return returnedSociety;
}

@Override
protected void onPostExecute(Society returnedSociety) {
super.onPostExecute(returnedSociety);
progressDialog.dismiss();
societyCallback.done(returnedSociety);
}
}

CustomListViewAdapter.java:

public class CustomListViewAdapter extends BaseAdapter {

LayoutInflater inflater;
List<SocietySearch.ListViewItem> items;

public CustomListViewAdapter(Activity context, List<SocietySearch.ListViewItem> items) {
super();

this.items = items;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
//Auto-generated method stub
return items.size(); // TODO Maybe this can be my sql count?
}

@Override
public Object getItem(int position) {
//Auto-generated method stub
return null;
}

@Override
public long getItemId(int position) {
//Auto-generated method stub
return 0;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
//Auto-generated method stub

ListViewItem item = items.get(position);

View vi = convertView;

if (convertView == null)
vi = inflater.inflate(R.layout.item_row, null);

ImageView test = (ImageView) vi.findViewById(R.id.imgThumbnail);
TextView txtTitle = (TextView) vi.findViewById(R.id.txtTitle);
TextView txtSubTitle = (TextView) vi.findViewById(R.id.txtSubTitle);

test.setImageResource(item.ThumbnailResource);
txtTitle.setText(item.Title);
txtSubTitle.setText(item.Subtitle);


return vi;
}
}

ListView 放置文件 (item_row.xml):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dip">

<ImageView
android:id="@+id/imgThumbnail"
android:layout_width="78dip"
android:layout_height="78dip"
android:layout_alignParentLeft="true"
android:layout_centerInParent="true"
android:layout_marginLeft="-3dip"
android:scaleType="centerInside"></ImageView>

<TextView
android:id="@+id/txtTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="6dip"
android:layout_marginTop="6dip"
android:layout_toRightOf="@+id/imgThumbnail"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceLarge"></TextView>

<TextView
android:id="@+id/txtSubTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/txtTitle"
android:layout_marginLeft="6dip"
android:layout_marginTop="3dip"
android:layout_toRightOf="@+id/imgThumbnail"
android:text="TextView"></TextView>

</RelativeLayout>

最佳答案

查看ArrayAdapter,特别是#notifyDataSetChanged。 (notifyDataSetChanged example)。您可以像您一样在 #onCreate 中设置 ListView,并存储对底层 Adapter 的引用。最初,Adapter 将为空,但当数据传入时,只需将其添加到 Adapter 并按照示例中的指导调用 #notifyDataSetChanged 即可。

关于java - 从数组填充 ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35875594/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com