グリッドビューから画像を選択するアクティビティがあり、画像を保存できます。すべてのコードに非同期タスクを使用しています。 AsyncTaskをいくつかのクラスから分離しました。自分のアクティビティからそれらを呼び出すにはどうすればよいですか?文字列をAsyncTaskに戻すにはどうすればよいですか。
SingleImageView.class
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save_image:
new SaveImageTask().execute(image_url,context); //<-- The method execute(String...) in the type AsyncTask<String,String,String> is not applicable for the arguments (String, Context)
return true;
default:
return false;
}
SaveImageTask.class
public class SaveImageTask extends AsyncTask<String, String, String>
{
private Context context;
private ProgressDialog pDialog;
String image_url;
URL myFileUrl = null;
Bitmap bmImg = null;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(context); //<<-- Couldnt Recognise
pDialog.setMessage("Downloading Image ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
try {
myFileUrl = new URL(image_url);
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
catch (IOException e)
{
e.printStackTrace();
}
try {
String path = myFileUrl.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File (filepath.getAbsolutePath() + "/Wallpaper/");
dir.mkdirs();
String fileName = idStr;
File file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String args) {
// TODO Auto-generated method stub
pDialog.dismiss();
}
}
SaveImageTask
の新しいインスタンスを作成し、そのexecute
メソッドを呼び出して、String引数を渡します(execute
は可変引数を取ります)。
new SaveImageTask().execute("foo", "bar");
編集
AsyncTask
はContext
を使用するため、コンストラクターを介して渡す必要があります。
public class SaveImageTask extends AsyncTask<String, String, String>
{
private Context context;
private ProgressDialog pDialog;
String image_url;
URL myFileUrl = null;
Bitmap bmImg = null;
public SaveImageTask(Context context) {
this.context = context;
}
...
}
次に、次のようにAsyncTask
からActivity
を呼び出します。
new SaveImageTask(this).execute("foo", "bar");
private PopupWindow popupWindow;
// this function will be on MainActivity class
findViewById(R.id.main_page_layout).post(new Runnable() {
public void run() {
new SendJsonValue ().execute();
}
});
public class SendJsonValue extends AsyncTask<String, Void, String>{
@Override
protected void onPreExecute(){
/*code for pop window initialization begins here*/
LayoutInflater layoutInflater =(LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
final View popupView = layoutInflater.inflate(R.layout.popup_window, null);
popupWindow = new PopupWindow(
popupView,
LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT); //creating popup
popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
}
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
//loadingMore = true;//parameter to take control on load more
HttpClient httpclient = new DefaultHttpClient();
final HttpParams httpParams = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 30000);//set time out for receiving response
HttpConnectionParams.setSoTimeout(httpParams, 30000);
HttpPost httppost = new HttpPost("http://10.0.2.2/upload_test/InsertData.php");
try{
BasicNameValuePair idValuePair = new BasicNameValuePair("dev_id", device_id);
BasicNameValuePair emailValuePair = new BasicNameValuePair("dev_email", device_email);
BasicNameValuePair jsonStringValuePair = new BasicNameValuePair("json", jObjectMain.toString());
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(idValuePair);
nameValuePairs.add(emailValuePair);
nameValuePairs.add(jsonStringValuePair);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost); //response class to handle responses
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
JSONObject object = new JSONObject(jsonResult);
}catch(ConnectTimeoutException e){
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e){
}
return jsonResult;
}
protected void onPostExecute(String Result){
System.out.println(Result);
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}