Я хочу создать фрагмент, который динамически добавляется и удаляется вкладки на основе длины массива JSON.Но это покажет ошибку в методе getTabAt ().Пожалуйста, помогите мне.Заранее спасибо.Вот мой код:
MainActivity.java
class MainActivity extends AppCompatActivity{
@Override
public void onCreate(){
productViewPager = findViewById(R.id.productPage_viewPager);
unitTab = findViewById(R.id.recycler_tab_layout);
productViewPager.addOnPageChangeenter code hereListener(new
ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
highLightCurrentTab(position);
/*System.out.println(tabLayout.getTag().toString());*/
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
productPageFragment = new ProductPageFragment();
adapterProductPageFragment = new
AdapterProductPageFragment(getSupportFragmentManager(), this);
new getQuantity().execute("");
}
class getQuantity extends AsyncTask<String, String, String> {
String str = null;
String splitCatagory = null;
@Override
protected void onPreExecute() {
super.onPreExecute(); }
@Override
protected String doInBackground(String... strings) {
splitCatagory = strings[0];
String[] SpliCatagory = splitCatagory.split("%26");
if (SpliCatagory.length > 1) {
str = SpliCatagory[0] + "&" + SpliCatagory[1];
} else {
str = strings[0];
}
String data1 = "";
OkHttpClient client = new OkHttpClient();
String s = new String();
orderid=" + strings[0];
Request request1 = new Request.Builder()
.url(data1)
.get()
.build();
try {
Response response = client.newCall(request1).execute();
//s = response.body().string();
s = "{\"individualProduct_details\":
[{\ "product_discount_range_per_tranch_2 \": \ "0.2 \", \ "total_product_quantity_for_deal \": \ "0.0 \", \ "product_discount_range_per_tranch_1 \": \ "0.1 \", \" product_inventory_details \ ": \" 40 \ ", \" product_key_features \ ": \" Без сахара 1 кг \ ", \" product_level_community_upper_cut_off \ ": \" 20 \ ", \" product_discount_range_per_tranch_3 \ ": \" 0.3\ ", \" product_mrp \ ": \" 70.0 \ ", \" tranch1_product_price \ ": \" 65.14 \ ", \" product_selling_quantity_community_tranch_1 \ ": \" 10 \ ", \" product_quantity \ ": \" 1 КГ \", \" product_selling_quantity_community_tranch_2 \ ": \" 15 \ ", \" product_selling_quantity_community_tranch_3 \ ": \" 20 \ ", \" product_sku \ ": \" Без сахара \ ", \" product_per_day_price_discount \ ": \" 0.2 ", \ "product_subcategory \": \ "Salt Sugar and Jaggery \", \ "product_id \": \ "51 \", \ "product_availability \": \ "Available \", \ "product_level_upper_cut_off \": \ "3 \", \" product_description \ ": \" Без сахара 1 кг \ ", \" tranch1_order_count \ ": 0, \" tranch2_order_count \ ": 0, \" product_demand_heatmap \ ": \" 1 \ ", \" product_per_quantity_percent_price_drop \ ": \" 0,1 \ "\ "tranch2_product_price \": \ "65,08 \", \ "product_selling_price \": \ "66,0 \", \ "product_purchase_price \": \ "60,0 \", \" product_deal_price \": \" 65,21 \ "\ "product_purchase_percent \": \ "30 \", \ "image_id \": \" 9,10,12,13,16,17,18,19,20,21,22 \", \" product_category \ ": \" Бакалея и скобы \ "}, \ n" + "\ n" + "{\" product_discount_range_per_tranch_2 \ ": \" 0.2 \ ", \" image_id \ ": \" \ ", \ "total_product_quantity_for_deal \": \ "0.0 \", \ "product_discount_range_per_tranch_1 \": \ "0.1 \", \ "product_inventory_details \": \ "10 \", \ "product_key_features \": \ "Без сахара 2,5 кг», \ "product_level_community_upper_cut_off \": \ "20 \", \ "product_discount_range_per_tranch_3 \": \ "0,3 \", \ "product_mrp \": \ "140,0 \", \ "tranch1_product_price \": \ "128,31 \",\ "product_selling_quantity_community_tranch_1 \": \ "10 \", \ "product_quantity \": \ "2.5 KG \", \ "product_selling_quantity_community_tranch_2 \": \ "15 \", \ "product_selling_quantity_community_tranch_3 \", "\", \ ":"product_sku \": \ "Sugar Free \", \ "product_per_day_price_discount \": \ "0.2 \", \ "product_subcategory \": \ "Salt Sugar and Jaggery \", \ "product_id \": \ "52 \", \ "product_availability \": \ "Available \", \ "product_level_upper_cut_off \": \ "2 \", \ "product_description \"": \" Без сахара 2,5 кг \ ", \" tranch1_order_count \ ": 0, \" tranch2_order_count \ ": 0, \" product_demand_heatmap \ ": \" 2 \ ", \" product_per_quantity_percent_price_drop \ ": \" 0.1 \ "\ "tranch2_product_price \": \ "128,18 \", \ "product_selling_price \": \ "130,0 \", \ "product_purchase_price \": \ "120,0 \", \ "product_deal_price \": \ "128,44 \", \"product_purchase_percent \": \ "55 \", \ "product_category \": \ "Бакалея и скобы \"}]} \ n ";Log.e («ПРОДУКТЫ ----», s);} catch (IOException e) {e.printStackTrace ();
}
return s;
}
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject object = new JSONObject(s);
JSONArray array =
object.getJSONArray("individualProduct_details");
arrayLength = array.length();
prod_quantity=new String[array.length()];
for (int i = 0; i < array.length(); i++) {
JSONObject item = array.getJSONObject(i);
String product_sku = item.getString("product_sku");
String product_quantity = item.getString("product_id");
String product_id = item.getString("product_id");
prod_quantity[i] = item.getString("product_id");
}
}catch (JSONException e1) {
e1.printStackTrace();
}
for (int i = 0; i < prod_quantity.length; i++) {
adapterProductPageFragment.addFragment(productPageFragment.newInstance
(i, prod_quantity [i]), prod_quantity [i]);}
productViewPager.setAdapter(adapterProductPageFragment);
unitTab.setupWithViewPager(productViewPager);
highLightCurrentTab(0);
}
}
private void highLightCurrentTab(int position) {
productPageFragment.newInstance(position,
adapterProductPageFragment.getPageTitle(position).toString());
TabLayout.Tab tab=new TabLayout.Tab();
for (int i = 0; i < unitTab.getTabCount(); i++) {
System.out.println("In for loop------------");
tab = unitTab.getTabAt(i);
assert tab != null;
tab.setCustomView(null);
tab.setCustomView(adapterProductPageFragment.getTabView(i));
}
tab = unitTab.getTabAt(position);
assert tab != null;
tab.setCustomView(null);
tab.setCustomView(
adapterProductPageFragment.getSelectedTabView(position));
}
ProductPageFragment.java
public class ProductPageFragment extends Fragment {
public ProductPageFragment() {
// Required empty public constructor
}
public static ProductPageFragment newInstance(int position,String
title) {
ProductPageFragment fragment = new ProductPageFragment();
Bundle args = new Bundle();
args.putInt("position", position);
args.putString("title", title);
System.out.println("Position and string"+position+"----"+title);
fragment.setArguments(args);
return fragment;
}
FragmentOfProducts.onClickListner monClickListner;
@Override
public void onAttach(Context context) {
super.onAttach(context);
monClickListner=(FragmentOfProducts.onClickListner) context;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
/*position = getArguments().getInt("position");*/
selectedTabTitle=getArguments().getString("title");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_product_page, container,
false);
return v;
}
AdapterProductPageFragment.java
public class AdapterProductPageFragment extends FragmentStatePagerAdapter
{
int noOfTabs;
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
private Context context;
public AdapterProductPageFragment(FragmentManager fm,Context context) {
super(fm);
this.context=context;
}
@Override
public int getCount() {
return noOfTabs;
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
public void addFragment(Fragment fragment, String title) {
/*Tab1Fragment.newInstance(title,"0");*/
System.out.println("Add fragment"+fragment.getTag()+"---"+title);
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
public View getTabView(int position) {
View view =
LayoutInflater.from(context).inflate(R.layout.layout_for_unit_sku,
null);
TextView tabTextView = view.findViewById(R.id.txt_unit);
tabTextView.setText(mFragmentTitleList.get(position));
tabTextView.setTextColor(ContextCompat.getColor(context,
R.color.whitetabs));
tabTextView.setTypeface(custom_of_alegreyasans_regular);
return view;
}
public View getSelectedTabView(int position) {
View view =
LayoutInflater.from(context).inflate(R.layout.layout_for_unit_sku,
null);
TextView tabTextView = view.findViewById(R.id.txt_unit);
tabTextView.setText(mFragmentTitleList.get(position));
tabTextView.setTextColor(ContextCompat.getColor(context,
R.color.white));
tabTextView.setTypeface(custom_of_alegreyasans_bold);
return view;
}
}
tab.setCustomView(null); at this line shows error in main activity.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: in.co.algotech.jars, PID: 9327
java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.design.widget.TabLayout$Tab android.support.design.widget.TabLayout$Tab.setCustomView(android.view.View)' on a null object reference
at in.co.algotech.jars.Home.ProductCardView.highLightCurrentTab)
at in.co.algotech.jars.Home.ProductCardView.access$000
at in.co.algotech.jars.Home.ProductCardView$getQuantity.onPostExecute
at in.co.algotech.jars.Home.ProductCardView$getQuantity.onPostExecute
at android.os.AsyncTask.finish(AsyncTask.java:695)
at android.os.AsyncTask.access$600(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7156)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)