I was testing the sample code from foursquare-api
What I would like to know, How can I get the onClick item for the list view ?
so after the get the list of venue, If the user click on the list item, I want to send the avenue name to another fragment to handle it.
thanks
Java Coding
ArrayList<FoursquareVenue> venuesList;
ArrayAdapter<String> myAdapter;
private static ArrayList<FoursquareVenue> parseFoursquare(final String response) {
ArrayList<FoursquareVenue> temp = new ArrayList<FoursquareVenue>();
try {
// make an jsonObject in order to parse the response
JSONObject jsonObject = new JSONObject(response);
// make an jsonObject in order to parse the response
if (jsonObject.has("response")) {
if (jsonObject.getJSONObject("response").has("venues")) {
JSONArray jsonArray = jsonObject.getJSONObject("response").getJSONArray("venues");
for (int i = 0; i < jsonArray.length(); i++) {
FoursquareVenue poi = new FoursquareVenue();
if (jsonArray.getJSONObject(i).has("name")) {
poi.setName(jsonArray.getJSONObject(i).getString("name"));
if (jsonArray.getJSONObject(i).has("location")) {
if (jsonArray.getJSONObject(i).getJSONObject("location").has("address")) {
if (jsonArray.getJSONObject(i).getJSONObject("location").has("city")) {
poi.setCity(jsonArray.getJSONObject(i).getJSONObject("location").getString("city"));
}
if (jsonArray.getJSONObject(i).has("categories")) {
if (jsonArray.getJSONObject(i).getJSONArray("categories").length() > 0) {
if (jsonArray.getJSONObject(i).getJSONArray("categories").getJSONObject(0).has("icon")) {
poi.setCategory(jsonArray.getJSONObject(i).getJSONArray("categories").getJSONObject(0).getString("name"));
}
}
}
temp.add(poi);
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
return new ArrayList<FoursquareVenue>();
}
return temp;
}
#Override
protected void onPostExecute(String result) {
if (temp == null) {
// we have an error to the call
// we can also stop the progress bar
} else {
// all things went right
// parseFoursquare venues search result
venuesList = (ArrayList<FoursquareVenue>) parseFoursquare(temp);
List<String> listTitle = new ArrayList<String>();
for (int i = 0; i < venuesList.size(); i++) {
// make a list of the venus that are loaded in the list.
// show the name, the category and the city
listTitle.add(i, venuesList.get(i).getName() + ", " + venuesList.get(i).getCategory() + "" + venuesList.get(i).getCity());
}
// set the results to the list
// and show them in the xml
myAdapter = new ArrayAdapter<String>(LocationActivity.this, R.layout.row_layout, R.id.listText, listTitle);
setListAdapter(myAdapter);
}
}
Thanks
I have tried this :
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Toast.makeText(getApplicationContext(), "position => " + position +
" - ListView =>" + l +
" - View => " + v +
" - id => " + id
, Toast.LENGTH_LONG).show();
}
I can get the position of the listView Item, But I can not the the data of the list view.
I am also using this:
public class FoursquareVenue {
private String name;
private String city;
private String category;
public FoursquareVenue() {
this.name = "";
this.city = "";
this.setCategory("");
}
public String getCity() {
if (city.length() > 0) {
return city;
}
return city;
}
public void setCity(String city) {
if (city != null) {
this.city = city.replaceAll("\\(", "").replaceAll("\\)", "");
;
}
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
init your listview from main.xml
listView = (ListView) findViewById(R.id.listview);
listView.setOnItemClickListener(this);
and add
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
}
Just override
onListItemClick(ListView l, View v, int position, long id)
which is called when an item in the list is selected. Since, you are invoking setListAdapter() I'm assuming you've extended either ListActivity or ListFragment.
To retrieve the ListView data use ListView#getItemAtPosition() method.
Now, here's where you would realise that using an ArrayAdapter<FoursquareVenue> instead of ArrayAdapter<String> would have been better because with the String version, all you would be able to retrieve with getItemAtPosition(), is exactly the same string that you passed at
listTitle.add(i, venuesList.get(i).getName() + ", " +
venuesList.get(i).getCategory() + "" + venuesList.get(i).getCity());
which is clearly not very flexible. You should pass your venuesList directly to the adapter as
myAdapter = new ArrayAdapter<FoursquareVenue>(
LocationActivity.this, R.layout.row_layout, R.id.listText, venuesList);
and then override FoursquareVenue#toString()
public String toString() {
return new StringBuilder(name).append(", ")
.append(category).append(", ").append(city).toString();
}
Related
I am using jd-alexander/LikeButton https://github.com/jd-alexander/LikeButton instead of normal buttons in the android app. The code works fine while enabling and disabling switches. But I want to save the state of the like button. Suppose I enable the like button and swap the list the background code will run fine but the like button state will change to unliked.
Every time when I swap the list the like button state becomes unliked. Is there any way to save the like button State??
Activity codes:
public class CollectorListAdapter extends ArrayAdapter<Collector> {
private static final String TAG = "CollectorListAdapter";
private Context mContext;
private int mResource;
public CollectorListAdapter(Context context, int resource, ArrayList<Collector> objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
}
public View getView(final int position, View convertView, ViewGroup parent) {
//Get the Shop information
String Shopname = getItem(position).getName();
String Specialoffers = getItem(position).getSpecialoffers();
int Price = getItem(position).getPrice();
final Double startLatitude = getItem(position).getLatitude();
final Double startLongitude = getItem(position).getLongitude();
final String user_id = String.valueOf(getItem(position).getUserid());
final String shop_id = String.valueOf(getItem(position).getShopid());
final String product_id = String.valueOf(getItem(position).getProductid());
//create the view result for showing the animation
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
TextView sname = (TextView) convertView.findViewById(R.id.textView);
TextView tvname = (TextView) convertView.findViewById(R.id.textView7);
TextView Location = (TextView) convertView.findViewById(R.id.textView9);
TextView tvdescription = (TextView) convertView.findViewById(R.id.textView10);
sname.setText(Shopname);
tvdescription.setText(Specialoffers);
tvname.setText(CurrencyFormatting(Integer.toString(Price)) + " EGP");
Location.setText(format(results[0]) + " km");
LikeButton heart;
heart = convertView.findViewById(R.id.favBtn);
heart.setOnLikeListener(new OnLikeListener() {
// Add Data to the Saved Shop Table by like
#Override
public void liked(LikeButton likeButton) {
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.URL_SAVED_SHOPS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", user_id);
params.put("shop_id", shop_id);
params.put("product_id", product_id);
return params;
}
};
Volley.newRequestQueue(getContext()).add(strReq);
Toast.makeText(getContext(),
"Shop Saved Successfully", Toast.LENGTH_LONG).show();
}
// Delete Data to the Saved Shop Table by Unlike
#Override
public void unLiked(LikeButton likeButton) {
StringRequest strReq10 = new StringRequest(Request.Method.POST, AppConfig.URL_Delete_SAVED_SHOPS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", user_id);
params.put("shop_id", shop_id);
params.put("product_id", product_id);
return params;
}
};
Volley.newRequestQueue(getContext()).add(strReq10);
Toast.makeText(getContext(),
"Shop Saved Deleted Successfully", Toast.LENGTH_LONG).show();
}
});
return convertView;
}
}
Collector Class:
public class Collector implements java.io.Serializable {
private String specialoffers, name;
private Double latitude, longitude;
private int price,userid,shopid,productid;
public Collector() {
}
//Sorting by Price method
public static Comparator<Collector> PriceSort = new Comparator<Collector>() {
public int compare(Collector s1, Collector s2) {
int rollno1 = s1.getPrice();
int rollno2 = s2.getPrice();
/*For ascending order*/
return rollno1 - rollno2;
/*For descending order*/
//rollno2-rollno1;
}
};
//Sorting by Distance method
public static Comparator<Collector> DistanceSort = new Comparator<Collector>() {
public int compare(Collector s1, Collector s2) {
float[] results1 = new float[3];
Location.distanceBetween(
LocationActivity.currentLocation.getLatitude(),
LocationActivity.currentLocation.getLongitude(),s1.getLatitude(),
s1.getLongitude(),
results1);
float[] results2 = new float[3];
Location.distanceBetween(
LocationActivity.currentLocation.getLatitude(),
LocationActivity.currentLocation.getLongitude(),s2.getLatitude(),
s2.getLongitude(),
results2);
/*For ascending order*/
return Float.compare(results1[0], results2[0]);
/*For descending order*/
//rollno2-rollno1;
}
};
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public int getShopid() {
return shopid;
}
public void setShopid(int shopid) {
this.shopid = shopid;
}
public int getProductid() {
return productid;
}
public void setProductid(int productid) {
this.productid = productid;
}
public String toString() {
return ("Shop Name:" + getName() +
" Price : " + getPrice() +
" SpecialOffers : " + getSpecialoffers() +
" latitude : " + getLatitude()) +
" longitude : " + getLongitude();
}
public String getSpecialoffers() {
return specialoffers;
}
public void setSpecialoffers(String specialoffers) {
this.specialoffers = specialoffers;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
This is the normal behaviour in ArrayAdapter, the whole list gets recreated again so you lose the state of the button. You should save the boolean of the button in the local list variable.
Add a field like isLiked = true/false in the Collector class and update the value at the particular position every time user click like/unlike buttons.
For some reason the only thing displayed in my RecyclerView is com.stu54259.plan2cook.Model.Shopping_list#5cb7482 repeated with various end codes not the contents of the ArrayList. Any suggestions must be something with the recylerview adapter. Can add xml etc if need be but i'm sure I've just missed something stupid.
Shopping_List class
package com.stu54259.plan2cook.Model;
public class Shopping_List {
private int id;
private String ingredient_type;
private String ingredient_name;
private Double quantity;
private String measurement_name;
public Shopping_List() {
}
public Shopping_List(String ingredient_type, String ingredient_name, Double quantity, String measurement_name) {
this.ingredient_type = ingredient_type;
this.ingredient_name = ingredient_name;
this.quantity = quantity;
this.measurement_name = measurement_name;
}
public Shopping_List(int id, String ingredient_type, String ingredient_name, Double quantity, String measurement_name) {
this.id = id;
this.ingredient_type = ingredient_type;
this.ingredient_name = ingredient_name;
this.quantity = quantity;
this.measurement_name = measurement_name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getIngredient_type() {
return ingredient_type;
}
public void setIngredient_type(String ingredient_type) {
this.ingredient_type = ingredient_type;
}
public String getIngredient_name() {
return ingredient_name;
}
public void setIngredient_name(String ingredient_name) {
this.ingredient_name = ingredient_name;
}
public Double getQuantity() {
return quantity;
}
public void setQuantity(Double quantity) {
this.quantity = quantity;
}
public String getMeasurement_name() {
return measurement_name;
}
public void setMeasurement_name(String measurement_name) {
this.measurement_name = measurement_name;
}
}
Activity
public class ShoppingList extends MainActivity {
ShoppingListAdapter adapterRecipe;
List<Shopping_List> shopList = new ArrayList<>();
RecyclerView listIngredient;
SQLiteDatabase db;
Cursor c;
EditText edittext;
String search;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shopping_list);
edittext = findViewById(R.id.editPlanName);
edittext.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
search = edittext.getText().toString();
Log.d("Search value", search);
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
loadIngredient();
adapterRecipe.notifyDataSetChanged();
return true;
}
return false;
}
});
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent a = new Intent(ShoppingList.this,MainActivity.class);
startActivity(a);
break;
case R.id.recipes:
Intent b = new Intent(ShoppingList.this,RecipeSearch.class);
startActivity(b);
break;
case R.id.shoppingList:
Intent c = new Intent(ShoppingList.this, ShoppingList.class);
startActivity(c);
break;
case R.id.mealPlan:
Intent d = new Intent(ShoppingList.this, MenuPlan.class);
startActivity(d);
break;
case R.id.reminder:
Intent e = new Intent(ShoppingList.this, Reminders.class);
startActivity(e);
break;
}
return false;
}
});
adapterRecipe = new ShoppingListAdapter(this, shopList);
listIngredient = findViewById(R.id.listIngredient);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
listIngredient.setLayoutManager(mLayoutManager);
listIngredient.setItemAnimator(new DefaultItemAnimator());
listIngredient.setAdapter(adapterRecipe);
}
public void loadIngredient() {
shopList.clear();
db = (new DatabaseManager(this).getWritableDatabase());
String RECIPE_SEARCH =
"SELECT SUM(A.ingredient_quantity) quantity, A.ingredient ingredient_name, A.recipe, B.ingredient_type, B.measurement_name, C.id, D.plan_name " +
"FROM " + DatabaseManager.TABLE_QUANTITY + " AS A JOIN " + DatabaseManager.TABLE_INGREDIENTS + " AS B ON A.ingredient = B.ingredient_name " +
"JOIN " + DatabaseManager.TABLE_PLAN_RECIPES + " AS C ON A.recipe = C.recipe_name " +
"JOIN " + DatabaseManager.TABLE_MEAL_PLAN + " AS D ON C.id = D.plan_recipe " +
"WHERE D.plan_name LIKE ? GROUP BY A.ingredient";
Log.d("Search query", RECIPE_SEARCH);
c = db.rawQuery(RECIPE_SEARCH, new String[]{"%" + search + "%"});
if (c.moveToFirst()) {
do {
Shopping_List shopping_list = new Shopping_List();
shopping_list.setQuantity(c.getDouble(c.getColumnIndex("quantity")));
shopping_list.setIngredient_name(c.getString(c.getColumnIndex("ingredient_name")));
shopping_list.setIngredient_type(c.getString(c.getColumnIndex("ingredient_type")));
shopping_list.setMeasurement_name(c.getString(c.getColumnIndex("measurement_name")));
shopList.add(shopping_list);
} while (c.moveToNext());
}
c.close();
db.close();
}
}
Adapter
public class ShoppingListAdapter extends RecyclerView.Adapter<com.stu54259.plan2cook.Adapters.ShoppingListAdapter.ViewHolder> {
private List<Shopping_List> shopList;
private LayoutInflater mInflater;
private com.stu54259.plan2cook.Adapters.RecyclerViewAdapter.ItemClickListener mClickListener;
// data is passed into the constructor
public ShoppingListAdapter(Context context, List<Shopping_List> data) {
this.mInflater = LayoutInflater.from(context);
this.shopList = data;
}
// inflates the row layout from xml when needed
#Override
public com.stu54259.plan2cook.Adapters.ShoppingListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.fragment_item, parent, false);
return new com.stu54259.plan2cook.Adapters.ShoppingListAdapter.ViewHolder(view);
}
// binds the data to the TextView in each row
#Override
public void onBindViewHolder(com.stu54259.plan2cook.Adapters.ShoppingListAdapter.ViewHolder holder, int position) {
if(shopList.get(position) != null)
{
holder.myTextView.setText(shopList.get(position).toString());
}
}
// total number of rows
#Override
public int getItemCount() {
return shopList.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.quantity);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// allows clicks events to be caught
void setClickListener(com.stu54259.plan2cook.Adapters.RecyclerViewAdapter.ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
Add this method in your Shopping_List class, so when you use toString() for a Shopping_List instance you will get all its properties separated by spaces:
public String toString() {
return ingredient_name + " " + ingredient_type + " " + quantity + " " + measurement_name;
}
You can change the order of the properties.
You have wrong code in onBindViewHolder method. You should set text with some field from Shopping_List object:
#Override
public void onBindViewHolder(com.stu54259.plan2cook.Adapters.ShoppingListAdapter.ViewHolder holder, int position) {
if(shopList.get(position) != null)
{
holder.myTextView.setText(shopList.get(position).toString());
}
}
You haven't put the Shopping_List object here, but if you have something like this:
public class Shopping_List {
public String title;
public String getTitle() {
return title;
}
}
Then you should do something like this:
#Override
public void onBindViewHolder(com.stu54259.plan2cook.Adapters.ShoppingListAdapter.ViewHolder holder, int position) {
if(shopList.get(position) != null)
{
holder.myTextView.setText(shopList.get(position).getTitle());
}
}
Although it doesn't give a direct solution, I would suggest that you use the groupie library. It will most likely remove your error and reduce boilerplate code and complexity.
I have 2 model classes(Data,Title) which contain the same field:
String dataID. I want to get both of this IDs with interface implementation.
I am passing Title model through Bundle to another Activity, passing Data model through Bundle in that same activity(just creating new instance of the activity and resetting information).
I want both of my model classes to implement SharedID interface, with method String getSharedId();
How can I get different ids but from different models? I need to put only one parameter and it should be String in my ViewModelFactory constructor.
public class Data implements SharedId,Parcelable {
private String text;
private String textHeader;
private int viewType;
private String mainId;
private String dataID;
public Data() { }
public String getDataID() {
return dataID;
}
public void setDataID(String dataID) {
this.dataID = dataID;
}
public String getText() {return (String) trimTrailingWhitespace(text); }
public void setText(String text) {
this.text = (String) trimTrailingWhitespace(text);
}
public String getTextHeader() {
return (String) trimTrailingWhitespace(textHeader);
}
public void setTextHeader(String textHeader) {
this.textHeader = textHeader;
}
public int getViewType() {
return viewType;
}
public void setViewType(int viewType) {
this.viewType = viewType;
}
public String getMainId() {
return mainId;
}
public void setMainId(String mainId) {
this.mainId = mainId;
}
protected Data(Parcel in) {
text = in.readString();
textHeader = in.readString();
viewType = in.readInt();
mainId = in.readString();
dataID = in.readString();
}
#Override
public String toString() {
return "Data{" +
"order=" +
", text='" + text + '\'' +
", textHeader='" + textHeader + '\'' +
", viewType=" + viewType +
'}';
}
#SuppressWarnings("StatementWithEmptyBody")
public static CharSequence trimTrailingWhitespace(CharSequence source) {
if (source == null) {
return "";
}
int i = source.length();
// loop back to the first non-whitespace character
while (--i >= 0 && Character.isWhitespace(source.charAt(i))) {
}
return source.subSequence(0, i + 1);
}
public static final Creator<Data> CREATOR = new Creator<Data>() {
#Override
public Data createFromParcel(Parcel in) {
return new Data(in);
}
#Override
public Data[] newArray(int size) {
return new Data[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(text);
dest.writeString(textHeader);
dest.writeInt(viewType);
dest.writeString(mainId);
dest.writeString(dataID);
}
#Override
public String getSharedDataId() {
return getDataID();
}
}
public class Title implements SharedId,Parcelable {
private String dataID;
private String title;
public Title() { }
protected Title(Parcel in) {
dataID = in.readString();
title = in.readString();
}
public String getDataID() {
return dataID;
}
public void setDataID(String dataID) {
this.dataID = dataID;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public static final Creator<Title> CREATOR = new Creator<Title>() {
#Override
public Title createFromParcel(Parcel in) {
return new Title(in);
}
#Override
public Title[] newArray(int size) {
return new Title[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(dataID);
dest.writeString(title);
}
#NonNull
#Override
public String toString() {
return "Title{" +
"dataID='" + dataID + '\'' +
", titleOrder=" +
", title='" + title + '\'' +
'}';
}
#Override
public String getSharedDataId() {
return getDataID();
}
}
And My DetailActivity code, I already succeeded with the mission of passing id, but i need to do this trough interfaces :( So help me out friends, would really appreciate it!
public class DetailActivity extends AppCompatActivity implements
DetailAdapter.OnDialogClickListener,
DetailAdapter.OnDetailClickListener {
private static String id;
private String parentId;
private Data data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
TextView tvToolbarTitle = findViewById(R.id.title_toolbar_detail);
tvToolbarTitle.setSelected(true);
findViewById(R.id.btn_back).setOnClickListener(v -> finish());
ArrayList<SharedId> sharedIds = new ArrayList<>();
sharedIds.add(new Title());
sharedIds.add(new Data());
for (SharedId sharedId : sharedIds){
System.out.println(sharedId.getSharedDataId());
}
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
Title model = bundle.containsKey("ID") ? bundle.getParcelable("ID") : null;
Data childModel = bundle.containsKey("idDetail") ? bundle.getParcelable("idDetail") : null;
}
if (bundle != null) {
Title model = bundle.containsKey("ID") ? bundle.getParcelable("ID") : null;
Data childModel = bundle.containsKey("idDetail") ? bundle.getParcelable("idDetail") : null;
String parentId = bundle.getString("mainScreenId");
if (parentId != null) {
this.parentId = parentId;
}
if (model != null) {
this.id = model.getDataID();
tvToolbarTitle.setText(model.getTitle());
}
if (childModel != null) {
this.id = childModel.getDataID();
tvToolbarTitle.setText(childModel.getTextHeader());
}
}
RecyclerView recyclerView = findViewById(R.id.rv_detail);
DetailAdapter adapter = new DetailAdapter(this, this);
recyclerView.setAdapter(adapter);
// TODO: 3/1/19 change it to single ID // DetailViewModelFactory(); // id != null ? id : parentId
DetailViewModelFactory detailViewModelFactory = new DetailViewModelFactory(id != null ? id : parentId);
DetailActivityViewModel viewModel = ViewModelProviders.of(this, detailViewModelFactory).get(DetailActivityViewModel.class);
FirebaseListLiveData<Data> liveData = viewModel.getLiveDataQuery();
liveData.observe(this, adapter::setNewData);
}
#Override
public void onDialogClicked(#NonNull String text) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(HtmlCompat.fromHtml(text, 0, null, new HandlerHtml()));
builder.setPositiveButton("Ok", null);
builder.show();
}
#Override
public void onDetailClicked(Data data) {
Intent intent = new Intent();
DetailActivity.open(DetailActivity.this);
intent.putExtra("idDetail", data);
intent.putExtra("mainScreenId", id);
startActivity(intent);
}
public static void open(#NonNull Context context) {
context.startActivity(new Intent(context, InfoActivity.class));
}
}
I found a bit different, but working solution!
I create an interface
public interface SharedId {
String getSharedDataId();
String getHeader();
}
Both of my model classes Data + Title implemented Interface and methods from it.
In DetailActivity i created 2 Strings.
private String mainId;
private String detailId;
And then passed ids with my model classes with bundle
`SharedId mainId = new Title();
SharedId detailId = new Data();
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
mainId = bundle.containsKey("ID") ? bundle.getParcelable("ID") : null;
detailId = bundle.containsKey("idDetail") ?
bundle.getParcelable("idDetail") : null;
}
if (mainId != null) {
this.detailId = mainId.getSharedDataId();
tvToolbarTitle.setText(mainId.getHeader());
}
if (detailId != null) {
this.mainId = detailId.getSharedDataId();
tvToolbarTitle.setText(detailId.getHeader());
}
And passed in my ViewmodelFactory
DetailViewModelFactory detailViewModelFactory =
new DetailViewModelFactory(this.detailId != null ?
this.detailId : this.mainId);
This is the Java code where I am parsing the data-
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...Please Wait...");
pDialog.show();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://sikkimexpress.itstunner.com/api/homenewslist/topnews", new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("HomeNews");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject homenews = jsonArray.getJSONObject(i);
Movie movie = new Movie();
String newsId = homenews.getString("NewsId");
String dateTime = homenews.getString("DateTime");
String newsType = homenews.getString("NewsType");
String title = homenews.getString("Title");
String description = homenews.getString("Description");
String mainImageURL = homenews.getString("MainImageThumbnail");
movieList.add(movie);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
System.out.println("Result:- " + newsId + " " + dateTime + " " + newsType + " " + title + " " + description + " " + mainImageURL);
}
} catch (JSONException e) {
e.printStackTrace();
}
// pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.getMessage());
// pDialog.hide();
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
This is the Model Class:-
public class Movie {
private String newsId;
private String dateTime;
private String newsType;
private String title;
private String description;
private String thumbnailUrl;
public Movie() {
}
public Movie(String news_id, String date_time, String news_type, String news_title, String news_description, String news_thumbnailUrl) {
this.title = news_title;
this.thumbnailUrl = news_thumbnailUrl;
this.newsId = news_id;
this.dateTime = date_time;
this.newsType = news_type;
this.description = news_description;
}
public String getNewsId() {
return newsId;
}
public void setNewsId(String newsId) {
this.newsId = newsId;
}
public String getDateTime() {
return dateTime;
}
public void setDateTime(String dateTime) {
this.dateTime = dateTime;
}
public String getNewsType() {
return newsType;
}
public void setNewsType(String newsType) {
this.newsType = newsType;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
}
The CustomListView Adapter:-
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Movie> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView.findViewById(R.id.thumbnail);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView desciption = (TextView) convertView.findViewById(R.id.desciption);
Movie m = movieItems.get(position);
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
title.setText(m.getTitle());
desciption.setText(m.getDescription());
return convertView;
}
}
There is no error while Parsing the data from server. I am getting the actual result. But the Progress Dialog is running after getting the data from the server. The data are not getting set in the CustomListView Adapter. I have already attached the code. Please Help me. I got stuck in it.
You are not closing your Dialog when you have your data.
You should not load data on the "main thread" - use a AsyncTask or something similiar to load your data. There you can show a progress dialog, before you start downloading your data:
From the docs:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
//Once created, a task is executed very simply:
new DownloadFilesTask().execute(url1, url2, url3);
Also, don't set the adapter multiple times to your ListView (unless you use a different adapter), and call notifyDataSetChanged() everytime your underlying data changes. r data, show progress and stop the dialog when you are finished.
But the Progress Dialog is running after getting the data from the server.?
ans: you are not closing the dialog in onResponse method
For listview you are not setting adapter with updated data. Please create a new adapter or follow this How to update listview when back pressed from another activity android?
You need to dismiss progressdialog in this two response method to hide.
#Override public void onResponse(JSONObject response) { pDialog.dismiss(); }
#Override public void onErrorResponse(VolleyError error) { pDialog.dismiss(); }
In onResponse() method after parsing json you need to notify adapter to display data in list.
I am having a custom adapter with checkbox and child elements in an expandable custom adapter, and when the parent items - for my case Orders are selected /checked the Orders are passed to a new custom adapter without checkbox . I am able pass the parent ie Orders but i am not able to pass the Child elements ie Items which are the childreen of ORDERS. So i need to pass the child elements of the orders that are selected to the new adapter view.
My code :
try {
System.out.println("READ/PARSING JSON");
serverStatus = jobj.getString("SERVER_STATUS");
System.out.println("serverStatusObj: "+serverStatus);
JSONArray serverResponseArray2=jobj.getJSONArray("SERVER_RESPONSE");
for (int m = 0; m < serverResponseArray2.length(); m++) {
String SERVER_RESPONSE = serverResponseArray2.getString(m);
JSONObject Open_Orders_obj = new JSONObject(SERVER_RESPONSE);
mMAX_ORDERS_TOBEPICKED = Open_Orders_obj.getInt("MAX_ORDERS_TOBEPICKED");
JSONArray ja = Open_Orders_obj.getJSONArray("ORDER_ITEM_DETAILS");
order_Item_Values.clear();
mOpenOrders = new ArrayList<OpenOrders>(ja.length());
for(int i=0; i<ja.length(); i++){
String ORDER_ITEM_DETAILS = ja.getString(i);
jobj1 = new JSONObject(ORDER_ITEM_DETAILS);
String ORDERNAME = jobj1.getString("ORDERNAME");
String ORDERID = jobj1.getString("ORDERID");
final OpenOrders parent = new OpenOrders();
parent.setOrderName(ORDERNAME+ " "+ i);
parent.setOrderID(ORDERID);
parent.setChecked((i % 2) == 0);
OpenOrders openOrderObj= new OpenOrders(ORDERID,ORDERNAME);
JSONArray Order_Items = jobj1.getJSONArray("ITEMS");
itemList =new ArrayList<String>();
parent.setChildren(new ArrayList<Child>());
for(int k=0; k<Order_Items.length(); k++){
String ITEMS = Order_Items.getString(k);
System.out.println(ITEMS);
ItemObj = new JSONObject(ITEMS);
String ITEMNUMBER = ItemObj.getString("ITEMNUMBER");
String ITEMNAME = ItemObj.getString("ITEMNAME");
itemList.add(ITEMNAME);//This adds item name's to the ArrayList named 'itemList'
openOrderObj.setItemID(ITEMNUMBER);
openOrderObj.setItemName(ITEMNAME);
System.out.println("item name"+ITEMNAME);
final Child child = new Child();
child.setName(ITEMNAME + i + "/" + k);
parent.getChildren().add(child);
}
mOpenOrders.add(parent);
}
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} //***End code to read json content from text file saved in device
enter code here
My open Order class:
import java.io.Serializable;
import java.util.ArrayList;
import com.kits.ddf_order_model.Child;
public class OpenOrders implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String orderID;
private String orderName;
private boolean selected;
private boolean checked;
private ArrayList<Child> children;
private String itemID;
private String itemName;
public OpenOrders(String orderID, String orderName) {
super();
this.orderID = orderID;
this.orderName = orderName;
}
public OpenOrders() {
// TODO Auto-generated constructor stub
}
public String getOrderID() {
return orderID;
}
public void setOrderID(String orderID) {
this.orderID = orderID;
}
public String getOrderName() {
return orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
#Override
public String toString() {
return this.orderName;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public ArrayList<Child> getChildren()
{
return children;
}
public void setChildren(ArrayList<Child> children)
{
this.children = children;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String getItemID() {
return itemID;
}
public void setItemID(String itemID) {
this.itemID = itemID;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
}
my Child class:
public class Child
{
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
So When the button is clicked what i do is :
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mAdapter != null) {
int isSelectedOrderNumber=0;//This Variable will check with the parameter passed from server
mOpenOrdersSelected = new ArrayList<OpenOrders>();
StringBuffer sb = new StringBuffer();
Iterator<OpenOrders> it = mOpenOrders.iterator();
while(it.hasNext())
{
OpenOrders objOpenOrders = it.next();
//Do something with objOpenOrders
if (objOpenOrders.isChecked()) {
isSelectedOrderNumber++;
// mOpenOrdersSelected.add(new OpenOrders(objOpenOrders.getOrderID(),objOpenOrders.getOrderName()));
sb.append(objOpenOrders.getOrderID());
sb.append(",");
final OpenOrders parent = new OpenOrders(objOpenOrders.getOrderID(),objOpenOrders.getOrderName());
ArrayList<Child> mOpenOrderItems=objOpenOrders.getChildren();
Iterator<Child> i = mOpenOrderItems.iterator();
mOpenOrdersSelected.add(parent);
}
}
//Below Condition Will Check the selected Items With parameter passed "mMAX_ORDERS_TOBEPICKED"
if(isSelectedOrderNumber<1){
ShowErrorDialog("Please Select atleast One order");
return;
}
if(isSelectedOrderNumber>mMAX_ORDERS_TOBEPICKED){
ShowErrorDialog(" Select Maximum of "+mMAX_ORDERS_TOBEPICKED+ " Orders only to process");
return;
}
//Below code is to Call again the adapter and Displays the Order's which are checked/selected.
expListView = (ExpandableListView) findViewById(R.id.expandable_order_item_list);
ExpandableOrderSelectedListAdapter mOrderSelectedAdapter = new ExpandableOrderSelectedListAdapter(SelectLocationActivity.this,mOpenOrdersSelected);
expListView.setAdapter(mOrderSelectedAdapter);
expListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//nothing to do , as Null Pointer exception Occurred ,to avoid that I just used this "setOnItemClickListener"
}
});
button.setVisibility(View.GONE);//Hide the Initial Button in the view
fullfilment_btn.setVisibility(View.VISIBLE);//Displays the confirm Button
fullfilment_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
}
}
});
So here in this part of the code i get error while iterating the child elements .
Any help will be greatfull
I Solved this issue by a for loop, which will add the child to the new "mOpenOrderSelected" variable:
if (objOpenOrders.isChecked()) {
isSelectedOrderNumber++;
sb.append(objOpenOrders.getOrderID());
sb.append(",");
final OpenOrders parent = new OpenOrders(objOpenOrders.getOrderID(),objOpenOrders.getOrderName());
ArrayList<Child> mOpenOrderItems=objOpenOrders.getChildren();
parent.setChildren(new ArrayList<Child>());
for(int k=0; k<mOpenOrderItems.size(); k++){
final Child child = (Child) mOpenOrderItems.get(k);
Log.d("ChildItemsname", "ChildItemsname:"+child.getName());
parent.getChildren().add(child);
}
mOpenOrdersSelected.add(parent);
}
So the new button click code will be like this:
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mAdapter != null) {
int isSelectedOrderNumber=0;//This Variable will check with the parameter passed from server
mOpenOrdersSelected = new ArrayList<OpenOrders>();
StringBuffer sb = new StringBuffer();
Iterator<OpenOrders> it = mOpenOrders.iterator();
while(it.hasNext())
{
OpenOrders objOpenOrders = it.next();
//Do something with objOpenOrders
if (objOpenOrders.isChecked()) {
isSelectedOrderNumber++;
sb.append(objOpenOrders.getOrderID());
sb.append(",");
final OpenOrders parent = new OpenOrders(objOpenOrders.getOrderID(),objOpenOrders.getOrderName());
ArrayList<Child> mOpenOrderItems=objOpenOrders.getChildren();
parent.setChildren(new ArrayList<Child>());
for(int k=0; k<mOpenOrderItems.size(); k++){
final Child child = (Child) mOpenOrderItems.get(k);
Log.d("ChildItemsname", "ChildItemsname:"+child.getName());
parent.getChildren().add(child);
}
mOpenOrdersSelected.add(parent);
}
}
//Below Condition Will Check the selected Items With parameter passed "mMAX_ORDERS_TOBEPICKED"
if(isSelectedOrderNumber<1){
ShowErrorDialog("Please Select atleast One order");
return;
}
if(isSelectedOrderNumber>mMAX_ORDERS_TOBEPICKED){
ShowErrorDialog(" Select Maximum of "+mMAX_ORDERS_TOBEPICKED+ " Orders only to process");
return;
}
//Below code is to Call again the adapter and Displays the Order's which are checked/selected.
expListView = (ExpandableListView) findViewById(R.id.expandable_order_item_list);
ExpandableOrderSelectedListAdapter mOrderSelectedAdapter = new ExpandableOrderSelectedListAdapter(SelectLocationActivity.this,mOpenOrdersSelected);
expListView.setAdapter(mOrderSelectedAdapter);
expListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//nothing to do , as Null Pointer exception Occurred ,to avoid that I just used this "setOnItemClickListener"
}
});
button.setVisibility(View.GONE);//Hide the Initial Button in the view
fullfilment_btn.setVisibility(View.VISIBLE);//Displays the confirm Button
fullfilment_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
}
}
});