Android 如何使用AsyncTask加载GridView图像?
下面是用URL中的位图填充gridview的片段。问题是,我知道这是一项非常“繁重”的工作,而且是在UI线程上完成的,因此在加载网格时会减慢片段的速度 我曾读到,在后台执行“繁重”的工作需要一个异步任务,但我找不到任何适合我需要的东西Android 如何使用AsyncTask加载GridView图像?,android,gridview,android-asynctask,Android,Gridview,Android Asynctask,下面是用URL中的位图填充gridview的片段。问题是,我知道这是一项非常“繁重”的工作,而且是在UI线程上完成的,因此在加载网格时会减慢片段的速度 我曾读到,在后台执行“繁重”的工作需要一个异步任务,但我找不到任何适合我需要的东西 public class HomeFragment extends Fragment { protected static final String TAG = null; public HomeFragment(){} GridView gridView; p
public class HomeFragment extends Fragment {
protected static final String TAG = null;
public HomeFragment(){}
GridView gridView;
private GridViewAdapter gridAdapter;
private SQLiteHandler db;
private SwipeRefreshLayout swipeLayout;
private ProgressDialog pDialog;
GPSTracker gps;
String uid;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
db = new SQLiteHandler(getActivity());
gridAdapter = new GridViewAdapter(getActivity(), R.layout.grid_item_layout, getData());
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(true);
uid="1";
String email = db.getFromTable(getActivity(), "email", SQLiteHandler.TABLE_LOGIN, "WHERE _id="+uid);
String from_age = db.getFromTable(getActivity(), "from_age", SQLiteHandler.TABLE_SETTINGS, "WHERE uid="+uid);
String to_age = db.getFromTable(getActivity(), "to_age", SQLiteHandler.TABLE_SETTINGS, "WHERE uid="+uid);
String distance = db.getFromTable(getActivity(), "distance", SQLiteHandler.TABLE_SETTINGS, "WHERE uid="+uid);
String unit = db.getFromTable(getActivity(), "unit", SQLiteHandler.TABLE_SETTINGS, "WHERE uid="+uid);
String men = db.getFromTable(getActivity(), "men", SQLiteHandler.TABLE_SETTINGS, "WHERE uid="+uid);
String women = db.getFromTable(getActivity(), "women", SQLiteHandler.TABLE_SETTINGS, "WHERE uid="+uid);
fetchUsers(email, from_age, to_age, distance, unit, men, women);
final View rootView = inflater.inflate(R.layout.fragment_home, container, false);
//getActivity().getActionBar().setTitle(R.string.home);
gridView = (GridView) rootView.findViewById(R.id.gridView);
gridView.setAdapter(gridAdapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
ImageItem item = (ImageItem) parent.getItemAtPosition(position);
ImageView imageView = (ImageView) v.findViewById(R.id.image);
//Create intent
Intent intent = new Intent(getActivity(), DetailsActivity.class);
int[] screenLocation = new int[2];
imageView.getLocationOnScreen(screenLocation);
intent.putExtra("left", screenLocation[0]).
putExtra("top", screenLocation[1]).
putExtra("width", imageView.getWidth()).
putExtra("height", imageView.getHeight()).
putExtra("uid", item.getUid());
startActivity(intent);
}
});
swipeLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh() {
//my update process
Fragment currentFragment = getFragmentManager().findFragmentByTag("0");
FragmentTransaction fragTransaction = getFragmentManager().beginTransaction();
fragTransaction.detach(currentFragment);
fragTransaction.attach(currentFragment);
fragTransaction.commit();
}
});
return rootView;
}
// Prepare some dummy data for gridview
private ArrayList<ImageItem> getData() {
final ArrayList<ImageItem> imageItems = new ArrayList<>();
Cursor cursor = db.getAllRows("*", SQLiteHandler.TABLE_USERS, "");
//Query local DB to initialize settings screen
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
String uid = cursor.getString(cursor.getColumnIndex(SQLiteHandler.KEY_UID));
String name = cursor.getString(cursor.getColumnIndex(SQLiteHandler.KEY_NAME));
String dob = cursor.getString(cursor.getColumnIndex(SQLiteHandler.KEY_DOB));
//String gender = cursor.getString(cursor.getColumnIndex(SQLiteHandler.KEY_GENDER));
String photourl = cursor.getString(cursor.getColumnIndex(SQLiteHandler.KEY_PHOTOURL));
//String distance = cursor.getString(cursor.getColumnIndex(SQLiteHandler.KEY_DISTANCE));
String[] birthdayArr = dob.split("-");
int age = getAge(Integer.parseInt(birthdayArr[0]), Integer.parseInt(birthdayArr[1]), Integer.parseInt(birthdayArr[2]));
Bitmap bitmap = getBitmapFromURL(photourl);
imageItems.add(new ImageItem(bitmap, name+" - " + age, uid));
}
return imageItems;
}
public static Bitmap getBitmapFromURL(String src) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
public int getAge(int year, int month, int day) {
//int nowMonth = now.getMonth()+1;
int nowMonth = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
//int nowYear = now.getYear()+1900;
int nowYear = Calendar.getInstance().get(Calendar.YEAR);
int result = nowYear - year;
if (month > nowMonth) {
result--;
}
else if (month == nowMonth) {
int nowDay = Calendar.getInstance().get(Calendar.DATE);
if (day > nowDay) {
result--;
}
}
return result;
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
Log.i("hideDialog", "called");
if (pDialog.isShowing())
pDialog.dismiss();
}
public void fetchUsers(final String email, final String agefrom, final String ageto, final String distance, final String distanceUnit, final String interested_men, final String interested_wmen){
// Tag used to cancel the request
gps = new GPSTracker(getActivity());
String tag_string_req = "req_login";
pDialog.setMessage("Finding users ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Fetch Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
int success = jObj.getInt("success");
JSONArray users = jObj.getJSONArray("users");
// Check for error node in json
if (success == 1) {
//Log.i("success", users+"");
if (users.length() == 0) {
Toast.makeText(getActivity(), "No users found! \nPlease try again soon.", Toast.LENGTH_LONG).show();
db.emptyTable(SQLiteHandler.TABLE_USERS);
}else{
db.emptyTable(SQLiteHandler.TABLE_USERS);
for (int i = 0; i < users.length(); i++) {
JSONObject user = users.getJSONObject(i);
String uid = user.getString("uid");
String name = user.getString("name");
String dob = user.getString("dob");
String gender = user.getString("gender");
String photourl = user.getString("photoUrl");
String distance = user.getString("distance");
String[][] userValues = {
{ SQLiteHandler.KEY_UID, uid},
{ SQLiteHandler.KEY_NAME, name},
{ SQLiteHandler.KEY_DOB, dob},
{ SQLiteHandler.KEY_GENDER, gender},
{ SQLiteHandler.KEY_PHOTOURL, photourl},
{ SQLiteHandler.KEY_DISTANCE, distance}
};
db.insert(SQLiteHandler.TABLE_USERS, userValues);
}
}
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getActivity(),errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getActivity(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
@Override
protected Map<String, String> getParams() {
// Posting parameters to login url
//$lat, $lng, $email, $agefrom, $ageto, $distance, $distanceUnit, $interested_men, $interested_wmen
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("lat", gps.getLatitude()+"");
params.put("lng", gps.getLongitude()+"");
params.put("email", email);
params.put("agefrom", agefrom);
params.put("ageto", ageto);
params.put("distance", distance);
params.put("distanceUnit", distanceUnit);
params.put("interested_men", interested_men+"");
params.put("interested_wmen", interested_wmen+"");
params.put("fetch", "y");
Log.i(TAG, params+"");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
公共类HomeFragment扩展了片段{
受保护的静态最终字符串标记=null;
公共HomeFragment(){}
GridView;
私有GridViewAdapter gridAdapter;
私有SQLiteHandler数据库;
私人泳道布局泳道布局;
私人对话;
全球定位系统;
字符串uid;
@凌驾
CreateView上的公共视图(布局、充气机、视图组容器、捆绑包保存状态){
db=新的SQLiteHandler(getActivity());
gridAdapter=新的GridViewAdapter(getActivity(),R.layout.grid_item_layout,getData());
pDialog=newprogressdialog(getActivity());
pDialog.setCancelable(真);
uid=“1”;
字符串email=db.getFromTable(getActivity(),“email”,SQLiteHandler.TABLE_LOGIN,“其中_id=“+uid”);
字符串from_age=db.getFromTable(getActivity(),“from_age”,SQLiteHandler.TABLE_设置,“其中uid=“+uid”);
字符串to_age=db.getFromTable(getActivity(),“to_age”,SQLiteHandler.TABLE_设置,“其中uid=“+uid”);
字符串距离=db.getFromTable(getActivity(),“距离”,SQLiteHandler.TABLE_设置,“其中uid=“+uid”);
字符串unit=db.getFromTable(getActivity(),“unit”,SQLiteHandler.TABLE_设置,“其中uid=“+uid”);
字符串men=db.getFromTable(getActivity(),“men”,SQLiteHandler.TABLE_设置,“其中uid=“+uid”);
字符串women=db.getFromTable(getActivity(),“women”,SQLiteHandler.TABLE_设置,“其中uid=“+uid”);
获取用户(电子邮件、从_年龄、到_年龄、距离、单位、男性、女性);
最终视图根视图=充气机。充气(R.layout.fragment\u home,container,false);
//getActivity().getActionBar().setTitle(R.string.home);
gridView=(gridView)rootView.findviewbyd(R.id.gridView);
setAdapter(gridAdapter);
setOnItemClickListener(新的OnItemClickListener(){
public void onItemClick(AdapterView父视图、视图v、整型位置、长id){
ImageItem项=(ImageItem)父项.getItemAtPosition(position);
ImageView ImageView=(ImageView)v.findViewById(R.id.image);
//创造意图
Intent Intent=new Intent(getActivity(),DetailsActivity.class);
int[]屏幕位置=新int[2];
imageView.getLocationOnScreen(屏幕位置);
intent.putExtra(“左”,屏幕位置[0])。
putExtra(“顶部”,屏幕位置[1])。
putExtra(“宽度”,imageView.getWidth()。
putExtra(“height”,imageView.getHeight())。
putExtra(“uid”,item.getUid());
星触觉(意向);
}
});
swipeLayout=(SwipeRefreshLayout)rootView.findViewById(R.id.swipe_容器);
setOnRefreshListener(新的OnRefreshListener(){
@凌驾
公共void onRefresh(){
//我的更新过程
Fragment currentFragment=getFragmentManager().findFragmentByTag(“0”);
FragmentTransaction FragmentTransaction=getFragmentManager().beginTransaction();
fragTransaction.detach(currentFragment);
fragTransaction.attach(当前片段);
fragTransaction.commit();
}
});
返回rootView;
}
//为gridview准备一些虚拟数据
私有ArrayList getData(){
最终ArrayList imageItems=新ArrayList();
Cursor Cursor=db.getAllRows(“*”,SQLiteHandler.TABLE_USERS,“”;
//查询本地数据库以初始化设置屏幕
对于(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()){
stringuid=cursor.getString(cursor.getColumnIndex(SQLiteHandler.KEY_uid));
String name=cursor.getString(cursor.getColumnIndex(SQLiteHandler.KEY_name));
stringdob=cursor.getString(cursor.getColumnIndex(SQLiteHandler.KEY_-dob));
//String性别=cursor.getString(cursor.getColumnIndex(SQLiteHandler.KEY_性别));
String photourl=cursor.getString(cursor.getColumnIndex(SQLiteHandler.KEY_photourl));
//字符串距离=cursor.getString(cursor.getColumnIndex(SQLiteHandler.KEY_distance));
字符串[]birthdayArr=dob.split(“-”);
int age=getAge(Integer.parseInt(birthdayArr[0])、Integer.parseInt(birthdayArr[1])、Integer.parseInt(birthdayArr[2]);
位图位图=getBitmapFromURL(photourl);
添加(新的ImageItem(位图,名称+“-”+年龄,uid));
}
归还物品;
}
公共静态位图getBitmapFromURL(字符串src){
StrictMode.ThreadPolicy policy=新建StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(策略);
试试{
URL=新URL(src);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream输入=连接。getInputStream();
位图myBitmap=BitmapFactory.decodeStream(输入);
返回我的位图;
}捕获(IOE异常){
//日志异常
返回null;
}
}
公共整数获取(整数年、整数月、整数日){
//int nowMonth=now.getMonth()+1;
int nowMonth=Calendar.getInstance().get(Calendar.DAY\u OF\u MONTH);
//int nowYear=now.getYear()+1900;
int nowYear=Calendar.getInstance().get(Calendar.YEAR);
int result=nowYear-year;
如果(月>现在月){
结果--;
}
else if(月==nowMonth){
int nowDay=Calendar.getInstance().get(Calendar.DATE);
如果(天>现在天){
结果--;
}
}
返回结果;
}
私有void showDialog(){
如果(!pDialog.isShowing())
pDialog.show();
}
私有void hideDialog(){
public class GridDataAsyncTask extends AsyncTask<GridDataAsyncTask.GridCallback, Void, GridAdapter> {
public interface GridCallback {
void onAdapterReady(GridAdapter adapter);
}
private GridCallback mCallBack;
@Override
protected GridAdapter doInBackground(GridCallback... callbacks) {
mCallBack = callbacks[0];
// TODO get data and create grid adapter
return adapter;
}
@Override
protected void onPostExecute(GridAdapter gridAdapter) {
super.onPostExecute(gridAdapter);
mCallBack.onAdapterReady(gridAdapter);
}
}
public class GridActivity extends AppCompatActivity implements GridDataAsyncTask.GridCallback {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new GridDataAsyncTask().execute(this);
}
@Override
public void onAdapterReady(GridAdapter adapter) {
// TODO set adapte to GridView
}
}