我正在尝试从我自己的PHP服务器中检索JSON。 我工作的服务器端部分很好,实际上它返回了一个JSON文件,我很容易在我的Android应用程序中导入。 但是,请查看我的代码:
我的onCreate方法
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loans_list);
setTitle("Catalogo Libri");
bookList = new ArrayList<>();
new LoadAllBooks().execute();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
我的AsyncTask类
class LoadAllBooks extends AsyncTask<String, String, String> {
ArrayList<String> titoli = new ArrayList<String>();
ArrayList<String> autori = new ArrayList<String>();
ArrayList<Bitmap> immagini = new ArrayList<Bitmap>();
/**
* Before starting background thread Show Progress Dialog
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoansList.this);
pDialog.setMessage("Loading books. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args) {
// Building Parameters
postRequest("0");
//
for (Map m : bookList) {
titoli.add((String) m.get("Title"));
autori.add((String) m.get("Author"));
byte[] data = Base64.decode((String) m.get("Cover"), Base64.DEFAULT);
immagini.add(BitmapFactory.decodeByteArray(data, 0, data.length));
}
authors = autori.toArray(new String[autori.size()]);
names = titoli.toArray(new String[titoli.size()]);
images = immagini.toArray(new Bitmap[immagini.size()]);
return null;
}
/**
* After completing background task Dismiss the progress dialog
**/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListView l = (ListView) findViewById(R.id.books);
CustomAdapter ad = new CustomAdapter();
l.setAdapter(ad);
}
});
}
}
我的自定义适配器类
class CustomAdapter extends BaseAdapter {
@Override
public int getCount() {
return images.length;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup parent) {
view = getLayoutInflater().inflate(R.layout.custom_layout, null);
ImageView im = (ImageView) view.findViewById(R.id.cover);
TextView t1 = (TextView) view.findViewById(R.id.title);
TextView t2 = (TextView) view.findViewById(R.id.author);
im.setImageBitmap(images[i]);
t1.setText(names[i]);
t2.setText(authors[i]);
return view;
}
}
**My PostRequest method :**
public void postRequest(final String user_id) {
final String[] a = new String[1];
RequestQueue queue = Volley.newRequestQueue(LoansList.this);
String url = getBooksPhp;
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
a[0] = response;
try {
JSONObject json = new JSONObject(a[0]);
books = json.getJSONArray("books");
try {
// looping through All Products
for (int i = 0; i < books.length(); i++) {
JSONObject c = books.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put("Title", c.getString("Titolo"));
map.put("Author", c.getString("Autore"));
map.put("Cover", c.getString("Copertina"));
System.out.println("CIAO " + c.getString("Autore"));
// adding HashList to ArrayList
bookList.add(map);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
} catch (JSONException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("OH NO");
}
}) {
//adding parameters to the request
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("user_id", user_id);
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
我的PostRequest方法:
public void postRequest(String user_id) {
final String[] a = new String[1];
RequestQueue queue = Volley.newRequestQueue(LoansList.this);
String url = getBooksPhp;
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
a[0] = response;
try {
JSONObject json = new JSONObject(a[0]);
books = json.getJSONArray("books");
try {
// looping through All Products
for (int i = 0; i < books.length(); i++) {
JSONObject c = books.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put("Title", c.getString("Titolo"));
map.put("Author", c.getString("Autore"));
map.put("Cover", c.getString("Copertina"));
// adding HashList to ArrayList
bookList.add(map);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
} catch (JSONException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("OH NO");
}
}) {
//adding parameters to the request
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("user_id", user_id);
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
现在,问题是ProgressDialog没有显示。 它首先创建视图,然后完成我的请求。 现在,我知道AsyncTask没有阻塞,但我想要做的是:
当我开始活动时,会出现progressdialog,直到asynctask完成抓取数据 - &gt;我得到了json - &gt;我解析它 - &gt;我构建我的内容数组(封面图像,标题和作者) - &gt;我将数据传递给我的CustomAdapter,它为我制作了ListView。
那么,我该如何“同步”线程并控制我的程序流程呢?
谢谢!