How to Remove Curly Braces in HashMap Android - java

I have ArrayAdapter for spinnner and i want to add item to this spinner. My code like below
public void parser()
{
final ArrayList<HashMap<String, String>> valuesList = new ArrayList<HashMap<String,String>>();
for(int i = 0;i<response.getPropertyCount();i++){
SoapObject dersListesi = (SoapObject)response.getProperty(i);
for (int j = 0; j < dersListesi.getPropertyCount(); j++) {
Object objectNames = dersListesi.getProperty(j);
SoapObject ders_kodu = (SoapObject)objectNames;
SoapObject ders_adi = (SoapObject)objectNames;
HashMap<String, String> map = new HashMap<String, String>();
String dersKodu = ders_kodu.getProperty("dersKodu").toString();
String dersAdi = ders_adi.getProperty("dersAdi").toString();
map.put( dersKodu,dersAdi);
valuesList.add(map);
System.out.println( "map"+map);
System.out.println(dersAdi);
}
ArrayAdapter<HashMap<String, String>> ad =
new ArrayAdapter<HashMap<String,String>>(this,
android.R.layout.simple_list_item_1,valuesList);
ad.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerDersKodu = (Spinner)findViewById(R.id.derscombo);
spinnerDersKodu.setAdapter(ad);
}
}
This code work correctly but my spinner's output like this:
{BIM101=Computer Programming}
How I can remove these curly braces and = ?
Thanks for help.

Change the your ArrayAdapter to hold string instance. You do not need an ArrayList of HashMap, if the purpose it's just printing the key and the value of the HashMap
final ArrayList<String> valuesList = new ArrayList<String>();
for(int i = 0;i<response.getPropertyCount();i++){
SoapObject dersListesi = (SoapObject)response.getProperty(i);
for (int j = 0; j < dersListesi.getPropertyCount(); j++) {
Object objectNames = dersListesi.getProperty(j);
SoapObject ders_kodu = (SoapObject)objectNames;
SoapObject ders_adi = (SoapObject)objectNames;
String dersKodu = ders_kodu.getProperty("dersKodu").toString();
String dersAdi = ders_adi.getProperty("dersAdi").toString();
valuesList.add(dersKodu+ " " + dersAdi);
}
ArrayAdapter<String> ad =
new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,valuesList);

Related

Android Json array data Error and unable to find or get data from json array index

Dear Friends, i want to get json array data's value from index and compare with my store id.
For example:
i want to get instituteID from json array and compare with value "3" and if it is true then display stored subject value in textview if (instituteID == 3){tv.setText(subject);} instituteID and subject is also coming from json.tell me where i'm wrong
ArrayList<HashMap<String,String>> arraylist = new ArrayList<>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView)findViewById(R.id.subject1);
tv2 = (TextView)findViewById(R.id.subject2);
tv3 = (TextView)findViewById(R.id.subject3);
tv4 = (TextView)findViewById(R.id.subject4);
tv5 = (TextView)findViewById(R.id.subject5);
tv6 = (TextView)findViewById(R.id.subject6);
//here calling json asynctask
new getTacherJson().execute();
DisplayData();
}
public void DisplayData(){
SharedPreferences preferences = getSharedPreferences("Email's response",MODE_PRIVATE);
shared_pref_emal = preferences.getString("response",null);
Log.e("Email's response",shared_pref_emal);
SharedPreferences preferences1 = getSharedPreferences("Institute's ID",MODE_PRIVATE);
shared_pref_ins_id = preferences1.getString("response id",null);
Log.e("inst. id",shared_pref_ins_id);
if (institute_ID == shared_pref_ins_id){
tv1.setText(subject);
tv2.setText(subject2);
tv3.setText(subject3);
tv4.setVisibility(View.GONE);
tv5.setVisibility(View.GONE);
tv6.setVisibility(View.GONE);
}
else {
tv1.setText("Nothing");
}
}
//here is my Json Data
{"response":[{"id":"11","class":"One Class","section":"Morning","teacher":"abc#gmail.com","subject":"Urdu","fromTime":"08:00","toTime":"08:30","instituteID":"3","created_at":"2019-09-12 04:39:31"},{"id":"12","class":"One Class","section":"Morning","teacher":"abc#gmail.com","subject":"Pakistan Studies","fromTime":"08:30","toTime":"09:00","instituteID":"3","created_at":"2019-09-12 04:39:49"},{"id":"13","class":"BSSE","section":"Evening","teacher":"abc#gmail.com","subject":"Introduction to CMP","fromTime":"15:00","toTime":"17:30","instituteID":"3","created_at":"2019-09-16 07:39:43"}]}
MyHttpHandler myhttp = new MyHttpHandler();
String teacherURL = url+"/showTeacherCourses/"+get_email+"/"+shared_pref_ins_id;
String teachDash = myhttp.MyServiceCall(teacherURL);
Log.e(TAG,"Response From Teacher Courses"+teachDash);
if (teachDash != null) {
try {
JSONObject jsonObject = new JSONObject(teachDash);
JSONArray teachArray = jsonObject.getJSONArray("response");
Log.e("Array length", String.valueOf(teachArray.length()));
// looping through All Contacts
for (int i = 0; i < teachArray.length(); i++) {
JSONObject c = teachArray.getJSONObject(i);
id1 = c.getString("id");
clasx = c.getString("class");
section = c.getString("section");
teacher_emaill = c.getString("teacher");
subject = c.getString("subject");
from_time = c.getString("fromTime");
to_time = c.getString("toTime");
institute_ID = c.getString("instituteID");
created_at = c.getString("created_at");
HashMap<String, String> tech_dta_ftch = new HashMap<>();
// adding each child node to HashMap key => value
tech_dta_ftch.put("id", id1);
tech_dta_ftch.put("class",clasx);
tech_dta_ftch.put("section",section);
tech_dta_ftch.put("teacher",teacher_emaill);
tech_dta_ftch.put("subject",subject);
tech_dta_ftch.put("fromTime",from_time);
tech_dta_ftch.put("toTime",to_time);
tech_dta_ftch.put("created_at", created_at);
tech_dta_ftch.put("instituteID", institute_ID);
// adding contact to contact list
arraylist.add(tech_dta_ftch);
Try this :
for(int i = 0; i < teachArray.length(); i++){
JSONObject c = teachArray.getJSONObject(i);
HashMap<String, String> tech_dta_ftch = new HashMap<>();
tech_dta_ftch.put("id", c.getString("id"));
tech_dta_ftch.put("class",c.getString("class"));
tech_dta_ftch.put("section",c.getString("section"));
tech_dta_ftch.put("teacher",c.getString("teacher"));
tech_dta_ftch.put("subject",c.getString("subject"));
tech_dta_ftch.put("fromTime",c.getString("fromTime"));
tech_dta_ftch.put("toTime",c.getString("toTime"));
tech_dta_ftch.put("created_at", c.getString("created_at"));
tech_dta_ftch.put("instituteID", c.getString("instituteID"));
arraylist.add(tech_dta_ftch);
}
And to compare institute ID of at a specific index of your array list currently I am selecting at first index, you could use it probably your way:
if (arraylist.get(0).get("instituteID").equalsIgnoreCase("ID_TO_CHECK_WITH")){
//DO YOUR STUFF
}

.replace(list(x), "") Doesn't Work Java

I wrote code:
List<String> Names = new ArrayList<String>();
List<Double> Prices = new ArrayList<Double>();
List<String> Dates = new ArrayList<String>();
List<String> Hours = new ArrayList<String>();
List<String> iDs = new ArrayList<String>();
SimpleAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView resultsListView = (ListView) findViewById(R.id.listMyReceipts);
SearchView m = (SearchView) findViewById(R.id.action_search);
HashMap<String, String> NamePrice = new HashMap<>();
TextView test = (TextView) findViewById(R.id.test);
Names.add("Starbucks"); Prices.add(11.99); Dates.add("01/01/2017"); Hours.add("9:33");
Names.add("Apple Store"); Prices.add(500.00); Dates.add("01/01/2017"); Hours.add("9:30");
Names.add("Esselunga"); Prices.add(135.67); Dates.add("01/01/2017"); Hours.add("11:51");
Names.add("Mediaworld"); Prices.add(19.98); Dates.add("01/01/2017"); Hours.add("12:03");
Names.add("Starbucks"); Prices.add(11.99); Dates.add("01/01/2017"); Hours.add("12:47");
for (int i = 0; i < Names.size(); i++) {
iDs.add(";+#:" + i + ":#+;");
NamePrice.put(iDs.get(i) + Names.get(i), " " + Prices.get(i).toString() + "€" + " - " + Dates.get(i) + " " + Hours.get(i));
}
List<HashMap<String, String>> listItems = new ArrayList<>();
adapter = new SimpleAdapter(this, listItems, R.layout.list_item,
new String[] {"First", "Second"},
new int[] {R.id.listitemTitle, R.id.listitemSubItem});
//Integer x = 0;
//int x = -1;
Iterator it = NamePrice.entrySet().iterator();
for (int i = 0; i < iDs.size(); i++) {
HashMap<String, String> resultMap = new HashMap<>();
Map.Entry pair = (Map.Entry) it.next();
resultMap.put("First", pair.getKey().toString().replace(iDs.get(i), ""));
resultMap.put("Second", pair.getValue().toString());
listItems.add(resultMap);
}
//test.setText(IDs.get(x - 1));
resultsListView.setAdapter(adapter);
}
This should replace all the IDs into "". It doesn't. So the output could be: ;+#:0:#+;NAME1 12.99 ;+#:1:#+;NAME2 0.99
But in the second loop, if I say
resultMap.put("First", pair.getKey().toString().replace(IDs.get(0), ""));
it replaces correctly the element 0.
The output would be: NAME1 12.99 ;+#:1:#+;NAME2 0.99
You are not getting the entries of NamePrice in the order you expect. I inserted a System.out.println() in your second for loop and got the output in this order:
;+#:3:#+;Mediaworld
;+#:0:#+;Starbucks
;+#:4:#+;Starbucks
;+#:1:#+;Apple Store
;+#:2:#+;Esselunga
So you are trying to replace ;+#:0:#+; in ;+#:3:#+;Mediaworld and so forth. That doesn’t replace anything. The reason is that NamePrice is a HashMap. A HashMap’s iterator does not return the entries in any specific order, particularly not in the order they were inserted.
You may use a LinkedHashMap instead:
LinkedHashMap<String, String> NamePrice = new LinkedHashMap<>();
Its iterator returns the entries in the order they were created. So now the replacements work.

need to save all the values coming in for loop?

if (Username.equals(RegisteredUSer)) {
JSONArray nameObject = msg.getJSONArray("NameList");
for (int j = 0; j < nameObject.length(); j++) {
JSONObject name = nameObject.getJSONObject(j);
USername = name.getString("FirstName");
USerweight = name.getString("Weight");
Weight = Double.parseDouble(USerweight);
}
}
HERE i need to save all the username and weight coming within for loop and convert the userweight in double ,and extracting the save values within the same class??
Your version:
ArrayList<String> username = new ArrayList<String>();
ArrayList<Double> weight = new ArrayList<Double>();
if (Username.equals(RegisteredUSer)) {
JSONArray nameObject = msg.getJSONArray("NameList");
for (int j = 0; j < nameObject.length(); j++) {
JSONObject name = nameObject.getJSONObject(j);
USername = name.getString("FirstName");
USerweight = name.getString("Weight");
Weight = Double.parseDouble(USerweight);
username.add(USername);
weight.add(Weight);
}
}
U can use a string array or an arraylist.The syntax is ArrayList username=new ArrayList (); username.add (variablename); to extract the values call username.get (loopvariable);

ArrayList of HashMaps to string, and then back to ArrayList of HashMaps

I have a ArrayList<HashMap<String,String>> that I am using the toString() method on to store in a database.
Here is the code that I use to store it the toString() to a database (it works):
HashMap<String, String> commentsHash = null;
ArrayList<HashMap<String, String>> test2 = new ArrayList<HashMap<String, String>>();
for (int i=0; i < test.size(); i++)
{
String timestamp = test.get(i).get("timestamp");
String last_name = test.get(i).get("last_name");
String first_name = test.get(i).get("first_name");
String comment = test.get(i).get("comment");
commentsHash = new HashMap<String, String>();
commentsHash.put("creation_timestamp", timestamp);
commentsHash.put("first_name", first_name);
commentsHash.put("last_name", last_name);
commentsHash.put("comment", comment);
test2.add(commentsHash);
}
dbHelper.addCommentsToMyLiPost(Integer.parseInt(sqlId), test2.toString());
Here is the method I want to use to convert a string to a HashMap<String, String>:
protected HashMap<String,String> convertToStringToHashMap(String text){
HashMap<String,String> data = new HashMap<String,String>();
Pattern p = Pattern.compile("[\\{\\}\\=\\, ]++");
String[] split = p.split(text);
for ( int i=1; i+2 <= split.length; i+=2 ){
data.put( split[i], split[i+1] );
}
return data;
}
I have tried using .split(",") on the string to split the string into 2 parts, but instead of returning two, it returns 8.
Here is what the toString() method prints. It is an ArrayList of HashMaps, and I am trying to grab the two HashMaps that are inside of the ArrayList.
[{comment=hello, last_name=u1, first_name=u1, creation_timestamp=1404938643772}, {comment=hello2, last_name=u2, first_name=u2, creation_timestamp=1404963221598}]
In convertToStringToHashMap, when you put your data into HashMap, the old value will be replaced since they have same key for each records, such as comment, last_name, etc.
public static Map<String, Map<String, String>> convertToStringToHashMap(String text)
{
Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();
Pattern p = Pattern.compile("[\\{\\}\\=\\, ]++");
String[] split = p.split(text);
Map<String, String> data = new HashMap<String, String>();
int gap = 8;
int key = 1;
for (int i = 1; i + 2 <= split.length; i += 2)
{
data.put(split[i], split[i+1]);
if((i + 1) % gap == 0)
{
map.put(String.valueOf(key++), data);
data = new HashMap<String, String>();
data.clear();
}
}
return map;
}
This will return a Map:
2={first_name=u2, last_name=u2, comment=hello2, creation_timestamp=1404963221598}
1={first_name=u1, last_name=u1, comment=hello, creation_timestamp=1404938643772}
This program will recreate the whole list from the database entry
Pattern firstPat = Pattern.compile("\\{.*?\\}");
Matcher firstMat = firstPat.matcher(text);
ArrayList<HashMap<String, String>> list = new ArrayList<>();
while(firstMat.find()){
HashMap<String, String> map = new HashMap<>();
String assignStrings = firstMat.group();
String [] assignGroups = assignStrings.substring(1,assignStrings.length()-1).split("\\s*\\,\\s*");
for(String assign:assignGroups){
String [] parts = assign.split("\\=");
map.put(parts[0], parts[1]);
}
list.add(map);
}
return list

Android : HashMap is showing only last array item in a Listview field

I'm prsing information from a json file and showing data in a custom ListView. Now, I have an Array named authors. Where authors are multiple. But, in ListView I can only see the last authors name or last array item .
How can I show all items ? Here is my code
for (int index = 0; index < jsonArray.length(); index++)
{
HashMap<String, String> temp = new HashMap<String,String>();
JSONObject jsonObject = jsonArray.getJSONObject(index);
String topic = jsonObject.getString("topic");
String type = jsonObject.getString("type");
String title = jsonObject.getString("title");
String absData = jsonObject.getString("abstract");
JSONArray getAuthorsArray = new JSONArray(jsonObject.getString("authors"));
for(int a =0 ; a < getAuthorsArray.length(); a++){
JSONObject getJSonObj = (JSONObject)getAuthorsArray.get(a);
String authordName = getJSonObj.getString("name");
Log.e("Name", authordName);
temp.put(KEY_AUTHOR, authordName);
}
temp.put(KEY_TOPIC, topic);
temp.put(KEY_TYPE, type);
temp.put(KEY_TITLE, title);
temp.put(KEY_ABSTRACT,absData);
list.add(temp);
}
}
simpleAdapter = new SimpleAdapter(this, list, R.layout.abstract_items, from, new int[]{R.id.abTopic,R.id.abType,R.id.abTitle,R.id.SubTitle});
setListAdapter(simpleAdapter);
temp.put(KEY_AUTHOR, authordName);
That's probably why. You are iterating over the all authors but HashMap will override values and only the last one is being saveed.
As I understand you are getting back a JSON response with an array of JSONObject. Each JSONObject holding some info and a sub-JSONArray of associated authors.
The easiest approach could be just building ArrayList<JSONObject> and extending BaseAdapter implementing an adapter of your own. It's very easy. For large collections of data search on ViewHolder pattern, for optimization.
'HashMap<String, String> temp;
for (int index = 0; index < jsonArray.length(); index++)
{
temp = new HashMap<String,String>();
JSONObject jsonObject = jsonArray.getJSONObject(index);
String topic = jsonObject.getString("topic");
String type = jsonObject.getString("type");
String title = jsonObject.getString("title");
String absData = jsonObject.getString("abstract");
JSONArray getAuthorsArray = new JSONArray(jsonObject.getString("authors"));
for(int a =0 ; a < getAuthorsArray.length(); a++){
JSONObject getJSonObj = (JSONObject)getAuthorsArray.get(a);
String authordName = getJSonObj.getString("name");
Log.e("Name", authordName);
temp.put(KEY_AUTHOR, authordName);
}
temp.put(KEY_TOPIC, topic);
temp.put(KEY_TYPE, type);
temp.put(KEY_TITLE, title);
temp.put(KEY_ABSTRACT,absData);
list.add(temp);
}
}
simpleAdapter = new SimpleAdapter(this, list, R.layout.abstract_items, from, new int[]{R.id.abTopic,R.id.abType,R.id.abTitle,R.id.SubTitle});
setListAdapter(simpleAdapter);'
you declare the "HashMap"line in above the onstart values.it will help for you.

Categories

Resources