我正在尝试使用HTTP请求将ListView加载到我自己的Apache服务器上,该服务器输出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);
}
}
Media.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 + "]";
}
}
DownloadMediaList.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;
}
}
答案 0 :(得分:3)
在execute()
实施对象上调用AsyncTask
。
task.execute();
有关详细信息,请查看链接
http://developer.android.com/reference/android/os/AsyncTask.html
答案 1 :(得分:1)
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));
}
}).execute();
或
task.execute(); //at some part appropriate in your code.
答案 2 :(得分:0)
对onPreExecute
onPostExecute
和doInBackground
方法以及AsyncTask
new AsyncTask<Void, Void, Boolean>() {
Exception error;
@Override
protected void onPreExecute() {
Toast.makeText(MainActivity.this,
"Start...", Toast.LENGTH_SHORT)
.show();
setProgressBarIndeterminateVisibility(true);
}
@Override
protected Boolean doInBackground(Void... arg0) {
try {
Toast.makeText(MainActivity.this,
"Process in Background...", Toast.LENGTH_SHORT)
.show();
return true;
}
catch (Exception e)
{
Log.e(TAG, "Error: " + e.getMessage(), error);
error = e;
return false;
}
}
@Override
protected void onPostExecute(Boolean result) {
setProgressBarIndeterminateVisibility(false);
if (result) {
Toast.makeText(MainActivity.this, "End....",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, error.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}.execute();