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>
Related
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;
}
}
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 need to display a table with the help of Json but i am getting error.
A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'
Index.cshtml
var table = $('#maintable').DataTable({
"ajax": {
"type": "POST",
"url": '#Url.Action("BindDatatable", "Sales")',
"data": { itemtyyID: $("#ddl_item").val(), itloccid: $("#getlocation").val() },
//"contentType": application/json,
"traditional": true,
"datatype": "json",
"dataSrc": function (json) {
//Make your callback here.
alert("Done!");
// var x = JSON.parse(json);
// return x;
return json.data;
}
},
"columns": [
{ "data": "Item", "autowidth": true },
{ "data": "qty", "autowidth": true },
{ "data": "rate", "autowidth": true },
{ "data": "ppb", "autowidth": true, "visible": false }
],
select: true
});
SalesController.cs
[HttpPost]
public JsonResult BindDatatable(string itemtyyID, string itloccid)
{
Int32 itemtyyIDD, itloccIDD;
DataSet ds = new DataSet();
if (!string.IsNullOrEmpty(itemtyyID) && !string.IsNullOrEmpty(itloccid))
{
itemtyyIDD = Convert.ToInt32(itemtyyID);
itloccIDD = Convert.ToInt32(itloccid);
}
else
{
itemtyyIDD = 0;
itloccIDD = 0;
}
DataTable dt = new DataTable();
OracleCommand cmdsp = new OracleCommand();
cmdsp.CommandType = System.Data.CommandType.StoredProcedure;
cmdsp.CommandText = "Pkg_Inventory.Prc_sale_stock";
cmdsp.Parameters.Add("ITEMYYID", OracleType.Int32, 25).Value = itemtyyIDD;
cmdsp.Parameters.Add("ITLOCID", OracleType.Int32, 25).Value = itloccIDD;
cmdsp.Parameters.Add("SALESTOCK", OracleType.Cursor).Direction = ParameterDirection.Output;
cmdsp.Parameters.Add("Pmsg", OracleType.VarChar, 10).Direction = ParameterDirection.Output;
dt = MyContext.FillDataTable(cmdsp);
List<justatest.Models.SalesModel.Sales> details = new List<justatest.Models.SalesModel.Sales>();
if (cmdsp.Parameters["Pmsg"].Value.ToString() == "T")
{
foreach (DataRow dtrow in dt.Rows)
{
justatest.Models.SalesModel.Sales user = new justatest.Models.SalesModel.Sales();
user.Item = dtrow["item"].ToString();
user.qty = dtrow["quan"].ToString();
user.rate = dtrow["rate"].ToString();
user.ppb = dtrow["price_bag"].ToString();
details.Add(user);
}
}
var data = details.ToArray();
return Json(new { data = data}, JsonRequestBehavior.AllowGet);
}
Model(Sales.cs)
public class Sales
{
public Sales() { }
public string Item { get; set; }
public string Loc { get; set; }
public Int64 ID { get; set; }
public Int64 SALES_R_ID { get; set; }
public Int64 car_IDD { get; set; }
public Int64 driver_IDD { get; set; }
public Int64 labor_IDD { get; set; }
public string qty { get; set; }
public Int64 t_qty { get; set; }
public Int64 ship_qty { get; set; }
public string rate { get; set; }
public string ppb { get; set; }
public string inv_lock_id { get; set; }
public string Nameofcustomer { get; set; }
public string Descrip { get; set; }
public DateTime Date { get; set; }
public Int32 InvoiceID { get; set; }
public Int32 TotAmount { get; set; }
public Int32 Disc { get; set; }
public Int32 GTotal { get; set; }
public Int32 Customer_Presence { get; set; }
public Int32 paid { get; set; }
public Int32 pay_amt { get; set; }
public Int32 ship { get; set; }
public Int32 shipamt { get; set; }
public Int32 trips_no { get; set; }
public Int32 bags_no { get; set; }
[Required(ErrorMessage = "Customer Name is Required")]
public string Customer_Name { get; set; }
[MaxLength(7)]
[MinLength(1)]
[RegularExpression("^[0-9]*$", ErrorMessage = "Loan must be numeric")]
public string LoanAmount { get; set; }
[MaxLength(7)]
[MinLength(1)]
[RegularExpression("^[0-9]*$", ErrorMessage = "Loan must be numeric")]
public string ReceivedLoan { get; set; }
public DataTable GetItems()
{
//this.Address = "N/A";
DataTable dt = new DataTable();
OracleCommand CmdCommand = new OracleCommand();
CmdCommand.CommandType = System.Data.CommandType.StoredProcedure;
CmdCommand.CommandText = "Pkg_Inventory.PRC_Shop_Sale_Stock";
CmdCommand.Parameters.Add("SHOPSALE", OracleType.Cursor).Direction = ParameterDirection.Output;
CmdCommand.Parameters.Add("PMSG", OracleType.VarChar, 10).Direction = ParameterDirection.Output;
dt = MyContext.FillDataTable(CmdCommand);
return dt;
}
//For Item List
public System.Web.Mvc.SelectList DT1SelectList(DataTable de, string valueField, string textField, object selectedvalue)
{
if (de == null || valueField == null || valueField.Trim().Length == 0
|| textField == null || textField.Trim().Length == 0)
return null;
var list = new List<Object>();
for (int i = 0; i < de.Rows.Count; i++)
{
list.Add(new
{
value = de.Rows[i][valueField].ToString(),
text = de.Rows[i][textField].ToString()
});
}
return new System.Web.Mvc.SelectList(list.AsEnumerable(), "value", "text", selectedvalue);
}
//For Car
public System.Web.Mvc.SelectList DT2SelectList(DataTable de, string valueField, string textField, object selectedvalue)
{
if (de == null || valueField == null || valueField.Trim().Length == 0
|| textField == null || textField.Trim().Length == 0)
return null;
var list = new List<Object>();
for (int i = 0; i < de.Rows.Count; i++)
{
list.Add(new
{
value = de.Rows[i][valueField].ToString(),
text = de.Rows[i][textField].ToString()
});
}
return new System.Web.Mvc.SelectList(list.AsEnumerable(), "value", "text", selectedvalue);
}
//For Driver
public System.Web.Mvc.SelectList DT3SelectList(DataTable de, string valueField, string textField, object selectedvalue)
{
if (de == null || valueField == null || valueField.Trim().Length == 0
|| textField == null || textField.Trim().Length == 0)
return null;
var list = new List<Object>();
for (int i = 0; i < de.Rows.Count; i++)
{
list.Add(new
{
value = de.Rows[i][valueField].ToString(),
text = de.Rows[i][textField].ToString()
});
}
return new System.Web.Mvc.SelectList(list.AsEnumerable(), "value", "text", selectedvalue);
}
//For Labor
public System.Web.Mvc.SelectList DT4SelectList(DataTable de, string valueField, string textField, object selectedvalue)
{
if (de == null || valueField == null || valueField.Trim().Length == 0
|| textField == null || textField.Trim().Length == 0)
return null;
var list = new List<Object>();
for (int i = 0; i < de.Rows.Count; i++)
{
list.Add(new
{
value = de.Rows[i][valueField].ToString(),
text = de.Rows[i][textField].ToString()
});
}
return new System.Web.Mvc.SelectList(list.AsEnumerable(), "value", "text", selectedvalue);
}
//For sales Invoice
public DataTable GetInvoice()
{
DataTable dt = new DataTable();
OracleCommand CmdCommand = new OracleCommand();
CmdCommand.CommandType = System.Data.CommandType.StoredProcedure;
CmdCommand.CommandText = "Pkg_Sales.Prc_Show_Invoice";
CmdCommand.Parameters.Add("SALES_REF_ID", OracleType.Int32, 25).Value = InvoiceID;
CmdCommand.Parameters.Add("SALECUR", OracleType.Cursor).Direction = ParameterDirection.Output;
CmdCommand.Parameters.Add("PMSG", OracleType.VarChar, 10).Direction = ParameterDirection.Output;
dt = MyContext.FillDataTable(CmdCommand);
return dt;
}
//For sales Details
public DataTable GetSaleDetails()
{
DataTable dt = new DataTable();
OracleCommand CmdCommand = new OracleCommand();
CmdCommand.CommandType = System.Data.CommandType.StoredProcedure;
CmdCommand.CommandText = "Pkg_Sales.Prc_Show_Sale_Details";
CmdCommand.Parameters.Add("SALES_REF_ID", OracleType.Int32, 25).Value = InvoiceID;
CmdCommand.Parameters.Add("SALECUR", OracleType.Cursor).Direction = ParameterDirection.Output;
CmdCommand.Parameters.Add("PMSG", OracleType.VarChar, 10).Direction = ParameterDirection.Output;
dt = MyContext.FillDataTable(CmdCommand);
return dt;
}
//For Item Details
public DataTable GetItemDetails()
{
DataTable dt = new DataTable();
OracleCommand CmdCommand = new OracleCommand();
CmdCommand.CommandType = System.Data.CommandType.StoredProcedure;
CmdCommand.CommandText = "Pkg_Sales.Prc_Show_Item_Details";
CmdCommand.Parameters.Add("SALES_REF_ID", OracleType.Int32, 25).Value = InvoiceID;
CmdCommand.Parameters.Add("SALECUR", OracleType.Cursor).Direction = ParameterDirection.Output;
CmdCommand.Parameters.Add("PMSG", OracleType.VarChar, 10).Direction = ParameterDirection.Output;
dt = MyContext.FillDataTable(CmdCommand);
return dt;
}
//For Item Shipment
public DataTable GetItemShipment()
{
DataTable dt = new DataTable();
OracleCommand CmdCommand = new OracleCommand();
CmdCommand.CommandType = System.Data.CommandType.StoredProcedure;
CmdCommand.CommandText = "Pkg_Sales.PRC_Ship_Details";
CmdCommand.Parameters.Add("SALE_R_ID", OracleType.Int32, 25).Value = InvoiceID;
CmdCommand.Parameters.Add("SHIPCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output;
CmdCommand.Parameters.Add("PMSG", OracleType.VarChar, 10).Direction = ParameterDirection.Output;
dt = MyContext.FillDataTable(CmdCommand);
return dt;
}
public DataTable SaleDetails
{
get { return GetSaleDetails(); }
}
public DataTable ItemDetails
{
get { return GetItemDetails(); }
}
public DataTable ItemShipment
{
get { return GetItemShipment(); }
}
public string JavascriptToRun { get; set; }
}
StackTrace
<!DOCTYPE html>
<html>
<head>
<title>A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'.</title>
<meta name="viewport" content="width=device-width" />
<style>
body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
.marker {font-weight: bold; color: black;text-decoration: none;}
.version {color: gray;}
.error {margin-bottom: 10px;}
.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
#media screen and (max-width: 639px) {
pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
}
#media screen and (max-width: 479px) {
pre { width: 280px; }
}
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/justatest' Application.<hr width=100% size=1 color=silver></H1>
<h2> <i>A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'.</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
<br><br>
<b> Exception Details: </b>System.InvalidOperationException: A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'.<br><br>
<b>Source Error:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code>
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code>
</td>
</tr>
</table>
<br>
<b>Stack Trace:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
[InvalidOperationException: A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'.]
System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +1767
System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +166
System.Web.Script.Serialization.JavaScriptSerializer.SerializeCustomObject(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +793
Circular references in your object hierarchy which is not supported by the JSON serializer.
You need to have something like:
return Json(new {
PropertyA = data.PropertyA,
PropertyB = data.PropertyB,
PropertyC = data.PropertyC,
}, JsonRequestBehavior.AllowGet);
I solve this question with code below
public async Task<JsonResult> GetAll(int id)
{
using (Context context = new Context())
{
var menus = context.GetAll(id);
List<MenuView> menusView = Mapper.Map<List<Menu>, List<MenuView>>(menus);
//Solve circular reference on JSONResult
var result = JsonConvert.SerializeObject(menusView, Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return Json(result, JsonRequestBehavior.AllowGet);
}
}
I Added this code in my Control, in the Client Side i used JSON.parse() for make object.
There are a lot of these types of questions, and looking at all of them, I'm not particularly sure what the difference is with my setup.
I've tried a few different variations of the ajax data and how to format the JSON, but this seems to get me the closest. I've done this quite a few times before, and I never ran into this issue.
When I hit the controller, modelDetails is a full object, and ScopeRecord is populated with data. However, each child array is empty -- including ProcedureFields, which isn't making sense. It's not null, but the count is 0.
Simplified js:
$("#submitButton")
.click(function() {
var result = {};
result.ScopeRecord = {};
result.ScopeRecord.ReferenceNumber = "testing123";
result.RoomFields = [];
result.BioFields = [];
result.ReprocessingFields = [];
result.CultureFields = [];
result.ProcedureFields = [];
var fieldInfo = {};
//examDate
fieldInfo.FieldID = 1;
fieldInfo.FieldValue = "test me";
fieldInfo.ItemHistoryID = 3;
fieldInfo.AssociationID = 2;
fieldInfo.IsModified = 1;
result.ProcedureFields.push(fieldInfo);
result.ProcedureFields.push(fieldInfo);
result.ProcedureFields.push(fieldInfo);
var options = {};
options.url = "/MyController/SaveDetails";
options.type = "POST";
options.traditional = true;
var test = JSON.stringify(result);
options.data = test;
options.contentType = "application/json; charset=UTF-8";
options.dataType = "json";
$.ajax(options);
});
My data on the request:
"{
"ScopeRecord":
{
"ReferenceNumber":"testing123"
},
"RoomFields":[],
"BioFields":[],
"ReprocessingFields":[],
"CultureFields":[],
"ProcedureFields":
[{
"FieldID":1,
"FieldValue":"test me",
"ItemHistoryID":3,
"AssociationID":2,
"IsModified":1
},
{
"FieldID":1,
"FieldValue":"test me",
"ItemHistoryID":3,
"AssociationID":2,
"IsModified":1
},
{
"FieldID":1,
"FieldValue":"test me",
"ItemHistoryID":3,
"AssociationID":2,
"IsModified":1
}]
}"
Controller:
[HttpPost]
public ActionResult SaveDetails(RecordDetails modelDetails)
{
....
}
Model:
public class RecordDetails
{
public ScopeRecord ScopeRecord { get; set; }
public List<FieldInfo> ProcedureFields = new List<FieldInfo>();
public List<FieldInfo> RoomFields = new List<FieldInfo>();
public List<FieldInfo> BioFields = new List<FieldInfo>();
public List<FieldInfo> ReprocessingFields = new List<FieldInfo>();
public List<FieldInfo> CultureFields = new List<FieldInfo>();
}
public class FieldInfo
{
public int ItemHistoryID { get; set; }
public int FieldID { get; set; }
public string FieldValue { get; set; }
public bool IsModified { get; set; }
public int? AssociationID { get; set; }
}
I've tried options.data = { modelDetails : JSON.stringify(result) }; but that gives me a 500 error.
What part am I missing?
The DefaultModelBinder cannot set the value of fields. You need to make your collections properties by adding a getter/setter
public class RecordDetails
{
public ScopeRecord ScopeRecord { get; set; }
public List<FieldInfo> ProcedureFields { get; set; }
public List<FieldInfo> RoomFields = { get; set; }
....
When I run this code repeated - except the first time, null pointer exception is thrown even though the file already exists.
static public class writeexcel {
public void write(){
try{
File f = new File("C:/Users/acer/Desktop/2.xls");
Workbook existingbook=null;
WritableWorkbook ww;
WritableSheet sr;
if(!f.exists()){
ww = Workbook.createWorkbook(f);
sr = ww.createSheet("mysheet", 0);
}else{
existingbook = Workbook.getWorkbook(f);
ww = Workbook.createWorkbook(f, existingbook);
sr = ww.getSheet("Mysheet");
}
Label lb = new Label(0, 0, " success");
Label lb1 = new Label (1,5,"new task");
sr.addCell(lb);
sr.addCell(lb1);
ww.write();
ww.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
writeexcel exl = new writeexcel() ;
exl.write();
}
}
Try beloe code, it will write "Success"in 100 cells and rows. you can then modify it as per your requirement.
public class Test {
public static void main(final String[] args) {
Test exl = new Test();
exl.write();
}
public void write() {
try {
File f = new File("fileLocation.xls");
Workbook existingbook = null;
WritableWorkbook ww;
WritableSheet sr;
if (!f.exists()) {
ww = Workbook.createWorkbook(f);
sr = ww.createSheet("mysheet", 0);
} else {
existingbook = Workbook.getWorkbook(f);
ww = Workbook.createWorkbook(f, existingbook);
sr = ww.getSheet("Mysheet");
}
for (int i = 0; i < 100; i++) {
for (int x = 0; x < 100; x++) {
Label lb1 = new Label(i + 1, x + 1, "new task");
// Label lb = new Label(i, x, " success");
// sr.addCell(lb);
sr.addCell(lb1);
}
}
ww.write();
ww.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}