Stack上的第一篇帖子让我轻松一点......
我试图制作一个应用程序,我从ViewPagerFragment中加载了4个标签,每个标签都在加载一个片段。第一个选项卡(让我们称之为片段A)从在线获取数据,然后将其保存在数据库中,然后将其发布到列表视图,片段B和数据库中的其余部分,并在列表视图中发布数据&# 39;也是。
第一个片段在其列表视图中完美地显示数据,但所有其他片段都显示为空白..我还注意到,如果我没有放入片段A并让其他标签(B,C) ,D)从数据库中已保存的数据加载,显示的数据仅用于最后一个选项卡(D),但它的数据将显示在选项卡B上。所有数据都显示为空白。
每个片段启动网络
片段A
public class HomeFragment extends Fragment {
public static HomeFragment newInstance(String text) {
HomeFragment mFragment = new HomeFragment();
Bundle mBundle = new Bundle();
mBundle.putString("f", text);
mFragment.setArguments(mBundle);
return mFragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
context = getActivity();
setHasOptionsMenu(true);
info = new Db(context);
anime = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_up);
return inflater.inflate(R.layout.homelist, container, false);
}
@Override
public void onStart() {
super.onStart();
new NetworkClass().execute("0");
}
// -------------------------------xxx----------------------------
public class NetworkClass extends AsyncTask<String, Integer, String> {
//ProgressDialog progressDialog;
private StringBuilder sb;
private InputStream is;
private String result;
MaterialDialog dialog;
@Override
protected void onPreExecute() {
//show loading...runs in main UI thread
if (pre == 0) {
dialog = new MaterialDialog.Builder(getActivity())
.content(loadingMsg)
.progress(true, 0)
.show();
}
}
@Override
protected String doInBackground(String... arg0) {
//runs in background thread
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient3 = new DefaultHttpClient();
HttpPost httppost3;
JSONObject jsonObject = getDetails();
if (!SearchActivity.searchCheck) {
Log.v("home post: ", "" + jsonObject);
nameValuePairs.add(new BasicNameValuePair("jsonObj", ""
+ jsonObject));
httppost3 = new HttpPost(
"URL");
} else {
Log.v("Phone Details: ", "" + jsonObject);
httppost3 = new HttpPost(
"URL");
}
return null;
}
@Override
protected void onPostExecute(String result) {
//stop refresh if any
swipeLayout.setRefreshing(false);
try {
final MyAdapter adapter = new MyAdapter(context, inboxList,
R.layout.home_list_sub_layout, new String[]{}, new int[]{
R.id.title_TV_HLN, R.id.story_TV_HLN,
R.id.Date_TV_HLN, R.id.tonality_TV_HLN,
R.id.avatar_HLN, R.id.favImageView});
list = (ListView) ((Activity) context).findViewById(R.id.home_list);
list.setAdapter(adapter);
//change on refresh
//adapter.notifyDataSetChanged();
getActivity().runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
}
});
int x = adapter.getCount();
Log.v("Count : ", "" + x);
if (pre == 0) {
//progressDialog.dismiss();
dialog.dismiss();
}
list.setTextFilterEnabled(true);
SearchActivity.searchCheck = false;
}
}
private class MyAdapter extends SimpleAdapter {
int list_count;
public MyAdapter(Context context, List<? extends Map<String, ?>> data,
int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(context);
String fetch = SP.getString("no_of_stories", "2");
System.out.println(fetch);
if (fetch.equals("1")) {
list_count = 50;
} else if (fetch.equals("2")) {
list_count = 100;
} else if (fetch.equals("3")) {
list_count = 150;
}
//change on refresh
notifyDataSetChanged();
}
//no. of items to display
@Override
public int getCount() {
System.out.println(list_count + " Check this out");
return list_count;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.home_list_sub_layout,
null, false);
}
anime = AnimationUtils.loadAnimation(getActivity(), (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
convertView.startAnimation(anime);
lastPosition = position;
return convertView;
}
}
ViewPagerFragment
public class ViewPagerFragment extends Fragment {
public List<TabPagerItem> mTabs = new ArrayList<>();
private HomeFragment home;
private int x = 0;
private Context context;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity();
createTabPagerItem();
}
private void createTabPagerItem() {
mTabs.add(new TabPagerItem(getText(R.string.all), HomeFragment.newInstance(getString(R.string.all))));
mTabs.add(new TabPagerItem(getText(R.string.print), PrintFragment.newInstance(getString(R.string.print))));
mTabs.add(new TabPagerItem(getString(R.string.reports), MainFragment.newInstance(getString(R.string.all))));
mTabs.add(new TabPagerItem(getText(R.string.radio), RadioFragment.newInstance(getString(R.string.radio))));
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_viewpager, container, false);
rootView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
return rootView;
}
@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
ViewPager mViewPager = (ViewPager) view.findViewById(R.id.viewPager);
//pages to store in memory
mViewPager.setOffscreenPageLimit(4);
mViewPager.setAdapter(new ViewPagerAdapter(getChildFragmentManager(), mTabs));
getActivity().runOnUiThread(new Runnable() {
public void run() {
(new ViewPagerAdapter(getChildFragmentManager(), mTabs)).notifyDataSetChanged();
}
});
TabLayout mSlidingTabLayout = (TabLayout) view.findViewById(R.id.tabLayout);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mSlidingTabLayout.setElevation(15);
}
mSlidingTabLayout.setupWithViewPager(mViewPager);
}
ViewPagerAdapter
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fragmentManager, List<TabPagerItem> tabs) {
super(fragmentManager);
this.mTabs = tabs;
}
public void setDatasource(List<TabPagerItem> datasource){
mTabs = datasource;
notifyDataSetChanged();
}
@Override
public Fragment getItem(int i) {
return mTabs.get(i).getFragment();
}
@Override
public int getCount() {
return mTabs.size();
}
public Fragment getRegisteredFragment(int position) {
return mTabs.get(position).getFragment();
}
@Override
public CharSequence getPageTitle(int position) {
return mTabs.get(position).getTitle();
}
片段B,C,D ......
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
context = getActivity();
setHasOptionsMenu(true);
info = new Db(context);
return inflater.inflate(R.layout.homelist, container, false);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
MenuInflater flat = getActivity().getMenuInflater();
flat.inflate(R.menu.menu, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.menu_search:
SearchDialog searchDialog = new SearchDialog(getActivity());
searchDialog.show();
break;
}
return true;
}
@Override
public void onStart() {
super.onStart();
new NetworkClass().execute("0");
}
public class NetworkClass extends
AsyncTask<String, Integer, ArrayList<HashMap<String, ?>>> {
@Override
protected ArrayList<HashMap<String, ?>> doInBackground(String... arg0) {
if (SearchDialog.iconChaeck) {
searchDb = new SearchDB(context);
searchDb.open();
inboxList = new ArrayList<HashMap<String, ?>>();
inboxList = searchDb.getData(arg0[0]);
searchDb.close();
} else {
homeDb = new HomeStoriesDB(context);
homeDb.open();
inboxList = new ArrayList<HashMap<String, ?>>();
inboxList = homeDb.getData(arg0[0]);
homeDb.close();
}
favouriteDB = new FavouriteDB(context);
favouriteDB.open();
favoritesList = favouriteDB.getFavoriteStoryIDList();
favouriteDB.close();
return inboxList;
}
@Override
protected void onPostExecute(final ArrayList<HashMap<String, ?>> result) {
try {
if (!result.isEmpty()) {
MyAdapter adapter = new MyAdapter(context, inboxList,
R.layout.home_list_sub_layout, new String[]{
"Title", "Story", "StoryDate",
"Media_House_ID", "tonality", "pic",
"favorite"}, new int[]{
R.id.title_TV_HLN, R.id.story_TV_HLN,
R.id.Date_TV_HLN, R.id.tonality_TV_HLN,
R.id.avatar_HLN, R.id.favImageView});
list = (ListView) ((Activity) context)
.findViewById(R.id.home_list);
list.setAdapter(adapter);
//adapt.setDatasource(null);
// ---------------------Click Event of List
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
int type = Integer.parseInt((String) inboxList.get(
position).get("Media_ID"));
switch (type) {
case 0:
Intent it = new Intent(context,
PrintDetailActivity.class);
it.putExtra("map", inboxList.get(position));
startActivity(it);
break;
case 1:
it = new Intent(context,
RadioDetailActivity.class);
it.putExtra("map", inboxList.get(position));
startActivity(it);
break;
case 2:
it = new Intent(context, TVDetailActivity.class);
it.putExtra("map", inboxList.get(position));
startActivity(it);
break;
default:
System.out.println("No form available");
break;
}
}
});
} else {
Toast.makeText(getActivity(), "No Data Found",
Toast.LENGTH_SHORT).show();
}
//progressDialog.dismiss();
} catch (Exception e)
{
}
}
}
private class MyAdapter extends SimpleAdapter {
public MyAdapter(Context context, List<? extends Map<String, ?>> data,
int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.home_list_sub_layout,
null, false);
}
@SuppressWarnings("unchecked")
HashMap<String, Object> data = (HashMap<String, Object>) getItem(position);
TextView title = (TextView) convertView.findViewById(R.id.title_TV_HLN);
title.setText((String) data.get("Title"));
title.setTypeface(null, Typeface.BOLD);
((TextView) convertView.findViewById(R.id.Date_TV_HLN))
.setText("" + ((String) data.get("StoryDate")).replace(",", ""));
((TextView) convertView.findViewById(R.id.media_TV_HLN))
.setText((String) data.get("Media_House_ID"));
String mention_value = (String) data.get("mentioned");
TextView mention = ((TextView) convertView.findViewById(R.id.story_TV_HLN));
if (mention_value == null || mention_value.equals("null")) {
mention
.setText(Html
.fromHtml("<b><font color='#8c8c8c'>Mentioned:</font></b>"
+ " " + "N.A"));
} else {
if (mention_value.length() > 100) {
mention_value = mention_value.substring(0, 99) + "...";
}
mention.setText(Html
.fromHtml("<b><font color='#8c8c8c'>Mentioned:</font></b>"
+ " " + mention_value));
}
String tonality_value = (String) data.get("tonality");
String two = "negative";
if (tonality_value.equals(two)) {
((TextView) convertView.findViewById(R.id.tonality_TV_HLN))
.setTextColor(Color.parseColor("#AD0B11"));
} else {
((TextView) convertView.findViewById(R.id.tonality_TV_HLN))
.setTextColor(getResources().getColor(R.color.black));
}
((TextView) convertView.findViewById(R.id.tonality_TV_HLN))
.setText(Html
.fromHtml("<b><font color='#8c8c8c'>Effect:</font></b>"
+ " " + tonality_value));
ImageView storyIcon = ((ImageView) convertView
.findViewById(R.id.avatar_HLN));
int media_id = Integer.parseInt((String) inboxList.get(pos).get(
"Media_ID"));
switch (media_id) {
case 0:
storyIcon.setImageResource(R.drawable.ic_print);
break;
case 1:
storyIcon.setImageResource(R.drawable.ic_radio);
break;
case 2:
storyIcon.setImageResource(R.drawable.ic_tv);
break;
default:
storyIcon.setImageResource(R.drawable.ic_print);
break;
}
final ImageView imageview = ((ImageView) convertView
.findViewById(R.id.favImageView));
if (favoritesList.contains(inboxList.get(pos).get("Story_ID"))) {
// Log.v(" favorit story ", );
imageview.setImageResource(R.drawable.favorite_red);
} else {
imageview.setImageResource(R.drawable.favorite_blue);
}
imageview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
favouriteDB.open();
String story_id = (String) inboxList.get(pos).get(
"Story_ID");
String msg = "";
try {
if (!(favoritesList.contains(story_id))) {
favouriteDB.createEntry(inboxList.get(pos));
favouriteDB.close();
imageview.setImageResource(R.drawable.favorite_red);
favoritesList.add(story_id);
msg = "Successfully added in favorite list";
} else {
favouriteDB.deleteStoryID(story_id);
favoritesList.remove(story_id);
imageview
.setImageResource(R.drawable.favorite_blue);
msg = "Successfully deleted from favorite list";
}
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
favouriteDB.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
return convertView;
}
}