Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am trying to save location in Firebase. I can't find any information about how to save location in Firebase. And I develop my in Android Studio in Java. I put a button in layout and when I click to this button it should send coordinates to Firebase. But I don't know anything about saving data to Firebase.
Please if you can help me I will be happy!
OK, just so you know your question is WAY too general and this code is not complete by any means; as large as the response is. It is enough to get you going you will need to do more research. I hope this helps. What is not included is the UI to allow a user to save the location from a map or whatever the source is.
Also not included is the authentication do do this [Oauth] that is a whole separate issue. If I were you I would start with a tutorial that adds and shows data, get that working then substitute the data with location
tutorial
There are lots of steps, you might want to start with a tutorial, there are lots of good ones out there.
your db ref:
mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
final DatabaseReference locationsRef = mFirebaseDatabaseReference
.child(USERS_CHILD.concat("/" + mFirebaseAuth.getUid()).concat("/locations"));
FirebaseRecyclerOptions<Location> options =
new FirebaseRecyclerOptions.Builder<Location>()
.setQuery(locationsRef
.orderByChild("name"), parser)
.build();
mFirebaseAdapter = new FirebaseRecyclerAdapter<Location,
PlacesFragment.LocationViewHolder>(options) {
#Override
public PlacesFragment.LocationViewHolder onCreateViewHolder(ViewGroup viewGroup,
final int position) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
PlacesFragment.LocationViewHolder holder = new
PlacesFragment.LocationViewHolder(inflater.inflate(R.layout.location_item,
viewGroup, false));
Log.d(TAG, "viewHolder created");
return holder;
}
#Override
protected void onBindViewHolder(final PlacesFragment.LocationViewHolder viewHolder,
int position, Location location) {
if (location.getName() != null) {
viewHolder.locationNameTextView.setText(location.getName());
viewHolder.locationNameTextView.setVisibility(TextView.VISIBLE);
viewHolder.locationAddressTextView.setText(location.getAddress());
viewHolder.locationLatTextView.setText(String.valueOf(location.getLatitude()));
viewHolder.locationLongTextView.setText(String.valueOf(location.getLongitude()));
}
}
#Override
public int getItemCount() {
int count = super.getItemCount();
return count;
}
#Override
public void onDataChanged() {
Log.d(TAG, "OnDataChanged");
mLandmarks.clear();
ArrayList<Location> arr = new ArrayList<Location>();
for (int i = 0; i < mFirebaseAdapter.getSnapshots().toArray().length; i++) {
Location loc = mFirebaseAdapter.getItem(i);
arr.add(loc);
mLandmarks.put(loc.getName(), new LatLng(loc.getLatitude(),
loc.getLongitude()));
}
if (mService != null) {
mService.setLocationsData(arr);
Log.d(TAG, "onDataChanged: updating locations");
} else {
mService_not_updated = true;
Log.d(TAG, "onDataChanged: not updating locations");
}
// Get the geofences used.
populateGeofenceList();
super.onDataChanged();
}
};
mFirebaseAdapter.startListening();
database rules so each user can have their own list of locations:
// These rules grant access to a node matching the authenticated
// user's ID from the Firebase auth token
{
"rules": {
"users": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid"
}
}
}
}
This is how you might store a location:
private void storeLocation(com.wfs.android.walkingjinni.Location location) {
com.wfs.android.walkingjinni.Location loc = new com.wfs.android.walkingjinni.Location(
mFirebaseUserId,
location.getName(),
location.getAddress(),
location.getLatitude(), location.getLongitude()
,location.getPlaceId());
mFirebaseDatabaseReference
.child(PlacesFragment.USERS_CHILD).child(mFirebaseUserId)
.child(PlacesFragment.LOCATIONS_CHILD).push().setValue(loc);
Log.d(TAG, location.getAddress() + " stored from map");
}
and this is what a location might be:
#Keep
public class Location implements Parcelable {
public static final Parcelable.Creator CREATOR = new Parcelable.Creator<Location>() {
public Location createFromParcel(Parcel in) {
return new Location(in);
}
public Location[] newArray(int size) {
return new Location[size];
}
};
private String id;
private String user_id;
private String name;
private String address;
private double latitude, longitude;
private String place_id = "";
private Location(Parcel in) {
id = in.readString();
user_id = in.readString();
name = in.readString();
address = in.readString();
latitude = in.readDouble();
longitude = in.readDouble();
place_id = in.readString();
}
public Location() {
}
/// used for onCreate for the home location, nothing else
public Location(String name, String address,
double latitude, double longitude, String placeId) {
this.name = name;
this.address = address;
this.latitude = latitude;
this.longitude = longitude;
this.place_id = placeId;
}
public Location(
String userId,
String name,
String address,
double latitude, double longitude, String placeId) {
this.user_id = userId;
this.name = name;
this.address = address;
this.latitude = latitude;
this.longitude = longitude;
this.place_id = placeId;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUserId() {
return user_id;
}
public void setUserId(String userId) {
this.user_id = userId;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public String getPlaceId() {
return place_id;
}
public void setPlaceId(String placeId) {
this.place_id = placeId;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(id);
parcel.writeString(user_id);
parcel.writeString(name);
parcel.writeString(address);
parcel.writeDouble(latitude);
parcel.writeDouble(longitude);
parcel.writeString(place_id);
}
#Override
public String toString() {
return "Location{" +
" id='" + id + '\'' +
", user_id='" + id + '\'' +
", name='" + name + '\'' +
", address='" + address + '\'' +
", latitude='" + latitude + '\'' +
", longitude='" + longitude + '\'' +
", place_id='" + place_id + '\'' +
'}';
}
public android.location.Location getLocation() {
android.location.Location loc = new android.location.Location("");
loc.setLatitude(this.getLatitude());
loc.setLongitude(this.getLongitude());
return loc;
}
}
Related
I have a dropdown list using another dropdown list. The issue i am facing is that I am able to retrieve the choice of the first dropdown list but not the second one.
Here is my script under view
$(function() {
$("#Off").change(function() {
$.get("/Reference/GetSubjectById", {
id: $("#Off").val()
}, function(data) {
$("#Su").empty() $.each(data, function(mail, row) {
$("#Su").append(" <option value='" + row.Id_Subject + "'>" + row.Subject_Matter + "</option>")
});
})
});
});
Here my controller
public ActionResult Mail()
{
fillingEntities db = new fillingEntities();
ViewBag.OfficeName = new SelectList(db.offices, "Office_Id", "Office_Name");
//ViewBag.SubjectName = new SelectList(db.subjects, "Subject_Id", "Subject_Matter");
MailViewModel mailView = new MailViewModel();
mailView.date = DateTime.Now;
return View(mailView);
}
public JsonResult GetSubjectById(int id)
{
fillingEntities db = new fillingEntities();
db.Configuration.ProxyCreationEnabled = false;
return Json(db.subjects.Where(m => m.Office_Id == id), JsonRequestBehavior.AllowGet);
}
public ActionResult New(int newref)
{
return View();
}
public ActionResult Save(MailViewModel mail)
{
fillingEntities db = new fillingEntities();
//subject mySubject = db.subjects.Where(m => m.Subject_Id == mail.id_subject).FirstOrDefault();
string subValue = Request.Form["Su"].ToString();
reference lastRef = db.references.ToList().LastOrDefault();
int numeroRef = (lastRef.Opening_Ref+1);
//string referenceNumber = mySubject.Subject_Code + "/" + numeroRef + "/" + "2020";
string referenceNumber = subValue + "/" + numeroRef + "/" + "2020";
mail.NewReference = referenceNumber;
reference newRef = new reference();
newRef.Opening_Ref = numeroRef;
db.references.Add(newRef);
db.SaveChanges();
mail newMail = new mail();
newMail.Location = mail.location;
newMail.Mail_Year = (short) DateTime.Now.Year;
newMail.Mail_Date = DateTime.Now.Date;
newMail.Addressed_Name = mail.addTo;
newMail.Addressed_Department = mail.addDep;
newMail.Addressed_Organisation = mail.addOrg;
newMail.Mail_Subject = mail.subject;
newMail.Reference_Id = newRef.Reference_Id;
newMail.Office_Id = mail.id_office;
db.mails.Add(newMail);
db.SaveChanges();
return View("Save", mail);
}
And finaly my viewmodel
namespace FillingSystem.ViewModel
{
public class MailViewModel
{
public string addTo { get; set; }
public string addOrg { get; set; }
public string addDep { get; set; }
public string subject { get; set; }
public string location { get; set; }
public DateTime year { get; set; }
public DateTime date { get; set; }
public IEnumerable<office> offices { get; set; }
public int id_office { get; set; }
public int id_subject { get; set; }
public IEnumerable<subject> subjects { get; set; }
public int Opening_Ref { get; set; }
public string NewReference { get; set; }
}
}
I don't know how to avoid repeated aadhar value. please help me anyone, it is very useful for my college project. i stored my data in sqlite database, i need, if we enter exists value means show alert msg like "this value already exists" and exit the page.
if anyone tell me how to modify my coding and give me some relevant coding.
Votingpage.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_votingpage);
myDb = new DatabaseHelper(this);
emailview = findViewById(R.id.emailview);
edtaadhar1 = findViewById(R.id.edtaadhar1);
btnlogout = findViewById(R.id.btnlogout);
btnadd = findViewById(R.id.btnadd);
radioGroup = findViewById(R.id.radioGroup);
AddData();
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
emailview.setText(firebaseUser.getEmail());
btnlogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Votingpage.this,MainActivity.class);
startActivity(intent);
}
});
}
private void AddData() {
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (edtaadhar1.getText().toString().trim().length() <= 0) {
Toast.makeText(Votingpage.this, "Please enter aadhar no", Toast.LENGTH_SHORT).show();
}else {
int radioid = radioGroup.getCheckedRadioButtonId();
radioButton = findViewById(radioid);
boolean isInserted = myDb.insertData(radioButton.getText().toString(),edtaadhar1.getText().toString());
if (isInserted = true)
Toast.makeText(Votingpage.this, "Thanks for giving your vote", Toast.LENGTH_SHORT).show();
else
Toast.makeText(Votingpage.this, "data not inserted", Toast.LENGTH_SHORT).show();
}
}
});
}
public void check_button(View v){
int radioid = radioGroup.getCheckedRadioButtonId();
radioButton = findViewById(radioid);
}
}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Vote.db";
public static final String TABLE_NAME = "voter_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "PARTY";
public static final String COL_3 = "AADHAR";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,PARTY TEXT,AADHAR INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String party,String aadhar) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, party);
contentValues.put(COL_3, aadhar);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
}
With this method you can add below your insertData() method, you can check the value is exist in your db.
private boolean isValueExist(String value){
String query = "SELECT * FROM " + TABLE_NAME + " WHERE " + COL_3 + " = ?";
String[] whereArgs = {value};
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, whereArgs);
int count = cursor.getCount();
cursor.close();
return count >= 1;
}
If the count is 0 this method will return false so you can save your data.
To make it work you should modify your insertData() method like,
public boolean insertData(String party,String aadhar) {
if(!isValueExist(addhar)){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, party);
contentValues.put(COL_3, aadhar);
long result = db.insert(TABLE_NAME, null, contentValues);
return result != -1;
} else {
return false;
}
}
var data = google.visualization.arrayToDataTable(JSON.parse(newRows), false);
I am not able to pass the data in arrayToDataTable() of var data, since newRows of string data is cannot able to fetch the newRows data.
So please help..
I have inserted my code below, how to obtain GeoChart.
GeoChartData.java
public class GeoChartData {
int id;
String Country;
String Total;
#JavascriptInterface
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#JavascriptInterface
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
#JavascriptInterface
public String getTotal() {
return Total;
}
public void setTotal(String total) {
Total = total;
}
#Override
public String toString() {
return "\n[" + "'" + Country + "'"+ ":" +Integer.valueOf(Total)+ "]";
}}
GeoChartActivity.java
#SuppressLint("SetJavaScriptEnabled")
public class GeoChartActivity extends Activity {
WebView webView;
int num1, num2;
List listOfCountry;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_geo_chart);
num1 = 390;
webView = (WebView)findViewById(R.id.web);
webView.addJavascriptInterface(new WebAppInterface(), "Android");
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("file:///android_asset/geochart.html");
webView.setPadding(0, 0, 0, 0);
}
public class WebAppInterface {
#JavascriptInterface
public String getArrayGeoChartData() {
// System.out.println(listOfCountry.toString());
return String.valueOf(getCountryData());
}
#JavascriptInterface
public int getNum1() {
return num1;
}
}
public List getCountryData() {
listOfCountry = new ArrayList<>();
GeoChartData s1 = new GeoChartData();
s1.setId(100);
s1.setCountry("Germany");
s1.setTotal("200");
listOfCountry.add(s1);
GeoChartData s2 = new GeoChartData();
s2.setId(101);
s2.setCountry("Canada");
s2.setTotal("200");
listOfCountry.add(s2);
return listOfCountry;
} }
assets/geochart.html
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {
'packages':['geochart'],
// Note: you will need to get a mapsApiKey for your project.
// See: https://developers.google.com/chart/interactive/docs/basic_load_libs#load-settings
'mapsApiKey': 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
});
google.charts.setOnLoadCallback(drawRegionsMap);
var newRows = [];
var rowData = [];
var dataTable = null;
function drawRegionsMap() {
//console.log(Android.getArrayGeoChartData());
var jsonString = Android.getArrayGeoChartData(); // json string of array
console.log(jsonString);
newRows.push(jsonString);
console.log(newRows);
var dataArray = ["['Country', 'Popularity']"];
console.log(dataArray);
console.log(dataArray.push(dataArray, newRows));
var data = google.visualization.arrayToDataTable(JSON.parse(newRows), false);
//data.setColumnProperty ('Country', 'Popularity');
var csv = google.visualization.dataTableToCsv(data);
console.log(csv);
// console.log("france" +Android.getNum1());
var options = {};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="regions_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
Error occur
https://ctalandroid.blogspot.com/2019/02/android-geochart.html
GeoChartActivity.java
#SuppressLint("SetJavaScriptEnabled")
public class GeoChartActivity extends Activity {
String url = "https://battery-75d95.firebaseio.com/";
WebView webView;
int num1, num2;
public static List<GeoTotalByCountry> lstItemArry;
List listOfStudent;
public static List<Order> salArry;
public static List<Order> hosArry;
public static List<Order> ProductData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_geo_chart);
ProductData = new ArrayList<>();
hosArry = new ArrayList();
salArry = new ArrayList();
lstItemArry = new ArrayList();
listOfStudent = new ArrayList();
getOrderArray();
num1 = 390;
webView = (WebView)findViewById(R.id.web);
webView.addJavascriptInterface(new WebAppInterface(), "Android");
webView.getSettings().setJavaScriptEnabled(true);
// webView.loadUrl("file:///android_asset/chart.html");
webView.loadUrl("file:///android_asset/geochart.html");
//WebView web = new WebView(this);
webView.setPadding(0, 0, 0, 0);
}
public class WebAppInterface {
#JavascriptInterface
public String getArrayGeoChartData() {
// System.out.println(listOfStudent.toString());
return String.valueOf(listOfStudent);
}
#JavascriptInterface
public int getNum1() {
return num1;
}
}
//arrayOrder
void getOrderArray() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitArrayAPI service = retrofit.create(RetrofitArrayAPI.class);
Call<List<Order>> call = service.getOrderDetails();
call.enqueue(new Callback<List<Order>>() {
#Override
public void onResponse(Response<List<Order>> response, Retrofit retrofit) {
try {
ProductData = response.body();
for (int i = 0; i < ProductData.size(); i++) {
//displaying the string array into gridView
Order b = new Order();
b.setId(ProductData.get(i).getId());
b.setStatus(ProductData.get(i).getStatus());
b.setTotal(ProductData.get(i).getTotal());
b.setBilling(ProductData.get(i).getBilling());
hosArry.add(b);
}
listOfStudent = new ArrayList<>();
// Log.v("hosarry", String.valueOf(hosArry.size()));
for (int i =0; i<hosArry.size(); i++){
// if(hosArry.get(i).getStatus().contains("completed"))
{
GeoTotalByCountry b = new GeoTotalByCountry();
b.setId(hosArry.get(i).getId());
b.setTotal(hosArry.get(i).getTotal());
b.setCountry(hosArry.get(i).getBilling().getCountry());
lstItemArry.add(b);
}
}
// Log.v("listOfStudent", String.valueOf(salArry.size()));
Map<String, List<GeoTotalByCountry>> map = new HashMap<String, List<GeoTotalByCountry>>();
for (GeoTotalByCountry student : lstItemArry) {
String key = String.valueOf(student.getCountry());
if(map.containsKey(key)){
List<GeoTotalByCountry> list = map.get(key);
list.add(student);
}else{
List<GeoTotalByCountry> list = new ArrayList<GeoTotalByCountry>();
list.add(student);
map.put(key, list);
}
}
System.out.println("map"+map);
//Summing for Net Quentity
for (Map.Entry<String, List<GeoTotalByCountry>> entry : map.entrySet()) {
// System.out.println("Key : " + entry.getKey() + " value : " + entry.getValue());
// for (int i=0 ; i< entry.getKey().length(); i++){
Double sum = 0.00, value;
for (int j = 0; j < entry.getValue().size(); j++){
value = Double.valueOf(String.valueOf(entry.getValue().get(j)));
//System.out.println(j+ "value = " + value);
sum += value;
// System.out.println(j+"chgevalue = " + sum);
}
System.out.println("chgevalue = " + sum.intValue());
// System.out.println( "Key : " + entry.getKey() + "qty = " + sum);
//System.out.println(getProductById(Integer.valueOf(entry.getKey())));
ChartGeoModel pieDataXYChart = new ChartGeoModel();
pieDataXYChart.setCountry(entry.getKey());
pieDataXYChart.setTotal(sum.intValue());
listOfStudent.add(pieDataXYChart);
}
System.out.println(listOfStudent.toString());
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
Log.d("onFailure", t.toString());
}
});
}
}
Androidmanifest.xml
<uses-permission android:name="android.permission.INTERNET" />
GeoTotalByCountry.java
public class GeoTotalByCountry {
int id;
String Country;
String Total;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
public String getTotal() {
return Total;
}
public void setTotal(String total) {
Total = total;
}
#Override
public String toString() {
return String.valueOf(Total);
}
}
ChartGeoModel.java
public class ChartGeoModel {
int id;
String Country;
int Total;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
public int getTotal() {
return Total;
}
public void setTotal(int total) {
Total = total;
}
#Override
public String toString() {
return new Gson().toJson(this);
}
}
assets/geochart.html
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
google.charts.load('current', {
'packages':['geochart'],
// Note: you will need to get a mapsApiKey for your project.
// See: https://developers.google.com/chart/interactive/docs/basic_load_libs#load-settings
'mapsApiKey': 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
});
google.charts.setOnLoadCallback(drawRegionsMap);
var newRows = [];
var rowData = [];
var dataTable = null;
var data=[];
function drawRegionsMap() {
var jsonString = Android.getArrayGeoChartData(); // json string of array
console.log(jsonString);
newRows.push(jsonString);
console.log(newRows);
var obj = JSON.parse(newRows);
console.log(obj);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Country');
data.addColumn('number', 'NetTotal');
for (var i = 0; i < obj.length; i++) {
data.addRow([obj[i].Country, obj[i].Total]);
}
var csv = google.visualization.dataTableToCsv(data);
console.log(csv);
// console.log("france" +Android.getNum1());
var options = {};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="regions_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
I'm trying to update my map so that the map automatically moves to centre the marker. I want it such that if I move around, after 5 seconds, the map will animate itself to move such that the marker is central again.
Here is the code:
public class TrackDifferentLocation extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LatLng mLatlng;
String json_string;
public static TextView data;
LatLng latLng = null;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Toast.makeText(this, "Tracking location...", Toast.LENGTH_LONG).show();
setContentView(R.layout.activity_track_different_location);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map_fragment);
mapFragment.getMapAsync(this);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//new FetchJSON.execute(); //Not valid syntax
new FetchJSON().execute();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Log.i("", "onMapReady()");
displayMarkers();
}
private void displayMarkers(){
if (mMap == null)return;
//If mLatlng is null (as the Async task has not finished, then nothing will happen.
if(mLatlng == null) return;
//The camera and map will then update to the new location with zoom.
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mLatlng, 17));
mMap.addMarker(new MarkerOptions().position(mLatlng).title(String.valueOf(mLatlng)));
}
//Part of menu see following
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home){
//ends the activity
this.finish();
}
switch (item.getItemId()) {
case R.id.mapTypeNone:
mMap.setMapType(GoogleMap.MAP_TYPE_NONE);
break;
case R.id.mapTypeNormal:
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
break;
case R.id.mapTypeTerrain:
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
break;
case R.id.mapTypeSatellite:
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case R.id.mapTypeHybrid:
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
class FetchJSON extends AsyncTask<String, Integer, LatLng> {
String JSONStr = "";
String name, address, type = "";
String lat = "";
String lng = "";
String id = "";
//double lat, lng;
int idInt;
double latDouble = -1;
double lngDouble = -1;
protected LatLng doInBackground(String... args) {
//LatLng latLng = null;
try {
//URL url = new URL("https://api.myjson.com/bins/ehzqu");
URL url = new URL("https://api.myjson.com/bins/sv5vm");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
Log.d("BufferedReader: ", String.valueOf(bufferedReader));
String line = "lind";
while (line != null) {
line = bufferedReader.readLine();
JSONStr = JSONStr + line;
}
Log.d("", JSONStr);
JSONObject obj = new JSONObject(JSONStr);
JSONArray array = obj.getJSONArray("server response");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
id = o.optString("id");
name = o.optString("name");
address = o.optString("address");
lat = o.optString("lat");
lng = o.optString("lng");
Log.d("lat: ",lat);
latDouble = Double.parseDouble(lat);
lngDouble = Double.parseDouble(lng);
latLng = new LatLng(latDouble, lngDouble);
Log.i("JSON Values", lat + " " + lng);
type = o.optString("type");
}
} catch (Exception ex) {
Log.e(TAG, "FetchJSON --- " + ex.getMessage());
}
return latLng;
}
protected void onPostExecute(LatLng latLng) {
if (latLng != null) {
mLatlng = latLng;
displayMarkers();
}
}
}
}
Please note, for the question I have removed all imports and package.
To demonstrate how this can work I have changed the code which is more applicable to your code:
int index = 0;
private void loadLocation() {
new FetchJSON().execute();
startAutoHandler();
}
class FetchJSON extends AsyncTask<String, Integer, LatLng> {
#Override
protected LatLng doInBackground(String... params) {
LatLng latLng = null;
try {
URL url = new URL("https://api.myjson.com/bins/sv5vm");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
String json = stringBuilder.toString();
Log.e(TAG, "Return = " + json);
String lat= "";
String lng= "";
JSONObject obj = new JSONObject(json);
JSONArray array = obj.getJSONArray("server response");
for(int i = 0; i < array.length(); i++){
JSONObject o = array.getJSONObject(i);
lat = o.optString("lat");
lng = o.optString("lng");
}
Log.e(TAG, "Lat = " + lat);
Log.e(TAG, "lng = " + lng);
index++;
double adjustLat = 0.1 * index;
double adjustLng = 0.01 * index;
double latDouble = Double.parseDouble(lat) + adjustLat;
double lngDouble = Double.parseDouble(lng) + adjustLng;
latLng = new LatLng(latDouble, lngDouble);
}
catch (Exception ex) {
Log.e(TAG, "doInBackground --- " + ex.getMessage());
}
return latLng;
}
#Override
protected void onPostExecute(LatLng latLng) {
try{
if(latLng != null){
mLatLng = latLng;
displayMarker();
}
}
catch(Exception ex){
Log.e(TAG, "onPostExecute" + ex.getMessage());
}
}
}
private void displayMarker(){
if(mMap == null) return;
if(mLatLng == null) return;
mMap.clear();
MarkerOptions markerOption = new MarkerOptions();
markerOption.position(mLatLng);
CameraUpdate loc = CameraUpdateFactory.newLatLngZoom(mLatLng, 10.3f);
mMap.animateCamera(loc);
mMap.addMarker(markerOption);
}
Handler mAutoHandler = new Handler();
long delay = 2000l; //this delay is in ms change as needed
private void startAutoHandler(){
try{
Log.e(TAG, "startAutoHandler");
mAutoHandler.postDelayed(mAutoRunnable, delay);
}
catch (Exception ex){
Log.e(TAG, ex.getMessage());
}
}
private Runnable mAutoRunnable = new Runnable() {
#Override
public void run() {
new FetchJSON().execute();
mAutoHandler.postDelayed(mAutoRunnable, delay);
}
};
private void stopAutoHandler(){
mAutoHandler.removeCallbacks(mAutoRunnable);
}
You will need to call stopAutoHandler(); in your onPause() method. Otherwise it will carry on and can cause some real issues!
i am trying to post complex data structure to my server side method with jquery.
here i am giving my c# class structure
public partial class SerializeJSON : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static string GetData(List<Customer> oCust)
{
int empid = oCust[0].EmpID;
string name = oCust[0].Name.ToString();
DateTime dob = oCust[0].BirthDate;
double sal = oCust[0].Salary;
Address add = oCust[0].Address[0];
return "";
}
}
public class Customer
{
List<Address> add = null;
public Customer()
{
add = new List<Address>();
}
public int EmpID { get; set; }
public string Name { get; set; }
public DateTime BirthDate { get; set; }
public List<Address> Address
{
get { return add; }
set { add = value; }
}
public double Salary { get; set; }
}
public class Address
{
public string Address1 { get; set; }
public string Address2 { get; set; }
public string PostCode { get; set; }
}
i know that how right json would look like. the right json would be
[
{
"EmpID":1,
"Name":"Keith",
"BirthDate":"\/Date(947874600000)\/",
"Address":[{"Address1":"Salt lake","Address2":"Kolkata","PostCode":"784512"}],"Salary":5200
}
]
here i am telling you how to send data actually from my client to server side
this my javascript code by which i am populating data at client side and late i am sending this like
var Person = {};
Person["EmpID"] = 1;
Person["Name"] = "Keith";
Person["BirthDate"] = "08/15/2011";
var Address = {};
Address["Address1"] = "Salt lake";
Address["Address2"] = "Kolkata";
Address["PostCode"] = "741258";
Person["Address"] = Address;
$(function () {
$('#btnSubmit').click(function () {
alert(JSON.stringify(Person));
$.ajax({
type: "POST",
url: "SerializeJSON.aspx/GetData",
data: "{'oCust':'" + JSON.stringify(Person) + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
}
,
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
return false;
});
});
but i am getting error. JSON.stringify() not generating correct json.
so please tell me what would be the best approach to populate & generate right json data programatically. one thing i need to say that i dont want to generate json manually rather show me the way to generate right json programatically.
so guide me how to generate right json programatically with javascript.
also tell my approach like to populate data with javascript was wrong.
var Person = {};
Person["EmpID"] = 1;
Person["Name"] = "Keith";
Person["BirthDate"] = "08/15/2011";
var Address = {};
Address["Address1"] = "Salt lake";
Address["Address2"] = "Kolkata";
Address["PostCode"] = "741258";
Person["Address"] = Address;
the above code is wrong approach.
so please guide me how to generate right json with javascript which can be easily deserialize at server side. thanks
Here i restructure my code according to naveen
var Persons = [];
var Person = {};
Person["EmpID"] = 1;
Person["Name"] = "Keith";
Person["BirthDate"] = "08/15/2011";
var Address = [];
var addr = {};
addr["Address1"] = "Salt lake";
addr["Address2"] = "Kolkata";
addr["PostCode"] = "741258";
Address.push(addr);
Person["Address"] = Address;
Persons.push(Person)
var DTO = { oCust : Persons }
data: JSON.stringify( DTO )
i hope now it will work....isn't it?
var Persons = [];
var Person = {};
Person["EmpID"] = 1;
Person["Name"] = "Keith";
Person["BirthDate"] = "08/15/2011";
var Address = [];
var addr = {};
addr["Address1"] = "Salt lake";
addr["Address2"] = "Kolkata";
addr["PostCode"] = "741258";
Address.push(addr);
Person["Address"] = Address;
var DTO = { oCust : Person }
data: JSON.stringify( DTO )
am i right?
if my class structure would be like below one
public partial class SerializeJSON : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static string GetData(Customer oCust)
{
int empid = oCust.EmpID;
string name = oCust.Name.ToString();
DateTime dob = oCust.BirthDate;
double sal = oCust.Salary;
Address add = oCust.Address[0];
return "";
}
}
public class Customer
{
List<Address> add = null;
public Customer()
{
add = new List<Address>();
}
public int EmpID { get; set; }
public string Name { get; set; }
public DateTime BirthDate { get; set; }
public List<Address> Address
{
get { return add; }
set { add = value; }
}
public double Salary { get; set; }
}
public class Address
{
public string Address1 { get; set; }
public string Address2 { get; set; }
public string PostCode { get; set; }
}
then my json would look like
This is a snippet on auto de-serializing complex JSON using a WebMethod.
Please go through the comments in case of doubts.
Class
public class Customer
{
public int EmpID { get; set; }
public string Name { get; set; }
public DateTime BirthDate { get; set; }
// why did you use the conventional get set in this case?
// feel free to revert if you are using the class elsewhere.
public List<Address> Address { get; set; }
public double Salary { get; set; }
}
public class Address
{
public string Address1 { get; set; }
public string Address2 { get; set; }
public string PostCode { get; set; }
}
WebMethod
[System.Web.Services.WebMethod]
public static string GetData(Customer oCust)
{
try
{
int empid = oCust.EmpID;
string name = oCust.Name.ToString();
DateTime dob = oCust.BirthDate;
double sal = oCust.Salary;
Address add = oCust.Address[0];
return "Success";
}
catch (Exception exception)
{
//Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
return "Failed";
}
}
AJAX Call
$(function () {
$('#btnSubmit').click(function (evt) {
var Person = {};
Person["EmpID"] = 1;
Person["Name"] = "Keith";
//converting to date is not mandatory, but its more typesafe
Person["BirthDate"] = new Date("08/15/2011");
var Address = [];
var addr = {};
addr["Address1"] = "Salt lake";
addr["Address2"] = "Kolkata";
addr["PostCode"] = "741258";
Address.push(addr);
Person["Address"] = Address;
var DTO = { oCust: Person }
//save yourself some typing. dataType and charset in content type are not needed.
//Courtesy: http://encosia.com/save-yourself-some-typing-when-you-call-asp-net-services/
$.ajax({
type: "POST",
url: "SerializeJSON.aspx/GetData",
data: JSON.stringify(DTO),
contentType: "application/json",
success: function (msg) {
//ASP.NET 2.0 fallback.
var data = msg.hasOwnProperty("d") ? msg.d : msg;
//place a div with id=content to show the result.(not mandatory)
$("#content").hide().html(msg.d).delay(1000).show(400);
},
error: function (xhr, textStatus, errorThrown) {
//you should ideally call the xhr.responseText to see the error
alert(xhr.responseText);
}
});
evt.preventDefault();
});
});
HTML
<div id="content"></div>
<asp:Button ID="btnSubmit" runat="server" Text="Submit"/>
Hope this helps.