how to get json array into dialog fragment - java

I have an issue in a dailog fragment. I want to get a json array into the dailog fragment, but I don't know how to do it, here is what am trying. Any suggetion's ?
public class MyAlertSortDialogFragmentIndividual extends DialogFragment {
public static final String DATA = "items";
public static final String SELECTED = "selected";
CharSequence[] cs;
ArrayList<User> transactionList = new ArrayList<>();
List <User> users;
String s;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
users=new ArrayList<>();
Bundle bundle = getArguments();
AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
dialog.setTitle("Sort By");
dialog.setPositiveButton("Cancel", new PositiveButtonClickListener());
bundle.putSerializable("key", transactionList);
String str = bundle.getString("str");
users = new Gson().fromJson(str,ArrayList.class);
return dialog.create();
}
class PositiveButtonClickListener implements DialogInterface.OnClickListener {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}
DialogInterface.OnClickListener selectItemListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// process
//which means position
dialog.dismiss();
}
};
how should I get the data from model class.

public class NewItem {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
If this is your model class then to get data:
String userName,age;
for (NewItem item : users) {
if(item.getName().equals(REQUIRED_USERNAME)){
userName = item.getName();
age = item.getAge();
}
}

First the json format you get is not valid json format send json format like
{
"Users": [
{
"username": "ashish",
"userid": "97"
}
]
}
not like -"Users": [ { "username": "ashish", "userid": "97" } ]
after that map this into class
public class UsersResponce implements Serializable {
#SerializedName("Users")
#Expose
private List<User> users = null;
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public class User implements Serializable{
#SerializedName("username")
#Expose
private String username;
#SerializedName("userid")
#Expose
private String userid;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
}
}
Than pass that str value and get Pojo Class like
UsersResponce users = new Gson().fromJson(str,UsersResponce.class);
if(null!=UsersResponce){
List<User> usersList =UsersResponce.getUsers();
if(null!=usersList&&usersList.size()>0){
for (User item : usersList) {
if(item.getUserid().equals(CURRENT_LOGIN_USERID)){
//than set your adapter selcted here
}
}
}
}
For single choice adapter refer this link

Related

Passing array problem in retrofit post request

I have face a problem retrofit library in android java.
here is the json Body
{
"title":"Android ",
"type":"project",
"category_id":"1",
"tags":["swift","java","android"],
"end_date":"2021-9-30",
"description":"testing",
"budget":"500"
}
This the pojo class
public class draftedJobPostModel {
private String title;
private String type;
private int category_id;
ArrayList<String> tags;
private String end_date;
private String description;
private int budget;
private String post_type;
public draftedJobPostModel() {
}
public draftedJobPostModel(String title, String type, int category_id, ArrayList<String> tags, String end_date, String description, int budget, String post_type) {
this.title = title;
this.type = type;
this.category_id = category_id;
this.tags = tags;
this.end_date = end_date;
this.description = description;
this.budget = budget;
this.post_type = post_type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getCategory_id() {
return category_id;
}
public void setCategory_id(int category_id) {
this.category_id = category_id;
}
public ArrayList<String> getTags() {
return tags;
}
public void setTags(ArrayList<String> tags) {
this.tags = tags;
}
public String getEnd_date() {
return end_date;
}
public void setEnd_date(String end_date) {
this.end_date = end_date;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getBudget() {
return budget;
}
public void setBudget(int budget) {
this.budget = budget;
}
public String getPost_type() {
return post_type;
}
public void setPost_type(String post_type) {
this.post_type = post_type;
}
}
Add value from chip:
ArrayList<String> arrayTags = new ArrayList<>();
for (int i=0;i<chipGroup.getChildCount();i++)
{
Chip chip = (Chip) chipGroup.getChildAt(i);
arrayTags.add(chip.getText().toString());
}
retrofit call method:
Service service = Client.retrofit.create(Service.class);
Call<createJobPostModel> call = service.createJob("Bearer"+" "+token,title,jobtype,fieldId, arrayTags,date,budget,description);
call.enqueue(new Callback<createJobPostModel>() {
#Override
public void onResponse(Call<createJobPostModel> call, Response<createJobPostModel> response) {
if (response.isSuccessful()){
/* Toast.makeText(getActivity(), "Success", Toast.LENGTH_SHORT).show();*/
Toast.makeText(getActivity(),arrayTags.toString(), Toast.LENGTH_LONG).show();
/*arrayTags.clear();*/
}else{
Toast.makeText(getActivity(), "Error", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<createJobPostModel> call, Throwable t) {
Toast.makeText(getActivity(), "Failed", Toast.LENGTH_SHORT).show();
}
});
Everything is ok but when i pass the arraylist its shows only last index of array value in database.
here is the return value:
"tags": "Android",
but i want this:
"tags": [
"swift",
"IOS",
"android"
],

Getting Null object in HashMap implementation

Iam trying t get values from a HashMap but when i call him and setText the value i always get Null, let me show the code:
MyValues.class
private List<ItemsBean> items;
public List<ItemsBean> getItems() { return items;}
public void setItems(List<ItemsBean> items) { this.items = items; }
public static class ItemsBean {
private Map<String, leakBean> Gitt;
public Map<String, leakBean> getGitt() { return Gitt;}
public void setGitt(Map<String, leakBean> Gitt) { this.Gitt = Gitt;}
public static class leakBean {
private int id;
private String dev;
public int getId() {return id; }
public String getDev(){return dev;}
public void setId(int id) { this.id = id;}
public void setDev(String dev){this.dev = dev;}
}
I´m using Gson so for get the values and use it for .setText or Toast im trying to access like this:
MyValues object;
txt1.setText(String.valueOf( object.getItems().get(0).getGitt().get("id")));
Here i get null, can someone helpme with this? i just need to access to values, also the items.size(); return 1 and must return 3
here is hte JSON:
{
"id": 1001,
"name": "Super1",
"user": {
"name": "The Super 1"
},
"items": [
{
"987987M7812b163eryrt": {
"id": 1,
"dev": "seed"
},
"90812bn120893juuh": {
"id": 2,
"dev": "none"
},
"981273jn19203nj123rg": {
"id": 3,
"dev": "mine"
}
}
]}
Try with these POJOs:
MyValues.java
public class MyValues {
private int id;
private String name;
private User user;
private List<HashMap<String, ItemsBean>> items;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<HashMap<String, ItemsBean>> getItems() {
return items;
}
public void setItems(List<HashMap<String, ItemsBean>> items) {
this.items = items;
}
}
User.java
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
ItemsBean.java
public class ItemsBean {
private int id;
private String dev;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDev() {
return dev;
}
public void setDev(String dev) {
this.dev = dev;
}
}
You can no access the values like so:
object.getItems().get(0).get("987987M7812b163eryrt").getId();

JSON deserializer with GSON using HashMap

I'm trying to deserialize a JSON data using GSON and helping myself using HashMap<> but i have an error when i set the json string into the java class, the app just stop, and mark the line with the origin of the error:
funt = gson.fromJson(String.valueOf(R.string.json), stack.class);
Note im trying to get the json data to put in custom adapter, heres the code:
1 Question: I´m correctly getting and setting the json string into java class?
2 Question: I´m correctly Maping the Identifier?
(i'm using "identifier" has class name coz i can't make a each class for every item thats why i need mapping) if not can you tell me how?
Java class where i'm trying to put the json string:
public class stack {
private int id;
private String name;
private UserBean user;
private ItemsBean items;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public UserBean getUser() {
return user;
}
public void setUser(UserBean user) {
this.user = user;
}
public ItemsBean getItems() {
return items;
}
public void setItems(ItemsBean items) {
this.items = items;
}
public static class UserBean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static class ItemsBean {
private HashMap<String, IdentifierBean> identifier;
public HashMap<String, IdentifierBean> getIdentifier(){
return identifier;
}
public void setIdentifier(HashMap<String,IdentifierBean> identifier){
this.identifier = identifier;
}
public static class IdentifierBean {
private int id;
private int strong;
private boolean active;
private String sell;
public int getId() {return id;}
public void setId(int id) {this.id = id; }
public int getStrong() {return strong;}
public void setStrong(int strong) {this.strong = strong;}
public boolean isActive() {return active;}
public void setActive(boolean active) {this.active = active;}
public String getSell() {return sell;}
public void setSell(String sell) {this.sell = sell;}
}
}
}
Here is the Activity class:
public class stacker extends AppCompatActivity {
stack funt;
Gson gson;
adapterstack adapter;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stacker);
list = (ListVeew)findViewById(R.id.listss);
gson = new Gson();
funt = gson.fromJson(String.valueOf(R.string.json), stack.class);
adapter = new adapterstack(stacker.this, (List<stack.ItemsBean>) funt.getItems());
list.setAdapter(adapter);
}
}
Here is the Adapter:
public class adapterstack extends BaseAdapter {
List<stack.ItemsBean> itemlist;
Context sContext;
public adapterstack( Context sContext, List<stack.ItemsBean> itemlist) {
this.sContext = sContext;
this.itemlist = itemlist;}
#Override
public int getCount() {return itemlist.size();}
#Override
public Object getItem(int i) {return itemlist.get(i);}
#Override
public long getItemId(int i) {return i;}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) sContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rootView = inflater.inflate(R.layout.item_act, viewGroup, false);
final stack.ItemsBean item = (stack.ItemsBean) getItem(i);
TextView nombre = (TextView) rootView.findViewById(R.id.txt1);
TextView genero = (TextView) rootView.findViewById(R.id.txt2);
//Here i'm trying to get identifier data info from stack.class
nombre.setText(item.getIdentifier().get(i).getId());
genero.setText(item.getIdentifier().get(i).getStrong());
return rootView;
}
}
the JSON:
[{
"id": 1001,
"name": "Super1",
"user": {
"name": "The Super 1"
},
"items": {
"987987M7812b163eryrt": {
"id": 1,
"strong": 456,
"active": true,
"sell": "te"
},
"90812bn120893juuh": {
"id": 2,
"strong": 4700,
"active": true,
"sell": "tt"
},
"981273jn19203nj123rg": {
"id": 3,
"strong": 3000,
"active": true,
"sell": "ti"
}
}}]
I see the JSON string that you are trying to parse is indicating an array. In that case you need to parse the JSON as follows.
funt = gson.fromJson(String.valueOf(R.string.json), stack[].class);
Hope that helps!

How to use jdbctemplate and row mapper to create object with a list of objects?

I was wondering how to use jdbctemplate and RowMapper to create object with a list of objects?
Below are the three objects that I need to get mapped based on data from the db.
public class UserDTO {
private String userID;
private String email;
private List<RooftopDTO> rooftops;
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<RooftopDTO> getRooftops() {
return rooftops;
}
public void setRooftops(List<RooftopDTO> rooftops) {
this.rooftops = rooftops;
}
}
public class RooftopDTO {
private String dealerID;
private String name;
private String address;
private List<VenueDTO> venues;
public String getDealerID() {
return dealerID;
}
public void setDealerID(String dealerID) {
this.dealerID = dealerID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public List<VenueDTO> getVenues() {
return venues;
}
public void setVenues(List<VenueDTO> venues) {
this.venues = venues;
}
}
public class VenueDTO {
private int integrationID;
private String rooftopID;
public int getIntegrationID() {
return integrationID;
}
public void setIntegrationID(int integrationID) {
this.integrationID = integrationID;
}
public String getRooftopID() {
return rooftopID;
}
public void setRooftopID(String rooftopID) {
this.rooftopID = rooftopID;
}
}
As you can see, I need to create lists of objects within each object. This is what I have so far in my MapperClass, but I can't figure out what else to do..
public class UserDTOMapper implements RowMapper<UserDTO> {
#Override
public UserDTO mapRow(ResultSet rs, int rowNum) throws SQLException {
UserDTO userDTO = new UserDTO();
RooftopDTO rooftops = new RooftopDTO();
VenueDTO venues = new VenueDTO();
ArrayList<VenueDTO> venueList = new ArrayList<>();
ArrayList<RooftopDTO> rooftopList = new ArrayList<>();
userDTO.setUserID(rs.getString("user_id"));
userDTO.setEmail(rs.getString("email"));
rooftops.setDealerID(rs.getString("dealer_id"));
rooftops.setAddress(rs.getString("addr_1"));
rooftops.setName(rs.getString("dealer_nm"));
venues.setIntegrationID(rs.getInt("integration_id"));
venues.setRooftopID("act_org_id");
}
}
Can someone help me finish this mapRow method?

How to read json response from retrofit [duplicate]

This question already has answers here:
Retrofit 2: Get JSON from Response body
(14 answers)
Closed 5 years ago.
How to read this response from retrofit and store to java class and access somewhere ??
{
"user": {
"__v": 0,
"updated_at": "2017-11-08T12:07:46.729Z",
"created_at": "2017-11-08T12:07:46.729Z",
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRlc3QzIiwidXNlcmlkIjozLCJlbWFpbCI6ImFydWwzQHRlc3QuY29tIiwiYWNjZXNzX2xldmVsIjoiQWRtaW4iLCJfaWQiOiI1YTAyZjM5Mjk5OGM4OTI3MjQxYTQ3N2YiLCJncm91cHMiOlt7ImlkIjoxLCJuYW1lIjoiZGlhbGVyIiwiX2lkIjoiNThiM2JmODI5ZTg2MDFjMDVlNzIxNjI3In1dfQ.VKEt1JoXoL_xfRDrrFK-jVj8zC23j4sqZTT2S3HGMbc",
"username": "test3",
"userid": 3,
"email": "arul3#test.com",
"access_level": "Admin",
"_id": "5a02f392998c8927241a477f",
"groups": [{
"id": 1,
"name": "dialer",
"_id": "58b3bf829e8601c05e721627"
}]
}
}
Create classes from pojo like that then parse to retrofit Convert json response to classes
public class MyPojo{
private User user;
public User getUser ()
{
return user;
}
public void setUser (User user)
{
this.user = user;
}
}
User Class:
public class User{
private String username;
private String updated_at;
private String _id;
private String access_level;
private String email;
private String token;
private String userid;
private String __v;
private String created_at;
private Groups[] groups;
public String getUsername ()
{
return username;
}
public void setUsername (String username)
{
this.username = username;
}
public String getUpdated_at ()
{
return updated_at;
}
public void setUpdated_at (String updated_at)
{
this.updated_at = updated_at;
}
public String get_id ()
{
return _id;
}
public void set_id (String _id)
{
this._id = _id;
}
public String getAccess_level ()
{
return access_level;
}
public void setAccess_level (String access_level)
{
this.access_level = access_level;
}
public String getEmail ()
{
return email;
}
public void setEmail (String email)
{
this.email = email;
}
public String getToken ()
{
return token;
}
public void setToken (String token)
{
this.token = token;
}
public String getUserid ()
{
return userid;
}
public void setUserid (String userid)
{
this.userid = userid;
}
public String get__v ()
{
return __v;
}
public void set__v (String __v)
{
this.__v = __v;
}
public String getCreated_at ()
{
return created_at;
}
public void setCreated_at (String created_at)
{
this.created_at = created_at;
}
public Groups[] getGroups ()
{
return groups;
}
public void setGroups (Groups[] groups)
{
this.groups = groups;
}
}
Groups Class:
public class Groups{
private String id;
private String _id;
private String name;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String get_id ()
{
return _id;
}
public void set_id (String _id)
{
this._id = _id;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}}
Now follow that put your classes and get desire response Retrofit Json response

Categories