I am still not confident working with android and I have 2 problems here, I would like to make Multi level recyclerView with 3 levels. 1st level is categories RecyclerView, 2nd is ListView with list of exercises and 3rd level is details. So now I made a 1st level recyclerView which is not clickable. Another problem is how to fetch Listview in 2nd level to the details of the 3rd level? Here is my code of 1st level fragment:
public class BallTrainingFragment extends Fragment {
View mRootView;
String URL_TO_HIT = "https://gist.githubusercontent.com/tomasmaks/afbf3e836dabd72c95c4b3ec90e291ed/raw/7ba41948865f78f1ccb4058c61f8c6e06c601300/BasketballTraining.json";
BallTrainingAdapter adapter;
RecyclerView mRecyclerView;
private List<BallTrainingModel> ballTraining;
GridLayoutManager mGridLayoutManager;
public BallTrainingFragment() {
// Required empty public constructor
}
public static BallTrainingFragment newInstance(int sectionNumber) {
BallTrainingFragment fragment = new BallTrainingFragment();
Bundle args = new Bundle();
args.putInt(Constants.ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create default options which will be used for every
// displayImage(...) call if no options will be passed to this method
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity().getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config); // Do it on Application start
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mRootView = inflater.inflate(R.layout.fragment_balltraining, container, false);
mRecyclerView = (RecyclerView) mRootView.findViewById(R.id.balltraining_list);
mRecyclerView.setHasFixedSize(true);
// Display under one column
mGridLayoutManager = new GridLayoutManager(getActivity(), 2);
mRecyclerView.setLayoutManager(mGridLayoutManager);
// Set orientation
mGridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(mGridLayoutManager);
return mRootView;
}
#Override
public void onStart() {
super.onStart();
new FetchBallTask().execute(URL_TO_HIT);
}
public class FetchBallTask extends AsyncTask<String, String, List<BallTrainingModel>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<BallTrainingModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder buffer = new StringBuilder();
String line ="";
while ((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.optJSONArray("BasketballTraining");
List<BallTrainingModel> ballTrainingModelList = new ArrayList<>();
Gson gson = new Gson();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
/**
* below single line of code from Gson saves you from writing the json parsing yourself which is commented below
*/
BallTrainingModel ballTrainingModel = gson.fromJson(finalObject.toString(), BallTrainingModel.class);
ballTrainingModel.setCategory(finalObject.getString("category"));
ballTrainingModel.setThumbnail(finalObject.getString("thumb"));
List<BallTrainingModel.Cast> castList = new ArrayList<>();
for(int j=0; j<finalObject.getJSONArray("cast").length(); j++){
BallTrainingModel.Cast cast = new BallTrainingModel.Cast();
cast.setName(finalObject.getJSONArray("cast").getJSONObject(j).getString("name"));
castList.add(cast);
}
ballTrainingModel.setCastList(castList);
// adding the final object in the list
ballTrainingModelList.add(ballTrainingModel);
}
return ballTrainingModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(final List<BallTrainingModel> result) {
super.onPostExecute(result);
if(result != null) {
adapter = new BallTrainingAdapter(getActivity().getApplicationContext(), R.layout.fragment_balltraining_content, result);
mRecyclerView.setAdapter(adapter);
mRecyclerView.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View v) {
int position = mRecyclerView.indexOfChild(v);
BallTrainingModel ballTrainingModel = result.get(position);
Intent intent = new Intent(getActivity(), BallTrainingDetailsActivity.class);
intent.putExtra("ballTrainingModel", new Gson().toJson(ballTrainingModel));
getActivity().startActivity(intent);
}
});
} else {
Toast.makeText(getActivity().getApplicationContext(), "Not able to fetch data from server, please check url.", Toast.LENGTH_SHORT).show();
}
}
}
public class BallTrainingAdapter extends RecyclerView.Adapter<CustomViewHolder> {
private List<BallTrainingModel> ballTrainingList;
private int resource;
private LayoutInflater inflater;
public BallTrainingAdapter(Context context,int resource, List<BallTrainingModel> objects) {
ballTrainingList = objects;
this.resource = resource;
inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_balltraining_content, null);
CustomViewHolder viewHolder = new CustomViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int position) {
BallTrainingModel ballTraining = ballTrainingList.get(position);
ImageLoader.getInstance().displayImage(ballTrainingList.get(position).getThumbnail(), customViewHolder.thumbnail);
//Setting text view title
customViewHolder.textView.setText(ballTrainingList.get(position).getCategory());
}
#Override
public int getItemCount() {
return (null != ballTrainingList ? ballTrainingList.size() : 0);
}
}
public class CustomViewHolder extends RecyclerView.ViewHolder{
protected TextView textView;
protected ImageView thumbnail;
public CustomViewHolder(View view) {
super(view);
this.textView = (TextView) view.findViewById(R.id.category);
this.thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
}
}
}
I think that not clickable problem is on this line of code:
mRecyclerView.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View v) {
And here is 2nd level fragment, which should render ListView and be clickable to 3rd level of details. Can someone give any example of how to make this?
public class BallTrainingDetailsActivity extends ActionBarActivity {
private TextView name;
private TextView tvCast;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_balltraining_list);
// Showing and Enabling clicks on the Home/Up button
if(getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
// setting up text views and stuff
setUpUIViews();
// recovering data from MainActivity, sent via intent
Bundle bundle = getIntent().getExtras();
if(bundle != null){
String json = bundle.getString("ballTrainingModel");
BallTrainingModel ballTrainingModel = new Gson().fromJson(json, BallTrainingModel.class);
StringBuffer stringBuffer = new StringBuffer();
for(BallTrainingModel.Cast cast : ballTrainingModel.getCastList()){
stringBuffer.append(cast.getName() + ", ");
}
tvCast.setText(stringBuffer);
//tvStory.setText(movieModel.getStory());
}
}
private void setUpUIViews() {
name = (TextView)findViewById(R.id.Name);
}
}
Here is JSON file:
{
"BasketballTraining": [
{
"thumb":"https://kycapitalliving.files.wordpress.com/2014/02/basketball-thumbnail.jpg",
"category": "Ball Handling",
"cast": [
{
"name": "Robert Downey Jr."
},
{
"name": "Chris Evans"
},
{
"name": "Mark Ruffalo"
}
]
},
{
"thumb":"https://kycapitalliving.files.wordpress.com/2014/02/basketball-thumbnail.jpg",
"category": "Shooting",
"cast": [
{
"name": "Matthew McConaughey"
},
{
"name": "Anne Hathaway"
},
{
"name": "Jessica Chastain"
},
{
"name": "Wes Bentley"
}
]
},
{
"thumb":"https://kycapitalliving.files.wordpress.com/2014/02/basketball-thumbnail.jpg",
"category": "Post Moves",
"cast": [
{
"name": "Miles Teller"
},
{
"name": "Kate Mara"
},
{
"name": "Michael B. Jordan"
}
]
},
{
"thumb":"https://kycapitalliving.files.wordpress.com/2014/02/basketball-thumbnail.jpg",
"category": "Defense",
"cast": [
{
"name": "Christian Bale"
},
{
"name": "Heath Ledger"
},
{
"name": "Aaron Eckhart"
}
]
},
{
"thumb":"https://kycapitalliving.files.wordpress.com/2014/02/basketball-thumbnail.jpg",
"category": "Scoring",
"cast": [
{
"name": "Viggo Mortensen"
},
{
"name": "Ian McKellen"
},
{
"name": "Elijah Wood"
}
]
},
{
"thumb":"https://kycapitalliving.files.wordpress.com/2014/02/basketball-thumbnail.jpg",
"category": "Others",
"cast": [
{
"name": "Roberto Benigni"
},
{
"name": "Nicoletta Braschi"
},
{
"name": "Giorgio Cantarini"
}
]
}
]
}
and here is my model:
public class BallTrainingModel {
private String thumbnail;
private String category;
#SerializedName("cast")
private List<Cast> castList;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public List<Cast> getCastList() {
return castList;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public void setCastList(List<Cast> castList) {
this.castList = castList;
}
public static class Cast {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
Any examples or help would appreciated. Thank you in advance.
In RecyclerView Adapter there is a method onBindView
you have to apply there setOnClickListener :
For example :
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.mCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Your Code
});
}
}
For ref : check this link
Related
I am getting the data from server using JSON and when i try to search in the listview it just refreshes the whole list and does not narrate it, but when i debug i can see the result on getfilter is right right and it drugsFiltered = (ArrayList<drugs_json_data>) results.values; does have the filtered data inside it. just the listview.setadaptor is being done inside onPostExecute of the asynctask.
here is my adapter code:
public class drugs_adaptor_listView extends ArrayAdapter<drugs_json_data> implements Filterable {
ArrayList<drugs_json_data> drugs;
ArrayList<drugs_json_data> drugsFiltered;
Context context;
int resource;
public drugs_adaptor_listView(Context context, int resource, ArrayList<drugs_json_data> drugs) {
super(context, resource, drugs);
this.drugs = drugs;
this.drugsFiltered = drugs;
this.context = context;
this.resource = resource;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View r = convertView;
ViewHolder viewHolder;
if (r == null) {
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
r = layoutInflater.inflate(R.layout.row_layout_drugs, null, true);
viewHolder = new ViewHolder(r);
r.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) r.getTag();
}
drugs_json_data drugs_json_data = getItem(position);
viewHolder.txtDrugId.setText(drugs_json_data.getDrugId());
viewHolder.txtDrugName.setText(drugs_json_data.getDrugName());
viewHolder.txtDrugCategory.setText(drugs_json_data.getDrugCategory());
Picasso builder = new Picasso.Builder(context).build();
builder.load(drugs_json_data.getDrugImage()).memoryPolicy(MemoryPolicy.NO_STORE).placeholder(R.drawable.ic_launcher_foreground).into(viewHolder.imageView);
return r;
}
#NonNull
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
drugsFiltered = (ArrayList<drugs_json_data>) results.values; // has the filtered values
if (results.count>0) {
notifyDataSetChanged(); // notifies the data with new filtered values
}else {
notifyDataSetInvalidated();
}
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
ArrayList<drugs_json_data> FilteredArrList = new ArrayList<>();
if (drugs == null) {
drugs = new ArrayList<>(drugsFiltered); // saves the original data in mOriginalValues
}
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = drugs.size();
results.values = drugs;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < drugs.size(); i++) {
String data = drugs.get(i).getDrugName();
if (data.startsWith(constraint.toString())) {
FilteredArrList.add(new drugs_json_data(drugs.get(i).getDrugId(), drugs.get(i).getDrugName(), drugs.get(i).getDrugCategory(), drugs.get(i).getDrugImage()));
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
class ViewHolder {
TextView txtDrugId, txtDrugName, txtDrugCategory;
ImageView imageView;
ViewHolder(View v) {
txtDrugId = v.findViewById(R.id.txtDrugId);
txtDrugName = v.findViewById(R.id.txtDrugName);
txtDrugCategory = v.findViewById(R.id.txtDrugCat);
imageView = v.findViewById(R.id.ImageViewDrug);
}
}
}
here is the data model:
public class drugs_json_data {
private String drugImage;
private String drugName;
private String drugCategory;
private String drugId;
public drugs_json_data(String drugImage, String drugName, String drugCategory, String drugId) {
this.drugImage = drugImage;
this.drugName = drugName;
this.drugCategory = drugCategory;
this.drugId = drugId;
}
public String getDrugImage() {
return this.drugImage;
}
public void setDrugImage(String drugImage) {
this.drugImage = drugImage;
}
public String getDrugName() {
return this.drugName;
}
public void setDrugName(String drugName) {
this.drugName = drugName;
}
public String getDrugCategory() {
return this.drugCategory;
}
public void setDrugCategory(String drugCategory) {
this.drugCategory = drugCategory;
}
public String getDrugId() {
return this.drugId;
}
public void setDrugId(String drugId) {
this.drugId = drugId;
}
}
and here is the main activity code:
public class clerk_drugs extends AppCompatActivity {
ListView listView;
Button createDrug;
String drug_id, json_drug;
TextView noMed;
EditText searchTxt;
JSONObject jsonObject;
JSONArray jsonArray;
ArrayList<drugs_json_data> arrayList;
drugs_adaptor_listView adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clerk_drugs);
createDrug = findViewById(R.id.create_drug);
arrayList = new ArrayList<>();
listView = findViewById(R.id.list_drugs);
noMed = findViewById(R.id.no_med);
searchTxt = findViewById(R.id.listSearch);
searchTxt.setSingleLine(true);
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
new ReadJSON().execute("http://(mylink)").get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
try {
jsonObject = new JSONObject(json_drug);
jsonArray = jsonObject.getJSONArray("server_response");
} catch (JSONException e) {
e.printStackTrace();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
drug_id = ((TextView) view.findViewById(R.id.txtDrugId)).getText().toString();
for (int i = 0; i<jsonArray.length(); i++){
try {
JSONObject jobj = jsonArray.getJSONObject(i);
String drugid = jobj.getString("drug_id");
if(drugid.equals(drug_id)) {
String drugname = jobj.getString("drug_name");
String drugcategory = jobj.getString("drug_category");
String drugdescription = jobj.getString("drug_description");
String drugphoto = jobj.getString("drug_photo");
drug_update_dialog drug_update_dialog = new drug_update_dialog();
Bundle args = new Bundle();
args.putString("drug-id", drug_id);
args.putString("drug-name", drugname);
args.putString("drug-category", drugcategory);
args.putString("drug-description", drugdescription);
args.putString("drug_photo",drugphoto);
drug_update_dialog.setArguments(args);
drug_update_dialog.show(getSupportFragmentManager(),"ویرایش اطلاعات دارو");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
searchTxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
searchTxt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus){
hideKeyboard(v);
}
}
});
}
public void hideKeyboard(View view) {
InputMethodManager inputMethodManager =(InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
class ReadJSON extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
try {
JSONObject jsonObject = new JSONObject(content);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
for(int i=0; i<jsonArray.length();i++){
JSONObject drugObj = jsonArray.getJSONObject(i);
arrayList.add(new drugs_json_data(
drugObj.getString("drug_photo"),
drugObj.getString("drug_name"),
drugObj.getString("drug_category"),
drugObj.getString("drug_id")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new drugs_adaptor_listView(
getApplicationContext(), R.layout.row_layout_drugs, arrayList
);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
if (adapter.getCount()==0){
noMed.setVisibility(View.VISIBLE);
}
}
}
private String readURL(String theURL) {
StringBuilder content = new StringBuilder();
try{
URL url = new URL(theURL);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line=bufferedReader.readLine())!=null){
content.append(line).append("\n");
}
bufferedReader.close();
}catch (Exception e){
e.printStackTrace();
}
json_drug = content.toString();
return content.toString();
}
#Override
public void onBackPressed() {
finish();
Intent intent = new Intent(this,patient_mainPage.class);
startActivity(intent);
}
public void createDrugDialog(View view){
openDrugDialog();
}
private void openDrugDialog() {
drug_add_dialog drug_add_dialog = new drug_add_dialog();
drug_add_dialog.show(getSupportFragmentManager(),"ثبت داروی جدید");
}
}
I would be grateful if someone could help.
UPDATED
In getView method in Adapter
Replace
drugs_json_data drugs_json_data = getItem(position);
With
drugs_json_data drugs_json_data = drugsFiltered.get(position);
I want to get random photos from unsplash and show in my app. Here's the request url I have formed (works with api_key). random photos from unsplash
I have created my model class according to this structure with getters and setters(omitted) like below:
public class UnsplashImages {
public String imageId;
public String rawImg;
public String fullImg;
public String regularImg;
public String smallImg;
public String thumbImg;
public UnsplashImages() {}
public UnsplashImages(String imageId, String rawImg, String fullImg, String regularImg, String smallImg, String thumbImg) {
this.imageId = imageId;
this.rawImg = rawImg;
this.fullImg = fullImg;
this.regularImg = regularImg;
this.smallImg = smallImg;
this.thumbImg = thumbImg;
}
}
According to the docs, this endpoint will return only one image unless count is specified in request url, so I have added count to be max value (30).
This is the json response I am getting for count value > 1:
[
{
id: "7kWEtC4TZlE",
created_at: "2018-02-12T17:28:19-05:00",
updated_at: "2018-05-18T14:03:44-04:00",
width: 3980,
height: 4975,
color: "#FAC9A7",
description: null,
urls: {
raw: "https://images.unsplash.com/photo-1518474436123-0e44861523f7?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjI4ODUzfQ&s=6d9ef54c8c96afc3fbd6cd9aca9e2cf6",
full: "https://images.unsplash.com/photo-1518474436123-0e44861523f7?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjI4ODUzfQ&s=e12d5951d3907a1917eb9c1a1c2b67e4",
regular: "https://images.unsplash.com/photo-1518474436123-0e44861523f7?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjI4ODUzfQ&s=da9be90c5000190c773f31969059fdae",
small: "https://images.unsplash.com/photo-1518474436123-0e44861523f7?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjI4ODUzfQ&s=7630a6850ad1e87dfd580f5066482ee5",
thumb: "https://images.unsplash.com/photo-1518474436123-0e44861523f7?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=200&fit=max&ixid=eyJhcHBfaWQiOjI4ODUzfQ&s=fb527398e3ee3e8c411674fd0a65ce5b"
},
links: {},
categories: [ ],
sponsored: false,
likes: 54,
liked_by_user: false,
current_user_collections: [ ],
slug: null,
user: {},
exif: {},
location: {},
views: 262012,
downloads: 876
},
{},
.
.
.
}
In my fragment I have done json parsing like below:
String s = Constants.RANDOM_PHOTOS + "&count=30";
Log.d(TAG, "Unsplash Misc URL:\t" + s);
AndroidNetworking.get(s)
.addHeaders("Accept-Version", "v1")
.addHeaders("CLIENT-ID", Constants.UNSPLASH_ACCESS_KEY)
.setTag("Unsplash Scifi req")
.setPriority(Priority.HIGH)
.getResponseOnlyFromNetwork()
.build()
.getAsJSONArray(new JSONArrayRequestListener() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "Un-Response:\t" + response.toString());
if (response != null){
try {
JSONArray jsonArray = new JSONArray(response.toString());
UnsplashImages images = new UnsplashImages();
for (int m = 0; m < jsonArray.length(); m++){
JSONObject object = jsonArray.getJSONObject(m);
images.setImageId(object.getString("id"));
JSONObject urls = object.getJSONObject("urls");
images.setRawImg(urls.getString("raw"));
images.setFullImg(urls.getString("full"));
images.setRegularImg(urls.getString("regular"));
images.setSmallImg(urls.getString("small"));
images.setThumbImg(urls.getString("thumb"));
objectList.add(images);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onError(ANError anError) {
}
});
Here's the adapter code:
public class MiscAdapter extends RecyclerView.Adapter<WallpaperItemViewHolder> {
private static final String TAG = MiscAdapter.class.getSimpleName();
private final Context context;
private List<Object> itemsList;
private UnsplashImages unsplashImages;
public MiscAdapter(Context context, List<Object> itemsList) {
this.context = context;
this.itemsList = itemsList;
}
#Override
public WallpaperItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.wallpaper_items_layout, parent, false);
return new WallpaperItemViewHolder(view);
}
#Override
public void onBindViewHolder(final WallpaperItemViewHolder viewholder, final int position) {
unsplashImages = (UnsplashImages) itemsList.get(position);
Picasso.with(context)
.load(unsplashImages.getRegularImg())
.placeholder(R.drawable.drawer_header_trimmed)
.into(viewholder.wallpaperItemImg);
viewholder.favoriteWP_IV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Favorites favorites = new Favorites();
favorites.setFavoritesId(UUID.randomUUID().toString());
favorites.setLargeImgURL(unsplashImages.getRegularImg());
favorites.setPreviewImgURL(unsplashImages.getRegularImg());
favorites.save();
Log.d(TAG, "Fav id:\t" + favorites.getId());
Toast.makeText(context, "Added to Favorites", Toast.LENGTH_SHORT).show();
}
});
viewholder.setWallPaper_TV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final WallpaperManager wpm = WallpaperManager.getInstance(context);
Picasso.with(context)
.load(((UnsplashImages) itemsList.get(position)).getRegularImg())
.into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
try {
wpm.setBitmap(bitmap);
Toast.makeText(context, "Your New Wallpaper Has Been Set", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
Log.d(TAG, "Bitmap Load Failed");
Toast.makeText(context, "Could Not Set Wallpaper...Choose Another", Toast.LENGTH_SHORT).show();
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
Log.d(TAG, "Prep to Load Bitmap");
}
});
}
});
}
#Override
public int getItemCount() {
if (itemsList == null) {
return 0;
}
return itemsList.size();
}
}
The images show in the recyclerview list but instead of different items, the same image is shown 30 times in the list. Is this a problem with my json parsing or something else?.
My apologies for your time. I have fixed this by declaring the new instance of my model class inside the for loop like below:
for (int m = 0; m < jsonArray.length(); m++) {
JSONObject object = jsonArray.getJSONObject(m);
UnsplashImages images = new UnsplashImages(); // this here
images.setImageId(object.getString("id"));
JSONObject urls = object.getJSONObject("urls");
images.setRawImg(urls.getString("raw"));
images.setFullImg(urls.getString("full"));
images.setRegularImg(urls.getString("regular"));
images.setSmallImg(urls.getString("small"));
images.setThumbImg(urls.getString("thumb"));
objectList.add(images);
adapter.notifyDataSetChanged();
}
For future observers, take note. Thank you.
I used PagerAdapter for sliding images and i added a favorite button too in that sliding image. After clicking favorite button its not getting notified properly image not turns to unfavorite icon.
it is for loading api
private class PremiumProjectLoad extends AsyncTask<String, Void, JSONObject> {
JSONParser jsonParser = new JSONParser();
String url= ApiLinks.PremiumProject;
ProgressHUD mProgressHUD;
protected void onPreExecute(){
mProgressHUD = ProgressHUD.show(getActivity(),null, true);
super.onPreExecute();
}
protected JSONObject doInBackground(String... arg0) {
HashMap<String,String> params=new HashMap<>();
try {
params.put("languageID",CommonStrings.languageID);
params.put("cityID",CommonStrings.cityID);
if(session.isLoggedIn()){
params.put("userID",UserLogin.get(SessionManager.KEY_CUSTOMER_ID));
}
JSONObject json = jsonParser.SendHttpPosts(url,"POST",params);
if (json != null) {
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
if(json!=null) {
String Status=json.optString("status");
String Message=json.optString("message");
CommonImagePath=json.optString("imagepath");
PremiumDataArray.clear();
if(Status.equals("ok")){
JSONArray DataArray=json.optJSONArray("data");
if(DataArray!=null && DataArray.length()>0) {
for (int i = 0; i < DataArray.length(); i++) {
JSONObject DataObj = DataArray.optJSONObject(i);
String projectID = DataObj.optString("projectID");
String projectName = DataObj.optString("projectName");
String propertyUnitPriceRange = DataObj.optString("propertyUnitPriceRange");
String projectOfMonthImage = DataObj.optString("projectOfMonthImage");
String propertyUnitBedRooms = DataObj.optString("propertyUnitBedRooms");
String projectBuilderName = DataObj.optString("projectBuilderName");
String propertyTypeName = DataObj.optString("propertyTypeName");
String purpose = DataObj.optString("purpose");
String projectBuilderAddress = DataObj.optString("projectBuilderAddress");
String projectFavourite = DataObj.optString("projectFavourite");
PremiumData premiumData = new PremiumData();
premiumData.setProjectID(projectID);
premiumData.setProjectName(projectName);
premiumData.setPropertyUnitPriceRange(propertyUnitPriceRange);
premiumData.setProjectOfMonthImage(projectOfMonthImage);
premiumData.setPropertyUnitBedRooms(propertyUnitBedRooms);
premiumData.setProjectBuilderName(projectBuilderName);
premiumData.setPropertyTypeName(propertyTypeName);
premiumData.setPurpose(purpose);
premiumData.setProjectBuilderAddress(projectBuilderAddress);
premiumData.setProjectFavourite(projectFavourite);
PremiumDataArray.add(premiumData);
}
LoopViewPager viewpager = (LoopViewPager) homeView.findViewById(R.id.viewpager);
CircleIndicator indicator = (CircleIndicator) homeView.findViewById(R.id.indicator);
// if(pagerAdapter==null)
pagerAdapter = new PremiumProjectAdapter(getActivity(), PremiumDataArray);
viewpager.setAdapter(pagerAdapter);
indicator.setViewPager(viewpager);
// pagerAdapter.notifyDataSetChanged();
}
}
else {
Toast.makeText(getActivity(),Message, Toast.LENGTH_LONG).show();
}
}
mProgressHUD.dismiss();
}
}
pager adapter
public class PremiumProjectAdapter extends PagerAdapter {
private final Random random = new Random();
private ArrayList<PremiumData> mSize;
Context mContext;
LayoutInflater mLayoutInflater;
String ProjectID;
String path=CommonImagePath+"/uploads/projectOfMonth/orginal/";
// public PremiumProjectAdapter() {
// }
public PremiumProjectAdapter(Context contexts, ArrayList<PremiumData> count) {
mSize = count;
mContext=contexts;
}
#Override public int getCount() {
return mSize.size();
}
#Override public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override public void destroyItem(ViewGroup view, int position, Object object) {
view.removeView((View) object);
}
#Override public Object instantiateItem(ViewGroup view, final int position) {
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = mLayoutInflater.inflate(R.layout.home_premium_layout, view, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.premium_ProImage);
TextView ProjectName = (TextView) itemView.findViewById(R.id.premium_ProName);
TextView ProjectUnitPrice = (TextView) itemView.findViewById(R.id.premium_UnitPrice);
TextView ProjectUnitBedroom = (TextView) itemView.findViewById(R.id.premium_UnitBedrooms);
TextView ProjectAddress = (TextView) itemView.findViewById(R.id.premium_ProAddress);
ImageView unshortlisted = (ImageView) itemView.findViewById(R.id.unshortlisted);
ImageView shortlisted = (ImageView) itemView.findViewById(R.id.shortlisted);
final PremiumData data = mSize.get(position);
if (data.getProjectFavourite() != null) {
if (data.getProjectFavourite().equals("ShortListed")) {
shortlisted.setVisibility(View.VISIBLE);
unshortlisted.setVisibility(View.GONE);
} else {
shortlisted.setVisibility(View.GONE);
unshortlisted.setVisibility(View.VISIBLE);
}
}
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
ProjectUnitPrice.setText(Html.fromHtml(data.getPropertyUnitPriceRange(), Html.FROM_HTML_MODE_COMPACT));
}else{
ProjectUnitPrice.setText(Html.fromHtml(data.getPropertyUnitPriceRange()));
}
ImageLoader.getInstance().displayImage(path+data.getProjectOfMonthImage(), imageView);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
if(!data.getProjectName().equals("null") && data.getProjectName().length()>30){
String s = data.getProjectName().substring(0, 25);
String subString = s + "...";
ProjectName.setText(subString);
}
else{
ProjectName.setText(data.getProjectName());
}
ProjectUnitBedroom.setText(data.getPropertyUnitBedRooms());
ProjectAddress.setText(data.getProjectBuilderAddress());
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent DetailsAction=new Intent(mContext, DetailsActivity.class);
DetailsAction.putExtra("projectID",data.getProjectID());
DetailsAction.putExtra("purpose",data.getPurpose());
mContext.startActivity(DetailsAction);
}
});
unshortlisted.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!session.isLoggedIn()){
Intent toLogin=new Intent(mContext, LoginActivity.class);
CommonStrings.FromSearchIndex="true";
mContext.startActivity(toLogin);
}else{
ProjectID=data.getProjectID();
new ShortlistProject().execute();
}
}
});
shortlisted.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProjectID=data.getProjectID();
new UnShortlistProject().execute();
}
});
view.addView(itemView);
return itemView;
}
private class ShortlistProject extends AsyncTask<String, Void, JSONObject> {
JSONParser jsonParser = new JSONParser();
String url=ApiLinks.AddShortListProject;
ProgressHUD mProgressHUD;
protected void onPreExecute(){
mProgressHUD = ProgressHUD.show(mContext,null, true);
super.onPreExecute();
}
protected JSONObject doInBackground(String... arg0) {
HashMap<String,String> params=new HashMap<>();
try {
params.put("languageID",CommonStrings.languageID);
params.put("userID",User.get(SessionManager.KEY_CUSTOMER_ID));
params.put("projectID",ProjectID);
params.put("userType",User.get(SessionManager.KEY_USERTYPE_ID));
JSONObject json = jsonParser.SendHttpPosts(url,"POST",params);
if (json != null) {
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
if(json!=null) {
String status=json.optString("status");
String message=json.optString("message");
if(status.equals("ok")){
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
//SearchFragment.getInstance().onResume();
HomeFragment.getInstance().async_premium();
}else{
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
}
}
mProgressHUD.dismiss();
}
}
private class UnShortlistProject extends AsyncTask<String, Void, JSONObject> {
JSONParser jsonParser = new JSONParser();
String url=ApiLinks.RemoveShortListProject;
ProgressHUD mProgressHUD;
protected void onPreExecute(){
mProgressHUD = ProgressHUD.show(mContext,null, true);
super.onPreExecute();
}
protected JSONObject doInBackground(String... arg0) {
HashMap<String,String> params=new HashMap<>();
try {
params.put("userID",User.get(SessionManager.KEY_CUSTOMER_ID));
params.put("projectID",ProjectID);
params.put("userType",User.get(SessionManager.KEY_USERTYPE_ID));
JSONObject json = jsonParser.SendHttpPosts(url,"POST",params);
if (json != null) {
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject json) {
if(json!=null) {
String status=json.optString("status");
String message=json.optString("message");
if(status.equals("ok")){
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
// HomeFragment.getInstance().async_Premium();
HomeFragment.getInstance().async_premium();
}else{
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
}
}
mProgressHUD.dismiss();
}
}
As far as i am able to understand your question you want favorite and unfavorite functionality by adapter . Please use this code below to achieve that :
public class CustomGridAdapterFoodDrink extends BaseAdapter {
private Context mContext;
private ProgressDialog loading;
ArrayList<FoodDrink> foodDrinkArrayList = new ArrayList<>();
SharedPreferences pref;
String userId;
String like_dislike_value = "Like";
String likeValueStr = "1";
boolean like = true;
int positionVal = 444;
HashMap<Integer,Boolean> state = new HashMap<>();
public CustomGridAdapterFoodDrink(Context c, ArrayList<FoodDrink> foodDrinkArrayList) {
mContext = c;
this.foodDrinkArrayList = foodDrinkArrayList;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return foodDrinkArrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_single, null);
TextView projectNamtTxtView = (TextView) grid.findViewById(R.id.projectName);
TextView totalOfferText = (TextView) grid.findViewById(R.id.TotalOffers);
ImageView merchantImage = (ImageView) grid.findViewById(R.id.merchantImage);
final ImageView like_dislike_icon = (ImageView) grid.findViewById(R.id.like_dislike_icon);
totalOfferText.setText(foodDrinkArrayList.get(position).getOffers());
projectNamtTxtView.setText(foodDrinkArrayList.get(position).getProject_name());
Glide.with(mContext)
.load(foodDrinkArrayList.get(position).getProject_photo())
.centerCrop()
.placeholder(R.drawable.review_pro_pic1)
.crossFade()
.into(merchantImage);
like_dislike_icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
userId = pref.getString("userId", null);
/* if(state.size()> 0){
like = state.get(position);*/
if (!like) {
like = true;
/* state.put(position,like);*/
like_dislike_icon.setImageResource(R.mipmap.like_it_act);
likeDislike2(foodDrinkArrayList.get(position).getID(), "1");
} else {
like = false;
/* state.put(position,like);*/
like_dislike_icon.setImageResource(R.mipmap.like_it);
likeDislike2(foodDrinkArrayList.get(position).getID(), "0");
}
/* } else {
like = true;
state.put(position,like);
like_dislike_icon.setImageResource(R.mipmap.like_it_act);
likeDislike2(foodDrinkArrayList.get(position).getID(), "1");
}*/
// if(positionVal !=position) {
// likeValueStr ="1";
// positionVal = position;
// likeDislike(foodDrinkArrayList.get(position).getID(), likeValueStr, like_dislike_icon);
// }
// else {
// likeValueStr ="0";
// likeDislike(foodDrinkArrayList.get(position).getID(), likeValueStr, like_dislike_icon);
// }
}
});
} else {
grid = (View) convertView;
}
return grid;
}
private void likeDislike(String merchantId, final String like_dislike, final ImageView imageView) {
loading = ProgressDialog.show(mContext, "Loading ", "Please wait...", true, true);
AsyncHttpClient client = new AsyncHttpClient();
String url = getlikeUrl(userId, merchantId, like_dislike);
client.setMaxRetriesAndTimeout(5, 20000);
client.post(url, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String responseString) {
try {
JSONObject _object = new JSONObject(responseString);
String status = _object.getString("success");
String msg = _object.getString("response");
if ("true".equalsIgnoreCase(status)) {
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
if (msg.equalsIgnoreCase("Like")) {
imageView.setImageResource(R.mipmap.like_it_act);
} else {
imageView.setImageResource(R.mipmap.like_it);
}
} else {
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
}
loading.dismiss();
// AppUtility.showToast(SignUp.this, message);
} catch (JSONException e) {
e.printStackTrace();
new Global().saveReport("abc", e.getStackTrace(), e.toString());
}
loading.dismiss();
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
}
});
}
private String getlikeUrl(String userId, String merchantId, String like_dislike) {
String url = "";
try {
url = NetworkURL.URL
+ "likeMerchant"
+ "?user_id=" + URLEncoder.encode(new Global().checkNull(userId), "UTF-8")
+ "&merchant_id=" + URLEncoder.encode(new Global().checkNull(merchantId), "UTF-8")
+ "&like_dislike=" + URLEncoder.encode(new Global().checkNull(like_dislike), "UTF-8")
;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
new Global().saveReport("abc", e.getStackTrace(), e.toString());
}
return url;
}
private void likeDislike2(String merchantId, final String like_dislike) {
loading = ProgressDialog.show(mContext, "Loading ", "Please wait...", true, true);
AsyncHttpClient client = new AsyncHttpClient();
String url = getlikeUrl(userId, merchantId, like_dislike);
client.setMaxRetriesAndTimeout(5, 20000);
client.post(url, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String responseString) {
try {
JSONObject _object = new JSONObject(responseString);
String status = _object.getString("success");
String msg = _object.getString("response");
if ("true".equalsIgnoreCase(status)) {
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
}
loading.dismiss();
// AppUtility.showToast(SignUp.this, message);
} catch (JSONException e) {
e.printStackTrace();
new Global().saveReport("abc", e.getStackTrace(), e.toString());
}
loading.dismiss();
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
}
});
}
}
This is my Fragment Class - Here i get the JSON array object and call the adapter class for setting it. In the corressponding XML file, i have used a card view and lsit view to display the data. i want to know how to implement a onItemClickListener{} function so that i can go to another activity and display the list in a more detailed manner.
{
String url = "http://www.appplay.in/student_project/public/staff_details";
ProgressDialog mProgressDialog;
ListView lvDetail;
Context context;
ArrayList<staff_model> myList = new ArrayList<>();
ListView lv;
public static ArrayList<staff_model> staff_array;
JSONObject jsonObject;
JSONObject jsonKey;
Button submit;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
context=container.getContext();
View v = inflater.inflate(R.layout.tab_fragment_2, container, false);
lvDetail = (ListView) v.findViewById(R.id.CustomList);
// submit=(Button)v.findViewById(R.id.button) ;
new GetGalleryimage().execute();
v.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
Intent in = new Intent(getActivity(), Staff_Main.class);
startActivity(in);
}
});
return v;
}
public void positionAction(View view) {
int position = (int) view.getTag();
Toast.makeText(view.getContext(),Integer.toString(position),Toast.LENGTH_SHORT).show();
}
private class GetGalleryimage extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage("Please wait...");
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray jsonarr = jsonObj.getJSONArray("User_Details");
for(int i=0; i<jsonarr.length(); i++)
{
JSONObject jsonObject = jsonarr.getJSONObject(i);
myList.add(new staff_model(jsonObject.getString("name"),jsonObject.getString("dob"),jsonObject.getString("occupation"),jsonObject.getString("emailid"),jsonObject.getString("contact"),jsonObject.getString("timetable"),jsonObject.getString("image")));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
Log.v("result",""+result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
staff_BaseAdapter rcAdapter = new staff_BaseAdapter(getActivity(),0, myList);
lvDetail.setAdapter(rcAdapter);
}
}
public class MAP_Detailservice extends
AsyncTask<String, String, String> {
Context mContext;
JSONObject mJsnObj;
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
showProgress();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
JSONObject json = new JSONObject();
String cricketAllMatchesLink = "http://www.appplay.in/student_project/public/staff_details";
try {
return String.valueOf(HttpUtils.getJson(cricketAllMatchesLink));
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.v("POST EXECUTE", "RESULT :" + result);
super.onPostExecute(result);
hideProgress();
// mProgressDialog.dismiss();
// if (HttpUtils.status == 408) {
// Toast.makeText(getActivity(), "Conection Lost ",
// Toast.LENGTH_SHORT).show();
// }
try {
JSONArray array = new JSONArray(result);
JSONObject mJsonObject = array.getJSONObject(0);
// ArrayList<user_agent> GetSearchResults();
ArrayList<staff_model> staff_result = new ArrayList<staff_model>();
/**
* Question Array Parsing
*/
JSONArray jsonQuesstionsArray = mJsonObject
.getJSONArray("User_Details");
for (int i = 0; i < jsonQuesstionsArray.length(); i++) {
// Reading questions
JSONObject jsonQuestionObject = jsonQuesstionsArray
.getJSONObject(i);
String name = jsonQuestionObject.getString("name");
String dob = jsonQuestionObject.getString("dob");
String occupation = jsonQuestionObject.getString("occupation");
String emailid = jsonQuestionObject.getString("emailid");
String contact = jsonQuestionObject.getString("contact");
String timetable = jsonQuestionObject.getString("timetable");
String image = jsonQuestionObject.getString("image");
}
lvDetail.setAdapter(new staff_BaseAdapter(
getActivity(), 0,staff_result));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void showProgress() {
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage("Loading please wait");
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
public void hideProgress() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
#Override
public void onDestroy(){
super.onDestroy();
if ( mProgressDialog!=null && mProgressDialog.isShowing() ){
mProgressDialog.cancel();
}
}
}
This is my Adapter class - Where I have gotten the data and set the code
ArrayList<StaffList> myList = new ArrayList<StaffList>();
LayoutInflater inflater;
Context context;
public StaffBaseAdapter(Context context, ArrayList<StaffList> myList) {
this.myList = myList;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public StaffList getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.staff_list_view, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
StaffList currentListData = getItem(position);
mViewHolder.tvTitle.setText(currentListData.getTitle());
return convertView;
}
private class MyViewHolder {
TextView tvTitle, tvDesc;
ImageView ivIcon;
public MyViewHolder(View item) {
tvTitle = (TextView) item.findViewById(R.id.tvTitle);
}
}
}
This is my Model Class
String title;
int imgResId;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getImgResId() {
return imgResId;
}
public void setImgResId(int imgResId) {
this.imgResId = imgResId;
}
}
first your model class "staff_model" implement parcelable it will help to transfer your single model item pass to other activity.
Then add ItemClickListener in your listview
add this into your getView function
MyViewHolder rowHolder=new MyViewHolder(convertView);
rowHolder.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//do whatever u want
}
});
listView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Here you can convert your json to string
startActivity(new Intent(this, MainActivity.class).putExtra("myList",new Gson().toJson(list)));
}
});
and in your receiving activity
Type type = new TypeToken<List<String>>() {
}.getType();
List<String> list1=new Gson().fromJson(getIntent().getStringExtra("myList"),type);
Here Specify the TypeToken .You will have the exact json that you passed in the intent.
I am making Expandable RecyclerView. The problem is I have Data in ArrayList but Adapter is not getting set.
I have tried by setting adapter after arrayListNotiTypes.add(new NotiTypes("About SMS", addNotiToParticularNotiType(jaSms, ""))); this line, but same error occurs. I have made this type of Expandable RecyclerView for different module. There it is working fine.
Below is what I have tried..
Notification_Activity.java
public class Notification_Activity extends AppCompatActivity {
// Widgets
private ProgressDialog progressDialog;
private RecyclerView recyclerView_Noti;
// Variables
private String url = "notification.php";
private ArrayList<NotiTypes> arrayListNotiTypes;
private ArrayList<ActualNotis> arrayListActualNotis;
// Others
private AdapterNotification adapterNoti;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
find_view_by_id();
init();
if (Commom_Methods.isNetworkAvailable(this)) {
fetchData();
} else {
Toast.makeText(this, "Please, Coonect to internet!!", Toast.LENGTH_SHORT).show();
}
// Setting Adapter for Notification
adapterNoti = new AdapterNotification(Notification_Activity.this, arrayListNotiTypes);
recyclerView_Noti.setAdapter(adapterNoti);
recyclerView_Noti.setLayoutManager(new LinearLayoutManager(Notification_Activity.this));
}
private void find_view_by_id() {
recyclerView_Noti = (RecyclerView) findViewById(R.id.recycle_noti);
}
private void init() {
arrayListNotiTypes = new ArrayList<>();
}
private void fetchData() {
StringRequest stringReq = new StringRequest(Request.Method.POST, Constants.base_url + url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("onResponse: ", response);
progressDialog.dismiss();
if (response != null) {
try {
JSONObject jo = new JSONObject(response);
if (jo.has("success")) {
JSONObject joNoti = jo.getJSONObject("notification");
/*JSONArray jaStu = joNoti.getJSONArray("noti_student");
arrayListNotiTypes.add(new NotiTypes("About Student", addNotiToParticularNotiType(jaStu, "")));*/
JSONArray jaBatch = joNoti.getJSONArray("noti_batch");
arrayListNotiTypes.add(new NotiTypes("About Batch", addNotiToParticularNotiType(jaBatch, "")));
JSONArray jaInst = joNoti.getJSONArray("noti_institute");
arrayListNotiTypes.add(new NotiTypes("About Institute", addNotiToParticularNotiType(jaInst, "attach")));
JSONArray jaFee = joNoti.getJSONArray("noti_fee");
arrayListNotiTypes.add(new NotiTypes("About Fees", addNotiToParticularNotiType(jaFee, "attach")));
JSONArray jaSms = joNoti.getJSONArray("noti_sms");
arrayListNotiTypes.add(new NotiTypes("About SMS", addNotiToParticularNotiType(jaSms, "")));
} else {
Toast.makeText(getApplicationContext(), jo.getString("error_msg"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Server error! Don't get Data from server. Try again later.", Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Error:" + error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Preferences.readString(getApplicationContext(), Preferences.KEY_SL_ID, ""));
params.put("tution_center_sl", Preferences.readString(getApplicationContext(), Preferences.KEY_TUTION_CENTER_SL, ""));
params.put("batch_sl", Preferences.readString(getApplicationContext(), Preferences.KEY_BATCH_SL, ""));
params.put("batch_grup_sl", Preferences.readString(getApplicationContext(), Preferences.KEY_BATCH_GRUP_SL, ""));
params.put("co_sl", Preferences.readString(getApplicationContext(), Preferences.KEY_CO_SL, ""));
params.put("drange_sl", Preferences.readString(getApplicationContext(), Preferences.KEY_DRANGE_SL, ""));
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("X-Apikey", Preferences.readString(getApplicationContext(), Preferences.KEY_USER_XAPIKEY, ""));
return headers;
}
};
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(stringReq);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
private ArrayList<ActualNotis> addNotiToParticularNotiType(JSONArray jsonArray, String attachments) throws JSONException {
arrayListActualNotis = new ArrayList<>();
if (jsonArray.length() > 0) {
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject joInner = jsonArray.getJSONObject(j);
String notiTitle = joInner.getString("title");
String notiDesc = joInner.getString("decription");
String attach = "";
if (!attachments.equals(""))
attach = joInner.getString("attach");
arrayListActualNotis.add(new ActualNotis(notiTitle, notiDesc, attach));
}
} else {
arrayListActualNotis.add(new ActualNotis("No Notifications!!", "", ""));
}
return arrayListActualNotis;
}
}
AdapterNotification.java
public class AdapterNotification extends ExpandableRecyclerViewAdapter<AdapterNotification.NotiTypesViewHolder, AdapterNotification.ActualNotisViewHolder> {
private Activity mActivity;
public AdapterNotification(Activity activity, List<? extends ExpandableGroup> groups) {
super(groups);
this.mActivity = activity;
}
#Override
public NotiTypesViewHolder onCreateGroupViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = (LayoutInflater) mActivity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.noti_type_group_view_holder, parent, false);
return new NotiTypesViewHolder(view);
}
#Override
public ActualNotisViewHolder onCreateChildViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = (LayoutInflater) mActivity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.actual_notis_child_view_holder, parent, false);
return new ActualNotisViewHolder(view);
}
#Override
public void onBindGroupViewHolder(NotiTypesViewHolder holder, int flatPosition, ExpandableGroup group) {
holder.setGroupName(group);
}
#Override
public void onBindChildViewHolder(ActualNotisViewHolder holder, int flatPosition, ExpandableGroup group, int childIndex) {
final ActualNotis notis = ((NotiTypes) group).getItems().get(childIndex);
holder.onBind(notis, group);
}
public class NotiTypesViewHolder extends GroupViewHolder {
private TextView txt_noti_type;
public NotiTypesViewHolder(View itemView) {
super(itemView);
txt_noti_type = (TextView) itemView.findViewById(R.id.txt_noti_type);
}
#Override
public void expand() {
txt_noti_type.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.up_arrow, 0);
Log.e("Adapter", "Expand");
}
#Override
public void collapse() {
txt_noti_type.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.down_arrow, 0);
Log.e("Adapter", "collapse");
}
public void setGroupName(ExpandableGroup group) {
txt_noti_type.setText(group.getTitle());
}
}
public class ActualNotisViewHolder extends ChildViewHolder {
private TextView txt_noti, txt_noti_desc;
public ActualNotisViewHolder(View itemView) {
super(itemView);
txt_noti = (TextView) itemView.findViewById(R.id.txt_noti);
txt_noti_desc = (TextView) itemView.findViewById(R.id.txt_noti_desc);
}
public void onBind(ActualNotis actualNotis, ExpandableGroup group) {
switch (actualNotis.getmNotiTitle()) {
case "noti_student":
txt_noti.setText(actualNotis.getmNotiTitle());
txt_noti_desc.setText(actualNotis.getmNotiDesc());
break;
case "noti_batch":
txt_noti.setText(actualNotis.getmNotiTitle());
txt_noti_desc.setText(actualNotis.getmNotiDesc());
break;
case "noti_institute":
txt_noti.setText(actualNotis.getmNotiTitle());
txt_noti_desc.setText(actualNotis.getmNotiDesc());
break;
case "noti_fee":
txt_noti.setText(actualNotis.getmNotiTitle());
txt_noti_desc.setText(actualNotis.getmNotiDesc());
break;
case "noti_sms":
txt_noti.setText(actualNotis.getmNotiTitle());
txt_noti_desc.setText(actualNotis.getmNotiDesc());
break;
default:
break;
}
}
}
}
JSON Response From Server
{
"notification": {
"noti_batch": [
{
"title": "testtest",
"decription": "testtest"
}
],
"noti_institute": [
{
"title": "test",
"decription": "testtest",
"attach": ""
}
],
"noti_fee": [
{
"title": "test",
"decription": "test",
"attach": ""
}
],
"noti_sms": [
{
"title": "2016-11-03 00:00:00",
"decription": ""
}
]
},
"success": true
}
Thanks in advance!
setAdapter after getting data from the server i.e. inside onResponse() Or you have to notify adapter after changing data in List