android studio and sqlite check if username already exists - javascript

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;
}
}

Related

How to save coordinates to Firebase [closed]

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;
}
}

How to fetch arrayToDataTable() in GeoChart in Android?

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>

How to correctly animate a map created in Android Studio to follow the marker

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!

Telerik Kendo DropDown sends the previous value to the Controller

I have been working in ASP MVC (C#) razor Entity Framework project, Visual Studio 2012, that uses Telerik Kendo DropDown:
#(Html.Kendo().DropDownListFor(run => run.Repair)
.Name("Repair")
.OptionLabel(RunStrings.Select)
.DataTextField("Text")
.DataValueField("Value")
.DataSource(dataSource => dataSource
.Read(read => read.Action("GetRepairCodes", "Run")
)
)
.Value(myModel.Repair.ToString())
.HtmlAttributes(new { style = "width:50% !important;" })
.Events( e => e.Change("RepairDropDown_OnChange")))
The DropDown sends its value to the Controller, in the object outcomeModel. The code of the Controller is:
public ActionResult OutcomeEdit(OutcomeModel outcomeModel, string previous, string next, string finish)
{
Run run = Session["Run"] as Run;
if (run == null) return RedirectToAction("Index", "Home", new { area = "" });
if (ModelState.IsValid)
{
outcomeModel.CopyToRun(run);
Repository myRepo = new Repository();
myRepo.UpdateOutcome(run);
// now update the Organ failure column
string organFailureString = string.Empty;
if (run.Discontinuation == Discontinuation.DiedOrganFailure && ModelState["OrganFailureType"] != null)
{
organFailureString = outcomeModel.DecodeOrganFailureFromString(ModelState["OrganFailureType"].Value.AttemptedValue).ToString();
myRepo.UpdateOrganFailureValue(run.RunId, organFailureString);
}
else
{
run.OrganFailure = null;
myRepo.UpdateOutcome(run);
}
/***
* This will redirect user to a selected tab
*/
string jumptToTab = Request.Form["JumpToTab"];
if (jumptToTab != "-1")
{
TabIndex gotoindex = (TabIndex)Convert.ToInt32(jumptToTab);
TempData["TabIndex"] = (int)gotoindex;
return RedirectToAction(GiveLinkToPage(gotoindex));
}
// continue normally
// Find which command was selected (non-null parameter)
var selection = (new[] { previous, next, finish })
.Select((item, index) => new { ItemName = item, Position = index })
.First(x => x.ItemName != null);
TabIndex currentTab = TabIndex.SeverityScores;
LinkDirection command = LinkDirection.Finish;
if (selection.Position == 0) { command = LinkDirection.Previous; }
if (selection.Position == 1) { command = LinkDirection.Next; }
if (selection.Position == 2) { command = LinkDirection.Finish; }
TempData.Keep("TabIndex");
TempData["TabIndex"] = this.GiveFutureTabIndex(command, currentTab);
string link = this.GiveFutureLink(command, currentTab);
return RedirectToAction(link);
}
return View(outcomeModel);
}
But, in outcomeModel, in Repair property, in debugger I always see the previous value of the DropDown, not that value which is chosen. I cannot find the reason why. So, I decided to set the value of the DropDown by force of in the JavaScript OnChange event of the DropDown:
<script>
function RepairDropDown_OnChange(e) {
console.log('RepairDropDown_OnChange');
console.log('Model ' + e.model);
console.log('Container ' + e.container.find('#Repair').length);
e.model.set("Repair", e.container.find('#Repair').val());
}
</script>
But, in Console of the Browser I see that e.model is undefined. How can I solve the bug? Thank you in advance for any help.
UPDATE
OutcomeModel is :
public class OutcomeModel : RunModelBase
{
#region Construction
public OutcomeModel() { }
public OutcomeModel(Run run)
{
if (Mapper.FindTypeMapFor<DateTimeOffset, DateTime>() == null)
{
Mapper.CreateMap<DateTimeOffset, DateTime>().ConvertUsing<DateTimeOffsetConverter>();
}
if (Mapper.FindTypeMapFor<Run, OutcomeModel>() == null)
{
Mapper.CreateMap<Run, OutcomeModel>()
.ForMember(dest => dest.UniqueId, opt => opt.MapFrom(src => src.Patient.UniqueId))
.ForMember(dest => dest.Birthdate, opt => opt.MapFrom(src => src.Patient.Birthdate))
.ForMember(dest => dest.Sex, opt => opt.MapFrom(src => src.Patient.Sex))
.ForMember(dest => dest.Race, opt => opt.MapFrom(src => src.Patient.Race))
.IgnoreAllNonExisting();
Mapper.AssertConfigurationIsValid();
}
Mapper.Map(run, this);
}
#endregion Construction
#region Properties
public string OrganFailureType { get; set; }
[Display(Name = "Discontinuation", Description = "DiscontinuationDescription", ResourceType = typeof(RunStrings))]
[UIHint("Enum")]
public Discontinuation? Discontinuation { get; set; }
[Display(Name = "OrganFailure", Description = "OrganFailureDescription", ResourceType = typeof(RunStrings))]
public OrganFailure OrganFailure { get; set; }
[Display(Name = "DischargedAlive", Description = "DischargedAliveDescription", ResourceType = typeof(RunStrings))]
public bool? DischargedAlive { get; set; }
[Display(Name = "DischargeLocation", Description = "DischargeLocationDescription", ResourceType = typeof(RunStrings))]
[UIHint("Enum")]
public DischargeLocation? DischargeLocation { get; set; }
[Display(Name = "ExtubationDate", Description = "ExtubationDateDescription", ResourceType = typeof(RunStrings))]
[DisplayFormat(DataFormatString = "{0:f}")]
[CompareValues("IntubationDate", CompareValues.GreaterThanOrEqualTo, ErrorMessageResourceName = "ExtubationDateError", ErrorMessageResourceType = typeof(RunStrings))]
[CompareValues("AdmitDate", CompareValues.GreaterThanOrEqualTo, ErrorMessageResourceName = "ExtubationDateError", ErrorMessageResourceType = typeof(RunStrings))]
public DateTime? ExtubationDate { get; set; }
[Display(Name = "DischargeDate", Description = "DischargeDateDescription", ResourceType = typeof(RunStrings))]
[DisplayFormat(DataFormatString = "{0:f}")]
[CompareValues("IntubationDate", CompareValues.GreaterThanOrEqualTo, ErrorMessageResourceName = "DischargeDateError", ErrorMessageResourceType = typeof(RunStrings))]
[CompareValues("AdmitDate", CompareValues.GreaterThanOrEqualTo, ErrorMessageResourceName = "DischargeDateError", ErrorMessageResourceType = typeof(RunStrings))]
public DateTime? DischargeDate { get; set; }
[Display(Name = "DeathDate", Description = "DeathDateDescription", ResourceType = typeof(RunStrings))]
[DisplayFormat(DataFormatString = "{0:f}")]
[CompareValues("IntubationDate", CompareValues.GreaterThanOrEqualTo, ErrorMessageResourceName = "DeathDateError", ErrorMessageResourceType = typeof(RunStrings))]
[CompareValues("AdmitDate", CompareValues.GreaterThanOrEqualTo, ErrorMessageResourceName = "DeathDateError", ErrorMessageResourceType = typeof(RunStrings))]
public DateTime? DeathDate { get; set; }
[Display(Name = "Repair", Description = "RepairDescription", ResourceType = typeof(RunStrings))]
public short? Repair { get; set; }
// Following properties are in model for validation, but are not copied/persisted
public DateTime? AdmitDate { get; set; }
public DateTime? IntubationDate { get; set; }
#endregion Properties
UPDATE2
myModel is:
ELSORegistry.DataAccess.Run myModel = Session["run"] as ELSORegistry.DataAccess.Run;

SQLite database not working in Android 4.4

I am using SQLite database for my PhoneGap project.The database is getting populated on every other OS I have tested except Android 4.4.0+ .
The Code for accessing database is below :-
public class MathWhiz extends CordovaActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init();
super.loadUrl(Config.getStartUrl());
SharedPreferences sp = getSharedPreferences("MYPREFS",
Activity.MODE_PRIVATE);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
// If no shared prefs exist, e.g. first install, it doesn't matter - the
// following will return false as a default
Boolean database_copied = sp.getBoolean("database_copied", false);
if (!database_copied) {
try {
String pName = this.getClass().getPackage().getName();
this.copy("Databases.db", "/data/data/" + pName
+ "/app_database/");
this.copy("sample.db", "/data/data/" + pName
+ "/app_database/myFile/");
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("database_copied", true);
editor.apply();
} catch (IOException e) {
e.printStackTrace();
}
}
}
void copy(String file, String folder) throws IOException {
File CheckDirectory;
CheckDirectory = new File(folder);
if (!CheckDirectory.exists()) {
CheckDirectory.mkdir();
}
InputStream in = getApplicationContext().getAssets().open(file);
OutputStream out = new FileOutputStream(folder + file);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
out.write(buf, 0, len);
in.close();
out.close();
}
}
And this is how I am using the database :-
window.openDatabase("sampleDB", "1.0", "sample", 200000);
Can anybody please point out what updates I need to do in order to make it work on Android 4.4 + ? Thanks
try it.. its working well...
public boolean copyDataBaseFromAssets(Context c) throws IOException {
if(android.os.Build.VERSION.SDK_INT >= 17)
DB_PATH = context.getApplicationInfo().dataDir + "/databases/"+ DATABASE_NAME;
else
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/"+DATABASE_NAME;
String pathToDatabaseFileInAssetFolder = DATABASE_NAME;
String pathToDatabaseFileInSystem = DB_PATH;
this.getReadableDatabase();
> getReadableDatabase funcation used in db import code
AssetManager assetManager = c.getResources().getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open(pathToDatabaseFileInAssetFolder);
} catch (IOException ex) {
return false;
}
if (inputStream != null) {
OutputStream outputStream = new FileOutputStream(pathToDatabaseFileInSystem);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
Log.d(TAG, "Database is copied");
return true;
}
return false;
}
Change this
this.copy("Databases.db", "/data/data/" + pName + "/databases/");
this.copy("sample.db", "/data/data/" + pName + "/databases/");

Categories