AVG(COLUMN_SCORE) Not Getting Written To SQLite Database - javascript

I have created the following method to generate the average score for a series:
//Getting Series Averages From Game.COLUMN_SCORE
public String getSeriesAverage(String leagueId, String bowlerId)
{
String total = "";
Series series = new Series();
ContentValues values = new ContentValues();
SQLiteDatabase database = getWritableDatabase();
Cursor cursor = database.rawQuery("SELECT AVG(" + Game.COLUMN_SCORE + ") FROM " + Game.TABLE_NAME + " WHERE " + Game.COLUMN_LEAGUE_ID + " = '" + leagueId + "'" + " AND " + Game.COLUMN_BOWLER_ID + " = '" + bowlerId + "'" + " GROUP BY " + Game.COLUMN_SERIES_ID /*+ " = '" + seriesId + "'"*/, null);
if (cursor.moveToFirst()) {
do {
total = cursor.getString(0);
values.put(Series.COLUMN_SERIES_AVERAGE, total);
database.update(Series.TABLE_NAME, values, Series.COLUMN_ID + "=" + series.getId(), null);
Log.d("SERIES_AVERAGE - SQL","COLUMN_SERIES_AVERAGE = >>>>" + Series.COLUMN_SERIES_AVERAGE + "<<<<");
Log.d("TOTAL - CURSOR VALUE","Total = >>>>" + total + "<<<<");
} while (cursor.moveToNext());
values.put(Series.COLUMN_SERIES_AVERAGE, total);
database.update(Series.TABLE_NAME, values, Series.COLUMN_ID + "=" + series.getId(), null);
}
cursor.close();
//Close Database Connection
database.close();
//Log.d("GET AVERAGE FROM SQL","Average = >>>>" + total + "<<<<");
return total;
}
It seems to work and I can see the averages for each of the Series listed for an individual Bowler in Logcat:
07-26 14:50:15.158 25330-25330/ca.rvogl.tpbcui D/GETALLSERIES-SQL: SQL used = >>>>SELECT * FROM Series WHERE league_id = '1' AND bowler_id = '1' ORDER BY timestamp DESC<<<<
07-26 14:50:15.167 25330-25330/ca.rvogl.tpbcui D/GETALLSERIESS-CNT: Number of rows retrieved = 3
07-26 14:50:15.175 25330-25330/ca.rvogl.tpbcui D/SERIES_AVERAGE - SQL: COLUMN_SERIES_AVERAGE = >>>>average<<<<
07-26 14:50:15.175 25330-25330/ca.rvogl.tpbcui D/AVERAGE OF FIRST SERIES: Average = >>>>207<<<<
07-26 14:50:15.175 25330-25330/ca.rvogl.tpbcui D/SERIES_AVERAGE - SQL: COLUMN_SERIES_AVERAGE = >>>>average<<<<
07-26 14:50:15.175 25330-25330/ca.rvogl.tpbcui D/AVERAGE OF FIRST SERIES: Average = >>>>111<<<<
07-26 14:50:15.175 25330-25330/ca.rvogl.tpbcui D/SERIES_AVERAGE - SQL: COLUMN_SERIES_AVERAGE = >>>>average<<<<
07-26 14:50:15.175 25330-25330/ca.rvogl.tpbcui D/AVERAGE OF FIRST SERIES: Average = >>>>300<<<<
07-26 14:50:15.175 25330-25330/ca.rvogl.tpbcui D/SERIES_AVERAGE - SQL: COLUMN_SERIES_AVERAGE = >>>>average<<<<
07-26 14:50:15.175 25330-25330/ca.rvogl.tpbcui D/AVERAGE OF FIRST SERIES: Average = >>>>1<<<<
07-26 14:50:15.175 25330-25330/ca.rvogl.tpbcui D/AVERAGE OF SERIES: Average = >>>>1<<<<
07-26 14:50:15.177 25330-25330/ca.rvogl.tpbcui D/GETALLSERIES-CNT: Number of elements in serieslist = 3
However as you can also see from the logcat the value is not being written to the database as shown here:
07-26 14:50:15.175 25330-25330/ca.rvogl.tpbcui D/AVERAGE OF FIRST SERIES: Average = >>>>300<<<<
07-26 14:50:15.175 25330-25330/ca.rvogl.tpbcui D/SERIES_AVERAGE - SQL: COLUMN_SERIES_AVERAGE = >>>>average<<<<
It is actually only displaying the name of the variable from Series Class.
Can anyone help me get these values written to the database. I am not sure what I am doing incorrectly and any assistance would be appreciated. If you need to see any additional code please let me know I will post it.
Structure of Series Table:
// Create table SQL query
public static final String CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_LEAGUE_ID + " TEXT,"
+ COLUMN_BOWLER_ID + " TEXT,"
+ COLUMN_NAME + " TEXT,"
+ COLUMN_SERIES_AVERAGE + " TEXT,"
+ COLUMN_TIMESTAMP + " DATETIME DEFAULT CURRENT_TIMESTAMP"
+ ")";
public Series() {
}
public Series(int id, String league_id, String bowler_id, String name, String average, String timestamp) {
this.id = id;
this.league_id = league_id;
this.bowler_id = bowler_id;
this.name = name;
this.average = average;
this.timestamp = timestamp;
}
Logcat:
07-26 19:00:42.250 32441-32441/ca.rvogl.tpbcui D/GETALLSERIES-SQL: SQL used = >>>>SELECT * FROM Series WHERE league_id = '1' AND bowler_id = '1' ORDER BY timestamp DESC<<<<
07-26 19:00:42.263 32441-32441/ca.rvogl.tpbcui D/GETALLSERIESS-CNT: Number of rows retrieved = 2
07-26 19:00:42.279 32441-32441/ca.rvogl.tpbcui D/SERIES_AVERAGE - SQL: COLUMN_SERIES_AVERAGE = >>>>null<<<<
07-26 19:00:42.279 32441-32441/ca.rvogl.tpbcui D/TOTAL - CURSOR VALUE: Total = >>>>111<<<<
07-26 19:00:42.281 32441-32441/ca.rvogl.tpbcui D/SERIES_AVERAGE - SQL: COLUMN_SERIES_AVERAGE = >>>>null<<<<
07-26 19:00:42.281 32441-32441/ca.rvogl.tpbcui D/TOTAL - CURSOR VALUE: Total = >>>>300<<<<
07-26 19:00:42.286 32441-32441/ca.rvogl.tpbcui D/GETALLSERIES-CNT: Number of elements in serieslist = 2
SeriesActivity
public class SeriesActivity extends AppCompatActivity {
private SeriesAdapter mAdapter;
private final List<Series> seriesList = new ArrayList<>();
private TextView noSeriesView;
private DatabaseHelper db;
private TextView leagueId;
private String savedLeagueId;
private TextView bowlerId;
private String savedBowlerId;
private TextView seriesAverage;
private String savedSeriesAverage;
private static final String PREFS_NAME = "prefs";
private static final String PREF_BLUE_THEME = "blue_theme";
private static final String PREF_GREEN_THEME = "green_theme";
private static final String PREF_ORANGE_THEME = "purple_theme";
private static final String PREF_RED_THEME = "red_theme";
private static final String PREF_YELLOW_THEME = "yellow_theme";
#Override
protected void onCreate(Bundle savedInstanceState) {
//Use Chosen Theme
SharedPreferences preferences = getSharedPreferences( PREFS_NAME, MODE_PRIVATE );
boolean useBlueTheme = preferences.getBoolean( PREF_BLUE_THEME, false );
if (useBlueTheme) {
setTheme( R.style.AppTheme_Blue_NoActionBar );
}
boolean useGreenTheme = preferences.getBoolean( PREF_GREEN_THEME, false );
if (useGreenTheme) {
setTheme( R.style.AppTheme_Green_NoActionBar );
}
boolean useOrangeTheme = preferences.getBoolean( PREF_ORANGE_THEME, false );
if (useOrangeTheme) {
setTheme( R.style.AppTheme_Orange_NoActionBar );
}
boolean useRedTheme = preferences.getBoolean( PREF_RED_THEME, false );
if (useRedTheme) {
setTheme( R.style.AppTheme_Red_NoActionBar );
}
boolean useYellowTheme = preferences.getBoolean( PREF_YELLOW_THEME, false );
if (useYellowTheme) {
setTheme(R.style.AppTheme_Yellow_NoActionBar);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_series);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar( toolbar );
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String seriesLeagueId = String.valueOf( getIntent().getStringExtra( "seriesLeagueId" ) );
String seriesBowlerId = String.valueOf( getIntent().getIntExtra( "seriesBowlerId", 2 ) );
Intent intent=new Intent();
intent.putExtra("seriesLeagueId",seriesLeagueId);
intent.putExtra("seriesBowlerId",seriesBowlerId);
setResult(1,intent);
finish();//finishing activity
overridePendingTransition(0, 0);
}
/*#Override
public void onClick(View v) {
startActivity(new Intent(SeriesActivity.this, BowlerActivity.class));
finish();
}*/
});
savedLeagueId = String.valueOf( getIntent().getStringExtra( "seriesLeagueId" ) );
leagueId = (TextView) findViewById( R.id.tvLeagueId );
savedBowlerId = String.valueOf( getIntent().getIntExtra( "seriesBowlerId", 2 ) );
bowlerId = (TextView) findViewById( R.id.tvBowlerId );
seriesAverage = (TextView) findViewById(R.id.tvSeriesAverage);
CoordinatorLayout coordinatorLayout = findViewById( R.id.coordinator_layout );
RecyclerView recyclerView = findViewById( R.id.recycler_view );
noSeriesView = findViewById( R.id.empty_series_view );
db = new DatabaseHelper( this );
seriesList.addAll( db.getAllSeries( savedLeagueId, savedBowlerId) );
FloatingActionButton fab = (FloatingActionButton) findViewById( R.id.add_series_fab );
fab.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
showSeriesDialog( false, null, -1 );
}
} );
mAdapter = new SeriesAdapter( this, seriesList );
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager( getApplicationContext() );
recyclerView.setLayoutManager( mLayoutManager );
recyclerView.setItemAnimator( new DefaultItemAnimator() );
recyclerView.addItemDecoration( new MyDividerItemDecoration( this, LinearLayoutManager.VERTICAL, 16 ) );
recyclerView.setAdapter( mAdapter );
toggleEmptySeries();
//On Long Click On The RecyclerView Item An Alert Dialog Is Opened With The Option To Choose Edit/Delete
recyclerView.addOnItemTouchListener( new RecyclerTouchListener( this, recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, final int position) {
int seriesId = seriesList.get( position ).getId();
String seriesLeagueId = seriesList.get( position ).getLeagueId();
String seriesBowlerId = seriesList.get( position ).getBowlerId();
Intent myIntent = new Intent( SeriesActivity.this, GameActivity.class );
myIntent.putExtra( "gameLeagueId", seriesLeagueId );
myIntent.putExtra( "gameBowlerId", seriesBowlerId );
myIntent.putExtra( "gameSeriesId", seriesId );
startActivityForResult(myIntent, 1);
overridePendingTransition(0, 0);
}
#Override
public void onLongClick(View view, int position) {
showActionsDialog( position );
}
} ) );
}
//Inserting New Series In The Database And Refreshing The List
private void createSeries(String leagueId, String bowlerId, String series) {
//Inserting Series In The Database And Getting Newly Inserted Series Id
long id = db.insertSeries( leagueId, bowlerId, series );
//Get The Newly Inserted Series From The Database
Series n = db.getSeries( leagueId, bowlerId );
if (n != null) {
//Adding New Series To The Array List At Position 0
seriesList.add( 0, n );
//Refreshing The List
mAdapter.notifyDatasetChanged( db.getAllSeries( savedLeagueId, savedBowlerId ) );
toggleEmptySeries();
}
}
//Updating Series In The Database And Updating The Item In The List By Its Position
private void updateSeries(String name, int position) {
Series n = seriesList.get( position );
//Updating Series Text
n.setLeagueId( savedLeagueId );
n.setBowlerId( savedBowlerId );
n.setName( name );
//Updating The Series In The Database
db.updateSeries( n );
//Refreshing The List
seriesList.set( position, n );
//mAdapter.notifyItemChanged(position);
mAdapter.notifyDatasetChanged( db.getAllSeries( savedLeagueId, savedBowlerId ) );
toggleEmptySeries();
}
//Deleting Series From SQLite Database And Removing The Bowler Item From The List By Its Position
private void deleteSeries(int position) {
//Deleting The Series From The Database
db.deleteSeries( seriesList.get( position ) );
//Removing The Bowler From The List
seriesList.remove( position );
mAdapter.notifyItemRemoved( position );
toggleEmptySeries();
}
//Opens Dialog With Edit/Delete Options
//Edit - 0
//Delete - 0
private void showActionsDialog(final int position) {
CharSequence colors[] = new CharSequence[]{"Edit", "Delete"};
AlertDialog.Builder builder = new AlertDialog.Builder( this );
builder.setTitle( "Choose option" );
builder.setItems( colors, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
showSeriesDialog( true, seriesList.get( position ), position );
} else {
deleteSeries( position );
}
}
} );
builder.show();
}
//Show Alert Dialog With EditText Options to Enter/Edit A Series
//When shouldUpdate = true, It Will Automatically Display Old Series Name And Change The Button Text To UPDATE
private void showSeriesDialog(final boolean shouldUpdate, final Series series, final int position) {
LayoutInflater layoutInflaterAndroid = LayoutInflater.from( getApplicationContext() );
final View view = View.inflate( this, R.layout.dialog_series, null );
AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder( SeriesActivity.this );
alertDialogBuilderUserInput.setView( view );
final EditText inputSeries = view.findViewById( R.id.etSeriesNameInput );
leagueId.setText( savedLeagueId );
bowlerId.setText( savedBowlerId );
TextView dialogTitle = view.findViewById( R.id.dialog_title );
dialogTitle.setText( !shouldUpdate ? getString( R.string.lbl_new_series_title ) : getString( R.string.lbl_edit_series_title ) );
if (shouldUpdate && series != null) {
inputSeries.setText( series.getName() );
leagueId.setText( series.getLeagueId() );
bowlerId.setText( series.getBowlerId() );
}
alertDialogBuilderUserInput.setCancelable( false ).setPositiveButton( shouldUpdate ? "update" : "save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
}
} ).setNegativeButton( "cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
dialogBox.cancel();
}
} ) .setNeutralButton("use date",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
String dateNow = getDateNow();
inputSeries.setText(dateNow);
}
});
final AlertDialog alertDialog = alertDialogBuilderUserInput.create();
alertDialog.show();
alertDialog.getButton( AlertDialog.BUTTON_NEUTRAL ).setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
//Show Toast Message When No Text Is Entered
if (inputSeries.getText().toString() !=null || !inputSeries.getText().toString().isEmpty() ) {
String dateNow = getDateNow();
inputSeries.setText(dateNow);
return;
} else {
alertDialog.dismiss();
}
//Check If User Is Updating Series
if (shouldUpdate && series != null) {
//Updating Series By Its Id
updateSeries( inputSeries.getText().toString(), position );
} else {
//Creating New Series
createSeries( leagueId.getText().toString(), bowlerId.getText().toString(), inputSeries.getText().toString() );
}
}
} );
alertDialog.getButton( AlertDialog.BUTTON_POSITIVE ).setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
//Show Toast Message When No Text Is Entered
if (TextUtils.isEmpty( inputSeries.getText().toString() )) {
Toast.makeText( SeriesActivity.this, "Enter Series!", Toast.LENGTH_SHORT ).show();
return;
} else {
alertDialog.dismiss();
}
//Check If User Is Updating Series
if (shouldUpdate && series != null) {
//Updating Series By Its Id
updateSeries( inputSeries.getText().toString(), position );
} else {
//Creating New Series
createSeries( leagueId.getText().toString(), bowlerId.getText().toString(), inputSeries.getText().toString() );
}
}
} );
}
//Toggling List And Empty Series View
private void toggleEmptySeries() {
//You Can Check seriesList.size() > 0
if (db.getSeriesCount() > 0) {
noSeriesView.setVisibility( View.GONE );
} else {
noSeriesView.setVisibility( View.VISIBLE );
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate( R.menu.menu_main, menu );
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
overridePendingTransition(0, 0);
return true;
}
return super.onOptionsItemSelected( item );
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
//Check If Request Code Is The Same As What Is Passed - Here It Is 1
if(requestCode==1)
{
String savedLeagueId=data.getStringExtra("seriesLeagueId");
String savedBowlerId=data.getStringExtra("seriesBowlerId");
seriesList.addAll( db.getAllSeries( savedLeagueId, savedBowlerId ) );
}
}
private String getDateNow() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE. MMM. dd, yyyy", Locale.ENGLISH);
return sdf.format(cal.getTime());
}
#Override protected void onResume() {
super.onResume(); //seriesList.addAll( db.getAllSeries( savedLeagueId, savedBowlerId) );
}
}

In order for the values to be written in the db you must call:
values.put(Series.COLUMN_SERIES_AVERAGE, total);
update(table_name, values, "column_name=column_value", null)
table_name is the name of the table where you insert the values

Related

api layer, exchangerate // IOException : Server returned HTTP response code: 403 for URL

control.java
public class control {
public static void main(String[] args) {
boolean success = true;
String timestamp = "1659072666";
String base = "USD";
String date = "2022-07-29";
double GBP = 0.82011;
double JPY = 133.000499;
double EUR = 0.979105;
excJSON vwJson = new excJSON();
exc vw = vwJson.getexc(success, timestamp, base, date, GBP, JPY, EUR);
excDAO vwDao = new excDAO();
vwDao.intertexc(1, vw);
}
}
exc.java
public class exc {
String base;
String date;
String timestamp;
public String getbase() {
return base;
}
public void setbase(String base) {
this.base = base;
}
public String getdate() {
return date;
}
public void setdate(String date) {
this.date = date;
}
public String gettimestamp() {
return timestamp;
}
public void settimestamp(String timestamp) {
this.timestamp = timestamp;
}
}
excDAO.java
import java.sql.Statement;
import java.sql.Connection;
//import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
//import java.util.Enumeration;
public class excDAO {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/test?useSSL=false";
static final String USERNAME = "root"; // DB ID
static final String PASSWORD = "************"; // DB Password
private Connection conn = null;
private Statement stmt = null;
private ResultSet rs = null;
public void intertVillageWeather(int id, exc v) {
String query = "INSERT INTO exchangerate"
+ " VALUE(" + id +",'"+v.gettimestamp() + "','" + v.getbase() + "','" + v.getdate() + "');";
System.out.print("Your Database in : ");
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL,USERNAME,PASSWORD);
if (conn != null){System.out.println("good");}
else{System.out.println("bad");}
System.out.println(query);
stmt = conn.createStatement();
stmt.executeUpdate(query);
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
System.out.println("Class Not Found Exection");
} catch (SQLException e) {
System.out.println("SQL Exception : " + e.getMessage());
}
}
public void intertexc(int i, exc vw) {
}
}
excJSON.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
final static String apiKey = "tUxsDwwjT72GgMLoJRprXlqc34wmOzX4";
public exc getexc(boolean success, String timestamp, String base, String date, double GBP, double JPY, double EUR) {
String urlStr = "https://api.apilayer.com/exchangerates_data/latest?symbols=GBP%2CJPY%2CEUR&base=USD"
+ "&apiKey=" + apiKey + "&success=" + success + "&timestamp=" + timestamp
+ "&base="+ base + "&date=" + date + "&GBP=" + GBP + "&JPY=" + JPY + "&EUR=" + EUR + "&_type=json";
exc vl = new exc(); // 결과 데이터를 저장할 객체를 만듭니다.
try {
URL url = new URL(urlStr);
BufferedReader bf = new BufferedReader(new InputStreamReader(url.openStream()));
String line = "";
String result="";
while((line=bf.readLine())!=null){
result=result.concat(line);
}
//System.out.println(result);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObj = (JSONObject) jsonParser.parse(result);
JSONObject parse_response = (JSONObject) jsonObj.get("response");
JSONObject obj;
String category;
vl.timestamp = timestamp;
vl.base = base;
vl.date = date;
for(int i = 0; i < parse_response.size(); i++) {
obj = (JSONObject) parse_response.get(i);
category = (String)obj.get("category");
switch(category) {
case "timestamp":
vl.timestamp = (obj.get("fcstValue")).toString();
break;
case "base":
vl.base = (obj.get("fcstValue")).toString();
break;
case "date":
vl.date = (obj.get("fcstValue")).toString();
break;
}
}
} catch (MalformedURLException e) {
System.out.println("MalformedURLException : " + e.getMessage());
} catch (IOException e) {
System.out.println("IOException : " + e.getMessage());
} catch (ParseException e) {
System.out.println("ParseException : " + e.getMessage());
}
return vl;
}
}
*Help me please. I think error in excJSON.java. I want make exchangerate program.
I want fix error.
error code : IOException : Server returned HTTP response code: 403 for URL: https://api.apilayer.com/exchangerates_data/latest?symbols=GBP%2CJPY%2CEUR&base=USD&apiKey=tUxsDwwjT72GgMLoJRprXlqc34wmOzX4&success=true&timestamp=1659072666&base=USD&date=2022-07-29&GBP=0.82011&JPY=133.000499&EUR=0.979105&_type=json
I assess "https://api.apilayer.com/exchangerates_data/latest?symbols=GBP%2CJPY%2CEUR&base=USD&apiKey=tUxsDwwjT72GgMLoJRprXlqc34wmOzX4&success=true&timestamp=1659072666&base=USD&date=2022-07-29&GBP=0.82011&JPY=133.000499&EUR=0.979105&_type=json"
but http say {"message":"No API key found in request"}
but i surely receive apikey and api.*

javascript function can't find the element

I need to call some file uploader JavaScript from code behind. The JavaScript is basically customizing the style of the file uploader control. However, the JavaScript function can't find the element. I get this from the inspector:
*o = {element: null,
action: "/Web/UploadHandler.axd?UploadID=55f3930c-6aa9-4201…ccfdfae6c6&ObjectID=145649&RelationshipTypeID=223",
sizeLimit: 209715
when it should look like this:
o = {element: div#uploadContent, action: "/Web/UploadHandler.axd?UploadID=c1829b40-7869-4f19…411e7a542c&ObjectID=151808&RelationshipTypeID=223", sizeLimit: 20971520, acceptTypes: "image/*", onSubmit: ƒ, …}
qq.extend
This is the code:
div = new HtmlGenericControl("div") { ID = ("dlWrapper") };
Literal litScript = new Literal();
litScript.Mode = LiteralMode.PassThrough;
div.Controls.Add(litScript);
var imageUploader = (ImageUpload)CreateImageUploader(ActiveObject, p, litScript);
div.Controls.Add(imageUploader);
controls.Add(div);
private static Control CreateImageUploader(ObjectInstance objectInstance, PropertyType propertyType, Literal litScript)
{
ImageUpload imageUpload = new ImageUpload (objectInstance, litScript) { ID = ControlFactory.GetControlId(ControlFactory.IMAGE_PREFIX, ControlFactory.PROPERTY_TYPE_PREFIX, objectInstance.Id, propertyType.Id), Width = Unit.Pixel(80), Height = Unit.Pixel(30) };
PropertyInstanceValue piv = objectInstance.GetPropertyInstanceValue(propertyType.Id);
return imageUpload;
}
public class ImageUpload : FileUpload
{
public ObjectInstance ActiveObject {get; set; }
public Literal litScript { get; set; }
private string uploadID;
private string accept = "image/*";
public string UploadID
{
get
{
if (string.IsNullOrEmpty(uploadID))
{
uploadID = GetUploadID();
}
return uploadID;
}
set { uploadID = value; }
}
public ImageUpload(ObjectInstance activeObject, Literal literal)
{
ActiveObject = activeObject;
litScript = literal;
}
public string GetUploadID()
{
string uploadID;
if (HttpContext.Current.Session[EDM.Common.Definitions.SessionKey.UPLOAD_ID] != null)
{
uploadID = (string)HttpContext.Current.Session[EDM.Common.Definitions.SessionKey.UPLOAD_ID];
HttpContext.Current.Cache.Remove("cacheFlashSessionID_" + uploadID);
HttpContext.Current.Cache.Remove("cacheFlashAuth_" + uploadID);
}
uploadID = Guid.NewGuid().ToString();
HttpContext.Current.Session[EDM.Common.Definitions.SessionKey.UPLOAD_ID] = uploadID;
HttpContext.Current.Cache.Insert("cacheFlashSessionID_" + uploadID, HttpContext.Current.Session.SessionID, null, DateTime.Now.AddMinutes(20), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);
if (HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
// ReSharper disable PossibleNullReferenceException
HttpContext.Current.Cache.Insert("cacheFlashAuth_" + uploadID, HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value, null, DateTime.Now.AddMinutes(20), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);
// ReSharper restore PossibleNullReferenceException
}
return uploadID;
}
protected override void OnLoad(EventArgs e)
{
Literal litScript = new Literal();
ScriptManager scriptManager = ScriptManager.GetCurrent(Page);
StringBuilder sb = new StringBuilder();
sb.Append("<div id=\"uploadContent\"></div>");
litScript.Text = sb.ToString();
sb.Remove(0, sb.Length);
sb.Append("<script type=\"text/javascript\">");
int maxBytes = ProcessUnity.Common.Utility.GetMaxRequestLength() * 1024;
sb.Append("var uploader = new qq.FileUploader({ element: document.getElementById('uploadContent'), action: '" + Context.Request.ApplicationPath + "/UploadHandler.axd?UploadID=" + UploadID + "&ObjectID=" + ActiveObject.Id + "&RelationshipTypeID=" + EDM.Common.Definitions.RelationshipTypeId.IMAGE_FILE + "', sizeLimit: " + maxBytes + ", acceptTypes:'" + accept + "', onSubmit: uploadStart, onComplete: uploadComplete, onError: uploadError, multiple: false });");
sb.Append("</script>");
if (scriptManager != null)
{
ScriptManager.RegisterClientScriptBlock(this, typeof(ImageUpload), Guid.NewGuid().ToString(), sb.ToString(), false);
}
else
{
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), Guid.NewGuid().ToString(), sb.ToString());
}
base.OnLoad(e);
}
private object GetScriptManager()
{
foreach (DictionaryEntry entry in Page.Items)
{
if (entry.Key.ToString().IndexOf("System.Web.UI.ScriptManager") >= 0)
{
return entry.Value;
}
}
return null;
}
}
It looks like you're expecting litScript here:
Literal litScript = new Literal();
litScript.Mode = LiteralMode.PassThrough;
div.Controls.Add(litScript);
To be modified by the OnLoad event:
protected override void OnLoad(EventArgs e)
{
Literal litScript = new Literal();
// ...
StringBuilder sb = new StringBuilder();
sb.Append("<div id=\"uploadContent\"></div>");
litScript.Text = sb.ToString();
// ...
base.OnLoad(e);
}
But your OnLoad is constructing its own local Literal. Just because it has the same litScript name as the outer Literal doesn't mean that the two are related. In short, nothing is writing that div to the page.

Java Program TextFile Issue

I have a program where a text file is read in and then each word in the file is outputted, followed by the # of times it is repeated throughout the file.
Use the following code.
import java.io.*;
class FileRead {
public static void main(String args[]) {
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("C:\\Users\\Desktop\\formate.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println(strLine);
}
//Close the input stream
in.close();
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Try this code:
public static void main(String[] args) throws Throwable
{
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
Scanner scanner = new Scanner(inputFile);
HashMap<String, Integer> count = new HashMap<String, Integer>();
while (scanner.hasNext())
{
String word = scanner.next();
if (count.containsKey(word))
{
count.put(word, count.get(word) + 1);
}
else
{
count.put(word, 1);
}
}
scanner.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
for (Entry<String, Integer> entry : count.entrySet())
{
writer.write("#" + entry.getKey() + " " + entry.getValue()+"\r\n");
}
writer.close();
}
This also, it is a lot simpler if You can't use HashMap or BufferedReader:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Scanner;
public class WordCounter
{
public static void main(String[] args) throws Throwable
{
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
Scanner scanner = new Scanner(inputFile);
LinkedList<Word> words = new LinkedList<Word>();
while (scanner.hasNext())
{
String word = scanner.next();
addWord(words, word);
}
scanner.close();
WriteToFile(outputFile, words);
}
private static void WriteToFile(File outputFile, LinkedList<Word> words) throws IOException
{
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
for (Word word : words)
{
writer.write("#" + word.getWord() + " " + word.getCount() + "\r\n");
}
writer.close();
}
private static void addWord(LinkedList<Word> words, String word)
{
for (Word aWord : words)
{
if (aWord.getWord().equals(word))
{
aWord.incrementCount();
return;
}
}
words.add(new Word(word, 1));
}
}
class Word
{
private String word;
private int count;
public Word(String word, int count)
{
this.word = word;
this.count = count;
}
public String getWord()
{
return word;
}
public void setWord(String word)
{
this.word = word;
}
public int getCount()
{
return count;
}
public void setCount(int count)
{
this.count = count;
}
public void incrementCount()
{
count++;
}
#Override
public String toString()
{
return "Word: " + word + " Count: " + count;
}
}

Marker.remove() is not working in Google map?

In my application I have two set of marker when I click a marker another marker should be removed.But marker.remove() is not working, have checked whether the marker!=null then am removing the marker but the marker is not removed please help me.
public class MapFragment extends Fragment implements LocationListener
{
private static final String LOG_TAG = "ExampleApp";
private MapView mMapView;
private GoogleMap mMap;
private Bundle mBundle;
private static final String SERVICE_URL = "http://203.187.247.199/primevts/vtsservice.svc/data";
JSONObject json = null;
JSONObject jsonobject = null;
JSONObject jsonobject1 =null;
JSONObject jsonobject2 =null;
JSONObject ja = null;
JSONArray jsonarray = null;
JSONArray jsonarray1 = null;
JSONArray jsonarray2 = null;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist1;
ArrayList<HashMap<String, String>> arraylist11;
ArrayList<HashMap<String, String>> arraylist12;
ArrayList<HashMap<String, String>> arraylist;
List<Marker> markerList = new ArrayList<Marker>();
private Timer timer;
static String LONG = "Long";
static String LAT = "Lat";
ArrayList<String> ct;
public double latt = 0;
public double lng = 0;
public ArrayList<Integer> dLat;
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
private Handler handler;
public Marker marker;
Marker stop;
String RegistrationNo="";
LatLng destination,source,destination2,center;
Polyline polylin;
String ime1,destname,routeid;
GMapV2GetRouteDirection md;
private HashMap<String, Marker> mMarkers = new HashMap<>();
int value=1;
// LatLngBounds values ;
double latitude, longitude,destlat,destlong,sourcelat,sourcelong,destlat2,destlong2;
String ime,reg,regi;
Geocoder geocoder;
List<Address> addresses;
CircleOptions circleOptions;
Circle circle;
// LatLng val;
float[] distance = new float[2];
static HashMap<String, String> datas;
static HashMap<String, String> map;
String[] latlngvalues;
// LocationManager locman;
Context context;
View rootView;
ImageView imageView1;
TextView Address;
public MapFragment() {
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_layout_one, container, false);
MapsInitializer.initialize(getActivity());
mMapView = (MapView)rootView.findViewById(R.id.mapView);
Address=(TextView)rootView.findViewById(R.id.adressText);
//imageView1=(ImageView) rootView.findViewById(R.id.imageView1);
mMapView.onCreate(mBundle);
MapsInitializer.initialize(getActivity());
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
new DestinationJSON().execute();
mMap.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoContents(Marker marker) {
// TODO Auto-generated method stub
return null;
}
#Override
public View getInfoWindow(Marker marker) {
// TODO Auto-generated method stub
View v = getActivity().getLayoutInflater().inflate(R.layout.info_window_layout, null);
TextView markerLabel = (TextView)v.findViewById(R.id.ime);
TextView destiname=(TextView)v.findViewById(R.id.destname);
TextView route=(TextView)v.findViewById(R.id.routeid);
markerLabel.setText(regi);
destiname.setText(destname);
route.setText(routeid);
Log.e("imeid", ""+ime1);
return v;
}
});
/* handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
Log.e("Data in Log", "");
}
}, 1000);
*/
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
//mMap.clear();
//Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
}
});
}
};
timer.schedule(doAsynchronousTask, 20000, 20000);
/*LocationManager locman = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
//locman.requestLocationUpdates(minTime, minDistance, criteria, intent);
locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this);*/
return rootView;
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap();
mMap.setMyLocationEnabled(true);
Location myLocation = mMap.getMyLocation();
if (mMap != null) {
//mMap.clear();
mMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(final CameraPosition arg0) {
mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
LatLng latLng= mMap.getCameraPosition().target;
double lat = latLng.latitude;
double lng = latLng.longitude;
Log.e("lati",""+lat);
Log.e("longi",""+lng);
Log.d("TAG", latLng.toString());
//mMap.clear();
if(circle!=null){
circle.remove();
//mMap.clear();
}
circleOptions = new CircleOptions();
circleOptions.center(latLng);
//circleOptions.fillColor(Color.TRANSPARENT);
circleOptions.radius(10000);
circleOptions.strokeColor(Color.TRANSPARENT);
circle = mMap.addCircle(circleOptions);
Log.e("",""+circle);
center = mMap.getCameraPosition().target;
new GetLocationAsync(center.latitude, center.longitude).execute();
/* geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
addresses = geocoder.getFromLocation(lat, lng, 1);
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
Log.e("address",""+address);
String city = addresses.get(0).getLocality();
Log.e("city",""+city);
String state = addresses.get(0).getAdminArea();
Log.e("state",""+state);
String country = addresses.get(0).getCountryName();
Log.e("contry",""+country);
String postalCode = addresses.get(0).getPostalCode();
Log.e("postalcode",""+postalCode);
String knownName = addresses.get(0).getFeatureName();
Log.e("knownName",""+knownName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // Here 1 represent max location result to returned, by documents it recommended 1 to 5
//Toast.makeText(this, latLng.toString(), Toast.LENGTH_LONG).show();
}*/
}
});
}
});
mMap.setOnMarkerClickListener(new OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker arg0) {
// TODO Auto-generated method stub
if(stop!=null){
stop.remove();
}
arg0.showInfoWindow();
regi=arg0.getTitle().toString();
Log.e("aaa", ""+regi);
JSONPost jsonpost= new JSONPost();
ja=jsonpost.datewise(regi);
Log.e("Home_details..", "" + ja);
// new DownloadJSON2().execute();
try
{
arraylist11 = new ArrayList<HashMap<String, String>>();
arraylist12 = new ArrayList<HashMap<String, String>>();
jsonarray = ja.getJSONArray("Routeinbus");
for (int i = 0; i <jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
json = jsonarray.getJSONObject(i);
Log.e("G>>>>>>>>>>>", "" + json);
// Retrive JSON Objects
// map.put("flatID", jsonobject.getString("flatID"));
map.put("FromLat", json.getString("FromLat"));
map.put("FromLong", json.getString("FromLong"));
sourcelat = json.getDouble("FromLat");
sourcelong=json.getDouble("FromLong");
source=new LatLng(sourcelat, sourcelong);
map.put("Fromaddress", json.getString("Fromaddress"));
map.put("ToLat", json.getString("ToLat"));
map.put("ToLong", json.getString("ToLong"));
routeid=json.getString("RouteID");
destname=json.getString("Toaddress");
destlat2=json.getDouble("ToLat");
destlong2=json.getDouble("ToLong");
destination2=new LatLng(destlat2, destlong2);
jsonarray1 = json.getJSONArray("Routes");
Log.d("Hbbbbbbbbbbbbbbb", "" + jsonarray1);
for (int j = 0; j <jsonarray1.length(); j++) {
jsonobject1 = jsonarray1.getJSONObject(j);
jsonarray2=jsonobject1.getJSONArray("stages");
Log.d("jsonarray2", "" + jsonarray2);
for(int k=0;k<jsonarray2.length();k++)
{
jsonobject2 =jsonarray2.getJSONObject(k);
HashMap<String, String> map1 = new HashMap<String, String>();
map1.put("Lat",jsonobject2.getString("Lat"));
Log.d("Hbbbbbbbbbbbbbbb", "" + jsonobject2.getString("Lat"));
map1.put("Long",jsonobject2.getString("Long"));
map1.put("StopName", jsonobject2.getString("StopName"));
Log.d("Hbbbbbbbbbbbbbbb", "" + jsonobject2.getString("Long"));
// map1.put("LiveLongitude",jsonobject1.getString("LiveLongitude"));
// Log.d("Hbbbbbbbbbbbbbbb", "" + jsonobject1.getString("LiveLongitude"));
arraylist12.add(map1);
Log.e("arraylist12", ""+arraylist12);
//marker=mMap.addMarker(new MarkerOptions().position(destination2).icon(BitmapDescriptorFactory .fromResource(R.drawable.bustour)));
for (int m = 0; m < arraylist12.size(); m++)
{
final LatLng stopposition = new LatLng(Double .parseDouble(arraylist12.get(m).get("Lat")),Double.parseDouble(arraylist12.get(m).get("Long")));
Log.e("position", ""+stopposition);
String stopname = arraylist12.get(m).get("StopName");
Log.e("markcheck",""+stopname);
final MarkerOptions options = new MarkerOptions().position(stopposition);
//mMap.addMarker(options);
stop=mMap.addMarker(options.icon(BitmapDescriptorFactory .fromResource(R.drawable.bustour)).title(stopname));
}
}
}
arraylist11.add(map);
Log.e("arraylist11",""+arraylist11);
}
}catch (Exception e) {
String result = "Error";
}
return false;
}
});

Passing array from js to android

Hi I have this activity code:
public class WebActivity extends ActionBarActivity {
TextView number;
WebView mWebView;
CountDownTimer mTimer;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
number = (TextView) findViewById(R.id.number);
mTimer=new CountDownTimer(10000, 1000) {
String[] myArray={"javascript:document.getElementById(\"utente\").value=\""+LoginActivity.username+"\"; document.getElementById(\"j_password\").value=\""+LoginActivity.password+"\"; document.querySelector(\"input[type=submit]\").click();","javascript:document.getElementById(\"menu-servizialunno:_idJsp14\").click();"};
int currentIndex=0;
public void onTick(long millisUntilFinished) {
number.setText("seconds remaining: " + millisUntilFinished / 1000 + " " + (currentIndex + 1) + "/" + (myArray.length + 1));
}
//code comment start
// i think this part could be written better
// but it works!!
public void onFinish() {
if (currentIndex<myArray.length) {
number.setText("done!");
mWebView.loadUrl(myArray[currentIndex]);
currentIndex++;
mTimer.start();
} else{
mTimer.cancel();
}
}
//code comment end
};
mTimer.start();
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebSliderWebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(mWebView, url);
Toast.makeText(getApplicationContext(), "Done!", Toast.LENGTH_SHORT).show();
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
mWebView.loadUrl("http://www.ss16374.scuolanext.info");
}
and this js function:
function voti( showSubject, showData, showVote ){
var votitotali = []
document.getElementById("menu-servizialunno:_idJsp14").click();
setTimeout(function(){
elems = document.querySelectorAll("td, legend");
for(var i = 0; i < elems.length; i++){
curText = elems[i].innerHTML;
if( elems[i].tagName == "LEGEND" && showSubject ){
votitotali += [curText]
//console.log( curText );
}else if( elems[i].innerHTML.indexOf("Voto") != -1 && showVote ){
votitotali += [curText.replace(/.*\(([0-9\.]+)\)/,"$1")]
//console.log( curText.replace(/.*\(([0-9\.]+)\)/,"$1") );
}else if( /\d{2}\/\d{2}\/\d{4}/.test(elems[i].innerHTML) && showData ){
votitotali += [curText.replace(/.*(\d{2}\/\d{2}\/\d{4}).*/,"$1")]
//console.log( curText.replace(/.*(\d{2}\/\d{2}\/\d{4}).*/,"$1") );
}
}
document.getElementsByClassName("btl-modal-closeButton")[0].click()
},3000);
return votitotali
}
Can I store the votitotali array in my android app? Because I need to get some informations from a site and I have to print them on a textView in the app, but I really do not know how to do this using webview...
That's actually easy. You need to inject a Java object which has a method receiving an array:
class MyReceiver {
#JavascriptInterface
public void receive(String[] input) {
// input is your data!
}
}
// At the very beginning
mWebView.addJavascriptInterface(new MyReceiver(), "receiver");
// ...
Then if you call it like that in your JavaScript code:
receiver.receive(voti( ... ));
You will get the array inside MyReceiver.receive.
Note that non-string array elements (e.g. numbers) will not be converted into strings, and will be replaced by nulls instead.

Categories

Resources