im worked in soap message, using SAXparser to retrieve the value(from Webservice) stored in ArrayList and the ArrayList working fine, but i want to store in HashMap, because Using key to identify a each name has certain SystemId, Please any one help me
Thanks
I tried the code:
public class SitesList
{
private ArrayList<String> name = new ArrayList<String>();
private ArrayList<String> systemid = new ArrayList<String>();
//Map <String,String> map = new HashMap<String,String>();
public ArrayList<String> getName()
{
return name;
}
public void setName(String nameString)
{
this.name.add(nameString);
System.out.println("name "+ name);
}
public ArrayList<String> getSystemId()
{
return systemid;
}
public void setSystemId(String systemidString)
{
this.systemid.add(systemidString);
System.out.println("systemid "+systemid);
}
you can store like this way
you arraylist for name
private ArrayList<String> name = new ArrayList<String>();
and HashMap like this way
HashMap<String, ArrayList<String>>h = new HashMap<String, ArrayList<String>>();
and you can store your arraylist like this way
h.put("name", name);
If you don't need to preserve the order of entries, you can do something like this:
public class SitesList {
private final Map <String,String> map = new HashMap<String,String>();
public Set<String> getNames() {
return map.keySet();
}
public void add(String nameString, String systemidString) {
map.put(nameString, systemidString);
}
public Collection<String> getSystemIds() {
return map.values(); // may contain duplicates
}
}
Related
I want to get string from arraylist inside oncreateview fragment but i cant figure itout since no position index has been pass. get(position) return error.
String price = arrayList.get(position).getPrice();
i need to get string price and settext for price.this is my main concern.
this values should return from arraylist.
this is response JSON array from volley using mysingleton.
Single Product Response: [{"price":"75","date":"2017-07-13 03:25:31","pk_i_id":"4"}]
this main activty fragment
public class MainActivityFragment extends Fragment {
private TextView product,price,date,title;
private String product_id;
ArrayList<ProductItem> arrayList = new ArrayList<>();
Context context;
public MainActivityFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_main_activity, container, false);
product = (TextView) view.findViewById(R.id.tv1);
title = (TextView) view.findViewById(R.id.tvTitle);
price = (TextView) view.findViewById(R.id.tvPrice);
date = (TextView) view.findViewById(R.id.tvDate);
if (getArguments() != null) {
Log.i(TAG, "getArgument is not null");
product_id = getArguments().getString("product_id");
ProductBackgroundTask productBackgroundTask = new ProductBackgroundTask(this.getActivity(), product_id);
arrayList = productBackgroundTask.getList();
String price = arrayList.get(position).getPrice();
// Log.d(TAG, "price: " + price);
product.setText(product_id);
// price.setText(price);
}else {
Log.i(TAG, "getArgument is null");
}
return view;
}
}
this is task to get arraylist using volley
public class ProductBackgroundTask {
private Context context;
ArrayList<ProductItem> arrayList = new ArrayList<>();
String json_url = "phpfile.php";
private String product_id;
public ProductBackgroundTask(Context context, String product_id) {
this.context = context;
this.product_id = product_id;
}
public ArrayList<ProductItem> getList(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, json_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Single Product Response: " + response);
try {
JSONArray jsonarr = new JSONArray(response);
for (int i = 0; i < jsonarr.length(); i++) {
JSONObject jsonobj = jsonarr.getJSONObject(i);
ProductItem productItem = new ProductItem(jsonobj.getString("price"), jsonobj.getString("date"), jsonobj.getInt("pk_i_id"));
arrayList.add(productItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("product_id", product_id);
return params;
}
};
MySingleton.getInstance(context).addToRequestQueue(stringRequest);
return arrayList;
}
}
and this is class of array list
public class ProductItem {
private String Price,Date;
private int ProductId;
public ProductItem(String Price, String Date, int ProductId){
this.setPrice(Price);
this.setDate(Date);
this.setProductId(ProductId);
}
public int getProductId() {
return ProductId;
}
public void setProductId(int productId) {
ProductId = productId;
}
public String getPrice() {
return Price;
}
public void setPrice(String price) {
Price = price;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
Date = date;
}
Clearly in your oncreate you haven’t initialized the product item and you cannot parse the complete list.You can try two to solve this
1.Pass specific item number instead of position i.e
say if you want to show 4th item then position=3
2.Or write a loop like this to parse entire arrayList like this
for(ProductItem productItem:arrayList){
String price = productItem.getPrice();
// Log.d(TAG, "price: " + price);
product.setText(product_id);
price.setText(price);
}
Mistake you're doing is that in the MainActivityFragment your trying to assign the value to the arrayList even before the data is added to the arrayList in the ProductBackgroundTask-getList. That's the reason you are getting the list null all the time. Try to use interfaces.
1.Make your MainActivityFragment implement the interface.
2.Set the value to the interface method once you get the data from the server.
3.Get the data in the MainActivityFragment inside interface method and do all the operation you're doing inside the onCreateView method.
Now your arraylist will have the data whatever you received from the server.
Below is the link for the example on interfaces if you haven't used them before. He is doing exactly as your requirement.
https://www.justinmccandless.com/post/setting-up-a-callback-function-in-android/
Allow me. The arrayList that you return from getList isn't populated at the time you call String price = arrayList.get(position).getPrice();. The server call using volley takes some time to process and that's when the onResponse gets called. This happens AFTER you've returned the arrayList which is in fact empty.
The sequence of events is as follows.
• Call to arrayList = productBackgroundTask.getList(); which returns an empty ArrayList.
• String price = arrayList.get(position).getPrice();
Now after a while..
• onResponse inside getList() gets called.
Do you now see why it's empty?
Simple Solution: • Define a simple interface ProductListener alongside ProductBackgroundTask. (With only a single abstract method onProducts).
• Instantiate it inside the Fragment's onCreateView using an anonymous class and pass it to the constructor of ProductListener to save it for later use. Do whatever you want to do with the products inside the onProducts method. (Since that will be called with the actual data)
• Call its onProducts method with the data that's parsed and fetched inside the onResponse method.
ProductBackgroundTask code:
public class ProductBackgroundTask {
private Context context;
// I removed the instance ArrayList since that can be made
// local.
// Here, we add a reference to our callback interface as we can use it later.
private ProductListener listener;
String json_url = "http://192.168.43.55/android/v1/productList.php";
private String product_id;
// Instantiate this class using an additional listener argument
// which would be a concrete implementation of our interface.
public ProductBackgroundTask(Context context, String product_id, ProductListener listener) {
this.context = context;
this.product_id = product_id;
this.listener = listener;
}
// getList should not return anything,
// so I keep the return as void.
public void getList() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, json_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
ArrayList<ProductItem> arrayList = new ArrayList<>();
Log.d(TAG, "Single Product Response: " + response);
try {
JSONArray jsonarr = new JSONArray(response);
for (int i = 0; i < jsonarr.length(); i++) {
JSONObject jsonobj = jsonarr.getJSONObject(i);
ProductItem productItem = new ProductItem(jsonobj.getString("price"), jsonobj.getString("date"), jsonobj.getInt("pk_i_id"));
arrayList.add(productItem);
}
// Notice this line here, this is what
// calls the callback with the products.
listener.onProducts(arrayList);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("product_id", product_id);
return params;
}
};
MySingleton.getInstance(context).addToRequestQueue(stringRequest);
}
}
// Callback interface, we would need a concrete implementation
// of this and pass that to the constructor of ProductBackgroundTask.
interface ProductListener {
void onProducts(ArrayList<ProductItem> products);
}
The code inside onCreateView:
ProductBackgroundTask productBackgroundTask = new ProductBackgroundTask(this.getActivity(), product_id, new ProductListener() {
// This method will be called with the needed products.
// Give an anonymous class implementation of our interface
// right here since we won't be using it anymore.
public void onProducts(ArrayList<ProductItem> products) {
// Get the price you want.
String str = arrayList.get(0).getPrice();
// Use str wherever necessary. Use the UI thread here if you need
// to change any visible elements on the screen.
}
});
// Simply call this method to get the ball rolling.
productBackgroundTask.getList();
This is a concrete implementation of the this answer and you won't be changing much code.
I am getting following exception while updating an existing value in the Firebase using updateChildren method.
com.firebase.client.FirebaseException: Failed to parse node with class class com.shajeelafzal.quicktasks_app.models.HashTagModel
at com.firebase.client.snapshot.NodeUtilities.NodeFromJSON(NodeUtilities.java:84)
at com.firebase.client.snapshot.NodeUtilities.NodeFromJSON(NodeUtilities.java:12)
at com.firebase.client.utilities.Validation.parseAndValidateUpdate(Validation.java:127)
at com.firebase.client.Firebase.updateChildren(Firebase.java:438)
at com.shajeelafzal.quicktasks_app.fragments.AddEditTaskFragment$4.onDataChange(AddEditTaskFragment.java:408)
My model looks like this:
public class HashTagModel implements Parcelable {
private HashMap<String, Object> timeStampLastUsed;
#Expose
private String name;
#Expose
private String createByUserEmail;
private List<String> tasksKeys;
public HashTagModel() {
}
public HashTagModel(HashMap<String, Object> timeStampLastUsed, String name,
String createByUserEmail, ArrayList<String> tasksKeys) {
this.timeStampLastUsed = timeStampLastUsed;
this.name = name;
this.createByUserEmail = createByUserEmail;
this.tasksKeys = tasksKeys;
}
}
JSON Object that I want to update looks like this on Firebase:
"hashTags" : {
"USER_EMAIL" : {
"USA" : {
"createByUserEmail" : "USER_EMAIL",
"name" : "#USA",
"tasksKeys" : [ "-K6mS36uhKthKf1-1pF1" ],
"timeStampLastUsed" : {
"timestamp" : 1451514461234
}
}
}
}
And my onDateChange method looks like this:
public void onDataChange(DataSnapshot dataSnapshot) {
/** if the hash tag does not exists already then create new one. */
if (dataSnapshot.getValue() == null) {
HashMap<String, Object> timestampJoined = new HashMap<>();
timestampJoined.put(Constants.FIREBASE_PROPERTY_TIMESTAMP, ServerValue.TIMESTAMP);
ArrayList<String> keysList = new ArrayList<String>();
keysList.add(key);
HashTagModel hashTag = new HashTagModel(timestampJoined, "#" + mHashTags.get(finalI),
Utils.decodeEmail(mEncodedEmail), keysList);
finalHashTagLocation.setValue(hashTag);
} else {
HashTagModel hashtaghModel = dataSnapshot.getValue(HashTagModel.class);
hashtaghModel.getTasksKeys().add(key);
/* HashMap for data to update */
HashMap<String, Object> updateUserTaskData = new HashMap<>();
Utils.updateMapForAllWithValue(null, mHashTags.get(finalI), mEncodedEmail,
updateUserTaskData, "", hashtaghModel, Constants.FIREBASE_LOCATION_USER_HASH_TAGS);
/** update the Hash Tag */
finalHashTagLocation.updateChildren(updateUserTaskData, new Firebase.CompletionListener() {
#Override
public void onComplete(FirebaseError firebaseError, Firebase firebase) {
Log.i("", "");
}
});
}
getActivity().finish();
}
Unlike the setValue() method, updateChildren() does not perform a Java-to-JSON conversion on the value(s) you pass in.
You're passing a HashMap<String, Object> into updateChildren(), which fits the contract of that API. But I'm pretty sure in some of the values you have a Java object (likely a HashTagModel) that is not directly mapped to a JSON type.
But what you can do is convert the POJO into a Map with:
Map<String, Object> hashtaghMap = new ObjectMapper().convertValue(hashtaghModel, Map.class);
Then you can put the map of values into the values that you're passing into updateChildren().
I need to show in a listview a query result to the DB. I'm returning the query 2 values ("cod", "value"). I thought of using a SimpleAdapter to solve the problem, but it did not work.
this is my code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.techcharacteristic);
PopulateTechCharacteristicList populateList = new PopulateTechCharacteristicList(
this);
populateList.execute();
SimpleAdapter adapter = new SimpleAdapter(this, list,
R.layout.techcharacteristic_rows,
new String[] {"cod", "value"}, new int[] {
R.id.techCharacteristic, R.id.techCharacteristicName });
setListAdapter(adapter);
}
public class PopulateTechCharacteristicList extends
AsyncTask<Integer, String, Integer> {
ProgressDialog progress;
Context context;
public PopulateTechCharacteristicList(Context context) {
this.context = context;
}
protected void onPreExecute() {
progress = ProgressDialog.show(TechCharacteristicList.this,
getResources().getString(R.string.Wait), getResources()
.getString(R.string.LoadingOperations));
}
protected Integer doInBackground(Integer... paramss) {
ArrayList<TechCharacteristic> arrayTechChar = new ArrayList<TechCharacteristic>();
TechCharacteristicWSQueries techCharWSQueries = new TechCharacteristicWSQueries();
try {
arrayTechChar = techCharWSQueries
.selectTechCharacteristicByAsset("ARCH-0026");
HashMap<String, String> temp = new HashMap<String,
for(TechCharacteristic strAux : arrayTechChar)
{
temp.put("cod", strAux.getTechCharacteristic() + " - " + strAux.getTechCharacteristicName());
temp.put("value", strAux.getTechCharacteristicValue());
list.add(temp);
}
} catch (QueryException e) {
e.printStackTrace();
return 0;
}
return 1;
}
protected void onPostExecute(Integer result) {
if(result == 1)
progress.dismiss();
}
}
On account of being utlizando the same codes ("cod", "value") to include values in the HashMap, my listView is always showing the last item inserted. But in my statement SimpleAdapter'm using hard coded ("cod", "value") and whenever I put any value other than ("cod", "value") in the HashMap, the listView carries empty.
Can anyone help me?
On account of being utlizando the same codes ("cod", "value") to
include values in the HashMap, my listView is always showing the
last item inserted.
As you are creating HashMap object out of for loop, and adding values to that object only in the for loop,hence the previous values get erased and you get only last values.
To solve this you need to create the HashMap object in for loop corresponding to each row.
Try
HashMap<String, String> temp = null;
for(TechCharacteristic strAux : arrayTechChar)
{
temp = new HashMap<String,String>();
temp.put("cod", strAux.getTechCharacteristic() + " - " + strAux.getTechCharacteristicName());
temp.put("value", strAux.getTechCharacteristicValue());
list.add(temp);
}
I have a question about saving an arraylist of custom objects. I have a class called notitie:
public class Notitie implements Serializable{
private String titel = "";
private String type = "";
private String datum = "";
public void setTitel (String titel){
this.titel = titel;
}
public String getTitel(){
return titel;
}
public void setType (String type){
this.type = type;
}
public String getType(){
return type;
}
public void setDatum (String datum){
this.datum = datum;
}
public String getDatum(){
return datum;
}
}
I create some objects of Notitie and add them to my arraylist called notities
ArrayList<Notitie> notities = new ArrayList<Notitie>();
Notitie notitie1 = new Notitie();
notitie1.setTitel("Meting");
notitie1.setType("Watermeting");
notitie1.setDatum("22-09-12");
notities.add(notitie1);
Notitie notitie2 = new Notitie();
notitie1.setTitel("Meting2");
notitie1.setType("Watermeting2");
notitie1.setDatum("23-09-12");
notities.add(notitie2);
Notitie notitie3 = new Notitie();
notitie1.setTitel("Meting3");
notitie1.setType("Watermeting3");
notitie1.setDatum("24-09-12");
notities.add(notitie3);
Now I want to save the filled Arraylist on the device's storage so it can be accessed anytime. I used to save data as a String or some Integers with sharedpreferences but I can't save this Arraylist with that.
Does anybody have a solution?
Thanks in advance!
You do have a few options:
Use serialization, XML or JSON, and store your data in a File. Refer to this solution if you wanna implement serialization.
Store you data using SQLite. Have a look at this tutorial to get started.
EDIT : You might want to read this as well!
I am trying to deserialize this JSON array into my android project.
[{"Name":"Ban","Price":1},{"Name":"Banana","Price":1},{"Name":"chicken","Price":14},{"Name":"pizza","Price":16},{"Name":"slice","Price":1}]
I have made this webservice in Asp.net.
The code I am using to deserialize it is below
public void onClick(View v)
{
String url="http://192.168.15.2/MyAndroid/InputCaller.aspx"; //do not use localhost
String response=callWebService(url);
List<Items> mObjectList = new ArrayList<Items>() ;
ItemsList list = null;
Gson gson = new Gson();
list = gson.fromJson(response, ItemsList.class);
// list = getItemsList(response);
Intent myIntent = new Intent(v.getContext(), Cart.class);
startActivity(myIntent);
}
public final ItemsList getItemsList (String jsonString)
{
ItemsList il = null;
Gson gson = new Gson();
il = gson.fromJson(jsonString, ItemsList.class);
return il;
}
public class ItemsList
{
private List<ItemsContainer> items = new ArrayList<ItemsContainer>();
public List<ItemsContainer> getItemsContainerList()
{
return items;
}
}
class ItemsContainer
{
Items items;
public Items getItem()
{
return items;
}
}
public class Items
{
String Name;
int Price;
}
It is not working and when I try to debug it I get this message on list = gson.fromJson(response, ItemsList.class);
Gson.class Source not found.
This is my first deserialisation program and I would really appreciate if anybody help me with it. Thank you,
Don't make things complicated by using further parent classes (as container) for Items class. Simply de-serialize all the items into a List object using Gson as below:
List<Items> listItems = (List<Items>) gson.fromJson(response,
new TypeToken<List<Items>>(){}.getType());
now you've got all the Items in a List object: listItems