我正在尝试从stackexchange api获取数据,但是在单击按钮以调用asynctask之后,listview没有填充。没有崩溃
我已经用Listview创建了一个简单的Custom Adapter来填充listview。
MainActivity.java
button.addEventListener("click", event => {
event.target.innerText = "In Cart";
event.target.disabled = true;
// get product from products
let cartItem = {
...Storage.getProduct(id),
amount: 1
};
activity_main.xml
public class MainActivity extends AppCompatActivity {
private EditText stackSearch;
private Button searchBtn;
private String text;
private static final String BASE_URL = "https://api.stackexchange.com/2.2/questions";
private StackAsyncTask stackAsyncTask;
private ArrayList<Questions> stackArrayList;
private String exception;
private ListView questionList;
private StackAdapter stackAdapter;
//private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stackAsyncTask = new StackAsyncTask();
stackSearch = findViewById(R.id.book_genre);
searchBtn = findViewById(R.id.btn_search);
questionList = findViewById(R.id.book_list);
stackArrayList = new ArrayList<>();
// progressBar = findViewById(R.id.progressBar);
searchBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("kunal","clicked");
text = stackSearch.getText().toString();
// progressBar.setVisibility(View.VISIBLE);
stackAsyncTask.execute();
}
});
}
class StackAsyncTask extends AsyncTask<Void,Void,Void> {
@Override
protected Void doInBackground(Void... voids) {
Uri uri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter("order","desc")
.appendQueryParameter("sort","activity")
.appendQueryParameter("tagged",text)
.appendQueryParameter("site","stackoverflow")
.build();
URL url;
try {
url = new URL(uri.toString());
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection() ;
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
StringBuilder buffer = new StringBuilder();
String line = reader.readLine();
while(line != null){
buffer.append(line);
line = reader.readLine();
}
JSONObject questions = new JSONObject(buffer.toString());
JSONArray items = questions.getJSONArray("items");
for(int i=0;i<20;i++) {
JSONObject first = items.getJSONObject(i);
JSONObject owner = first.getJSONObject("owner");
String profile_image = owner.getString("profile_image");
String display_name = owner.getString("display_name");
String view_count = first.getString("view_count");
String answer_count = first.getString("answer_count");
String score = first.getString("score");
String last_activity_date = first.getString("last_activity_date");
String creation_date = first.getString("creation_date");
String link = first.getString("link");
String title = first.getString("title");
stackArrayList.add(new Questions(display_name, title, link, profile_image, view_count, answer_count, last_activity_date, creation_date, score));
}
stackAdapter = new StackAdapter(MainActivity.this,R.layout.questionlistitem, stackArrayList);
questionList.setAdapter(stackAdapter);
}catch (Exception e){
exception = e.toString();
}
return null;
}
}
}
questionslistitem.xml
<?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"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="@+id/book_genre"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/query"
android:inputType="text" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btn_search"
android:layout_gravity="center_horizontal"
android:text="Search"/>
<ListView
android:id="@+id/book_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Questions.java
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/title"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
android:textColor="#000"/>
<LinearLayout
android:id="@+id/user_stats"
android:orientation="horizontal"
android:layout_below="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/image"
android:layout_weight="1"
android:contentDescription="@string/profile_image"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/name"
android:layout_weight="1"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/link"
android:layout_weight="1"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_below="@+id/user_stats"
android:id="@+id/views_stats"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/view_count"
android:text="@string/views"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Small"/>
<TextView
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/answers_count"
android:text="@string/answers"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Small"/>
<TextView
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/score"
android:text="@string/score"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Small"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:id="@+id/dates_stats"
android:layout_below="@+id/views_stats"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/last_date"
android:text="@string/last_date"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Small"/>
<TextView
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/creation_date"
android:text="@string/creation_date"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Small"/>
</LinearLayout>
</RelativeLayout>
StackAdapter.java
public class Questions{
private String owner;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
private String title;
private String link;
private String image;
private String view_count;
private String answer_count;
private String last_activity;
private String creation;
private String score;
public Questions(String owner, String title, String link, String image, String view_count, String answer_count, String last_activity, String creation, String score) {
this.owner = owner;
this.title = title;
this.link = link;
this.image = image;
this.view_count = view_count;
this.answer_count = answer_count;
this.last_activity = last_activity;
this.creation = creation;
this.score = score;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getView_count() {
return view_count;
}
public void setView_count(String view_count) {
this.view_count = view_count;
}
public String getAnswer_count() {
return answer_count;
}
public void setAnswer_count(String answer_count) {
this.answer_count = answer_count;
}
public String getLast_activity() {
return last_activity;
}
public void setLast_activity(String last_activity) {
this.last_activity = last_activity;
}
public String getCreation() {
return creation;
}
public void setCreation(String creation) {
this.creation = creation;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
}
我尝试只用字符串填充listvie,但是它没有用,所以这不是api提取的问题。谢谢。
修改
public class StackAdapter extends ArrayAdapter {
private int resourceLayout;
private Context mContext;
public StackAdapter(Context context, int resource,List objects) {
super(context, resource, objects);
this.resourceLayout = resource;
this.mContext = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(mContext);
v = vi.inflate(resourceLayout, null);
}
Questions questions = (Questions) getItem(position);
TextView title = v.findViewById(R.id.title);
TextView views = v.findViewById(R.id.view_count);
TextView score = v.findViewById(R.id.score);
TextView answers = v.findViewById(R.id.answers_count);
TextView author = v.findViewById(R.id.name);
TextView last = v.findViewById(R.id.last_date);
TextView creation = v.findViewById(R.id.creation_date);
TextView link = v.findViewById(R.id.link);
ImageView image = v.findViewById(R.id.image);
title.append(questions.getTitle());
views.append(questions.getView_count());
score.append(questions.getScore());
answers.append(questions.getAnswer_count());
author.append(questions.getOwner());
last.append(questions.getLast_activity());
creation.append(questions.getCreation());
link.append(questions.getLink());
try {
URL url = new URL(questions.getImage());
Glide.with(getContext()).load(url.toString()).into(image);
} catch (MalformedURLException e) {
e.printStackTrace();
}
return v;
}
}
这部分没有执行。请帮忙。
答案 0 :(得分:1)
我建议您在AsyncTask类中实现onPostExecute()方法,并在其中创建和设置适配器,它可能是这样的:
class GetOrders extends AsyncTask<Void, Void, List<ClientOrder>> {
@Override
protected List<ClientOrder> doInBackground(Void... voids) {
//here we get data from REST or database
appDatabase.clientOrderDao().deleteById(id);
clientOrderList = appDatabase.clientOrderDao().getAll();
return clientOrderList;
}
@Override
protected void onPostExecute(List<ClientOrder> orders) {
super.onPostExecute(orders);
MyAdapter adapter = new Adapter(orders);
recyclerView.setAdapter(adapter);
}
}
还有一个!从http服务获取数据的现代方法是Retrofit库,它非常有用,我建议您尝试一下:
答案 1 :(得分:0)
嗨,请检查此更新的代码
public class MainActivity extends AppCompatActivity {
private static final String BASE_URL = "https://api.stackexchange.com/2.2/questions";
private EditText stackSearch;
private Button searchBtn;
private String text;
private StackAsyncTask stackAsyncTask;
private ArrayList<Questions> stackArrayList;
private String exception;
private ListView questionList;
private StackAdapter stackAdapter;
//private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stackArrayList = new ArrayList<>();
stackAsyncTask = new StackAsyncTask();
stackSearch = findViewById(R.id.book_genre);
searchBtn = findViewById(R.id.btn_search);
questionList = findViewById(R.id.book_list);
// progressBar = findViewById(R.id.progressBar);
//add this both lines here
stackAdapter = new StackAdapter(MainActivity.this, R.layout.questionlistitem, stackArrayList);
questionList.setAdapter(stackAdapter);
searchBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("kunal", "clicked");
text = stackSearch.getText().toString();
// progressBar.setVisibility(View.VISIBLE);
stackAsyncTask.execute();
}
});
}
class StackAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... voids) {
Uri uri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter("order", "desc")
.appendQueryParameter("sort", "activity")
.appendQueryParameter("tagged", text)
.appendQueryParameter("site", "stackoverflow")
.build();
URL url;
try {
url = new URL(uri.toString());
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
StringBuilder buffer = new StringBuilder();
String line = reader.readLine();
while (line != null) {
buffer.append(line);
line = reader.readLine();
}
JSONObject questions = new JSONObject(buffer.toString());
JSONArray items = questions.getJSONArray("items");
for (int i = 0; i < 20; i++) {
JSONObject first = items.getJSONObject(i);
JSONObject owner = first.getJSONObject("owner");
String profile_image = owner.getString("profile_image");
String display_name = owner.getString("display_name");
String view_count = first.getString("view_count");
String answer_count = first.getString("answer_count");
String score = first.getString("score");
String last_activity_date = first.getString("last_activity_date");
String creation_date = first.getString("creation_date");
String link = first.getString("link");
String title = first.getString("title");
stackArrayList.add(new Questions(display_name, title, link, profile_image, view_count, answer_count, last_activity_date, creation_date, score));
}
} catch (Exception e) {
exception = e.toString();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
stackAdapter.notifyDataSetChanged();
}
} }
使用此代码继续编码:)