我正在尝试使用 HTTP 请求向我自己的 Apache 服务器加载 ListView,该服务器输出 JSON。问题是,当我插入断点并尝试调试时,我的 Android 应用程序的 doInBackground 方法永远不会触发,我认为它甚至没有到达我的服务器。该应用程序只是在没有显示 ListView 的情况下运行。(是的,我知道我在 RESTFunctions.java 中编辑了我的 IP,我的实际服务器 IP 在我的代码中)。
MainActivity.java:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadMediaList task = new DownloadMediaList (MainActivity.this,new TheInterface() {
@Override
public void theMethod(ArrayList<Media> result) {
ListView lv = (ListView) findViewById(R.id.media_list);
lv.setAdapter(new MediathequeListAdapter(MainActivity.this, result));
}
});
}
public interface TheInterface {
public void theMethod(ArrayList<Media> result);
}
}
媒体.java
public class Media {
private String title;
private String cover;
private String year;
private String length;
private String description;
public Media(){
}
public Media(String title, String cover, String description){
this.title = title;
this.cover = cover;
this.description = description;
}
public String getTitle(){
return title;
}
public String getCover(){
return cover;
}
public String getYear(){
return year;
}
public String getLength(){
return length;
}
public String getDescription(){
return description;
}
public void setTitle(String title){
this.title = title;
}
public void setCover(String cover){
this.cover = cover;
}
public void setYear(String year){
this.year = year;
}
public void setLength(String length){
this.length = length;
}
public void setDescription(String description){
this.description = description;
}
@Override
public String toString(){
return "[Titre=" + title + ", jaquette=" + cover + ", annee=" + year + ", duree=" + length + ", description=" + description + "]";
}
}
下载MediaList.java:
public class DownloadMediaList extends AsyncTask<Void, Void, ArrayList<Media>> {
ListView listView = null;
Activity mainActivity = null;
Context mainContext = null;
TheInterface mlistener;
public DownloadMediaList(Context main,TheInterface listener){
this.mainContext = main;
mlistener = listener;
}
// Operations that we do on a different thread.
@Override
protected ArrayList<Media> doInBackground(Void... params){
// Set an ArrayList to store the medias.
ArrayList<Media> mediaList = new ArrayList<Media>();
// Call the REST API and get the request info and media list in a JSONObject.
RESTFunctions restRequest = new RESTFunctions();
JSONObject jsonMedia = restRequest.getMediaList();
// Try catch to catch JSON exceptions.
try {
// Store the media list into a JSONArray.
JSONArray mediaArray = jsonMedia.getJSONArray("media");
// Create an instance of media to store every single media later.
Media media = new Media();
// Loop through the JSONArray and add each media to the ArrayList.
for (int i=0; i<mediaArray.length();i++){
media = new Media();
JSONObject singleMedia = mediaArray.getJSONObject(i);
media.setTitle(singleMedia.getString("titre"));
media.setYear(singleMedia.getString("annee"));
media.setLength(singleMedia.getString("duree"));
mediaList.add(media);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Return the ArrayList.
return mediaList;
}
// Operations we do on the User Interface. Synced with the User Interface.
@Override
protected void onPostExecute(ArrayList<Media> mediaList){
if (mlistener != null)
{
mlistener.theMethod(mediaList);
}
}
}
JSONParser.java(这个,我在某处从互联网上摘下来的):
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl (String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
RESTFunctions.java:
public class RESTFunctions {
private JSONParser jsonParser;
private static String url = "http://*MY SERVER IP HERE*/mediatheque_api";
public RESTFunctions() {
jsonParser = new JSONParser();
}
// Gets a JSON Object containing the id, title, year, length, and cover of all albums.
public JSONObject getMediaList(){
List<NameValuePair> params = new ArrayList<NameValuePair>();
// We add the request name to get all medias from the API service
params.add(new BasicNameValuePair("req","listemedias"));
// We get the JSON Object from the API service
JSONObject json = jsonParser.getJSONFromUrl(url, params);
return json;
}
}
MediathequeListAdapter(这是 BaseAdapter 的扩展):
public class MediathequeListAdapter extends BaseAdapter {
private ArrayList listData;
private LayoutInflater layoutInflater;
public MediathequeListAdapter(Context context, ArrayList listData){
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
}
@Override
public int getCount(){
return listData.size();
}
@Override
public Object getItem(int position){
return listData.get(position);
}
@Override
public long getItemId(int position){
return position;
}
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder;
if (convertView == null){
convertView = layoutInflater.inflate(R.layout.mediatheque_listview, null);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.year = (TextView) convertView.findViewById(R.id.year);
holder.length = (TextView) convertView.findViewById(R.id.length);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Media media = (Media) listData.get(position);
holder.title.setText(media.getTitle());
holder.year.setText(media.getYear());
holder.length.setText(media.getLength());
return convertView;
}
static class ViewHolder {
TextView title;
TextView year;
TextView length;
}
}