AsyncTask的不doInBackground [英] AsyncTask doesn't doInBackground
问题描述
我试图加载使用对我自己的Apache服务器,它输出JSON HTTP请求一个ListView。问题是,当我插入断点,并尝试调试我的Android应用程序的doInBackground方法从来没有特效,我不认为它甚至达到我的服务器。该应用程序只是运行,而无需在ListView显示出来。 (是的,我知道,我编辑了我的RESTFunctions.java IP,我的实际服务器的IP是有我的code)。
MainActivity.java:
公共类MainActivity延伸活动{ @覆盖
保护无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.activity_main); DownloadMediaList任务=新DownloadMediaList(MainActivity.this,新的这种接口的(){
@覆盖
公共无效theMethod(ArrayList的<媒体和GT;的结果){
LV的ListView =(ListView控件)findViewById(R.id.media_list);
lv.setAdapter(新MediathequeListAdapter(MainActivity.this,结果));
}
}); } 公共接口这种接口的{
公共无效theMethod(ArrayList的<媒体和GT;结果); }}
Media.java
公共类媒体{ 私人字符串称号;
私人字符串覆盖;
私人字符串年;
私人字符串的长度;
私人字符串描述; 公共传媒(){ } 公共传媒(标题字符串,字符串覆盖,字符串描述){
this.title =称号;
this.cover =盖;
this.description =描述;
} 公共字符串的getTitle(){
返回称号;
} 公共字符串getCover(){
返回覆盖;
} 公共字符串得到年(){
返回年;
} 公共字符串的getLength(){
返回的长度;
} 公共字符串getDescription(){
返回描述;
} 公共无效的setTitle(字符串名称){
this.title =称号;
} 公共无效setCover(字符串盖){
this.cover =盖;
} 公共无效setYear(字符串年){
this.year =年;
} 公共无效SetLength函数(字符串长度){
this.length =长度;
} 公共无效setDescription(字符串描述){
this.description =描述;
} @覆盖
公共字符串的toString(){
回归[滴度=+标题+,jaquette =+盖+,ANNEE =+一年+,绵延=+长度+,说明=+说明+];
}
}
DownloadMediaList.java:
公共类DownloadMediaList扩展的AsyncTask<无效,无效的ArrayList<媒体与GT;> { ListView控件的ListView = NULL;
活动mainActivity = NULL; 上下文mainContext = NULL;
这种接口的mlistener; 公共DownloadMediaList(上下文为主,这种接口的监听器){
this.mainContext =为主;
mlistener =侦听器;
} //操作,我们做不同的线程。
@覆盖
保护的ArrayList<媒体和GT; doInBackground(虚空...... PARAMS){
//设置一个ArrayList来存储媒体。
ArrayList的<媒体和GT; medialist中=新的ArrayList<媒体及GT;(); //调用REST API,并在一个JSONObject获得请求的信息和媒体名单。
RESTFunctions restRequest =新RESTFunctions();
JSONObject的jsonMedia = restRequest.getMediaList(); //尝试捕捉捕捉JSON异常。
尝试{
//存储介质列表转换成JSONArray。
JSONArray mediaArray = jsonMedia.getJSONArray(传媒); //创建的媒体实例的每一个媒体后存储。
媒体媒体=新媒体(); //循环遍历JSONArray和每个媒体添加到ArrayList。
的for(int i = 0; I< mediaArray.length();我++){
媒体=新媒体();
JSONObject的singleMedia = mediaArray.getJSONObject(I)
media.setTitle(singleMedia.getString(滴度));
media.setYear(singleMedia.getString(ANNEE));
media.setLength(singleMedia.getString(绵延));
mediaList.add(媒体);
}
}赶上(JSONException E){
// TODO自动生成catch块
e.printStackTrace();
} //返回ArrayList中。
返回medialist中;
} //我们的用户界面操作。同步使用用户界面。
@覆盖
保护无效onPostExecute(ArrayList的<媒体和GT; medialist中){
如果(mlistener!= NULL)
{
mlistener.theMethod(medialist中);
}
}
}
JSONParser.java(这一项,我什么地方剔去互联网):
公共类JSONParser { 静态InputStream为= NULL;
静态的JSONObject jObj = NULL;
静态JSON字符串=; //构造
公共JSONParser(){ } 公众的JSONObject getJSONFromUrl(字符串URL,列表和LT;&的NameValuePair GT; PARAMS){ //使HTTP请求
尝试{
// defaultHttpClient
DefaultHttpClient的HttpClient =新DefaultHttpClient();
HttpPost httpPost =新HttpPost(URL);
httpPost.setEntity(新UrlEn codedFormEntity(PARAMS)); HTT presponse HTT presponse = httpClient.execute(httpPost);
HttpEntity httpEntity = HTT presponse.getEntity();
是= httpEntity.getContent(); }赶上(UnsupportedEncodingException五){
e.printStackTrace();
}赶上(ClientProtocolException E){
e.printStackTrace();
}赶上(IOException异常五){
e.printStackTrace();
} 尝试{
读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
是,ISO-8859-1),8);
StringBuilder的SB =新的StringBuilder();
串线= NULL;
而((行= reader.readLine())!= NULL){
sb.append(线+的n);
}
is.close();
JSON = sb.toString();
Log.e(JSON,JSON);
}赶上(例外五){
Log.e(缓冲区错误,错误转换结果+ e.toString());
} //尝试分析字符串到一个JSON对象
尝试{
jObj =新的JSONObject(JSON);
}赶上(JSONException E){
Log.e(JSON解析器,错误分析数据+ e.toString());
} //返回JSON字符串
返回jObj; }
}
RESTFunctions.java:
公共类RESTFunctions {
私人JSONParser jsonParser; 私有静态字符串URL =HTTP:// *我的服务器IP HERE * / mediatheque_api 公共RESTFunctions(){
jsonParser =新JSONParser();
} //获取包含ID,名称,年份长,和所有专辑封面的JSON对象。
公众的JSONObject getMediaList(){
清单<&的NameValuePair GT; PARAMS =新的ArrayList<&的NameValuePair GT;(); //我们添加请求名称来从API服务的所有媒体
params.add(新BasicNameValuePair(REQ,listemedias)); //我们从API服务JSON对象
JSONObject的JSON = jsonParser.getJSONFromUrl(URL,则params); 返回JSON;
}
}
MediathequeListAdapter(这是BaseAdapter的扩展):
公共类MediathequeListAdapter延伸BaseAdapter { 私人的ArrayList的ListData;
私人LayoutInflater layoutInflater; 公共MediathequeListAdapter(上下文的背景下,ArrayList中的ListData){
this.listData =的ListData;
layoutInflater = LayoutInflater.from(上下文);
} @覆盖
公众诠释的getCount(){
返回listData.size();
} @覆盖
公共对象的getItem(INT位置){
返回listData.get(位置);
} @覆盖
众长getItemId(INT位置){
返回的位置;
} 公共查看getView(INT位置,查看convertView,父母的ViewGroup){
ViewHolder持有人;
如果(convertView == NULL){
convertView = layoutInflater.inflate(R.layout.mediatheque_listview,NULL);
持有人=新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(保持器);
}其他{
支架=(ViewHolder)convertView.getTag();
} 媒体媒体=(媒体)listData.get(位置);
holder.title.setText(media.getTitle());
holder.year.setText(media.getYear());
holder.length.setText(media.getLength()); 返回convertView;
} 静态类ViewHolder {
TextView的称号;
TextView的一年;
TextView的长度;
}
}
呼叫的execute()
在的AsyncTask
实施对象。
task.execute();
有关更多信息检查链接
http://developer.android.com/reference/android/os/ AsyncTask.html
I'm trying to load a ListView using an HTTP request towards my own Apache server, which outputs JSON. The issue is, my Android app's doInBackground method never procs when I insert breakpoints and try to debug, I don't think it even reaches my server. The application just runs without the ListView showing up. (Yes, I am aware that I edited out my IP in RESTFunctions.java, my actual server IP is there in my code).
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 (This one, I picked off the internet somewhere):
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 (This is an extension of the 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;
}
}
Call execute()
on your AsyncTask
implementation object.
task.execute();
For more info check the link
http://developer.android.com/reference/android/os/AsyncTask.html
这篇关于AsyncTask的不doInBackground的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!