Hashmap with Intent not working - android

I am trying to use HashMap to pass the values over to the other class but I am not sure why I got such weird results. I did a system.out.println and got [{Latitude=1.224119, username=borrow, Longitude=103.930041}],[{Latitude=1.224119, username=borrow, Longitude=103.930041}] repeatably but it shouldn't be the case as I have two different coordinates.
And when I pass it to the other class, it only returns me one coordinate and not two.
Anything went wrong with my code?
Get coordinates from db and pass to another class:
protected void onPostExecute(JSONObject json) {
ArrayList<HashMap<String, String>> list=new ArrayList<HashMap<String,String>>();
HashMap<String, String> h1=new HashMap<String, String>();
if (json != null) {
Toast.makeText(Borrower_AP.this, json.toString(),
Toast.LENGTH_LONG).show();
try {
dataJsonArr = json.getJSONArray("Posts");
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
Longitude = c.getDouble("longitude");
Latitude = c.getDouble("latitude");
String s_lat = Latitude.toString();
String s_long = Longitude.toString();
h1.put("Latitude",s_lat);
h1.put("Longitude",s_long);
h1.put("username",username);
list.add(h1);
Intent i = new Intent(this, BorrowerMap.class);
i.putExtra("list", list);
System.out.print(list);
startActivity(i);
}
Get the values out:
ArrayList<HashMap<String, String>> list=new ArrayList<HashMap<String,String>>();
list=(ArrayList<HashMap<String, String>>) getIntent().getExtras().get("list");
String Latitude=list.get(0).get("Latitude");
String Longitude=list.get(0).get("Longitude");
String s_lat = Latitude.toString();
String s_long = Longitude.toString();
System.out.println(Latitude);
System.out.println(Longitude);

If i follow your question than make the intent call after the loop body.Because it is getting only one list item and making the intent call in each loop process.
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
Longitude = c.getDouble("longitude");
Latitude = c.getDouble("latitude");
String s_lat = Latitude.toString();
String s_long = Longitude.toString();
h1.put("Latitude",s_lat);
h1.put("Longitude",s_long);
h1.put("username",username);
list.add(h1);
}
Intent i = new Intent(this, BorrowerMap.class);
i.putExtra("list", list);
System.out.print(list);
startActivity(i);

Related

Convert JSON object string into integer

I want to change the string value of latitude into integer which i want to use in map location determination.
My code is as below:
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String timedate = c.getString(TAG_TIMEDATE);
String binno = c.getString(TAG_BINNO);
String data1 = c.getString(TAG_DATA1);
String data2 = c.getString(TAG_DATA2);
String data3 = c.getString(TAG_DATA3);
String averagedata = c.getString(TAG_AVERAGEDATA);
String latitude = c.getString(TAG_LATITUDE);
String longitude = c.getString(TAG_LONGITUDE);
HashMap<String,String> trashcan = new HashMap<String,String>();
trashcan.put(TAG_TIMEDATE,timedate);
trashcan.put(TAG_BINNO,binno);
trashcan.put(TAG_DATA1,data1);
trashcan.put(TAG_DATA2,data2);
trashcan.put(TAG_DATA3,data3);
trashcan.put(TAG_AVERAGEDATA,averagedata);
trashcan.put(TAG_LATITUDE,latitude);
trashcan.put(TAG_LONGITUDE,longitude);
trashcanList.add(trashcan);
}
ListAdapter adapter = new SimpleAdapter(
MapsActivity.this, trashcanList, R.layout.list_item,
new String[]{TAG_TIMEDATE,TAG_BINNO,TAG_DATA1,TAG_DATA2,TAG_DATA3,TAG_AVERAGEDATA,TAG_LATITUDE,TAG_LONGITUDE},
new int[]{R.id.timedate,R.id.binno, R.id.data1,R.id.data2,R.id.data3,R.id.averagedata, R.id.latitude, R.id.longitude}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
I have tried the following solutions but the value of latitude comes out to be zero everytime.
int latitude1 = jsonObj.getInt("Latitude");
The value of Lat and Lng should be something like
"lat" : 22.3361462197085,
"lng" : 114.1725279197085
You cannot put them in primitive int or Integer. You may want to use another data type like
String myJSON = "{\"lat\":\"22.3361462197085\",\"lng\":\"114.1725279197085\"}";
try {
JSONObject jsonObj = new JSONObject(myJSON);
BigDecimal lat = jsonObj.getBigDecimal("lat");
BigDecimal lng = jsonObj.getBigDecimal("lng");
System.out.println(lat);
System.out.println(lng);
} catch (JSONException e) {
e.printStackTrace();
}
If you cannot find getBigDecimal() method, try getDouble(String name) or getLong(String name).

How to settext in arraylist

I've tried many possibilities and none worked. It needs to change the third value so that when the list is displayed immediately changed values
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray devices = jsonObj.getJSONArray("list");
for (int i = 0; i < devices.length(); i++) {
JSONObject c = devices.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String known = c.getString("known");
String description = c.getString("description");
String controllerId = c.getString("controllerId");
JSONObject frequencySurvey = c.getJSONObject("frequencySurvey");
if (frequencySurvey.has("5000")) {
JSONObject fivezero = frequencySurvey.getJSONObject("5000");
String timestamp = fivezero.getString("timestamp");
String clients = fivezero.getString("clients");
String enabled = fivezero.getString("enabled");
HashMap<String, String> device = new HashMap<>();
device.put("id", id);
device.put("name", name);
device.put("enabled", enabled);
device.put("clients", clients);
DevicesList.add(device);
}
ListAdapter adapter = new SimpleAdapter(Devices_5_0.this, DevicesList,
R.layout.list_item, new String[]{ "name","clients","enabled"},
new int[]{R.id.name,R.id.clients, enabled});
lv.setAdapter(adapter);
In third values I get values "false" or "true" and i want to set false = Not active but true = Active
OnCreate
tv = (TextView) findViewById(R.id.enabled);
DevicesList = new ArrayList<>();
And global declared:
private ListView lv;
private TextView tv;
ArrayList<HashMap<String, String>> DevicesList;
try this in the condition of for loop
DevicesList.add(i,device);
instead of
DevicesList.add(device);

Error when selecting an item in my spinner

I am getting an error java.lang.String cannot be cast to java.util.HashMap when i select a data on my spinner. I retrieve my data in my spinner from my database. Im am trying to have just only 1 class, when i select a item on my spinner it checks the id in my database to show filter and show only the selected id
Here is my spinner select
ArrayList<HashMap<String,String>> list1 = new ArrayList<>();
try
{
JSONArray JA = new JSONArray(result);
JSONObject json;
s_name = new String[JA.length()];
s_gender = new String[JA.length()];
for(int i = 0; i<JA.length(); i++)
{
json = JA.getJSONObject(i);
s_gender[i] = json.getString("s_gender");
s_name[i] = json.getString("s_name");
}
list1.add("All");
for(int i = 0; i<s_name.length; i++)
{
list1.add(s_name[i] + " "+s_gender[i]);
}
} catch (JSONException e) {
e.printStackTrace();
}
spinner_fn();
ArrayList<HashMap<String,String>> spinner = new ArrayList<Object>(Games.this, layout.simple_spinner_dropdown_item, s_name);
spinner1.setAdapter((SpinnerAdapter) spinner);
spinner1.setSelection(0);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Intent intent = null;
switch (position) {
case 1:
intent = new Intent(getApplication(), Basketball.class);
HashMap<Object, Object> map = (HashMap)parent.getItemAtPosition(position);
String news_id = map.get(Config.TAG_news_id).toString();
String title = map.get(Config.TAG_title).toString();
String content = map.get(Config.TAG_content).toString();
String n_date = map.get(Config.TAG_n_date).toString();
intent.putExtra(Config.News_id,news_id);
intent.putExtra(Config.Title,title);
intent.putExtra(Config.Content,content);
intent.putExtra(Config.N_date,n_date);
startActivity(intent);
break;
I am getting the error here saying in arraylist cannot be applied to java.lang.string
(Games.this, layout.simple_spinner_dropdown_item, s_name);
list1.add("All");
for(int i = 0; i<s_name.length; i++)
{
list1.add(s_name[i] + " "+s_gender[i]);
}
list1.add(s_name[i] + " "+s_gender[i]);
here is an error, as list1 is ArrayList of HASHMAP (you have a lot of hashmaps in one arraylist), and you've tried to add usual String to this list. May be you wanted the next:
for(int i = 0; i<s_name.length; i++)
{
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put(s_name[i], s_gender[i]);
list1.add(hashMap);
}
//Remove this line
list1.add("All");
use this.
HashMap<String,String> stringHashMap=new HashMap<>();
for(int i = 0; i<s_name.length; i++)
{
stringHashMap.put(s_name[i],s_gender[i]);
list1.add(stringHashMap);
}
ArrayList<String> spinnerArray=new ArrayList<>();
Map<String, String> map = stringHashMap;
for (Map.Entry<String, String> entry : map.entrySet()) {
spinnerArray.add(entry.getKey());
}
ArrayAdapter<String> spinner = new ArrayAdapter<String>(Games.this, layout.simple_spinner_dropdown_item, spinnerArray);
spinner1.setAdapter(spinner);
spinner1.setSelection(0);

arraylist with multiple latitude longitude

i have arraylist which have multiple atitude longitude having different
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(json);
Log.d("jsonObject", "new json Object");
// Getting JSON Array node
matchFixture = jsonObj.getJSONArray(TAG_FIXTURE);
Log.d("json aray", "user point array");
int len = matchFixture.length();
Log.d("len", "get array length");
for (int i = 0; i < matchFixture.length(); i++) {
JSONObject c = matchFixture.getJSONObject(i);
String matchId = c.getString(TAG_MATCHID);
Log.d("matchId", matchId);
// hashmap for single match
HashMap<String, String> matchFixture = new HashMap<String, String>();
// adding each child node to HashMap key => value
matchFixture.put(TAG_MATCHID, matchId);
matchFixtureList.add(matchFixture);
HashMap<String,String>[] stockArr = new HashMap[matchFixtureList.size()];
stockArr = matchFixtureList.toArray(stockArr);
for(HashMap<String,String> map : stockArr)
for(Map.Entry<String,String> entry : map.entrySet()){
Log.d("debug", entry.getKey() + ","+ entry.getValue());
}
}
i have no idea how to send this to MapActivity
public void setdaata(View view){
Intent intent = new Intent(this, Registration.class);
String[] myStrings = new String[] {"test", "test2"};
intent.putExtra("strings", myStrings);
startActivity(intent);
}
help me please that how to send this and use in MapActivity
You can send ArrayList between activities. But, if the object in array is not primitive data type(like below, MyObject), it has to implement Parcelable.
In current activity
ArrayList<MyObject> list = new ArrayList<>();
list.add(new MyObject(..));
list.add(new MyObject(..));
list.add(new MyObject(..));
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
intent.putParcelableArrayListExtra("list", list);
startActivity(intent);
In target activity
#Override
protected void onCreate(Bundle savedInstanceState) {
...
Intent intent = this.getIntent();
ArrayList<MyObject> list = (ArrayList<MyObject>)intent
.getParcelableArrayListExtra("list");
}
Edit
The above approach ideal for passing data when switching activities
(Your actual question).
If you want to access your fetched json data from every point of
app, it must be stored on your device.
Easy way of storing json data : Combine gson library and shared preferences. Check this link to get idea

How to set json data to list view?

I tried to add json data to listview.But i don't know how to add the json data to list adapter.
try {
mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("restaurants");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("name");
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
if(restName.equalsIgnoreCase(name)){//this name is predefined name.
String address = jsonChildNode.optString("address");
String mobile = jsonChildNode.optString("mobile");
String direction = "Direction: "+jsonChildNode.optString("direction");
String bestTime = "Best time to visite: "+jsonChildNode.optString("bestTime");
String food = jsonChildNode.optString("food");
String dress = jsonChildNode.optString("dress");
String priceRange = "Price Range: "+jsonChildNode.optString("priceRange");
String rate = jsonChildNode.optString("Rate");
String comment = "Price Range: "+jsonChildNode.optString("comment");
map.put("restName",restName);
map.put("address",address);
map.put("mobile",mobile);
map.put("direction",direction);
map.put("bestTime",bestTime);
map.put("food",food);
map.put("dress",dress);
map.put("priceRange",priceRange);
map.put("rate",rate);
map.put("comment",comment);
mylist = new ArrayList<HashMap<String, String>>();
mylist.add(map);
}else{
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
// ListAdapter adapter = new SimpleAdapter(getApplicationContext(),android.R.layout.simple_list_item_1,mylist);
// list.setAdapter(adapter);
}
Can anyone tel me how to set this data to list view.?
Try this..
Your doing reversely. declear the arraylist before for loop and declear the HashMap inside the for loop .
mylist = new ArrayList<HashMap<String, String>>();
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("restaurants");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("name");
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
if(restName.equalsIgnoreCase(name)){//this name is predefined name.
HashMap<String, String> map = new HashMap<String, String>();
String address = jsonChildNode.optString("address");
//So on
map.put("restName",restName);
//So on
mylist.add(map);
}else{
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}
google-gson
I would use gson for this. Check the gson project website for more details on how. This is an example for object serialisation/deserialisation:
Object Examples
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
Note that you can not serialize objects with circular references since that will result in infinite recursion.
(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
==> obj2 is just like obj

Categories

Resources