Java
1AsyncTaskClass task = new AsyncTaskClass(); 2task.execute(""); 3SharedPreferences.Editor editor = preferences.edit(); 4 editor.putInt("count",1); 5 editor.commit();
このような処理がMainActivityにあったとして、3行目以降をAsyncTaskクラスの処理が終わった後に実行したい場合はどのようにすればよいでしょうか。
Java
1public class AsyncTaskClass extends AsyncTask<String, String, String> { 2 3 @Override 4 protected String doInBackground (String... params) { 5 return ""; 6 } 7 8 @Override 9 protected void onPostExecute(String str) { 10 // ここ 11 } 12}
上記のコードのコメントがある部分に記載をすればよいと思うのですがここからMainActivityの処理を呼び出す方法がわかりません。
質問が複数になって申し訳ありませんが、以下のコードは正しいですか。特にContext(★)の部分が心配です。またほかに良い方法はありますでしょうか。
Java
1//MainActivity 2AsyncTaskClass task = new AsyncTaskClass(this); 3task.execute("");
Java
1public class AsyncTaskClass extends AsyncTask<String, String, String> { 2 3 Context context; //★ 4 5 public AsyncTaskClass(Context context) { 6 this.context = context; 7 } 8 9 @Override 10 protected String doInBackground (String... params) { 11 scanFile(); 12 return ""; 13 } 14 private void scanFile(String fileName){ 15 InputStream is = null; 16 BufferedReader br = null; 17 int times = 1; 18 try { 19 try { 20 is = context.getAssets().open(fileName+".txt"); //★ 21 br = new BufferedReader(new InputStreamReader(is)); 22 String str; 23 24 while ((str = br.readLine()) != null) { 25 //省略 26 } 27 } finally { 28 if (is != null) is.close(); 29 if (br != null) br.close(); 30 } 31 } catch (Exception e){ 32 } 33 } 34 35 @Override 36 protected void onPostExecute(String str) { 37 // UIスレッドに反映する処理 38 } 39}
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。