错误:android.view.ViewRootImpl $ CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触及其视图

时间:2016-01-19 10:30:55

标签: android multithreading timertask textwatcher

当用户在他的请求中输入时,我从服务器获得结果。 最初我在输入的每个角色上发出请求。 现在,用户输入他的最后一个角色后,我已经延迟了500毫秒。然后我发出请求从服务器获取结果。 我在onSuccess()中的下一行中遇到了问题中所述的错误:

search_listview.setAdapter(searchAdaptor);

以下是我的代码:

@Override
public void afterTextChanged(Editable s) {
if(!s.equals("")&&s.length()!=0){
        TextView tv_emptyView = (TextView)findViewById(R.id.tv_emptyView);
        tv_emptyView.setVisibility(View.GONE);
        if(frndList!=null&&frndList.size()!=0)
        frndList.removeAll(frndList);
        if(searchAdaptor!=null){
            searchAdaptor.notifyDataSetChanged();
        }
        search_listview.setVisibility(View.VISIBLE);
        pageNumber=0;

    timer.cancel();
    timer = new Timer();
    timer.schedule(
            new TimerTask() {
                @Override
                public void run() {
                    getListbyName(++pageNumber);
                }
            },
            DELAY
    );
}else if(s.equals("")||s.length()==0){
        TextView tv_emptyView = (TextView)findViewById(R.id.tv_emptyView);
        tv_emptyView.setVisibility(View.VISIBLE);
        search_listview.setVisibility(View.GONE);
    }

}

private void getListbyName(int page) {
    GlobalSearchRequestHandler globalSearchRequest = new GlobalSearchRequestHandler(
            this, this, UserInfoSettings.INSTANCE.getUserId(),
            editTextSearch.getText().toString(), page + "", true,progressBar);
    globalSearchRequest.execute();
}
@Override
public void onSuccess(Object response) {

    if (response instanceof GlobalSearchBean) {
        GlobalSearchBean advSearchResultbean = (GlobalSearchBean) response;
        if (advSearchResultbean.getErrorCode().equalsIgnoreCase("000")) {
            frndList = advSearchResultbean.getUserList();
                if (frndList != null && frndList.size() > 0) {
                loading = true;
                if(searchAdaptor!=null&& pageNumber!=1){
                    searchAdaptor.updateFriendList(frndList);
                }else{
                    searchAdaptor = new SmartEntourageSearchAdaptor(this, AdvanceSearchScreenActivity.this, frndList, true);
                    search_listview.setAdapter(searchAdaptor);
                    searchAdaptor.notifyDataSetChanged();
                }
            } else{
                if (searchAdaptor != null && pageNumber != 1) {
                    loading = true;
                    searchAdaptor.updateFriendList(frndList);
                } else {
                    TextView tv_emptyView = (TextView) findViewById(R.id.tv_emptyView);
                    tv_emptyView.setVisibility(View.VISIBLE);
                    search_listview.setVisibility(View.GONE);
                }
            }
        }
    }
}

我确实通过了&尝试了stackoverflow上的答案,但没有工作。

修改 GlobalSearchRequestHandler:

public class GlobalSearchRequestHandler extends JsonHttpResponseHandler {

private Context mContext;
//private Dialog mDialog;
private View progressBar;
private String encodedRequest;
private HttpCommunicationListener mHandler;
private boolean mShowProgress;
private static final String contentType = "application/x-www-form-urlencoded";

public GlobalSearchRequestHandler(Context mContext,
        HttpCommunicationListener handler, String userId, String keyword,
        String pageNumber, boolean canShowProgress,View pb) {
    this.mContext = mContext;
    this.encodedRequest = encodedRequest(userId, keyword, pageNumber);
    this.mHandler = handler;
    this.mShowProgress = canShowProgress;
    this.progressBar= pb;
}

private String encodedRequest(String userId, String keyword,
        String pageNumber) {

    JSONObject genInfoObj = new JSONObject();
    JSONObject globalSearch = new JSONObject();

    globalSearch.put("userId", userId);
    globalSearch.put("keyword", MysnlUtils.replaceSpecialCharacterEncodeRequest(keyword));
    globalSearch.put("pageNumber", pageNumber);

    genInfoObj.put("globalSearch", globalSearch);
    genInfoObj.put(getString(R.string.genInfo), MysnlUtils.getGenInfo());

    return genInfoObj.toString();
}

private String getString(int id) {
    return MysnlApplication.mAppContext.getResources().getString(id);
}

public void execute() {
    try {
        encodedRequest = "xmlrequest=" + encodedRequest;
        Logger.e(encodedRequest);
        StringEntity entity = new StringEntity(encodedRequest);
        AsyncHttpClient client = new AsyncHttpClient();

        KeyStore trustStore = KeyStore.getInstance(KeyStore
                .getDefaultType());
        trustStore.load(null, null);
        MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        client.setSSLSocketFactory(sf);
        /*
         * final int DEFAULT_TIMEOUT = 20 * 1000;
         * client.setTimeout(DEFAULT_TIMEOUT);
         */

        client.post(MysnlApplication.mAppContext,
                getString(R.string.php_server_url), entity, contentType,
                this);
    } catch (Exception e) {
        Logger.e(e.getMessage());
        ErrorBean errorBean = new ErrorBean();
        errorBean.setErrorCode(AppConstant.BAD_REQUEST);
        errorBean.setErrorMsg(e.getMessage());
        mHandler.onFail(errorBean);
    }
}

@Override
public void onSuccess(org.json.JSONObject response) {
    Logger.e("onSuccess : "+response.toString());       

    GlobalSearchBean bean = null;
    try {
        org.json.JSONObject headJsonObject = (org.json.JSONObject) response.get("globalSearch");
        Gson gson = new Gson();
        bean = gson.fromJson(headJsonObject.toString(), GlobalSearchBean.class);
        if (bean != null) {
            mHandler.onSuccess(bean);
        }
        else{
            mHandler.onFail(bean);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

@Override
public void onFailure(Throwable error, String content) {
    Logger.e("onFailure : "+content.toString());
    ErrorBean errorBean=new ErrorBean();
    errorBean.setErrorCode(AppConstant.BAD_REQUEST);
    errorBean.setErrorMsg(content);
    mHandler.onFail(errorBean);
    try {
        progressBar.setVisibility(View.GONE);
        /*if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }*/
    } catch (Exception e) {
    }

    super.onFailure(error, content);
}

@Override
public void onStart() {
    try {
        if(mShowProgress){
            progressBar.setVisibility(View.VISIBLE);
            /*mDialog = MysnlUtils.getProgressDialog(mContext);
            mDialog.show();*/
        }
    } catch (Exception e) {
    }

    super.onStart();
}

@Override
public void onFinish() {
    try {
        progressBar.setVisibility(View.GONE);
        /*if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }*/
    } catch (Exception e) {
    }

    super.onFinish();
}

}

1 个答案:

答案 0 :(得分:1)

替换它:

timer.cancel();
timer = new Timer();
timer.schedule(
        new TimerTask() {
            @Override
            public void run() {
                getListbyName(++pageNumber);
            }
        },
        DELAY
);

有了这个:

search_listview.postDelayed(new Runnable() {
    @Override
    public void run() {
        getListbyName(++pageNumber);
    }
}, DELAY);