hello i have this Json Data a link
and i parsing it like that
when i click into the image i want to parsing the JsonArray for the image to piccaso in recycler view but i got all image in the Json like that
for example if i click in "emo" i wont just image for "emo" not for all images !
any idea ?
this is my module :
public class AppShowModule
{
private List<String> Allimage = new ArrayList<String>();
public List<String> getAllimage() {
return Allimage;}
public void setAllimage(List<String> allimage) {
Allimage = allimage;}
this is my Fragment
public class ImageListFragment extends Fragment {
List<AppShowModule> appShowModules;
List<AppShowModule> imagesModule;
RecyclerView AppRecyclerView;
RecyclerView.Adapter imageRecyclerViewadapter;
List<String> imageUrls;
String feedKey = "feed";
String entryKey = "entry";
String imageKey = "im:image";
String labelKey = "label";
String jsonUrl = "https://itunes.apple.com/jo/rss/topfreeapplications/limit=50/json";
RequestQueue requestQueue;
private RecyclerView.LayoutManager mLayoutManager;
public ImageListFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_image_list, container, false);
}
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
AppRecyclerView = (RecyclerView) getView().findViewById(R.id.imageRecyclerView);
imagesModule = new ArrayList<>();
appShowModules = new ArrayList<>();
imageUrls = new ArrayList<>();
JsonAppShowData();
}
public void JsonAppShowData() {
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( jsonUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONObject(feedKey).getJSONArray( entryKey );
AppShowModule appShowModule = new AppShowModule();
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray imageArray = response.getJSONObject(feedKey).getJSONArray(entryKey).getJSONObject(i).getJSONArray(imageKey);
for (int j = 0; j < imageArray.length(); j++) {
String image = imageArray.getJSONObject(j).getString(labelKey).toString();
imageUrls.add(image);
appShowModule.setAllimage(imageUrls);
appShowModules.add(appShowModule);}}
imageRecyclerViewadapter = new ImageListAdapter(appShowModules,getContext(),imageUrls);
AppRecyclerView.setAdapter(imageRecyclerViewadapter);
} catch (JSONException e) {
e.printStackTrace();
}}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e( "LOG", error.toString() );
}
} );
requestQueue = Volley.newRequestQueue( getContext() );
requestQueue.add(jsonObjectRequest);
mLayoutManager = new GridLayoutManager( getContext().getApplicationContext(),3);
AppRecyclerView.setLayoutManager(mLayoutManager); }}
and this is the Recycler adapter
public class ImageListAdapter extends RecyclerView.Adapter<ImageListAdapter.ViewHolder> {
List<AppShowModule> appShowModules;
List<String> imageUrl;
Context context;
public ImageListAdapter(List<AppShowModule> appShowModules, Context context ,List<String>imageUrls
){
super();
this.imageUrl =imageUrls;
this.appShowModules = appShowModules;
this.context = context;}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from( parent.getContext() ).inflate( R.layout.imagelayout, parent,false );
ViewHolder viewHolder = new ViewHolder( v );
return viewHolder;}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Picasso.with(context).load(imageUrl.get(position)).into(holder.appImage);
}
public int getItemCount() {
return imageUrl.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView appImage;
public ViewHolder(View itemView) {
super(itemView);
appImage = (ImageView) itemView.findViewById( R.id.appImage);
}}}
and this is the activity that have the image view where click
public class ListViewDetailsFragment extends Fragment {
ImageView AppImage;
TextView AppName,AppArtist,AppContentType,AppRights,AppCategory,AppRealseDate,AppSammary;
ImageButton AppLink;
Context context;
public ListViewDetailsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_list_view_details, container, false);}
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
AppImage = (ImageView) getView().findViewById(R.id.imageView);
AppName = (TextView) getView().findViewById(R.id.textname);
AppArtist = (TextView) getView().findViewById(R.id.textartest);
AppContentType = (TextView) getView().findViewById(R.id.textcontent);
AppRights = (TextView) getView().findViewById(R.id.textrights);
AppCategory = (TextView) getView().findViewById(R.id.textCategory);
AppRealseDate = (TextView) getView().findViewById(R.id.textRelease);
AppSammary = (TextView) getView().findViewById(R.id.textSummary);
AppLink = (ImageButton) getView().findViewById(R.id.imageButton);
String name = getActivity().getIntent().getExtras().getString("App_name");
final String image = getActivity().getIntent().getExtras().getString("App_image");
String artist = getActivity().getIntent().getExtras().getString("App_artist");
String contentType = getActivity().getIntent().getExtras().getString("App_ContentType");
String rights = getActivity().getIntent().getExtras().getString("App_Rights");
String category = getActivity().getIntent().getExtras().getString("App_Category");
String realse = getActivity().getIntent().getExtras().getString("App_ReleaseDate");
final String link = getActivity().getIntent().getExtras().getString("App_link");
String sammary = getActivity().getIntent().getExtras().getString("App_summary");
AppName.setText(name);
AppArtist.setText(artist);
AppContentType.setText(contentType);
AppRights.setText(rights);
AppCategory.setText(category);
AppRealseDate.setText(realse);
AppSammary.setText(sammary);
Picasso.with(context).load(image).into(AppImage);
AppLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity().getBaseContext(),
WebView.class);
intent.putExtra("App_link", link);
getActivity().startActivity(intent);}});
AppImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String id = (String) view.getTag();
Intent intent = new Intent(getActivity().getBaseContext(), ImageList.class);
intent.putExtra("id", id);
getActivity().startActivity(intent);
}});}}
If you see the JSON properly, there are three types of images with differenct heights i.e. small, medium and large inside im:image.
You need only one not all three.
You have to change below code in your ImageListFragment inside JsonAppShowData() method.
AppShowModule appShowModule = new AppShowModule();
for (int i = 0; i < jsonArray.length(); i++) {
String image = response.getJSONObject(feedKey).getJSONArray(entryKey)
.getJSONObject(i).getJSONArray(imageKey)
/* this is main change -> */.get(2).getString(labelKey).toString();
imageUrls.add(image);
appShowModule.setAllimage(imageUrls);
appShowModules.add(appShowModule);
}
imageRecyclerViewadapter = new ImageListAdapter(appShowModules, getContext(), imageUrls);
Hope it helps you.
sample json: https://jsonblob.com/57d5cff8e4b0dc55a4f46fa8
Suggestion: You should try using GSON for JSON parsing. It is easy to understand and implement.
Dam, this is weard kind of coding. Anyway.. try to set set scaleType in imageview on your xml to centerInside, center, matrix or what ever it fits.
Related
I am trying to pass data Adapter class to TabView Layout. I have used fragment in tab. I want to pass data from adapter to fragment (fragment class for tab).
________________________________________Adapter Class________________________________________________
package com.livediscount.restaurants.Adapter;
public class LiveContestAdapter extends RecyclerView.Adapter<LiveContestAdapter.MyViewHolder> {
Context context;
List<Contest_Data> contest_data;
public LiveContestAdapter(Context context, List<Contest_Data> contest_data) {
this.context=context;
this.contest_data=contest_data;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
context=viewGroup.getContext();
View vh= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.custom_list_win_iphone,viewGroup,false);
MyViewHolder myViewHolder=new MyViewHolder(vh);
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull final LiveContestAdapter.MyViewHolder myViewHolder, final int i) {
final Contest_Data contest_position = contest_data.get(i);
Picasso.with(context).load(contest_data.get(i).getContestImage()).error(R.drawable.damme).placeholder(R.drawable.damme).into(myViewHolder.img);
myViewHolder.remainSlot.setText(contest_data.get(i).getContestTotal_slot());
myViewHolder.ent_fee.setText(contest_data.get(i).getContestEntry_Fee());
myViewHolder.Booked_Slot.setText(contest_data.get(i).getContestBooked());
final String contest_status = contest_data.get(i).getContestStatus();
String previous_contest = contest_data.get(i).getPrevious_contest();
String winner_announce = contest_data.get(i).getWinner_announce();
}
#Override
public int getItemCount() {
return contest_data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView name;
ImageView img;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
//name=itemView.findViewById(R.id.totalslot);
img=itemView.findViewById(R.id.imageView2);
htp = itemView.findViewById(R.id.button2);
remainSlot=itemView.findViewById(R.id.tvTotalSlotNumber);
}
}
}
___________________________________________AppCompactActivity______________________________________
public class PrizeBreakup extends AppCompatActivity {
ImageButton back;
TabLayout tabLayout;
ViewPager viewPager;
String contest_id,contest_name;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prize_breakup);
back = findViewById(R.id.back_button);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
tabLayout= findViewById(R.id.tabs);
viewPager = findViewById(R.id.container);
PrizeLayoutAdapter adapter = new PrizeLayoutAdapter(getSupportFragmentManager());
adapter.add(new PrizeLayout(),"Prize Breakup");
adapter.add(new WinnerLayout(),"Winners");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
//here
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("contestid1", "contest_id");
editor.apply();
/* Bundle bundle = getIntent().getExtras();
assert bundle!= null;
contest_id = bundle.getString("contest_id");
contest_name = bundle.getString("contest_name");*/
/* Bundle data = new Bundle();
data.putString("contestid1","contest_id");
Fragment argumentFragment = new PrizeLayout();
argumentFragment.setArguments(data);*/
}
}
_____________________________________PrizeLayout Fragment________________________________________
package com.livediscount.restaurants;
public class PrizeLayout extends Fragment {
List<Contest_Data> contest_data;
LiveContestAdapter live_contest_adapter;
private RecyclerView recyclerView;
TextView ContestId;
public static PrizeLayout newInstance() {
return new PrizeLayout();
}
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.prize_layout, container, false);
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String contestid = getActivity().prefs.getString("contestid1", "contestid not found");
String Contest_id = this.getArguments().getString("edttext");
ContestId= view.findViewById(R.id.referral_code);
ContestId.setText(contestid);
return view;
}
}
________________________________________Winner Fragment______________________________________________
package com.livediscount.restaurants;
public class WinnerLayout extends Fragment {
private List<Winner_data> winner_data=new ArrayList<>();
private RecyclerView recyclerView_winner;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container , Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.winner_layout,container,false);
recyclerView_winner = view.findViewById(R.id.Recyclerview_Winner);
if(winner_data!=null)
{
winner_data.clear();
}
Winner_Data();
return view;
}
private void Winner_Data() {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
String url = ("http://livediscounts.in/webservices/User_interface/Winner_List?contest_id=\"+razorpayPaymentID+\"");
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//progressBar_contest.setVisibility(View.GONE);
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("status").equals("1")) {
JSONArray jsonArray = jsonObject.getJSONArray("records");
/*for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
Winner_data wd = new Winner_data();
cd.setContestId(obj.getString("id"));
cd.setContestName(obj.getString("name"));
cd.setContestImage(obj.getString("prize_1"));
cd.setContestDescription(obj.getString("description"));
cd.setContestType(obj.getString("type"));
cd.setContestEntry_Fee(obj.getString("entry_fee"));
cd.setContestTotal_slot(obj.getString("total_slot"));
cd.setContestTotal_winner(obj.getString("total_winner"));
cd.setContestPrice_Description(obj.getString("price_description"));
cd.setContestPrize_21(obj.getString("prize_21"));
cd.setContestPrize_22(obj.getString("prize_22"));
cd.setContestPrize_31(obj.getString("prize_31"));
cd.setContestPrize_32(obj.getString("prize_32"));
cd.setContestPrize_41(obj.getString("prize_41"));
cd.setContestPrize_42(obj.getString("prize_42"));
cd.setContestPrize_51(obj.getString("prize_51"));
cd.setContestPrize_52(obj.getString("prize_52"));
cd.setContestPrize_61(obj.getString("prize_61"));
cd.setContestPrize_62(obj.getString("prize_62"));
cd.setContestPrize_71(obj.getString("prize_71"));
cd.setContestPrize_72(obj.getString("prize_72"));
cd.setContestStatus(obj.getString("status"));
cd.setContestContest_Note(obj.getString("contest_note"));
cd.setContestStart_date(obj.getString("start_date"));
cd.setContestEnd_date(obj.getString("end_date"));
cd.setContestBooked(obj.getString("booked_slot"));
winner_data.add(wd);
}*/
/*WinnerAdapter winnerAdapter = new WinnerAdapter(getApplicationContext(), winner_data);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView_winner.setLayoutManager(llm);
recyclerView_winner.setAdapter(winnerAdapter);*/
} else {
// Toast.makeText(getApplicationContext(),"Something went Wrong",Toast.LENGTH_SHORT).show();
}
} catch (Exception ex) {
//progressBar_contest.setVisibility(View.GONE);
//Toast.makeText(getApplicationContext(),"No Data Found",Toast.LENGTH_LONG).show(); ex.printStackTrace();
}
}
}
,
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(getApplicationContext(),"No Internet Connection",Toast.LENGTH_LONG).show();
}
}
);
requestQueue.add(request);
}
}
you can use shared pref using parent activity.
How do I set dynamic list in the dynamic fragment, as I filtered data for the list using viewPager onPageSelect position but not able to set in list View due to sequence problem of fetching data?
My sequence is
TabSet>ViewPager with Fragment set>Fragmnet OnCreateView>ViewPager.onPageSelect.
But
I'm getting error of Fragment's adapter.notifyDataChange on a null object reference
Can Anyone help me out?
Here is my code:
public class MainActivity extends AppCompatActivity {
private ViewPager mViewPager;
Activity activity = getParent();
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
private ArrayList<String> catList = new ArrayList<>();
private ArrayList<String> foodItemTitle = new ArrayList<>();
private ArrayList<String> foodItemTitleList = new ArrayList<>();
LinkedHashMap<String, ArrayList<String>> titleHashMap = new LinkedHashMap<>();
LinkedHashMap<String, ArrayList<String>> fullHashMap = new LinkedHashMap<>();
LinkedHashMap<String, ArrayList<String>> halfHashMap = new LinkedHashMap<>();
LinkedHashMap<String, ArrayList<String>> qtrHashMap = new LinkedHashMap<>();
private String category;``
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getItemList();
}
private void setViewIDs() {
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.addOnPageChangeListener(viewPagerPageChangeListener);
setUpViewPager(mViewPager);
tabLayout.setupWithViewPager(mViewPager);
}
private void setUpViewPager(ViewPager viewPager) {
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
for (int i = 0; i < catList.size(); i++) {
Bundle bundle = new Bundle();
bundle.putString("data", catList.get(i));
PlaceholderFragment categoryList = new PlaceholderFragment();
categoryList.setArguments(bundle);
sectionsPagerAdapter.addFragment(categoryList, catList.get(i));
}
sectionsPagerAdapter.notifyDataSetChanged();
viewPager.setAdapter(sectionsPagerAdapter);
}
public void getItemList() {
final ProgressDialog nDialog;
nDialog = new ProgressDialog(this);
nDialog.setMessage("Loading..");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, MENU_ITEM_List, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("DATA");
for (int i = 0; i < jsonArray.length(); i++) {
Model model = new Model();
jsonObject = jsonArray.getJSONObject(i);
model.setItemCategory(jsonObject.getString("CAT"));
model.setItemName(jsonObject.getString("TITLE"));
//Getting Item Menu..................................
if (titleHashMap.get(model.getItemCategory()) != null) {
foodItemTitle = titleHashMap.get(model.getItemCategory());
foodItemTitle.add(model.getItemName());
titleHashMap.put(model.getItemCategory(), foodItemTitle);
} else {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add(model.getItemName());
titleHashMap.put(model.getItemCategory(), arrayList);
}
}
category = titleHashMap.keySet().toString();
String[] cat = category.split(",");
for (int i = 0; i < cat.length; i++) {
String strReplaced = cat[i];
strReplaced = strReplaced.replace("[", "");
strReplaced = strReplaced.replace("]", "");
catList.add(strReplaced);
}
Iterator<String> key = titleHashMap.keySet().iterator();
while (key.hasNext()) {
String hashKey = key.next(); foodItemTitleList.add(titleHashMap.get(hashKey).toString());
}
setViewIDs();
nDialog.dismiss();
} catch (JSONException e) {
System.out.println("Error in code: " + e.getMessage());
nDialog.dismiss();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Time Out", Toast.LENGTH_LONG).show();
nDialog.dismiss();
}
});
RequestQueue requestqueue = Volley.newRequestQueue(this);
requestqueue.add(stringRequest);
}
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
Boolean first = true;
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (first && positionOffset == 0 && positionOffsetPixels == 0) {
onPageSelected(0);
first = false;
}
}
#Override
public void onPageSelected(int position) {
Log.v("TabData", foodItemTitleList.get(position));
String items = foodItemTitleList.get(position);
new PlaceholderFragment().setItemDetails(items);
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private ListView listView;
private ArrayList<Model> dataModelList = new ArrayList<Model>();
private ArrayAdapter<Model> adapter;
private final static String TAG = PlaceholderFragment.class.getSimpleName();
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
listView = (ListView) view.findViewById(R.id.item_list);
// setListViewAdapter();
return view;
}
private void setItemDetails(String item) {
String[] itemStr = item.split(",");
for (int i = 0; i < itemStr.length; i++) {
String oneItem = itemStr[i];
oneItem = oneItem.replace("[", "");
oneItem = oneItem.replace("]", "");
Model model = new Model();
model.setItemTitleFinal(oneItem);
Log.v("GEtdata", oneItem.toString());
dataModelList.add(model);
}
setListViewAdapter();
adapter.notifyDataSetChanged();
}
public void setListViewAdapter() {
dataModelList = new ArrayList<Model>();
adapter = new MenuListAdapter(getActivity(), R.layout.food_item_list, dataModelList);
listView.setAdapter(adapter);
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// Log.v("TabData", foodItemTitleList.get(position));
return mFragmentList.get(position);
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public int getCount() {
return mFragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
Toast.makeText(getApplicationContext(), "CharSequence", Toast.LENGTH_SHORT).show();
switch (position) {
}
return mFragmentTitleList.get(position);
}
}
}
This is my adapter:
public class MenuListAdapter extends ArrayAdapter<Model> {
private Activity activity;
LinkedHashMap<String, ArrayList<String>> fullHashMap = new LinkedHashMap<>();
LinkedHashMap<String, ArrayList<String>> halfHashMap = new LinkedHashMap<>();
LinkedHashMap<String, ArrayList<String>> qtrHashMap = new LinkedHashMap<>();
ArrayList<String> foodItemTitle = new ArrayList<>();
private ArrayList<String> priceFull = new ArrayList<>();
private ArrayList<String> priceHalf = new ArrayList<>();
private ArrayList<String> priceQtr = new ArrayList<>();
private String full;
private String half;
private String qtr;
public MenuListAdapter(Activity activity, int resource, List<Model> dataModelList) {
super(activity, resource, dataModelList);
this.activity = activity;
// getItemList();
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
//If holder not exist then loacte all view from UI file.
if (convertView == null) {
convertView = inflater.inflate(R.layout.food_item_list, parent, false);
holder = new ViewHolder(convertView);
final ImageButton removeBtn = convertView.findViewById(R.id.img_remove);
final ImageButton addBtn = convertView.findViewById(R.id.img_add);
final TextView spinnerItemQuanty = convertView.findViewById(R.id.spinner_item_quantity);
final TextView totalPrice = convertView.findViewById(R.id.total_price);
final TextView item = convertView.findViewById(R.id.item_name);
final ViewHolder finalHolder = holder;
removeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String currentQnty = spinnerItemQuanty.getText().toString().trim();
int qnty = Integer.valueOf(currentQnty);
qnty = qnty - 1;
if (qnty >= 0)
spinnerItemQuanty.setText(String.valueOf(qnty));
}
});
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String currentQnty = spinnerItemQuanty.getText().toString().trim();
int qnty = Integer.valueOf(currentQnty);
spinnerItemQuanty.setText(String.valueOf(qnty + 1));
String title = item.getText().toString();
customPopUp(title);
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Model model = getItem(position);
holder.itemTitle.setText(model.getItemTitleFinal());
return convertView;
}
private void customPopUp(String title) {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View dialogView = inflater.inflate(R.layout.price_popup, null);
dialogBuilder.setView(dialogView);
TextView itemName = dialogView.findViewById(R.id.popTitle);
Button cancel = dialogView.findViewById(R.id.cancel_order);
Button select = dialogView.findViewById(R.id.add_order);
itemName.setText(title);
final AlertDialog alert = dialogBuilder.create();
alert.show();
}
public void getItemList() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, MENU_ITEM_List, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("DATA");
for (int i = 0; i < jsonArray.length(); i++) {
Model model = new Model();
jsonObject = jsonArray.getJSONObject(i);
model.setItemName(jsonObject.getString("TITLE"));
}
// nDialog.dismiss();
} catch (JSONException e) {
System.out.println("Error in code: " + e.getMessage());
// nDialog.dismiss();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "Time Out", Toast.LENGTH_LONG).show();
// nDialog.dismiss();
}
});
RequestQueue requestqueue = Volley.newRequestQueue(getContext());
requestqueue.add(stringRequest);
}
}
private static class ViewHolder {
private TextView itemTitle;
private Spinner spinnerItem;
private ImageButton removeBtn;
private ImageButton addBtn;
private TextView spinnerItemQuanty;
private TextView totalPrice;
public ViewHolder(View v) {
itemTitle = v.findViewById(R.id.item_name);
spinnerItemQuanty = v.findViewById(R.id.spinner_item_quantity);
totalPrice = v.findViewById(R.id.total_price);
}
}
}
Here is list of title filtered according to category:
Category: [MORNING SPECIAL, DESSERT & ICE CREAM, CHINESE]
Food ITEMS: [[Tea, Puri Sabji, Samosa, momos], [ROSOGULLA, Softy], [Chicken Tandoori, Chicken Korma]]
I am trying to add food items to list but array adapter getting null data because onCreateView set first then I am getting data from onPageSelect that's why my application get crashed down.
i have this Json Data
and i prasing the data in in this json to this ,,
enter image description here
now i wont when click on the image of the application ,, open another activty and display the images in the "im:image" Jsonarray in the json !
this code give to me all images ,, but i wont just the image thats i clicked
this is my Module
private List<String> Allimage = new ArrayList<String>();
public List<String> getAllimage() {
return Allimage;}
public void setAllimage(List<String> allimage) {
Allimage = allimage;}
the Adapter
public class ImageListAdapter extends RecyclerView.Adapter<ImageListAdapter.ViewHolder> {
List<AppShowModule> appShowModules;
List<AppShowModule> imageUrls ;
Context context;
public ImageListAdapter(List<AppShowModule> appShowModules, Context context){
super();
this.appShowModules = appShowModules;
this.context = context;}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from( parent.getContext() ).inflate( R.layout.imagelayout, parent,false );
ViewHolder viewHolder = new ViewHolder( v );
return viewHolder;}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final AppShowModule appShowModule = appShowModules.get( position );
Picasso.with(context).load( appShowModule.getAllimage() ).into( holder.appImage );
}
#Override
public int getItemCount() {
return appShowModules.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView appImage;
public ViewHolder(View itemView) {
super(itemView);
appImage = (ImageView) itemView.findViewById( R.id.appImage);
}}}
and this is the Fragment `
public class ImageListFragment extends Fragment {
List<AppShowModule> appShowModules;
Context context;
List<AppShowModule> imagesModule;
RecyclerView AppRecyclerView;
ImageView Imageview;
RecyclerView.Adapter imageRecyclerViewadapter;
List<String> imageUrls;
String feedKey = "feed";
String entryKey = "entry";
String nameKey = "im:name";
String imageKey = "im:image";
String labelKey = "label";
String artistKey = "im:artist";
String contentTypeKey = "im:contentType";
String attribueKey = "attributes";
String rightsKey = "rights";
String categoryKey = "category";
String relaseDateKey = "im:releaseDate";
String linkKey = "link";
String hrefKey = "href";
String summaryKey = "summary";
String jsonUrl = "https://itunes.apple.com/jo/rss/topfreeapplications/limit=50/json";
RequestQueue requestQueue;
private RecyclerView.LayoutManager mLayoutManager;
public ImageListFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_image_list, container, false);
}
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
AppRecyclerView = (RecyclerView) getView().findViewById(R.id.imageRecyclerView);
imagesModule = new ArrayList<>();
appShowModules = new ArrayList<>();
imageUrls = new ArrayList<>();
JsonAppShowData();
}
public void JsonAppShowData() {
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( jsonUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONObject("feed").getJSONArray( "entry" );
AppShowModule appShowModule = new AppShowModule();
for (int i = 0; i < jsonArray.length(); i++) {
String image = response.getJSONObject(feedKey).getJSONArray(entryKey).getJSONObject(0).getJSONArray(imageKey).getJSONObject( 0 ).getString(labelKey).toString();
imageUrls.add(image);
appShowModule.setAllimage(imageUrls);
appShowModules.add(appShowModule);
}
imageRecyclerViewadapter = new ImageListAdapter(appShowModules,getContext());
AppRecyclerView.setAdapter(imageRecyclerViewadapter);
} catch (JSONException e) {
e.printStackTrace();
}}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e( "LOG", error.toString() );
}
} );
requestQueue = Volley.newRequestQueue( getContext() );
requestQueue.add(jsonObjectRequest);
mLayoutManager = new GridLayoutManager( getContext().getApplicationContext(),3);
AppRecyclerView.setLayoutManager(mLayoutManager); }}
You are trying to load complete list string by doing appShowModule.getAllimage() which is wrong. try to do following.
Picasso.with(context).load(appShowModule.getAllimage().get(position)).into(holder.appImage);
I have responsed JSONObject from API and i tried to send the response to the module using setter then to the Recyclerview adapter but its not working
This is my fragment
public class ListViewActivityFragment extends Fragment {
List<AppShowModule> appShowModule;
RecyclerView AppRecyclerView;
List<AppShowModule> GetDataAdapter1;
RecyclerView.LayoutManager AppRecyclerViewlayoutManager;
RecyclerView.Adapter AppRecyclerViewadapter;
String jsonUrl = "https://itunes.apple.com/jo/rss/topfreeapplications/limit=50/json";
TextView text;
Context context;
RequestQueue requestQueue;
public ListViewActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_list_view, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
appShowModule = new ArrayList<>();
AppRecyclerView = (RecyclerView) getView().findViewById( R.id.AppRecyclerView );
text = (TextView) getView().findViewById(R.id.textView2);
AppRecyclerView.setHasFixedSize( true );
GetDataAdapter1 = new ArrayList<>();
AppRecyclerView.setLayoutManager( AppRecyclerViewlayoutManager );
JsonAppShowData();}
public void JsonAppShowData() {
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( jsonUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONObject("feed").getJSONArray( "entry" );
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json1 = jsonArray.getJSONObject( i ).getJSONObject("im:name");
AppShowModule appShowModule111 = new AppShowModule();
String name = response.getJSONObject("feed").getJSONArray("entry").getJSONObject(i).getJSONObject("im:name").getString("label").toString();
text.setText(name);
appShowModule111.setAppName((name));}
} catch (JSONException e) {
e.printStackTrace();
}}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e( "LOG", error.toString() );
}
} );
requestQueue = Volley.newRequestQueue( getContext() );
requestQueue.add(jsonObjectRequest);
AppRecyclerView.setLayoutManager(new LinearLayoutManager(context));
AppRecyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1,this);
AppRecyclerView.setAdapter(AppRecyclerViewadapter);
}
}
and this is my adapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<AppShowModule> getDataAdapter;
Context MContext;
public RecyclerViewAdapter(List<AppShowModule> getDataAdapter, ListViewActivityFragment context){
super();
this.getDataAdapter = getDataAdapter;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.appitem, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position)
{
final AppShowModule getDataAdapter1 = getDataAdapter.get(position);
holder.NameTextView.setText(getDataAdapter1.getAppName());
Picasso.with(context).load(getDataAdapter1.getAppImageUrl()).into(holder.imgPost);
}
#Override
public int getItemCount() {
return getDataAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView NameTextView;
public ImageView imgPost;
LinearLayout lnrLayout;
public ViewHolder(View itemView) {
super(itemView);
NameTextView = (TextView) itemView.findViewById(R.id.appName);
imgPost = (ImageView) itemView.findViewById(R.id.appImage);
lnrLayout = (LinearLayout)itemView.findViewById(R.id.lnrLayout);
}
}
}
and this is my module
public class AppShowModule
{
private String appName;
private String appImageUrl;
public String getAppName() {
return appName;}
public void setAppName(String appName) {
this.appName = appName;}
public String getAppImageUrl() {
return appImageUrl;}
public void setAppImageUrl(String appImageUrl) {
this.appImageUrl = appImageUrl;}
}
Yo are creating the AppShowModule appShowModule111 = new AppShowModule(); Object but you never populated your adaapter with that object. Your JsonObjectRequest onResponse() should look like this;
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONObject("feed").getJSONArray( "entry" );
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json1 = jsonArray.getJSONObject( i ).getJSONObject("im:name");
AppShowModule appShowModule111 = new AppShowModule();
String name = response.getJSONObject("feed").getJSONArray("entry").getJSONObject(i).getJSONObject("im:name").getString("label").toString();
text.setText(name);
appShowModule111.setAppName((name));
GetDataAdapter1.add(appShowModule111);
}
AppRecyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1,ListViewActivityFragment.this);
AppRecyclerView.setAdapter(AppRecyclerViewadapter);
} catch (JSONException e) {
e.printStackTrace();
}}
hello i have this Json Data a link
and i parsing it like that
when i click into the image i want to parsing the JsonArray for the image to piccaso in recycler view like this ,
but i get all image like this picture
how i can solve this problem and get just the images for the item which i clicked ???
this is my module :
public class AppShowModule
{
private List<String> Allimage = new ArrayList<String>();
public List<String> getAllimage() {
return Allimage;}
public void setAllimage(List<String> allimage) {
Allimage = allimage;}
this is my Fragment
public class ImageListFragment extends Fragment {
List<AppShowModule> appShowModules;
List<AppShowModule> imagesModule;
RecyclerView AppRecyclerView;
RecyclerView.Adapter imageRecyclerViewadapter;
List<String> imageUrls;
String feedKey = "feed";
String entryKey = "entry";
String imageKey = "im:image";
String labelKey = "label";
String jsonUrl = "https://itunes.apple.com/jo/rss/topfreeapplications/limit=50/json";
RequestQueue requestQueue;
private RecyclerView.LayoutManager mLayoutManager;
public ImageListFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_image_list, container, false);
}
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
AppRecyclerView = (RecyclerView) getView().findViewById(R.id.imageRecyclerView);
imagesModule = new ArrayList<>();
appShowModules = new ArrayList<>();
imageUrls = new ArrayList<>();
JsonAppShowData();
}
public void JsonAppShowData() {
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( jsonUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONObject(feedKey).getJSONArray( entryKey );
AppShowModule appShowModule = new AppShowModule();
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray imageArray = response.getJSONObject(feedKey).getJSONArray(entryKey).getJSONObject(i).getJSONArray(imageKey);
for (int j = 0; j < imageArray.length(); j++) {
String image = imageArray.getJSONObject(j).getString(labelKey).toString();
imageUrls.add(image);
appShowModule.setAllimage(imageUrls);
appShowModules.add(appShowModule);}}
imageRecyclerViewadapter = new ImageListAdapter(appShowModules,getContext(),imageUrls);
AppRecyclerView.setAdapter(imageRecyclerViewadapter);
} catch (JSONException e) {
e.printStackTrace();
}}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e( "LOG", error.toString() );
}
} );
requestQueue = Volley.newRequestQueue( getContext() );
requestQueue.add(jsonObjectRequest);
mLayoutManager = new GridLayoutManager( getContext().getApplicationContext(),3);
AppRecyclerView.setLayoutManager(mLayoutManager); }}
and this is the Recycler adapter
public class ImageListAdapter extends RecyclerView.Adapter<ImageListAdapter.ViewHolder> {
List<AppShowModule> appShowModules;
List<String> imageUrl;
Context context;
public ImageListAdapter(List<AppShowModule> appShowModules, Context context ,List<String>imageUrls
){
super();
this.imageUrl =imageUrls;
this.appShowModules = appShowModules;
this.context = context;}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from( parent.getContext() ).inflate( R.layout.imagelayout, parent,false );
ViewHolder viewHolder = new ViewHolder( v );
return viewHolder;}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Picasso.with(context).load(imageUrl.get(position)).into(holder.appImage);
}
public int getItemCount() {
return imageUrl.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView appImage;
public ViewHolder(View itemView) {
super(itemView);
appImage = (ImageView) itemView.findViewById( R.id.appImage);
}}}
and this is the activity that have the image view where click
public class ListViewDetailsFragment extends Fragment {
ImageView AppImage;
TextView AppName,AppArtist,AppContentType,AppRights,AppCategory,AppRealseDate,AppSammary;
ImageButton AppLink;
Context context;
public ListViewDetailsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_list_view_details, container, false);}
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
AppImage = (ImageView) getView().findViewById(R.id.imageView);
AppName = (TextView) getView().findViewById(R.id.textname);
AppArtist = (TextView) getView().findViewById(R.id.textartest);
AppContentType = (TextView) getView().findViewById(R.id.textcontent);
AppRights = (TextView) getView().findViewById(R.id.textrights);
AppCategory = (TextView) getView().findViewById(R.id.textCategory);
AppRealseDate = (TextView) getView().findViewById(R.id.textRelease);
AppSammary = (TextView) getView().findViewById(R.id.textSummary);
AppLink = (ImageButton) getView().findViewById(R.id.imageButton);
String name = getActivity().getIntent().getExtras().getString("App_name");
final String image = getActivity().getIntent().getExtras().getString("App_image");
String artist = getActivity().getIntent().getExtras().getString("App_artist");
String contentType = getActivity().getIntent().getExtras().getString("App_ContentType");
String rights = getActivity().getIntent().getExtras().getString("App_Rights");
String category = getActivity().getIntent().getExtras().getString("App_Category");
String realse = getActivity().getIntent().getExtras().getString("App_ReleaseDate");
final String link = getActivity().getIntent().getExtras().getString("App_link");
String sammary = getActivity().getIntent().getExtras().getString("App_summary");
AppName.setText(name);
AppArtist.setText(artist);
AppContentType.setText(contentType);
AppRights.setText(rights);
AppCategory.setText(category);
AppRealseDate.setText(realse);
AppSammary.setText(sammary);
Picasso.with(context).load(image).into(AppImage);
AppLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity().getBaseContext(),
WebView.class);
intent.putExtra("App_link", link);
getActivity().startActivity(intent);}});
AppImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String id = (String) view.getTag();
Intent intent = new Intent(getActivity().getBaseContext(), ImageList.class);
intent.putExtra("id", id);
getActivity().startActivity(intent);
}});}}
The json data has links to three different sized images, it looks to me like you are requesting that all three images are fetched. If you don't want all three, just select the size you want (index 0, 1 or 2) and pull that image only.
JSONArray imageArray = response.getJSONObject(feedKey).getJSONArray(entryKey).getJSONObject(i).getJSONArray(imageKey);
for (int j = 0; j < imageArray.length(); j++) {
String image = imageArray.getJSONObject(j).getString(labelKey).toString();
imageUrls.add(image);
...
}
Sample Data:
"im:image":[
{
"label":"http://is1.mzstatic.com/image/thumb/Purple20/v4/87/35/82/87358231-ce91-3d14-b306-95888c23db3c/mzl.gdgtivnk.png/53x53bb-85.png",
"attributes":{
"height":"53"
}
},
{
"label":"http://is5.mzstatic.com/image/thumb/Purple20/v4/87/35/82/87358231-ce91-3d14-b306-95888c23db3c/mzl.gdgtivnk.png/75x75bb-85.png",
"attributes":{
"height":"75"
}
},
{
"label":"http://is3.mzstatic.com/image/thumb/Purple20/v4/87/35/82/87358231-ce91-3d14-b306-95888c23db3c/mzl.gdgtivnk.png/100x100bb-85.png",
"attributes":{
"height":"100"
}
}
Update 9/13/2016
Based on what I think you are after, I still think your problem is in your nested for loop in the jsonAppShowData() method. Though you do appear to pass some sort of ID extra in from the previous activity, I don't see you filtering on that item ID anywhere in the for loop. You need to restrict the outer for loop to only the item you wish to show.
For the image scaling issue, it may either be how your layout is setup or you can try some of the Picasso resize calls.