0

下面是我的完整代码,如果我不使用 public class getDataTask extends AsyncTask<Void, Void, Void>{ }类在 else 语句上显示文本消息但现在我想使用进度条直到服务器不加载问题是如果服务器返回数据然后代码工作正常如果服务器不返回数据 else 语句不起作用显示 toast 消息代码意外停止我该怎么办?

     public class SecondStep extends Activity {

ListView listMainMenu;
String SelectMenuAPI;
String SelectMenuAPI2;
String SearchSchoolurl;
String status;
String message;
ProgressBar prgLoading;
TextView txtAlert;

String param1;
String Menu_name;
String School_name;
secondscreenadapter mma;
TextView schoolname;

TextView textview1;
int IOConnect = 0;

static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
String URL, URL2, URL3, URL4;
String id;
String title;
String tmpString, finaldate, enddate;
String startdate;
String startdate2;
String val1, val2, val3, val4;
String mode;
String s2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.secondstep);
    prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
    txtAlert = (TextView) findViewById(R.id.txtAlert);

    s2 = "search";
    mode = HomeMenu.mode;
    if (mode.equals(s2.toString())) {

        Bundle bundle = this.getIntent().getExtras();
        School_name = bundle.getString("Serachvalue");
    } else {
        Bundle bundle = this.getIntent().getExtras();
        School_name = bundle.getString("School_name");
    }

    ImageView options = (ImageView) findViewById(R.id.options2);

    options.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent iMenuList = new Intent(SecondStep.this,
                    LinkButtons.class);
            startActivity(iMenuList);
        }
    });

    ImageView btnback = (ImageView) findViewById(R.id.btnback);

    ImageView logoimage = (ImageView) findViewById(R.id.bitmap);

    logoimage.setScaleType(ScaleType.FIT_CENTER);

    textview1 = (TextView) findViewById(R.id.textview1);
    listMainMenu = (ListView) findViewById(R.id.listMainMenu2);

    mma = new secondscreenadapter(this);
    new getDataTask().execute();

    // listMainMenu.setAdapter(mma);

    textview1
            .setText("If your school is not available in the list,.");

    listMainMenu.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1,
                int position, long arg3) {
            // TODO Auto-generated method stub
    Intent iMenuList = new Intent(SecondStep.this,MealGroups.class);

    iMenuList.putExtra("category_name",  Category_name.get(position));

            iMenuList.putExtra("id", val1);
            iMenuList.putExtra("title", val2);
            iMenuList.putExtra("startdate", val3);
            iMenuList.putExtra("enddate", val4);

            startActivity(iMenuList);

        }
    });

    btnback.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });

    // parseJSONData();
}

void clearData() {
    Category_ID.clear();
    Category_name.clear();

}

public class getDataTask extends AsyncTask<Void, Void, Void> {

    getDataTask() {
        if (!prgLoading.isShown()) {
            prgLoading.setVisibility(0);
            txtAlert.setVisibility(8);

            // count=1;
        }
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // TODO Auto-generated method stub
        parseJSONData();
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        prgLoading.setVisibility(8);

        if ((Category_ID.size() > 0) || IOConnect == 0) {
            listMainMenu.setVisibility(0);
            listMainMenu.setAdapter(mma);
        } else {
            txtAlert.setVisibility(0);
        }
    }
}

public void parseJSONData() {

    mode = HomeMenu.mode;
    if (mode.equals(s2.toString())) {

        SelectMenuAPI = Utils.SearchSchool + School_name;

        clearData();
        URL = SelectMenuAPI;
        URL2 = URL.replace(" ", "%20");

    } else {

        SelectMenuAPI = Utils.Schoolname + School_name;
        clearData();
        URL = SelectMenuAPI;
        URL2 = URL.replace(" ", "%20");
    }

    SelectMenuAPI2 = Utils.getSchedule;

    clearData();
    URL3 = SelectMenuAPI2;
    URL4 = URL3.replace(" ", "%20");

    try {

        HttpClient client = new DefaultHttpClient();
        HttpConnectionParams
                .setConnectionTimeout(client.getParams(), 15000);
        HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
        HttpUriRequest request = new HttpGet(URL2);
        HttpResponse response = client.execute(request);
        InputStream atomInputStream = response.getEntity().getContent();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                atomInputStream));

        String line;
        String str = "";
        while ((line = in.readLine()) != null) {
            str += line;
        }

        HttpClient client2 = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(client2.getParams(),
                15000);
        HttpConnectionParams.setSoTimeout(client2.getParams(), 15000);
        HttpUriRequest request2 = new HttpGet(URL4);
        HttpResponse response2 = client2.execute(request2);
        InputStream atomInputStream2 = response2.getEntity().getContent();
        BufferedReader in2 = new BufferedReader(new InputStreamReader(
                atomInputStream2));

        String line2;
        String str2 = "";
        while ((line2 = in2.readLine()) != null) {
            str2 += line2;
        }

        JSONObject json2 = new JSONObject(str);

        status = json2.getString("status");
        if (status.equals("1")) {

            JSONArray school = json2.getJSONArray("data");

            for (int i = 0; i < school.length(); i++) {
                JSONObject object = school.getJSONObject(i);

                Category_ID.add(Long.parseLong(object
                        .getString("school_id")));
                Category_name.add(object.getString("name"));

            }

        }

        else {

            mode = HomeMenu.mode;
            if (mode.equals(s2.toString())) {
                textview1
                        .setText("No school found,.");
            } else {
                textview1
                        .setText("No school found in "
                                + School_name
                                + ",.");
            }

        }

        JSONObject json3 = new JSONObject(str2);
        // message = json2.getString("message");
        status = json3.getString("status");
        if (status.equals("1")) {

            JSONArray school = json3.getJSONArray("data");

            for (int k = 0; k < school.length(); k++) {
                JSONObject jb = (JSONObject) school.getJSONObject(k);
                id = jb.getString("schedule_id");
                title = jb.getString("title");

                startdate = jb.getString("start_date");
                tmpString = startdate.replace(" 00:00:00", "");
                finaldate = tmpString.replace("-", "/");
                enddate = jb.getString("end_date");

            }

            val1 = id;
            val2 = title;
            val3 = finaldate;
            val4 = enddate;

        }

        else {

            JSONArray school1 = json3.getJSONArray("data");
            for (int i = 0; i < school1.length(); i++) {
                JSONObject object = school1.getJSONObject(i);

                Category_ID.add((long) i);
                Category_name.add(object.getString("name"));

            }

        }

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        IOConnect = 1;
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

 }

我的 Logcat 是:

        AndroidRuntime(574): FATAL EXCEPTION: AsyncTask #4
   AndroidRuntime(574): java.lang.RuntimeException: An error occured while executing  
  doInBackground()

 AndroidRuntime(574):   at android.os.AsyncTask$3.done(AsyncTask.java:200)
  AndroidRuntime(574):  at   
 java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
  AndroidRuntime(574):  at 
  java.util.concurrent.FutureTask.setException(FutureTask.java:124)
 AndroidRuntime(574):   at 
java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
 AndroidRuntime(574): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
 AndroidRuntime(574):at    
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
AndroidRuntime(574):    at   
 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
    AndroidRuntime(574):    at java.lang.Thread.run(Thread.java:1096)
 AndroidRuntime(574): Caused by: android.view.ViewRoot$CalledFromWrongThreadException:  
  Only     the original thread that created a view hierarchy can touch its views.
  AndroidRuntime(574): at android.view.ViewRoot.checkThread(ViewRoot.java:2802)
 AndroidRuntime(574):at android.view.ViewRoot.requestLayout(ViewRoot.java:594)
 0AndroidRuntime(574):at android.view.View.requestLayout(View.java:8125)
  AndroidRuntime(574):at android.view.View.requestLayout(View.java:8125)
  AndroidRuntime(574):at android.view.View.requestLayout(View.java:8125)
   AndroidRuntime(574):at android.view.View.requestLayout(View.java:8125)
  AndroidRuntime(574):at android.view.View.requestLayout(View.java:8125)
  AndroidRuntime(574):at android.view.View.requestLayout(View.java:8125)
  0AndroidRuntime(574):at android.widget.TextView.checkForRelayout(TextView.java:5378)
 AndroidRuntime(574):at android.widget.TextView.setText(TextView.java:2688)
 AndroidRuntime(574):at android.widget.TextView.setText(TextView.java:2556)
 AndroidRuntime(574):at android.widget.TextView.setText(TextView.java:2531)
 AndroidRuntime(574):at com.schoollunchapp.SecondStep.parseJSONData(SecondStep.java:281)
AndroidRuntime(574):at    
  com.schoollunchapp.SecondStep$getDataTask.doInBackground(SecondStep.java:177)
  AndroidRuntime(574):  at    
  com.schoollunchapp.SecondStep$getDataTask.doInBackground(SecondStep.java:1)
  AndroidRuntime(574):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
    AndroidRuntime(574):    at     
  java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
4

3 回答 3

0

您正在从不可能的后台线程更新 ui。

textview1.setText("No school found");

您需要在 ui 线程上更新 ui。在里面做onPostExecute

返回后台计算的结果doInbackground。计算的结果doInbackground是一个参数onPostExecute。所以根据结果更新 ui 中的onPostExecute.

您也可以使用runOnUiThreadwhich 是活动类的方法。

如果您的 asynctask 不是您的活动的内部类,您可以使用接口

无法将 AsyncTask 的响应发布到 MainActivity

于 2013-09-17T06:57:41.540 回答
0

你必须runOnUiThead()在你的工作线程中使用如下:

mode = HomeMenu.mode;

runOnUiThread(new Runnable() 
{
    public void run() 
    {
        if (mode.equals(s2.toString())) 
        {
            textview1.setText("No school found,.");
        } 
        else 
        {
            textview1.setText("No school found in " + School_name + ",.");
        }           
    }
});
于 2013-09-17T06:58:44.063 回答
-1

您正在尝试更新不允许直接更新UI part in doInBackground()的内容AsyncTask

parseJSONData()检查从里面调用的Following doInBackground()

 if (mode.equals(s2.toString())) {
        textview1.setText("No school found,.");
    } else {
        textview1.setText("No school found in "+ School_name+ ",.");
    }

如果你要更新UI part做同样onPostExecute()的事情AsyncTask

于 2013-09-17T06:57:09.833 回答