This is my code:
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("name")); //get json array name
}
// adding movie to movies array
movieList.add(movie);
}
and I have click listener like this when list onclick:
listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
//update json array name to sqlite
db.updateUser(XXXXXXXXXXXXXX); // this value i want get from json array movie.setTitle()
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
How can I get value from jsonarray and use it to onclicklistener?
Someone suggested using a bean class, but I'm not sure I understand how to do that..
In your Class which has the JsonArray
//create an ivar
private static Movie myMovie // <- this is the value you want.
// then make a method
public static Moive getMovie(){return MyJSONArrayClass.myMovie}
// modify your json Class to do this
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
myMovie = new Movie();
movie.setTitle(obj.getString("name")); //get json array name
}
// adding movie to movies array
movieList.add(movie);
}
// then in the class with the onclick listener do
listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
//update json array name to sqlite
db.updateUser(XXXXXXXXXXXXXX); // this value i want get from json array movie.setTitle()
Intent i = new Intent(getApplicationContext(), MainActivity.class);
Movie movie = MyJSONArrayClass.getMovie();
if(null != movie){
// add your code here
}
startActivity(i);
}
});
you could also look at implementing a Singleton to serve the movie if you dont want to use statics
In your first code snippet, the response variable references the JSON array, which you apparently received as the response from a network request. If you want the adapter to be able to continue to use that data after that code's method returns, you need to either retain a reference to the original data or you need to make a copy of the data (and either store it in memory for the lifetime of the adapter, or persist it somehow).
In your second code snippet, you only seem to need the movie titles. It so happens that in you first snippet, you are storing in movieList a list of Movie objects (each of which contains a movie title). So, if movieList is available for your second snippet to use, and if the Movie class provides a way to get the movie title (say, a getTitle() method), then you can do something like this in your second snippet to get the title of the clicked item:
String movieTitle = movieList.get(position).getTitle();
Note: The third parameter of onItemClick() is the position of the clicked item. Also, I assume that movieList has a type similar to java.util.List<Movie>.
Related
I am new and naive to android development so I apologize if this a very basic question.
In our current application, I have a recyclerview which renders a checkbox which contains a list of categories. Within each category, there are several other sub categories for example
Food (One of the Categories)
Veggies
Poultry
Meat
so on and so forth let's say 10 such sub-categories
My concern is initially on page load, the subcategory has 10 items. When the user scrolls in a way that only 5 items are visible on the UI and then selects the last value in sub category, I see an index out of bounds exception.
Root cause is that within the onBindView method, the sub category arraylist got refreshed by recyclerview to hold only 5 items and when I try to get(10th) position from that arraylist, I run into out of bounds exception.
I have spent 3 days searching this on the web but I have no idea how to stop my arraylist from getting refreshed such that it does not change its value if some of the categories are not visible on the UI when a user scrolls.
Request your help so that I can bring a peaceful end to 2020.
Below is my onbindview snippet
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.setIsRecyclable(false);
subCategoryModel = arrayList_sub_categories.get(position);
holder.catName.setText(subCategoryModel.getsSubCatName());
holder.catName.setChecked(arrayList_sub_categories.get(position).getSelected());
holder.catName.setTag(position);
String strSubCategory = SharedPrefrence_Seller.getFixr_shop_Subcategoryid();
holder.catName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//This is where I try to get the selected tag which gives me the index 10th if I selected the last sub category
Integer pos = (Integer) holder.catName.getTag();
//Below line gives an index out of bounds because my arrayList_sub_categories got refreshed to have only 5 values which are visible on the UI and I am trying to get the 10th value
subCategoryModel = arrayList_sub_categories.get(pos);
req = split;
if(!(subCategoryModel==null)) {
//Do bunch of stuff here
}
I am adding more code snippets to tell you about the list in question arrayList_sub_categories is set via API callout in another class via the below snippet
private void func_fetch_CategoryAPI(final String sCategoryNAme, final String stype) {
requestQueue = VolleySingleton.getInstance(ServiceSelctionActivity.this).getRequestQueue();
//if everything is fine
StringRequest stringRequest = new StringRequest(Request.Method.POST, Urls.URL_SALES_FETCH_CATEGORY_ITEMS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting response to json object and all this is not relevant to this question
JSONObject obj = new JSONObject(response);
String str = obj.getString("data");
arrayListCatItem.clear();
arrayListsubCatItem.clear();
JSONArray jsonArray = new JSONArray(str);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsoObject = jsonArray.getJSONObject(i);
Model_Item_Category model_item_category = new Model_Item_Category();
hashMapListChooseCat = new HashMap<>();
hashMapListChooseCatStatus = new HashMap<>();
model_item_category.setCatId(jsoObject.getString("id"));
model_item_category.setPosition_key(jsoObject.getString("position_key"));
model_item_category.setCatName(jsoObject.getString("cat_name"));
model_item_category.setCatIconName(jsoObject.getString("image_url"));
model_item_category.setSub_cat_status(jsoObject.getString("sub_cat_status"));
//finally
model_item_category.setCheckLevel(strcheck_level);
strSelectedService = SharedPrefrence_Seller.getFixr_shop_categoryid();
arrayListCatItem.add(model_item_category);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
//Here is where adapter_category is set which is a custom class object that includes the list model_item_category in question
rvSelectService.setAdapter(adapter_category);
adapter_category.notifyDataSetChanged();
}
}
Definition of adapter_category is
public Adapter_Category(Context activity, List<Model_Item_Category> subCategoryList, HashMap<String, String> hashMapListChooseCat,
HashMap<String, String> hashMapListChooseCatStatus, TextView tvService)
I'm not sure if this will fix the problem but you can give it a shot. In your getItemCount() method, did you accidently minus 1? If so remove that and just include the size of the arrayList_sub_categories.
#Override
public int getItemCount() {
return arrayList_sub_categories.size();
}
JSON format
I want to display the json in list view ,
here is my code
Call> call = api.getScheduledTasks("atos");
call.enqueue(new Callback<List<ScheduledTasks>>() {
#Override
public void onResponse(Call<List<ScheduledTasks>> call, Response<List<ScheduledTasks>> response) {
Toast.makeText(getApplicationContext(),"successsss",Toast.LENGTH_LONG);
List<ScheduledTasks> ScheduledTasksList = response.body();
// ScheduledTasksList.toString();
//Creating an String array for the ListView
String[] scheduledtask = new String[ScheduledTasksList.size()];
//looping through all the heroes and inserting the names inside the string array
for (int i = 0; i < ScheduledTasksList.size(); i++) {
scheduledtask[i] = ScheduledTasksList.get(i).getScheduleId();
}
//displaying the string array into listview
listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, scheduledtask));
It shows failure ,it doesnt display in list view because of int in json.Kindly provide me the right method,to display both string and int in array.
copy your json response, nothing but image which you upload for this question, and paste in this website. then the website(tool) convert your json response to POJO class and you can access easily like calling any setter and getter method.
hope this solve your problem.
How do I display multiple rows of data in ListView?
Now I am only able to retrieve and display one data(Item) at a time, I want to retrieve multiple rows of data(Items) and display all them in ListView.
In this case, I am using the name of the user to retrieve the coupons he/she have in the database. So for i can only display one coupon and I want to know how to display multiple coupon in ListView.
protected String doInBackground(String... args) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
JSONObject json = jsonParser.makeHttpRequest(
url_all_coupons, "GET", params);
Log.d("Single Voucher Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
JSONArray productObj = json
.getJSONArray(TAG_COUPONS); // JSON Array
JSONObject coupons = productObj.getJSONObject(0);
To populate the ListView I suggest you create a List of objects (vouchers) and create an Adapter that knows how to display any number of coupons in the list. First of all you may want to define a simple class for your coupons (reimplement it according to your data structure):
public class Coupon {
private String mCouponText;
public Coupon(String text) {
mCouponText = text;
}
public String getCouponText() {
return mCouponText;
}
}
After that you should create a List of these objects from your JSONArray. There are different approaches, one of them:
List<Coupon> couponsList = new ArrayList<>();
JSONArray coupons = json
.getJSONArray(TAG_COUPONS); // JSON Array
for (JSONObject coupon : (Iterable<JSONObject>) coupons) {
String text = coupon.get("text");
couponsList.add(new Coupon(text));
}
And the last thing to do is to create an Adapter and set it as an adapter of your ListView in your Activity:
ArrayAdapter<Coupon> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, couponsList);
yourListView.setAdapter(adapter);
After that the ListView will use the Adapter to populate its rows. You may want to implement your own adapter since it gets you far more options, you'll easily find out how to do it.
Update
Consider using RecyclerView instead.
Make a class call it anything you like (lets call it Item), and each instance of this call will represent relevant row in the Database ( or any source from where you are getting the information)
Item.java may have few instance variable like coupons and userName,
public class Item {
private String coupons;
private String userName;
public String getCoupons() {
return coupons;
}
public void setCoupons(String coupons) {
this.coupons = coupons;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
Make a Arraylist of type Item and feed this information to a custom ListView to show the details you want it to.
ArrayList<Item> list = new ArrayList<>();
for (int i = 0; i < productObj.length(); i++) {
Item item = new Item();
item.setCoupons(""+productObj.getJSONObject(i).getString("CouponKey"));
list.add(item);
}
I want to send the data of selected item in a listview to the next activity.This data has been fetched from JSON.
But it is returning last object's data of json and not that of the item i am selecting.Please help me to get the data of selected item that is fetched from json and pass it on to next activity using bundle.
String savedPlaceAddressLine1,savedPlaceAddressLine2,savedPlaceCity,savedPlaceZip,savedPlaceState,savedPlaceCountry,savedPlaceLat,savedPlaceLong;
class JSONAsyncTask extends AsyncTask<String,Void,Boolean>{
#Override
protected Boolean doInBackground(String... params) {
try {
....
JSONObject object2 = jsonArray.getJSONObject(2);
JSONArray jsonArraySavedPlaces = object2.getJSONArray("saved-places");
Log.i("Status2", "GotInnerArray");
for (int j = 0; j < jsonArraySavedPlaces.length(); j++)
{
JSONObject object4 = jsonArraySavedPlaces.getJSONObject(j);
ListItemDataSource listItemDataSource= new ListItemDataSource();
JSONObject addressObject=object4.getJSONObject("address");
Log.i("Status", "GotAddressesArray");
savedPlaceAddressLine1=addressObject.getString("address-line1");Log.i("Status1", savedPlaceAddressLine1);
savedPlaceAddressLine2=addressObject.getString("address-line2");Log.i("Status1", savedPlaceAddressLine2);
savedPlaceCity=addressObject.getString("city");Log.i("Status1", savedPlaceCity);
savedPlaceZip=addressObject.getString("zip");Log.i("Status1", savedPlaceZip);
savedPlaceState=addressObject.getString("state");Log.i("Status1", savedPlaceState);
savedPlaceCountry=addressObject.getString("country");Log.i("Status1", savedPlaceCountry);
savedPlaceTitle=addressObject.getString("address-title");Log.i("Status1", savedPlaceTitle);
savedPlaceLat=addressObject.getString("lattitude");Log.i("Status1", savedPlaceLat);
savedPlaceLong=addressObject.getString("longitude");Log.i("Status1", savedPlaceLong);
String placeAddress=savedPlaceAddressLine1+","+savedPlaceAddressLine2+","+savedPlaceCity+","+savedPlaceState+","+savedPlaceCountry;
listItemDataSource.setPlaceTitle(savedPlaceTitle);Log.i("Status2", "Title");
listItemDataSource.setPlaceAddress(placeAddress);Log.i("Status2", "Address");
itemsList.add(listItemDataSource);
Log.i("info","got data of object"+j);
}
}
return true;
}
...
}
in OnCreate:
Bundle extras=new Bundle();
extras.putString("savedPlacesAddress-title", savedPlaceTitle);
extras.putString("savedPlacesAddress1", savedPlaceAddressLine1);
extras.putString("savedPlacesAddress2", savedPlaceAddressLine2);
extras.putString("savedPlacesCity", savedPlaceCity);
extras.putString("savedPlacesZip", savedPlaceZip);
extras.putString("savedPlacesState", savedPlaceState);
extras.putString("savedPlacesCountry", savedPlaceCountry);
String data=savedPlaceAddressLine1+","+savedPlaceAddressLine2+","+savedPlaceCity+","+savedPlaceZip+","+savedPlaceState+","+savedPlaceCountry;
Log.d("data",data);
intent.putExtras(extras);
startActivity(intent);
Create a model class AppAddress.
Create all setter and getter method for your property like address1, address2, zip code etc.
implement this class by Serializable.
Create a Array list with AppAddress type.
Add all data in your AppAddress class by setter method and add it into arraylist.
When you will click on row of listview then pass object of AppAddress class by bundle.
Receive this object from other activity.
You can download sample code from below link:
http://www.wingnity.com/blog/android-json-parsing-and-image-loading-tutorial/
http://www.androidbegin.com/tutorial/android-json-parse-images-and-texts-tutorial/
http://wptrafficanalyzer.in/blog/android-json-parsing-with-jsonobject-and-loading-to-listview-example/
So I took data from my server. Than I built listView. On click on element i wan't to load new activity. So i need to get the id of element and send it to my server. How i can do it? is it possible to set some proprety = id_element when i create ListView?
So my code when i create list view"
this.adapter = new ArrayAdapter<String>(
InboxActivity.this,
R.layout.da_item,
emails
);
this.ll.setAdapter(this.adapter);
How i can to get id of selected element in the method onClick ?
So how i build **listView**
i do this code to build my listView
List<String> emails = new ArrayList<String>();
for(int i = 0; i < result.length(); i++)
{
try
{
JSONObject json_data = result.getJSONObject(i);
emails.add(json_data.getString("mittente"));
}
catch (JSONException e)
{
e.printStackTrace();
}
}
The data which i take from server it is json array like
[0][id] = 1;
[0][mitente] = my#email.ocm
[1][id] = 2;
[1][mitente] = my#emaasdil.ocm
How i can to pass in my listview id of element and than when i click to element get this id ?
Thanks to all!
Implement list setOnItemClickListener like:
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
System.out.println("Selected Email ID:::::" + emails[position));
}
});
ll.setOnItemClickListener(Adapter<?> adapter, View view, int position,, long id){
// here position means selected position of list item
}
If you are maintaining the data in Array list then you can simply get that particular Object from that array by using the position.