2013-08-12 4 views
1

Я просто хочу спросить, можно ли использовать мой тост в onPostExecute моей Asyntask в android. Если да, то как? Я попытался поместить его в onPostExecute, но у меня много красных линий. Вот мой код для моего подгоняют тост:Настроить тост в asyntask в android

Typeface tfR= Typeface.createFromAsset(getAssets(), "Gothic_Regular.TTF"); 
    LayoutInflater inflater = getLayoutInflater(); 
    View layouttoast = inflater.inflate(R.layout.toast_bg, (ViewGroup)findViewById(R.id.toastAttribute)); 
    TextView msg = ((TextView) layouttoast.findViewById(R.id.txt_toast)); 
    msg.setTypeface(tfR); 
    msg.setText(toast_msg); 
    msg.setTextSize(TypedValue.COMPLEX_UNIT_PX,16); 
    Toast mytoast = new Toast(getBaseContext()); 
    mytoast.setView(layouttoast); 
    mytoast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); 
    mytoast.setDuration(Toast.LENGTH_SHORT); 
    mytoast.show(); 

Тогда я хочу поставить его здесь:

public class DoPost extends AsyncTask<String, Void, Boolean> 
{ 
    Exception exception = null; 
    Context mContext = null; 

     . . . . . 


public DoPost(Context context, String username, String password, 
     String reportcode, String remarks, String date, String province, 
     String infotype, String competitor, ArrayList<String> brands, 
     ArrayList<String> segments) 
{ 
    mContext   = context; 

      . . . . 

    databaseHandler = new DatabaseHandler(context); 
    if (databaseHandler != null) 
    { 
     databaseHandler.close(); 
     databaseHandler.createDB(); 
    } 
} 

protected void onPreExecute() 
{ 
    progressDialog = new ProgressDialog(mContext); 
    progressDialog.setMessage("Uploading attachment details...."); 
    progressDialog.show(); 
    progressDialog.setCancelable(false); 
} 

@Override 
protected Boolean doInBackground(String... arg0) 
{ 

    try { 
      JSONObject jObject    = new JSONObject(); 

      Log.d("DoPost Constants.FILE_URI", Constants.FILE_URI.toString()); 
      Log.d("DoPost create SELECTEDFILE URI", SelectedFiles.listFileUri.toString()); 
      Log.d("DoPost create SELECTEDFILE FILENAME", SelectedFiles.listFileName.toString()); 

     // String filename     = "Chapt-19.pdf"; 
      String filename     = ""; 
      try { 

       JSONArray jArraySubrands   = new JSONArray(); 
       JSONArray jArrayConsumerSegments = new JSONArray(); 
       JSONArray jArrayReportUpload = new JSONArray(); 

       for (int i = 0; i < Constants.SHARED_PREFERENCES_SUBBRANDS.size(); i++) 
       { 
        JSONObject brand = new JSONObject(); 
        brand.put("Id", _brands.get(i)); 
        jArraySubrands.put(brand); 
       } 

       for (int j = 0; j < Constants.SHARED_PREFERENCES_SEGMENTS.size(); j++) 
       { 
        JSONObject consumerSegments = new JSONObject(); 
        consumerSegments.put("Id", _segments.get(j)); 
        jArrayConsumerSegments.put(consumerSegments); 
       } 

       for (int i = 0; i < Constants.ARRAYLIST_FILENAME.size(); i++) 
       { 
        JSONObject jObjectReportUpload = new JSONObject(); 
        filename = Constants.ARRAYLIST_FILENAME.get(i); 
        jObjectReportUpload.put("ReportUploadId", 0); 
        jObjectReportUpload.put("Filename", filename); 
        jObjectReportUpload.put("TempFilename", filename); 
        jObjectReportUpload.put("Description", "Image Testing"); 
        jObjectReportUpload.put("ReportUploadTypeId", 1); 
        jObjectReportUpload.put("ReportId", 0); 
        jArrayReportUpload.put(jObjectReportUpload); 

        Log.d("filename: ", filename); 

       } 

       jObject.put("ReportId", 0); 
       jObject.put("ReportCode", _code); 
       jObject.put("Title", "Mobile Developer"); 
       jObject.put("Remarks", _remarks); 
       jObject.put("DateObserved", _date); 
       jObject.put("ProvinceId", _province); 
       jObject.put("InformationTypeId", _infotype); 
       jObject.put("ReportTypeId", 1); 
       jObject.put("IsCompetitor", _competitor); 
       jObject.put("SubBrands", jArraySubrands); 
       jObject.put("ConsumerSegments", jArrayConsumerSegments); 
       jObject.put("ReportUploads", jArrayReportUpload); 

      } catch (Exception e) 
      { 
       e.printStackTrace(); 
      } 

      ResponseHandler<String> resonseHandler = new BasicResponseHandler(); 
      HttpParams httpParameters    = new BasicHttpParams(); 
      HttpConnectionParams.setConnectionTimeout(httpParameters, 15000); 
      HttpConnectionParams.setSoTimeout(httpParameters, 15000); 
      HttpPost httpPost      = new HttpPost("http://phsjghhghghulchghg4.hgh.com:1214/api/reports"); 
      HttpClient httpclient     = new DefaultHttpClient(httpParameters); 
      httpPost.addHeader("Authorization","Basic "+ Base64.encodeToString((_username + ":" + _password).getBytes(),Base64.NO_WRAP)); 
      httpPost.setHeader("Content-Type", "application/json"); 
      httpPost.setHeader("Accept", "application/json"); 
      httpPost.setEntity(new ByteArrayEntity(jObject.toString().getBytes(HTTP.UTF_8))); 

      String response = httpclient.execute(httpPost).toString(); 
      Log.i("response: ", response); 
      Log.i("JSON", jObject.toString()); 

     } catch (ClientProtocolException e) 
      { 
       e.printStackTrace(); 
       Log.e("Header","ClientProtocolException in callWebService(). "+ e.getMessage()); 
       error = String.valueOf(e); 
       return false; 
      } 
    catch (IOException e) 
     { 
      e.printStackTrace(); 
      Log.e("Header","IOException in callWebService(). " + e.getMessage()); 
      error = String.valueOf(e); 
      return false; 
     } 
    return true; 
} 

protected void onPostExecute(Boolean valid) 
{ 
    progressDialog.dismiss(); 

    Log.d("RESULT", String.valueOf(valid)); 

    if(valid){ 
     //Customzize toast here. 
     new DoPost(mContext,_username, _password, _code, _remarks, _date, _province, _infotype,_competitor,_brands, _segments).execute(); 

    }else{ 
     //Customzize toast here. 

    } 
} 
+0

много красных линий? журналы ошибок? – yushulx

+0

redlines, потому что getAssets, getLayoutInflater, findViewById, getBaseContext не работает над моим классом asyntask и просит создать такой метод, как – lolliloop

+0

, как вы инициализировали свой mContext? – yushulx

ответ

0

Я думаю, что я узнал, что происходит. Ваша область действия неверна. в настоящее время ваш код работает в AsyncTask, а не в действии! Вот почему вы не можете использовать getAssets, getLayoutInflater, findViewById, getBaseContext. Создайте свою AsyncTask в своей xxxActivity. И используйте свой xxxActivity.this.findViewById и т. Д.

+0

Да. из моей активности я вызываю этот класс асинтезы – lolliloop

+0

try 'LayoutInflater inflater = mContext.getLayoutInflater();' или «Развертывание макета флайтера» = xxxActivity.this.getLayoutInflater(); ' – yushulx

Смежные вопросы