我将动态id从arraylist存储到动态创建的每个选项卡
我使用了ViewPagerOnTabSelectedListener,它获取了单击的选项卡的id并将其存储在共享首选项中。
我正在将共享偏好中的id用于片段,根据该ID获取每个标签中的自定义列表。
是的,问题是自定义列表没有在选项卡点击时刷新,但是它已经获取旧值,它没有根据共享偏好中的id进行更新
public class ScrollableTabsActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
ConnectionClass connectionClass;
ArrayList<String> al,idal,pidal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrollable_tabs);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
viewPager = (ViewPager) findViewById(R.id.viewpager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
connectionClass = new ConnectionClass();
al = new ArrayList<String>();
idal = new ArrayList<String>();
pidal = new ArrayList<String>();
ScrollableTabsActivity.DoLogin doLogin = new ScrollableTabsActivity.DoLogin();
doLogin.execute("");
}
private void setupTags() {
int i;
for(i=0;i<al.size();i++) {
/* Tag t= new Tag();
t.setId(idal.get(i));
tabLayout.getTabAt(i).setTag(t);
*/
tabLayout.getTabAt(i).setTag(idal.get(i));
}
tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager){
@Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
// CharSequence numTab = ((Tag)tab.getTag()).getId();
CharSequence numTab = tab.getTag().toString();
SharedPreferences preferences2 = getSharedPreferences("AUTHENTICATION_FILE_NAME2", Context.MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor2 = preferences2.edit();
editor2.putString("tabselected",numTab.toString());
editor2.putString("Authentication_Status", "true");
editor2.apply();
}
});
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
int i;
for(i=0;i<al.size();i++){
adapter.addFrag(new MainActivity(), al.get(i),idal.get(i));
}
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
private final List<String> mFragmentId = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title,String id) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
mFragmentId.add(id);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_cart:
cart();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Launching new activity
* */
private void cart() {
Intent i = new Intent(ScrollableTabsActivity.this, Cart.class);
startActivity(i);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onBackPressed() {
super.onBackPressed();
Vibrator v = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(500);
MainActivity m= new MainActivity();
m.vacatelist();
}
public class DoLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSuccess = false;
@Override
protected void onPreExecute() {
}
@Override
protected void onPostExecute(String r) {
if(isSuccess) {
SharedPreferences preferences2 = getSharedPreferences("AUTHENTICATION_FILE_NAME2", Context.MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor2 = preferences2.edit();
editor2.putString("tabselected",idal.get(0).toString());
editor2.putString("Authentication_Status", "true");
editor2.apply();
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
setupTags();
}
else {
Toast.makeText(ScrollableTabsActivity.this,r, Toast.LENGTH_SHORT).show();
}
}
@Override
protected String doInBackground(String... params) {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "SELECT ID,Category_ItemName,Pi_Category_ID FROM [dbo].[MainMenuDetail] where Pi_Category_ID=0 and Delete_category=0";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
idal.add(rs.getString("ID"));
al.add(rs.getString("Category_ItemName"));
pidal.add(rs.getString("Pi_Category_ID"));
}
z = "Successful";
isSuccess=true;
}
}
catch (Exception ex)
{
isSuccess = false;
z = "Exceptions";
}
return z;
}
}
}
public class MainActivity extends android.support.v4.app.Fragment {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
ConnectionClass connectionClass;
// Movies json url
String url="http://i.imgur.com/mQPXunb.png";
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
private List templist = new ArrayList();
String image_url = "http://app.dartenogroup.com/admin/img/";
String image_url2="";
NetworkImageView img;
String restid;
Movie movie;
String tabselected;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_main, container, false);
}
@Override
public void onViewCreated(View view,Bundle savedInstanceState){
super.onViewCreated(view,savedInstanceState);
SharedPreferences prfs = getActivity().getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
restid = prfs.getString("restid", "");
SharedPreferences prfs2 = getActivity().getSharedPreferences("AUTHENTICATION_FILE_NAME2", Context.MODE_PRIVATE);
tabselected = prfs2.getString("tabselected", "");
Toast.makeText(getActivity(), tabselected, Toast.LENGTH_SHORT).show();
connectionClass = new ConnectionClass();
listView = (ListView) view.findViewById(R.id.list);
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
img = (NetworkImageView) view.findViewById(R.id.thumbnail);
// changing action bar color
//getActionBar().setBackgroundDrawable(
// new ColorDrawable(Color.parseColor("#ffffff")));
DoLogin doLogin = new DoLogin();
doLogin.execute("");
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent i2 = new Intent(getActivity(), ViewProduct.class);
TextView tv=(TextView)view.findViewById(R.id.itemid);
i2.putExtra("value",tv.getText().toString());
startActivity(i2);
}
});
}
/**
* On selecting action bar icons
* */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_cart:
cart();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Launching new activity
* */
private void cart() {
Intent i = new Intent(getActivity(), Cart.class);
startActivity(i);
}
public class DoLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSuccess = false;
@Override
protected void onPreExecute() {
movieList.clear();
templist.clear();
}
@Override
protected void onPostExecute(String r) {
if(isSuccess) {
updatelist();
Vibrator v = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(500);
}
else{
Toast.makeText(getActivity(),z,Toast.LENGTH_SHORT).show();
}
}
@Override
protected String doInBackground(String... params) {
try {
Connection con = connectionClass.CONN ();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "select * from [dbo].[MainMenuDetail] WHERE Delete_category = 0 AND Pi_Category_ID ='"+tabselected+"'" ;
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
movie = new Movie();
movie.setId(rs.getString("ID"));
movie.setItemname(rs.getString("Category_ItemName"));
movie.setDescription(rs.getString("Category_SHortDesc"));
movie.setPrice(rs.getString("Category_Price"));
image_url2=rs.getString("show_Image");
String img= image_url+image_url2;
movie.setThumbnailUrl(img);
update();
}
z = "Successful";
isSuccess=true;
}
}
catch (Exception ex)
{
isSuccess = false;
z = "Exceptions";
}
return z;
}
}
public void updatelist(){
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
movieList.addAll(templist);
adapter.notifyDataSetChanged();
}
});
}
public void refreshlist(){
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
adapter.notifyDataSetChanged();
}
}); }
public void vacatelist(){
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
movieList.clear();
}
});
}
public void update(){
templist.add(movie);
}
}
答案 0 :(得分:0)
你可以试试这个
@Override
public void onTabSelected(TabLayout.Tab tab) {
CharSequence numTab = tab.getTag().toString();
SharedPreferences preferences2 = getSharedPreferences("AUTHENTICATION_FILE_NAME2", Context.MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor2 = preferences2.edit();
editor2.putString("tabselected",numTab.toString());
editor2.putString("Authentication_Status", "true");
editor2.apply();
// super called last
super.onTabSelected(tab);
}
或存储ViewPagerAdapter adapter
&#34;全球&#34;在ScrollableTabsActivity
之上(不仅仅在setupViewPager
方法内)
ViewPagerAdapter adapter;
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager());
//rest of your code
}
然后
@Override
public void onTabSelected(TabLayout.Tab tab) {
// your current code
adapter.notifyDataSetChanged(); //ViewPagerAdapter's adapter
}
答案 1 :(得分:0)
对于此问题,可能有几种解决方法
1。)如果数据少,标签少并且可以增加,则一次加载所有数据
viewPager.setOffscreenPageLimit(noOfTabs);
2。)在用户可见后更新您的片段。
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser){
// load data
}
}
希望会有所帮助。