我在ListViewFragment中使用了AsyncTask和Listview和pager 我有一个问题
我遇到的问题是从Json获得的所有内容同时加载到片段上 所以,有时它会在片段列表视图中消失或混合。
这是我在MainActivity中的ViewPagerAdapter
private class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
if (position == 0)
{
return ScrollView_mainpage.newInstance(position);
}
else if (position == 1)
{
return ListViewFragment2.newInstance(position);
}
else if(position ==2)
{
return ListViewFragment_TIP.newInstance(position);
}
else
{
return ScrollView_userpage.newInstance(position);
}
}
@Override
public void destroyItem(View container, int position, Object object) {
}
@Override
public int getCount() {
return 4;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return " Home";
case 1:
return " YAAK";
case 2:
return " Tip";
case 3:
return " My";
}
return "";
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
这是我的第一个由ScrollView制作的片段
public class ScrollView_mainpage extends BaseViewPagerFragment {
private ScrollView mScrollView;
private ScrollViewDelegate mScrollViewDelegate = new ScrollViewDelegate();
private UserSessionManager session;
TextView status;
public static ScrollView_mainpage newInstance(int index) {
ScrollView_mainpage fragment = new ScrollView_mainpage();
Bundle args = new Bundle();
args.putInt(BUNDLE_FRAGMENT_INDEX, index);
fragment.setArguments(args);
return fragment;
}
//on start에서 사용자 pain에 맞는 sql 데이터와 탑 7아이템을 로드 한 뒤
// 두 엑티비티에 뿌리기
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.a_main_scroll_view, container, false);
mScrollView = (ScrollView) view.findViewById(R.id.scrollview);
session = new UserSessionManager(getActivity());
HashMap<String, String> user = session.getUserDetails();
status = (TextView)view.findViewById(R.id.status);
status.setText(user.get(UserSessionManager.POST_USER_PAIN) + " 이 걱정이신 " + user.get(UserSessionManager.POST_USERNAME) + "님");
android.support.v4.view.ViewPager pager = (android.support.v4.view.ViewPager) view.findViewById(R.id.list__top_pager);
pager.setAdapter(new MyPagerAdapter());
android.support.v4.view.ViewPager pager2 = (android.support.v4.view.ViewPager) view.findViewById(R.id.list__recommend_pager);
pager2.setAdapter(new MyPagerAdapter());
return view;
}
private class MyPagerAdapter extends PagerAdapter {
int NumberOfPages = 5;
int[] res = {
R.drawable.one,
R.drawable.two,
R.drawable.three,
R.drawable.four,
R.drawable.five };
int[] backgroundcolor = {
0xFF101010,
0xFF202020,
0xFF303030,
0xFF404040,
0xFF505050 };
@Override
public int getCount() {
return NumberOfPages;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
TextView textView = new TextView(getContext());
textView.setTextColor(Color.WHITE);
textView.setTextSize(30);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setText(String.valueOf(position));
ImageView imageView = new ImageView(getContext());
imageView.setImageResource(res[position]);
ViewGroup.LayoutParams imageParams = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
imageView.setLayoutParams(imageParams);
LinearLayout layout = new LinearLayout(getContext());
layout.setOrientation(LinearLayout.VERTICAL);
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layout.setBackgroundColor(backgroundcolor[position]);
layout.setLayoutParams(layoutParams);
layout.addView(textView);
layout.addView(imageView);
final int page = position;
layout.setOnClickListener(new View.OnClickListener(){
//여기서 세부 아이팀 리스트로 넘어가게끔 설정 해놓기.
@Override
public void onClick(View v) {
Toast.makeText(getContext(),
"Page " + page + " clicked",
Toast.LENGTH_LONG).show();
}});
container.addView(layout);
return layout;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout)object);
}
}
@Override public boolean isViewBeingDragged(MotionEvent event) {
return mScrollViewDelegate.isViewBeingDragged(event, mScrollView);
}
public void closeSilently(Closeable c) {
if (c == null) {
return;
}
try {
c.close();
} catch (Throwable t) {
// do nothing
}
}
}
第二个FragmentPage就是这个
public class ListViewFragment2 extends BaseViewPagerFragment
implements AbsListView.OnItemClickListener {
private ListView mListView;
private ListAdapter mAdapter;
private View v;
private AbsListViewDelegate mAbsListViewDelegate = new AbsListViewDelegate();
private TextView category;
private ListView list;
private String[] array={"전체 카테고리","눈","머리","피로","장(유산균)"};
private final String ITEM_ID = "item_id";
private final String ITEM_NAME = "item_name";
private final String ITEM_BRAND = "item_brand";
private final String ITEM_PRICE = "item_price";
private final String ITEM_IMG = "item_img";
private final String ITEM_USAGE = "item_usage";
private final String ITEM_CATEGORY = "item_category";
private final String ITEM_CAPACITY = "item_capacity";
private final String ITEM_INGREDIENT= "item_ingredient";
private final String TAG_POSTS = "posts";
private final String READ_ALL_CONTENTS = "http://cosmetictoworld.com/alcontents.php";
private final String READ_ITEM_CONTETNS = "http://cosmetictoworld.com/temcontents.php";
private ProgressBar pBar;
private ProgressDialog pDialog;
private JSONArray mComments = null;
public Integer len;
//private ArrayList<HashMap<String,String>> mCommentList;
//private ArrayList<HashMap<String,String>> AdapList;
private EditText filter;
public static String[] item_nameArray;
public static String[] item_brandArray;
public static String[] item_priceArray;
public static String[] item_capacityArray;
public static String[] item_usageArray;
public static String[] item_ingredientArray;
public static String[] item_imgArray;
public static String[] item_categoryArray;
public static String[] item_idArray;
ArrayList<Item> arrayList = new ArrayList<Item>();
itemListAdapter itemAdapter;
public static ListViewFragment2 newInstance(int index) {
ListViewFragment2 fragment = new ListViewFragment2();
Bundle args = new Bundle();
args.putInt(BUNDLE_FRAGMENT_INDEX, index);
fragment.setArguments(args);
return fragment;
}
public ListViewFragment2() {
}
@Override
public void onStart(){
super.onStart();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.a_item_list_view, container, false);
pBar = (ProgressBar)view.findViewById(R.id.circularProgressbar);
new LoadItem().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null);
category = (TextView)view.findViewById(R.id.category);
category.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder dlg = new AlertDialog.Builder(getContext());
dlg.setTitle("제품 카테고리");
dlg.setItems(array, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
category.setText(array[which]);
if(array[which].equals("전체 카테고리"))
itemAdapter.filter("all");
else if (array[which].equals("눈"))
itemAdapter.filter("eye");
else if (array[which].equals("장(유산균)"))
itemAdapter.filter("gut");
else if (array[which].equals("머리"))
itemAdapter.filter("brain");
else if (array[which].equals("피로"))
itemAdapter.filter("fatigue");
}
});
dlg.show();
}
});
return view;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
synchronized public void updateList(){
list = (ListView)getActivity().findViewById(R.id.list);
arrayList.clear();
for(int i=0; i<item_nameArray.length; i++)
{
Item item = new Item(item_nameArray[i],item_brandArray[i],item_priceArray[i],
item_capacityArray[i],item_usageArray[i],
item_ingredientArray[i],item_imgArray[i],item_categoryArray[i],
item_idArray[i]);
arrayList.add(item);
}
itemAdapter = new itemListAdapter(getContext(), arrayList);
list.setAdapter(itemAdapter);
list.setEmptyView(getActivity().findViewById(android.R.id.empty));
filter = (EditText)getActivity().findViewById(R.id.filter);
filter.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
String text = filter.getText().toString().toLowerCase(Locale.getDefault());
itemAdapter.filter(text);
}
});
}
synchronized public void updateJSONdata_item() {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_ALL_CONTENTS);
try{
mComments = json.getJSONArray(TAG_POSTS);
len = mComments.length();
item_nameArray = new String[len];
item_brandArray = new String[len];
item_priceArray = new String[len];
item_capacityArray = new String[len];
item_usageArray = new String[len];
item_ingredientArray = new String[len];
item_imgArray = new String[len];
item_categoryArray = new String[len];
item_idArray = new String[len];
for(int i= 0; i< mComments.length(); i++) {
final int index = i;
JSONObject c = mComments.getJSONObject(index);
item_idArray[index] = c.getString(ITEM_ID);
item_nameArray[index]=c.getString(ITEM_NAME);
item_brandArray[index] = c.getString(ITEM_BRAND);
item_imgArray[index]= c.getString(ITEM_IMG);
item_priceArray[index]= c.getString(ITEM_PRICE);
item_usageArray[index]= c.getString(ITEM_USAGE);
item_ingredientArray[index] = c.getString(ITEM_INGREDIENT);
item_categoryArray[index]= c.getString(ITEM_CATEGORY);
item_capacityArray[index]= c.getString(ITEM_CAPACITY);
}
}catch(JSONException e) {
e.printStackTrace();
}
}
private final class LoadItem extends AsyncTask<Void, Void, Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
Resources res = getResources();
Drawable drawable = res.getDrawable(R.drawable.circular);
pBar.setProgress(25); // Main Progress
pBar.setSecondaryProgress(50); // Secondary Progress
pBar.setMax(100); // Maximum Progress
pBar.setProgressDrawable(drawable);
}
@Override
protected Boolean doInBackground(Void... params) {
updateJSONdata_item();
return null;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pBar.setVisibility(v.INVISIBLE);
updateList();
}
}
private final class itemListAdapter extends BaseAdapter {
private final Context context;
LayoutInflater inflater;
private List<Item> Item_list = null;
private ArrayList<Item> arrayList;
public itemListAdapter(Context context,List<Item> Item_list) {
this.context = context;
this.Item_list = Item_list;
inflater = LayoutInflater.from(context);
this.arrayList = new ArrayList<Item>();
this.arrayList.addAll(Item_list);
}
class ViewHolder {
public ImageView img;
public TextView brand;
public TextView name;
public TextView capacity;
public TextView adapter_category;
}
@Override
public int getCount(){
return Item_list.size();
}
@Override
public Item getItem(int position){
return Item_list.get(position);
}
@Override public long getItemId(int position) {
return position;
}
@Override public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = LayoutInflater.from(context).inflate(R.layout.item_list_item, parent, false);
holder.img = (ImageView)view.findViewById(R.id.item_img);
holder.brand = (TextView)view.findViewById(R.id.item_brand);
holder.name = (TextView)view.findViewById(R.id.item_name);
holder.capacity = (TextView)view.findViewById(R.id.item_capacity);
holder.adapter_category = (TextView)view.findViewById(R.id.item_category);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.brand.setText(Item_list.get(position).getItemBrand());
holder.name.setText(Item_list.get(position).getItemName());
holder.capacity.setText(Item_list.get(position).getItemCapacity());
String ca = Item_list.get(position).getItemCategory();
if(ca.equals("fatigue"))
holder.adapter_category.setText("전신피로");
else if(ca.equals("gut"))
holder.adapter_category.setText("장(유산균)");
else if(ca.equals("eye"))
holder.adapter_category.setText("눈,시력");
else
holder.adapter_category.setText("머리,기억력");
String url =Item_list.get(position).getItemImg();
Picasso.with(context)
.load(url)
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
//.fit()
.resizeDimen(R.dimen.list_detail_image_size, R.dimen.list_detail_image_size)
.centerInside()
.tag(context)
.into(holder.img);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context,content_detail.class);
intent.putExtra("item_id", Item_list.get(position).getItemId());
intent.putExtra("item_name", Item_list.get(position).getItemName());
intent.putExtra("item_brand", Item_list.get(position).getItemBrand());
intent.putExtra("item_price", Item_list.get(position).getItemPrice());
intent.putExtra("item_ingredient", Item_list.get(position).getItemIngredient());
intent.putExtra("item_usage", Item_list.get(position).getItemUsage());
intent.putExtra("item_capacity", Item_list.get(position).getItemCapacity());
intent.putExtra("item_img", Item_list.get(position).getItemImg());
intent.putExtra("item_category", Item_list.get(position).getItemCategory());
startActivity(intent);
}
});
return view;
}
public void filter(String charText)
{
charText = charText.toLowerCase(Locale.getDefault());
Item_list.clear();
if(charText.equals("all"))
Item_list.addAll(arrayList);
if(charText.length()==0)
{
Item_list.addAll(arrayList);
} else {
for(Item item : arrayList)
{
if(item.getItemName().toLowerCase(Locale.getDefault()).contains(charText))
{
Item_list.add(item);
}
else if(item.getItemCategory().toLowerCase(Locale.getDefault()).contains(charText))
{
Item_list.add(item);
}
}
}
notifyDataSetChanged();
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
@Override public boolean isViewBeingDragged(MotionEvent event) {
return mAbsListViewDelegate.isViewBeingDragged(event, mListView);
}
}
这是我的第三个片段
public class ListViewFragment_TIP extends BaseViewPagerFragment
implements AbsListView.OnItemClickListener {
private ListView mListView;
private ListAdapter mAdapter;
private AbsListViewDelegate mAbsListViewDelegate = new AbsListViewDelegate();
private final String TIP_ID = "tip_id";
private final String TIP_NAMAE="tip_name";
private final String TIP_CONTENT="tip_content";
private final String TIP_IMG="tip_img";
private final String TAG_POSTS="posts";
private final String READ_ALL_TIP = "http://cosmetictoworld.cafe24.com/tip_contents.php";
private ProgressDialog pDialog;
private JSONArray mComments = null;
public Integer len;
private EditText filter;
private ListView list;
private ProgressBar pBar;
public static int indexing;
public static String[] tip_idArray;
public static String[] tip_nameArray;
public static String[] tip_contentArray;
public static String[] tip_imgArray;
ArrayList<Tip> arrayList = new ArrayList<Tip>();
tipListAdapter tipAdapter;
TextView button_tip;
public static ListViewFragment_TIP newInstance(int index) {
ListViewFragment_TIP fragment = new ListViewFragment_TIP();
Bundle args = new Bundle();
indexing=index;
args.putInt(BUNDLE_FRAGMENT_INDEX, index);
fragment.setArguments(args);
return fragment;
}
public ListViewFragment_TIP() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.a_board_list_view, container, false);
pBar = (ProgressBar)view.findViewById(R.id.circularProgressbar);
button_tip = (TextView)view.findViewById(R.id.button_tip);
new LoadTip().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null);
return view;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
synchronized public void updateList(){
list = (ListView)getActivity().findViewById(R.id.list);
arrayList.clear();
for(int i=0; i<tip_nameArray.length; i++)
{
Tip tip = new Tip(tip_idArray[i],tip_nameArray[i],tip_contentArray[i],
tip_imgArray[i]);
arrayList.add(tip);
}
tipAdapter = new tipListAdapter(getContext(),arrayList);
list.setAdapter(tipAdapter);
list.setEmptyView(getActivity().findViewById(android.R.id.empty));
}
synchronized public void updateJSONdata_tip() {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_ALL_TIP);
try{
mComments = json.getJSONArray(TAG_POSTS);
len = mComments.length();
tip_idArray = new String[len];
tip_nameArray = new String[len];
tip_contentArray = new String[len];
tip_imgArray = new String[len];
for(int i= 0; i< mComments.length(); i++) {
final int index = i;
JSONObject c = mComments.getJSONObject(index);
tip_idArray[index] = c.getString(TIP_ID);
tip_nameArray[index] = c.getString(TIP_NAMAE);
tip_contentArray[index] = c.getString(TIP_CONTENT);
tip_imgArray[index] = c.getString(TIP_IMG);
}
}catch(JSONException e) {
e.printStackTrace();
}
}
private final class LoadTip extends AsyncTask<Void, Void, Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
Resources res = getResources();
Drawable drawable = res.getDrawable(R.drawable.circular);
pBar.setProgress(25); // Main Progress
pBar.setSecondaryProgress(50); // Secondary Progress
pBar.setMax(100); // Maximum Progress
pBar.setProgressDrawable(drawable);
}
@Override
protected Boolean doInBackground(Void... params) {
updateJSONdata_tip();
return null;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pBar.setVisibility(View.INVISIBLE);
updateList();
}
}
private final class tipListAdapter extends BaseAdapter {
private final Context context;
LayoutInflater inflater;
private List<Tip> tip_list = null;
private ArrayList<Tip> arrayList;
public tipListAdapter(Context context, List<Tip> tip_list) {
this.context = context;
this.tip_list = tip_list;
inflater = LayoutInflater.from(context);
this.arrayList = new ArrayList<Tip>();
this.arrayList.addAll(tip_list);
}
class ViewHolder {
public ImageView img;
public TextView name;
}
@Override
public int getCount() {
return tip_list.size();
}
@Override
public Tip getItem(int position) {
return tip_list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = LayoutInflater.from(context).inflate(R.layout.tip_list_item, parent, false);
holder.img = (ImageView) view.findViewById(R.id.tip_img);
holder.name = (TextView) view.findViewById(R.id.tip_name);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
String url = tip_list.get(position).getTip_img();
Log.d("IMG: ",url);
Picasso.with(context)
.load(url)
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
//.fit()
.resizeDimen(R.dimen.tip_width_image_size, R.dimen.tip_height_size)
.centerInside()
.tag(context)
.into(holder.img);
holder.name.setText(tip_list.get(position).getTip_name());
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, content_detail.class);
intent.putExtra("tip_id", tip_list.get(position).getTip_id());
intent.putExtra("tip_name", tip_list.get(position).getTip_name());
intent.putExtra("tip_content", tip_list.get(position).getTip_content());
intent.putExtra("tip_img", tip_list.get(position).getTip_img());
startActivity(intent);
}
});
return view;
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
@Override public boolean isViewBeingDragged(MotionEvent event) {
return mAbsListViewDelegate.isViewBeingDragged(event, mListView);
}
}
如何避免同时加载的数据? 和 如何按时在列表视图中发送数据?
答案 0 :(得分:0)
new LoadItem().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null);
此行允许您的AsyncTasks并行执行。 如果你不想用SERIAL_EXECUTOR替换THREAD_POOL_EXECUTOR。