2016-07-13 10 views
2

MainActivityでビューページがスワイプしたときにビューページのフリーグを更新しようとしています。MainActivityでビューページがスワイプしたときのビューページの内容を更新する方法

MenuActivity: -

package jbit.kanha; 

import android.app.AlertDialog; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.database.Cursor; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.os.Bundle; 
import android.support.design.widget.TabLayout; 
import android.support.v4.app.Fragment; 
import android.support.v4.app.FragmentActivity; 
import android.support.v4.app.FragmentTransaction; 
import android.support.v4.view.ViewPager; 
import android.util.Log; 
import android.view.View; 
import android.widget.ImageView; 
import android.widget.ListView; 
import android.widget.RelativeLayout; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.koushikdutta.async.future.FutureCallback; 
import com.koushikdutta.ion.Ion; 
import com.romainpiel.shimmer.Shimmer; 
import com.romainpiel.shimmer.ShimmerTextView; 

import org.json.JSONArray; 
import org.json.JSONObject; 

import jbit.kanha.AllAdepters.SideMenuAdapter; 
import jbit.kanha.InternetConection.CheckInternetConection; 
import jbit.kanha.InternetConection.ConnectionDetector; 
import jbit.kanha.InternetConection.InternetDialoge; 
import jbit.kanha.ProgressDialog.MyProgressDialog; 
import jbit.kanha.SideMenuClasses.MyProfile; 
import jbit.kanha.db.Database; 

public class MenuActivity extends FragmentActivity implements View.OnClickListener{ 

    public static ResideMenu resideMenu; 
    private MenuActivity mContext; 
    private ResideMenuItem itemHome; 
    private ResideMenuItem itemProfile; 
    private ResideMenuItem itemCalendar; 
    private ResideMenuItem itemSettings; 
    SharedPreferences loginPreferences; 
    private SharedPreferences pref; 
    ImageView profile_image; 
    public static TextView title_bar_right_menu,txt_total_rate; 
    Database database; 
    JSONArray categoryItem; 
    // private PagerSlidingTabStrip tabLayout; 
    private TabLayout tabLayout; 
    ViewPager pager; 
    private ConnectionDetector connectionDetector; 
    private MyProgressDialog dialog; 
    ViewPagerAdapter adapter; 

    OneFregment fregment; 
// private int currentColor = Color.parseColor("#1D569B"); 
    // PagerSlidingTabStrip tabStrip; 
    /** 
    * Called when the activity is first created. 
    */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     mContext = this; 
     database = new Database(MenuActivity.this); 
     tabLayout= (TabLayout)findViewById(R.id.tabs); 

     pager = (ViewPager)findViewById(R.id.pager); 
     loginPreferences = getSharedPreferences("loginPrefs", Context.MODE_PRIVATE); 
     connectionDetector = new ConnectionDetector(mContext); 
     dialog = new MyProgressDialog(mContext); 
     adapter = new ViewPagerAdapter(getSupportFragmentManager()); 
     if (connectionDetector.isConnectingToInternet()){ 
      getCategoryName(); 
     }else{ 
      Toast.makeText(mContext, "No Internet Connection", Toast.LENGTH_SHORT).show(); 
     } 
     title_bar_right_menu = (TextView) findViewById(R.id.title_bar_right_menu); 
     txt_total_rate = (TextView) findViewById(R.id.txt_total_rate); 

     pref = getApplicationContext().getSharedPreferences("loginPrefs", MODE_PRIVATE); 
     Cursor cursor1 = database.getData("SELECT * FROM cart"); 
     int count = cursor1.getCount(); 
     cursor1.close(); 
     title_bar_right_menu.setText(count+""); 

     setUpMenu(); 


     pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { 
      @Override 
      public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { 

      } 

      @Override 
      public void onPageSelected(int position) { 
       getCategoryDataRefresh(position); 

      } 

      @Override 
      public void onPageScrollStateChanged(int state) { 

      } 
     }); 

    } 


    private void getCategoryData(final int postion){ 
     Ion.with(mContext) 
       .load(getResources().getString(R.string.api_main_url) + "categoryoriginal.php") 
       .setTimeout(30*1000) 
       .setBodyParameter("outlet_id",loginPreferences.getString("outlet_id","")) 
       .setBodyParameter("catid",String.valueOf(postion+1)) 
       .asString().setCallback(new FutureCallback<String>() { 
      @Override 
      public void onCompleted(Exception e, String result) { 
       dialog.hide(); 
       if (e != null) { 
        e.printStackTrace(); 
        DialogsClassTwoData(mContext, "Connection Timed Out!", "Message...",postion).show(); 
       } 
       if (result != null) { 
        try { 
         Log.d("name",result); 
         JSONObject mainJson = new JSONObject(result); 
         String status = mainJson.getString("status"); 
         if(status.equals("Success")){ 
          JSONArray jsonArray = mainJson.getJSONArray("data"); 
          setUpViewPager(pager,categoryItem,jsonArray); 
         } 
        }catch (Exception ex) { 
         ex.printStackTrace(); 
         Log.d("exaption", ex.toString()); 

        } 
       } else { 
        Log.d("exaption", e.toString()); 
       } 
      } 
     }); 

    } 
    private void getCategoryDataRefresh(final int postion){ 
     dialog.show(); 
     Ion.with(mContext) 
       .load(getResources().getString(R.string.api_main_url) + "categoryoriginal.php") 
       .setTimeout(30*1000) 
       .setBodyParameter("outlet_id",loginPreferences.getString("outlet_id","")) 
       .setBodyParameter("catid",String.valueOf(postion+1)) 
       .asString().setCallback(new FutureCallback<String>() { 
      @Override 
      public void onCompleted(Exception e, String result) { 
       dialog.hide(); 
       if (e != null) { 
        e.printStackTrace(); 
        DialogsClassTwoData(mContext, "Connection Timed Out!", "Message...",postion).show(); 
       } 
       if (result != null) { 
        try { 
         Log.d("name",result); 
         JSONObject mainJson = new JSONObject(result); 
         String status = mainJson.getString("status"); 
         if(status.equals("Success")){ 

          Fragment frg = null; 
          frg = new OneFregment(mainJson.getJSONArray("data")); 
          final FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); 
          ft.detach(frg); 
          ft.attach(frg); 
          ft.commit(); 
         } 
        }catch (Exception ex) { 
         ex.printStackTrace(); 
         Log.d("exaption", ex.toString()); 

        } 
       } else { 
        Log.d("exaption", e.toString()); 
       } 
      } 
     }); 

    } 

    private void getCategoryName(){ 
     dialog.show(); 
     Ion.with(mContext) 
       .load(getResources().getString(R.string.api_main_url) + "categoryname.php") 
       .setTimeout(30*1000) 
       .asString().setCallback(new FutureCallback<String>() { 
      @Override 
      public void onCompleted(Exception e, String result) { 
       // dialog.hide(); 
       if (e != null) { 
        e.printStackTrace(); 
        DialogsClassTwo(mContext, "Connection Timed Out!", "Message...").show(); 
       } 
       if (result != null) { 
        try { 
         Log.d("name",result); 
         JSONObject mainJson = new JSONObject(result); 
         String status = mainJson.getString("status"); 
         if(status.equals("Success")){ 
          JSONObject jsonObject = mainJson.getJSONObject("data"); 
          categoryItem = jsonObject.getJSONArray("items"); 

//       setUpViewPager(pager,jsonObject.getJSONArray("items")); 
          Log.d("json",jsonObject+""); 

          getCategoryData(0); 
          //data = jsonObject.getJSONArray("items"); 
          /* for(int i=0;i<data.length();i++){ 
           JSONObject jsonObject1 = data.getJSONObject(i); 
           bigImage.add(jsonObject1.getString("bigimage")); 
          } 
          pager.setAdapter(new CustomPagerAdapter(getActivity(),data)); 
          final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources() 
            .getDisplayMetrics()); 
          pager.setPageMargin(pageMargin); 
          tabs.setViewPager(pager); 
          changeColor(currentColor);*/ 

         } 
        }catch (Exception ex) { 
         ex.printStackTrace(); 
         Log.d("exaption", ex.toString()); 

        } 
       } else { 
        Log.d("exaption", e.toString()); 
       } 
      } 
     }); 
    } 
    private void setUpViewPager(ViewPager pager, JSONArray jsonArray,JSONArray products){ 
     try { 
      // ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); 
      for(int i=0;i<jsonArray.length();i++){ 
       JSONObject jsonObject = jsonArray.getJSONObject(i); 
       adapter.addFrag(new OneFregment(products),jsonObject.getString("categoryname")); 
      } 
      pager.setAdapter(adapter); 
      tabLayout.setupWithViewPager(pager); 
      // tabLayout.tabSelectedTextColor 
      // getCategoryData(); 
     } 
     catch (Exception e) { 
      Log.e("error", e.getMessage()); 
     } 
    } 

    public AlertDialog.Builder DialogsClassTwo(Context cxt, final String message, String title){ 
     return new AlertDialog.Builder(cxt).setTitle(title).setMessage(message).setPositiveButton("Try Again", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialogs, int which) { 
       // here you can add functions 
       if (CheckInternetConection.isInternetConnection(mContext.getApplicationContext())){ 
         getCategoryName(); 
        // getCategoryData(); 
       }else{ 
        InternetDialoge.showDialogFinishActivity(
          "Internet Connection Failed!", "connection error", mContext); 
       } 
      } 
     }); 
    } 
    public AlertDialog.Builder DialogsClassTwoData(Context cxt, final String message, String title, final int postion){ 
     return new AlertDialog.Builder(cxt).setTitle(title).setMessage(message).setPositiveButton("Try Again", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialogs, int which) { 
       // here you can add functions 
       if (CheckInternetConection.isInternetConnection(mContext.getApplicationContext())){ 
        //getCategoryName(); 
        getCategoryData(postion); 
       }else{ 
        InternetDialoge.showDialogFinishActivity(
          "Internet Connection Failed!", "connection error", mContext); 
       } 
      } 
     }); 
    } 

    private void setUpMenu() { 
     resideMenu = new ResideMenu(MenuActivity.this, R.layout.side_menu, R.layout.home); 
     //resideMenu.setBackground(Color.parseColor("#FAA514"));//FAA514 
     resideMenu.setBackground(R.drawable.slider_background); 
     resideMenu.attachToActivity(MenuActivity.this); 
     resideMenu.setScaleValue(0.5f); 
     View leftMenu = resideMenu.getLeftMenuView(); 
     Shimmer shimmer = new Shimmer();//#faebd7 
     shimmer.setDuration(3000) 
       .setStartDelay(500) 
       .setDirection(Shimmer.ANIMATION_DIRECTION_LTR); 
     ShimmerTextView powered = (ShimmerTextView)leftMenu.findViewById(R.id.powered); 
     ListView list = (ListView) leftMenu.findViewById(R.id.list1); 
     list.setAdapter(new SideMenuAdapter(MenuActivity.this)); 
     profile_image = (ImageView) leftMenu.findViewById(R.id.profile_image); 
     TextView title1 = (TextView) leftMenu.findViewById(R.id.title1); 
     TextView loction1 = (TextView) leftMenu.findViewById(R.id.loction1); 
     ImageView location_icon =(ImageView) leftMenu.findViewById(R.id.location_icon); 
     RelativeLayout ll_checkout = (RelativeLayout) findViewById(R.id.ll_checkout); 
     //loginPreferences = getSharedPreferences("loginPrefs", Context.MODE_PRIVATE); 
     title1.setText(loginPreferences.getString("fullname","")); 
     loction1.setText(loginPreferences.getString("address","")); 
     // if(!loginPreferences.getString("profileimage","").equals("")){ 
     /*  Picasso.with(MenuActivity.this) 
        .load(loginPreferences.getString("profileimage","")) 
        .error(R.drawable.images) 
        .placeholder(R.drawable.progress_animation) 
        .into(profile_image);*/ 
     // File file = new File("/main_json/main_json/com.example.w.lazymojo/app_imageDir/profile.jpg"); 

     shimmer.start(powered); 
     if(pref.getString("User_id", "").equals("")){ 
      profile_image.setImageResource(R.drawable.images); 
      location_icon.setVisibility(View.INVISIBLE); 
     } 
     else { 
      Bitmap bitmap1 = BitmapFactory.decodeFile("/data/data/jbit.kanha/app_imageDir/profile.jpg"); 
      if(bitmap1!=null){ 
       Log.d("MenuActivity:-","image not null"); 
       profile_image.setImageBitmap(bitmap1); 
       // Picasso.with(MenuActivity.this).load(file).resize(dpToPx(96),dpToPx(96)).centerCrop().into(profile_image); 
      } 
      else { 
       Log.d("MenuActivity:-","image is null"); 
       profile_image.setImageResource(R.drawable.images); 
      } 
     } 

     profile_image.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       if(pref.getString("User_id", "").equals("")){ 
        profile_image.setImageResource(R.drawable.images); 
        new AlertDialog.Builder(MenuActivity.this).setTitle("Login").setMessage("You have to login first").setPositiveButton("Login", new DialogInterface.OnClickListener() { 
         @Override 
         public void onClick(DialogInterface dialog, int which) { 
          Intent in = new Intent(MenuActivity.this,LoginActivity.class); 
          startActivity(in); 
         } 
        }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
         @Override 
         public void onClick(DialogInterface dialog, int which) { 
          dialog.dismiss(); 
         } 
        }).show(); 
       } 
       else { 
        Intent i = new Intent(MenuActivity.this, MyProfile.class); 
        startActivity(i); 
       } 
      } 
     }); 

     //  } 
     ll_checkout.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       if(!pref.getString("User_id", "").equals("")){ 
        Intent i = new Intent(MenuActivity.this,MyCart.class); 
        startActivity(i); 
        finish(); 
       } 
       else 
       { 
        new AlertDialog.Builder(MenuActivity.this).setTitle("Login").setMessage("You must login first").setPositiveButton("Login", new DialogInterface.OnClickListener() { 
         @Override 
         public void onClick(DialogInterface dialog, int which) { 
          Intent intent = new Intent(MenuActivity.this,LoginActivity.class); 
          startActivity(intent); 
         } 
        }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
         @Override 
         public void onClick(DialogInterface dialog, int which) { 
          dialog.dismiss(); 
         } 
        }).show(); 
       } 
      } 
     }); 
     resideMenu.setSwipeDirectionDisable(ResideMenu.DIRECTION_RIGHT); 
     resideMenu.setSwipeDirectionDisable(ResideMenu.DIRECTION_LEFT); 
     findViewById(R.id.title_bar_left_menu).setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       resideMenu.openMenu(ResideMenu.DIRECTION_LEFT); 
      } 
     }); 
     findViewById(R.id.cart_img).setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       if(!pref.getString("User_id", "").equals("")){ 
        Intent i = new Intent(MenuActivity.this,MyCart.class); 
        startActivity(i); 
        finish(); 
       } 
       else 
       { 
        new AlertDialog.Builder(MenuActivity.this).setTitle("Login").setMessage("You must login first").setPositiveButton("Login", new DialogInterface.OnClickListener() { 
         @Override 
         public void onClick(DialogInterface dialog, int which) { 
          Intent intent = new Intent(MenuActivity.this,LoginActivity.class); 
          startActivity(intent); 
         } 
        }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
         @Override 
         public void onClick(DialogInterface dialog, int which) { 
          dialog.dismiss(); 
         } 
        }).show(); 
       } 
       // resideMenu.openMenu(ResideMenu.DIRECTION_RIGHT); 
      } 
     }); 
    } 


    @Override 
    public void onClick(View view) { 
     resideMenu.closeMenu(); 
    } 

    private ResideMenu.OnMenuListener menuListener = new ResideMenu.OnMenuListener() { 
     @Override 
     public void openMenu() { 
      // Toast.makeText(mContext, "Menu is opened!", Toast.LENGTH_SHORT).show(); 
     } 

     @Override 
     public void closeMenu() { 
      //Toast.makeText(mContext, "Menu is closed!", Toast.LENGTH_SHORT).show(); 
     } 
    }; 

    // What good method is to access resideMenu? 
    public ResideMenu getResideMenu(){ 
     return resideMenu; 
    } 


    @Override 
    protected void onResume() { 
     super.onResume(); 
    } 

    @Override 
    public void onBackPressed() { 
     super.onBackPressed(); 
     finish(); 
     moveTaskToBack(true); 
    } 
} 

ViewPagerAdapter.java:

class ViewPagerAdapter extends FragmentPagerAdapter { 

    private final List<Fragment> mFragmentList = new ArrayList<>(); 
    private final List<String> mFragmentTitleList = 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) { 
      mFragmentList.add(fragment); 
      mFragmentTitleList.add(title); 
      } 

    @Override 
    public int getItemPosition(Object object) { 

     return POSITION_NONE; 
    } 

    @Override 
    public CharSequence getPageTitle(int position) { 
      return mFragmentTitleList.get(position); 
      } 
} 

OneFregement: -

public class OneFregment extends Fragment { 


    JSONArray jsonArray; 
    ListView listView; 
    HomeLiatAdapter adapter; 

    public OneFregment() { 
     // Required empty public constructor 
    } 

    @SuppressLint("ValidFragment") 
    public OneFregment(JSONArray jsonArray){ 
     this.jsonArray = jsonArray; 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     View v = inflater.inflate(R.layout.home_child_layout, container, false); 

     listView = (ListView) v.findViewById(R.id.list); 

     try { 
      JSONObject obj = jsonArray.getJSONObject(0); 
      adapter = new HomeLiatAdapter(getContext(),obj.getJSONArray("items"),obj.getString("bigimage")); 
      listView.setAdapter(adapter); 

     }catch (Exception e){ 
      e.printStackTrace(); 
     } 


     return v; 
    } 

    /* public void update(){ 
     try { 
      JSONObject obj = jsonArray.getJSONObject(0); 
      adapter = new HomeLiatAdapter(getContext(),obj.getJSONArray("items"),obj.getString("bigimage")); 
      listView.setAdapter(adapter); 

     }catch (Exception e){ 
      e.printStackTrace(); 
     } 
    }*/ 
} 

私はこれを行うしていますが、作成しようとも前のdata.I示しfregmentですfregmentクラスのupdateメソッドはすべてwainです。

私はAndroidで新しく開発中の私を助けてください。前もって感謝します。

+0

あなたのviewPagerAdapterには、メソッド名getItemPositionがあり、position_none ..を返します。これは、あるフラグメントを別のフラグメントにスワイプしたときにあなたのviewPagerが更新されることを意味します。だからあなたの次の問題は何か... –

答えて

1

カスタムインターフェイスを作成し、各フラグメントに実装する必要があります。そして、onpagechangelistenerにあなたはそれらのメソッドを呼び出さなければなりません。

check this詳細については、私のプロジェクトでも、断片的なライフサイクルが必要に応じて機能しないようにフラグメントを更新するように実装する必要がありました。あなたがスワイプすると、ビューページャがフラグメントを追加して保持するためです。

+0

私はfregment dynamicを追加し、指定したリンクは開かれていません。だからもっと説明してください。 –

+0

このURLを試すhttps://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjb-eW40u_NAhWCr48KHc8qBkIQFggcMAA&url=https%3A%2F%2Flooksok.wordpressコム%の2F2013の%2F11%2F02%2Fviewpager-と-詳細なフラグメント・ライフサイクル・onresumefragment-を含むソース・コード%2F&あなたがそんなにあなたが火格子の開発者であるUSG = AFQjCNFcLlfqi_zld8l8ZDpgrPcLFRV2VA&SIG2 = EYuZa3MUXNaqjeCMInwbEA&BVM = bv.126993452、d.c2I –

+0

感謝。 –

関連する問題