我收到以下错误:
java.lang.IllegalStateException: Cannot execute task: the task is already running.
这是片段:
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.app.Fragment;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by anameme on 10/24/2015.
*/
public class LatestJokesFrag extends Fragment{
ListView list;
public LatestJokesFrag() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
downloadImage();
}
public void downloadImage() {
// OkHttpHandler handler = new OkHttpHandler();
OkHttpHandler handler = new OkHttpHandler(getActivity(),
new OkHttpHandler.MyInterface() {
@Override
public void myMethod(ArrayList result) {
Toast.makeText(getActivity(), "Connection Succesful",
Toast.LENGTH_LONG).show();
GridViewAdapter adapter = new GridViewAdapter(getActivity(), R.layout.grid_item_layout, result);
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
}
});
handler.execute();
String image = null;
try {
image = handler.execute().get();
Log.d("e", "hhhh handler");
System.out.print(image);
//if (image != null && image.length > 0){
// Log.isLoggable("e",image.length);
//Log.d("e", "ddddddd entered the try");
// Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
// imageView.setImageBitmap(bitmap);
// txtBytes.setText("Total bytes downloaded: " + image.length);
} catch (Exception e) {
Log.d("e", "rrrrrr error");
e.printStackTrace();
// txtBytes.setText("Hmm sorry, something went wrong!");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View v = inflater.inflate(R.layout.latestjokesfrag, container, false);
list = (ListView) v.findViewById(R.id.ListView);
return inflater.inflate(R.layout.latestjokesfrag, container, false);
}
}
这是ohttphandler
public class OkHttpHandler extends AsyncTask<String, Void, String> {
private Context mContext;
private MyInterface mListener;
public OkHttpHandler (Context context, MyInterface mListener){
mContext = context;
this.mListener = mListener;
}
public interface MyInterface {
public void myMethod(ArrayList result);
}
private final String Fetch_URL = "http://justedhak.comlu.com/get-data.php";
ArrayList<Listitem> Listitem;
int resulta;
OkHttpClient httpClient = new OkHttpClient();
ListView list;
String myJSON;
JSONArray peoples = null;
InputStream inputStream = null;
@Override
protected String doInBackground(String... params) {
Log.d("e", "dddddddddd");
Log.d("e", Fetch_URL);
// list = (ListView) findViewById(R.id.ListView);
Request.Builder builder = new Request.Builder();
builder.url(Fetch_URL);
Request request = builder.build();
String result = null;
try {
// int statusCode = response.getStatusLine().getStatusCode();
// int statusCode =200;
// HttpEntity entity = response.body().byteStream();
// if (statusCode == 200) {
Response response = httpClient.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
inputStream = response.body().byteStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
resulta = 1; //"Success
Log.d("e", "response.");
// return response.body().bytes();
} catch (Exception e) {
Log.d("e", "r2r2 error");
e.printStackTrace(); }
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
@Override
protected void onPostExecute(String result){
if( resulta ==1){
myJSON=result;
Log.e("result",result);
showList();
}
else{
Log.e("d","zzzzzzzz");
}
}
protected void showList(){
try {
Log.e("d","jjjjjjjjjj");
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray("result");
Listitem = new ArrayList<Listitem>();
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String id = c.getString("id");
String url = c.getString("path");
Listitem.add(new Listitem(id,url));
Log.e("d", "ppppp");
System.out.println(Listitem);
}
if (mListener != null)
mListener.myMethod(Listitem);
// GridViewAdapter adapter = new GridViewAdapter(mContext, R.layout.grid_item_layout, Listitem);
// gridView.setAdapter(gridAdapter);
// adapter.notifyDataSetChanged();
// list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
这是完整的跟踪日志:
java.lang.IllegalStateException: Cannot execute task: the task is already running.
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:576)
at android.os.AsyncTask.execute(AsyncTask.java:535)
10-24 10:00:14.204 1395-1416/com.justedhak.www.i D/e﹕ dddddddddd
10-24 10:00:14.204 1395-1416/com.justedhak.www.i D/e﹕ http://justedhak.comlu.com/get-data.php
at com.justedhak.www.i.LatestJokesFrag.downloadImage(LatestJokesFrag.java:54)
at com.justedhak.www.i.LatestJokesFrag.onCreate(LatestJokesFrag.java:29)
at android.support.v4.app.Fragment.performCreate(Fragment.java:1939)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:988)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1207)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1572)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:545)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1106)
at android.support.v4.view.ViewPager.populate(ViewPager.java:952)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1474)
at android.view.View.measure(View.java:18557)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:607)
at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:674)
at android.view.View.measure(View.java:18557)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:464)
at android.view.View.measure(View.java:18557)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:124)
at android.view.View.measure(View.java:18557)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1435)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:721)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:612)
at android.view.View.measure(View.java:18557)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at android.view.View.measure(View.java:18557)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1435)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:721)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:612)
at android.view.View.measure(View.java:18557)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2888)
at android.view.View.measure(View.java:18557)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2250)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1306)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1548)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1191)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6645)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:777)
at android.view.Choreographer.doCallbacks(Choreographer.java:590)
at android.view.Choreographer.doFrame(Choreographer.java:560)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:763)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
答案 0 :(得分:3)
你调用相同的handler.execute(),根据docs,任务只能执行一次。
如果要再次执行任务,则必须初始化新的异步任务 请看方法
downloadImage()
你启动
OkHttpHandler handler = new OkHttpHandler(getActivity()..
并致电
handler.execute();
然后在try块
中再次执行此操作try{
///
image = handler.execute().get();
}
会导致帖子中描述的错误
您应该再次初始化一个新任务,如下所示
try{
image = new OkHttpHandler(getActivity()...).execute().get();
}
然后它会起作用