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/
Related
I have an arraylist of arraylist which I am tring to populate but its not working.The response is being fetched from server.the response comes as follows
[{"QKey":"1234","OptionLabel":"Ground Floor","optionValue":"0"},{"QKey":"5678","OptionLabel":"1st Floor","optionValue":"1"}
I am trying to fetch it,add it in arraylist and populate but it seems to be not working
this is my code
String dropDownResponse=readFromFile(2);
Log.d("Reading from file",dropDownResponse);
JSONArray jsonArray = new JSONArray(dropDownResponse);
formModel.setName(rowLabel);
formModel.setIsMandatory(isMandatory);
formModel.setInputType(inputType);
/* formModel.setName("SAMPLE LABEL");
formModel.setIsMandatory("Y");
formModel.setInputType("selectbox");*/
spinnerList.add(formModel);
spinnerPopulationList.get(spinnerList.size()-1).set(0,rowLabel);
for(int j=0;j<jsonArray.length();j++)
{
JSONObject jsonObject = jsonArray.getJSONObject(j);
spinnerRowId=jsonObject.getString("QKey");
Log.d("QKey",spinnerRowId);
optionLabel=jsonObject.getString("OptionLabel");
Log.d("Option Label",optionLabel);
if(rowId.equals(spinnerRowId))
{
spinnerPopulationList.get(spinnerList.size()-1).set(spinnerPopulationList.get(spinnerList.size()-1).size()-1,optionLabel);
}
}
for(int h=0;h<spinnerPopulationList.get(spinnerList.size()-1).size();h++)
{
Log.d("spinner item"+rowLabel+"["+h+"]",spinnerPopulationList.get(spinnerList.size()-1).get(h));
}
this line in the code shows indexOutOfBoundException
if(rowId.equals(spinnerRowId))
{
spinnerPopulationList.get(spinnerList.size()-1).set(spinnerPopulationList.get(spinnerList.size()-1).size()-1,optionLabel);
}
I don't think you need a two dimensional AllayList to accomodate this json. This is just an array of objects. You can use Gson to parse it quite easily.
You will need a couple of response classes like
class ResponseObj {
private String Qkey;
private String OptionLabel;
private String optionValue;
//Constructor(s), getters and setters
}
class Response {
private ArrayList<ResponseObj> objects = new ArrayList<>();
//Constructor(s), getters and setters
}
Then you can use Gson to parse the json and make an object out of it. You can use something like this where you are getting the response from server.
Response response = gson.fromJson(YOUR_JSON, Response.class);
for(ResponseObj object : response.getObjects()) {
//In this loop, you are iterating over each object in your json
//which looks like
//{"QKey":"1234","OptionLabel":"Ground Floor","optionValue":"0"}
doSomething(object);
doSomethingWithKey(object.getQKey());
}
Here is how you can use Gson in your project.
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);
}
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>.
if (status == 200) {
String result = EntityUtils.toString(response.getEntity());
Log.d("Response", result);
ArrayAdapter < String > adapter = new ArrayAdapter < String > (getActivity(),
android.R.layout.simple_list_item_1, result);
setListAdapter(adapter);
}
I am unable to set my response into my List. I get my response as
{
"Appointments": [{
"Name": "Kevin",
}, {
"Name": "John",
}]
}
How would i set my name parameter in the listView.
How would i set my name parameter in the listView.
At a glance. Third parameter of ArrayAdapter should be collection but you are passing only simple String. According to your JSON i recommend you:
Create own object that will represent Person with properties(name,
age, etc.)
Parse JSON and create collection of persons
Set collection to ListAdapter
Example:
public class Person {
private String name;
...
// getters and setters
#Override
public String toString() {
return this.name;
}
}
Then, you need to parse JSON and get proper data:
List<Person> persons = new ArrayList<Person>();
Person person = null;
JSONObject root = new JSONObject(sourceString);
JSONArray appointments = root.getJSONArray("Appointments");
JSONObject child = null;
for (int i = 0; i < appointments.length(); i++) {
child = appointments.getJSONObject(i);
if (child != null)
person = new Person();
person.setName(child.getString("Name"));
persons.add(person);
}
}
Then initialise ListAdapter:
new ArrayAdapter<String>(getActivity(), layout, persons);
and now you got it.
Note:
Reason why i'm overriding toString() method is that since you are using default ArrayAdapter with build-in Android layout each object in your List will be converted to String and will be shown in ListView but if i don't override toString() it won't return person's name but string representation of object that is human-unreadable string.
result is a String containing the entire response. You need to parse or split that string into the items that you want.
You need to give your adapter the items (either as a list or an array). Right now you've created an adapter but haven't provided it any data via the constructor or any setter.
I suggest you read more about ListViews and Adapters on the Android developers site.