Add a neutral button to androidx EditTextPrefence / DialogPreference - androidx

I have been using my own preference class derived from EditTextPreference to include a neutral button (so that the user can select a default value).
I did this by overriding onPrepareDialogBuilder (from searching stackoverflow of course.
)
override fun onPrepareDialogBuilder(builder: AlertDialog.Builder?) { //So can set have a button to set the default value
super.onPrepareDialogBuilder(builder)
builder?.setNeutralButton("Default") { dialogInterface: DialogInterface, i: Int ->
text = sharedPreferences.getString(dftKey, "")
}
}
However, this method does not seem possible with the androidx EditTextPreference.
Any suggestions on how to add a neutral button to androidx's EditTextPreference would be appreciated.

Having set up my settings activity as per
https://developer.android.com/guide/topics/ui/settings
I have found that I can add the PreferenceFragmentCompat.OnPreferenceDisplayDialogCallback
interface to the AppCompatActivity and override onPreferenceDisplayDialog to show my own dialog.
Edit 15/1/23
Someone wanted to know more about fun myPrefDialog, so I have added some more code. Hope it helps. It makes it rather lengthy and not "completely complete"
class MySettingsActivity: AppCompatActivity(), PreferenceFragmentCompat.OnPreferenceDisplayDialogCallback {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportFragmentManager
.beginTransaction()
.replace(android.R.id.content, MyPreferenceFragment())
.commit()
}
override fun onPreferenceDisplayDialog(caller: PreferenceFragmentCompat, pref: Preference?): Boolean {
var handeld = false
if(pref is MyEditTextPreference) {
myPrefDialog(caller, pref)
handled = true
}
return handled
}
}
open class TlEditTextPreference: EditTextPreference {
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context) : super(context)
protected var dlgOptions = 0
internal var origTitle = title.toString()
var valueBeforeEdit: String = ""
override fun onAttached() {
super.onAttached()
PrefUtils.chkSetPrefDefault(this)
//These lines are a debug warning
dialogTitle = "Don't use default dialog."
dialogMessage = "Override onPreferenceDisplayDialog in the preference activity\n"
" to call my own dialog"
positiveButtonText = "Hey stupid, read the warning above"
}
override fun setText(text: String?) {
super.setText(text)
updateTitle()
}
fun updateTitle() {
try {
title = "$origTitle [$text]"
} catch (e: Exception) {
e.printStackTrace()
}
}
open fun myPrefDialog(context: Context): Boolean {
valueBeforeEdit = text ?: ""
dlgOptions = dlgOptions or Misc.idoSTART_SELECTED or Misc.idoDONE_KEY
val dft = PrefUtils.chkSetPrefDefault(this)
Misc.inputDlg2(context, title.toString(), "(Default $dft)",valueBeforeEdit, "Cancel", "Default", "OK", dlgOptions)
{ editText, which ->
when(which) {
Misc.BTN_POS -> text = editText.text.toString()
Misc.BTN_NEUTRAL -> text = dft
}
}
return true
}
}
const val idoNONE = 0
const val idoNO_FULLSCREEN = 1
const val idoSTART_SELECTED = 2
const val idoDONE_KEY = 4
const val idoNUMERIC_KEYPAD = 8
const val idoFIRST_LETTER_LOWERCASE = 0x10
const val idoPASSWORD = 0x20
const val idoAll_CAPS = 0x40
class inputDlg2(context: Context, title: String, msg: String, text: String, btnNeg: String?, btnNeutral: String?,
btnPos: String?, options: Int = idoNONE, dialogCallback: (editText: EditText, which: Int) -> Unit){
val inflater = LayoutInflater.from(context)
// val rv = (context as Activity).window.decorView
val rootView: ViewGroup = (context as Activity).findViewById(android.R.id.content) as ViewGroup
val promptView = inflater.inflate(R.layout.input_box, rootView, false)
val db = AlertDialog.Builder(context)
var inputDlgEditText = promptView.findViewById(R.id.edittext) as EditText
val ocListener = DialogInterface.OnClickListener { dialog, which ->
lastInputDlgText = inputDlgEditText.text.toString()
dialogCallback(inputDlgEditText, which)
}
init {
inputDlgEditText.setText(text)
inputDlgEditText.setTextIsSelectable(true)
if (options and idoNUMERIC_KEYPAD != 0) {
// inputDlgEditText.inputType = InputType.TYPE_NUMBER_FLAG_DECIMAL
// inputDlgEditText.setRawInputType(Configuration.KEYBOARD_12KEY)
inputDlgEditText.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL or InputType.TYPE_NUMBER_FLAG_SIGNED
} else
inputDlgEditText.inputType = InputType.TYPE_TEXT_FLAG_CAP_SENTENCES or inputDlgEditText.inputType
if(options and idoPASSWORD != 0)
inputDlgEditText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
if (options and idoSTART_SELECTED != 0)
inputDlgEditText.setSelectAllOnFocus(true) //So that last current string will be selected and disapear if start typing
if(options and idoFIRST_LETTER_LOWERCASE != 0)
inputDlgEditText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
if(options and idoAll_CAPS != 0)
inputDlgEditText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS
if(options and idoPASSWORD != 0)
inputDlgEditText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
var editorInfoFlags = 0
if (options and idoNO_FULLSCREEN != 0) {
inputDlgEditText.isSingleLine = true //Added in API29
editorInfoFlags = editorInfoFlags or EditorInfo.IME_FLAG_NO_FULLSCREEN //to disable full screen editor
}
if (options and idoDONE_KEY != 0)
editorInfoFlags = editorInfoFlags or EditorInfo.IME_ACTION_DONE
inputDlgEditText.imeOptions = editorInfoFlags
val message = promptView.findViewById(R.id.inputPrompt) as TextView
message.text = msg
db.setView(promptView)
db.setTitle(title)
if (btnPos != null) db.setPositiveButton(btnPos, ocListener)
if (btnNeutral != null) db.setNeutralButton(btnNeutral, ocListener)
if (btnNeg != null) db.setNegativeButton(btnNeg, ocListener)
db.setIcon(android.R.drawable.ic_dialog_alert)
val dlg = db.create()
dlg.window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE) //Show the software keyboard immediately
val wmlp = dlg.window!!.attributes
wmlp.gravity = Gravity.TOP or Gravity.CENTER_HORIZONTAL
wmlp.x = 0 //x position
// wmlp.y = 100; //y position
inputDlgEditText.requestFocus()
dlg.show()
inputDlgEditText.setOnTouchListener { v, event ->
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(inputDlgEditText, 0)
false
}
if(options and idoDONE_KEY != 0) { //Callback when the done key pressed
inputDlgEditText.setOnEditorActionListener { textView: TextView?, action: Int, keyEvent: KeyEvent? ->
if (action == EditorInfo.IME_ACTION_DONE) {
dialogCallback(inputDlgEditText, Misc.BTN_POS)
dlg.dismiss()
}
false
}
}
}
}

Related

Xamarin forms: Issue with multiple events click on same day in XamForms.Controls.Calendar

I am using XamForms.Controls.Calendar for showing events on the calendar. I have give color for special dates on the calendar using the following code:
private void AddSpecialDateWithList(List<events> list)
{
List<SpecialDate> newList = new List<SpecialDate>();
foreach (events model in list)
{
if (string.IsNullOrWhiteSpace(model.end))
{
string date = model.start;
int index = date.IndexOf('T');
if (index > 0)
{
date = date.Substring(0, index);
}
var newDate = AddDate(DateTime.Parse(date), model);
newList.Add(newDate);
newEventsList.Add(model);
}
else
{
string startDate = model.start;
int startIndex = startDate.IndexOf('T');
if (startIndex > 0)
{
startDate = startDate.Substring(0, startIndex);
}
string endDate = model.end;
int endIndex = endDate.IndexOf('T');
if (endIndex > 0)
{
endDate = endDate.Substring(0, endIndex);
}
List<DateTime> dates = GetDatesBetween(DateTime.Parse(startDate), DateTime.Parse(endDate));
for (int i = 0; i < dates.Count; i++)
{
var newDate = AddDate(dates[i], model);
newList.Add(newDate);
newEventsList.Add(model);
}
}
}
calendar.SpecialDates = newList;
}
private SpecialDate AddDate(DateTime dateTime, events model)
{
SpecialDate newDate = new SpecialDate(dateTime)
{
Selectable = true,
BackgroundColor = Color.FromHex("#fec208"),
TextColor = Color.White
};
return newDate;
}
public List<DateTime> GetDatesBetween(DateTime startDate, DateTime endDate)
{
List<DateTime> allDates = new List<DateTime>();
for (DateTime date = startDate; date <= endDate; date = date.AddDays(1))
allDates.Add(date);
return allDates;
}
I have also enabled clicked event for special dates:
private async void calendar_DateClicked(object sender, DateTimeEventArgs e)
{
int num = 0;
var specialList = calendar.SpecialDates;
var date = e.DateTime;
selectedEventsList.Clear();
foreach (SpecialDate specialDate in specialList)
{
if (specialDate.Date.Year == date.Year && specialDate.Date.Month == date.Month && specialDate.Date.Day == date.Day)
{
events model = new events();
model = newEventsList[num];
selectedEventsList.Add(model);
}
else
{
num++;
}
}
if (selectedEventsList.Count == 1)
{
await DisplayAlert("Alert", "successs.", "Ok");
}
else
{
eventTitleList.Clear();
for (int j = 0; j < selectedEventsList.Count; j++)
{
eventTitleList.Add(selectedEventsList[j].title);
}
string action = await DisplayActionSheet(null, "Cancel", null, eventTitleList.ToArray());
for (int k = 0; k < eventTitleList.Count; k++)
{
if (action == eventTitleList[k])
{
//next page
}
}
}
}
When multiple events coming on the same day I need to show the events as a pop-up window. Then the user is able to select the event from the pop-up and go to the details page. I have implemented this on the above code, but sometimes duplicates events are showing on the pop-up window.
I have created a sample project for reproducing the issue. In the sample project, on 7May, the events are Chemistry Assignment and English Project. But Chemistry Assignment is showing duplicate. 10 may events are Chemistry Assignment and Physics, but showing Chemistry Assignment and English Project. I checked this lot of times, but didn't find the reason behind this.
The error caused by that the newEventsList do not get the correct index.
Change the code in calendar_DateClicked event from:
foreach (SpecialDate specialDate in specialList)
{
if (specialDate.Date.Year == date.Year && specialDate.Date.Month == date.Month && specialDate.Date.Day == date.Day)
{
events model = new events();
model = newEventsList[num];
selectedEventsList.Add(model);
}
else
{
num++;
}
}
To:
foreach (SpecialDate specialDate in specialList)
{
if (specialDate.Date.Year == date.Year && specialDate.Date.Month == date.Month && specialDate.Date.Day == date.Day)
{
events model = new events();
model = newEventsList[num];
selectedEventsList.Add(model);
}
num++;
}
Screenshot:

Set a high quality picture from camera in Kotlin inside a fragment

My problem is that I am getting an extremely low-quality picture from the camera when I display it on the imageView. The size of imageView is set to 250dpx250dp in the .xml.
Here is my code for capturing camera image:
class Category_Description : Fragment() {
var mBitmap: Bitmap? = null
private val ALL_PERMISSIONS_RESULT = 107
private val IMAGE_RESULT = 200
private val REQUEST_IMAGE_CAPTURE = 12345
var photo: Bitmap?=null
var resizedPhoto:Bitmap?=null
var imageUri: Uri?=null
var filePath:String?=null
var cursor:Cursor?=null
var reqFile:RequestBody?=null
var intermediate:String?=null
var outputFileUri: Uri? = null
var camera_FAB: FloatingActionButton? = null
var upload_FAB: FloatingActionButton? = null
var imageView:ImageView?= null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
// val permissions = arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE,
// android.Manifest.permission.CAMERA)
// requestPermissions( permissions,1)
val v = inflater.inflate(com.example.atry.R.layout.fragment_category__description, container, false)
camera_FAB = v.findViewById(com.example.atry.R.id.camera)
upload_FAB= v.findViewById(com.example.atry.R.id.upload)
imageView = v.findViewById<ImageView>(com.example.atry.R.id.display_image)
}
upload_FAB!!.setOnClickListener {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
// }
// }
pickImageFromGallery()
}
camera_FAB!!.setOnClickListener{
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
// intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri)
val frag = this
/** Pass your fragment reference **/
frag.startActivityForResult(
intent,
REQUEST_IMAGE_CAPTURE
) // REQUEST_IMAGE_CAPTURE = 12345
}
fun hasPermissionInManifest(context: Context, permissionName: String): Boolean {
val packageName = context.packageName
try {
val packageInfo = context.packageManager
.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)
val declaredPermisisons = packageInfo.requestedPermissions
if (declaredPermisisons != null && declaredPermisisons.size > 0) {
for (p in declaredPermisisons) {
if (p == permissionName) {
return true
}
}
}
} catch (e: PackageManager.NameNotFoundException) {
}
return false
}
private fun pickImageFromGallery() {
//Intent to pick image
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, IMAGE_PICK_CODE)
}
companion object {
//image pick code
private val IMAGE_PICK_CODE = 1000;
//Permission code
private val PERMISSION_CODE = 1001;
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK && data !=null) {
if (requestCode == REQUEST_IMAGE_CAPTURE){
val imageView = view!!.findViewById<ImageView>(R.id.display_image)
//FOR CAMERA CAPTURE
photo = data.getExtras()!!.get("data") as Bitmap
val uri = getImageUriFromBitmap(activity!!,photo!!)
filePath = getPathFromURI(uri)
Picasso.get().load(uri).into(imageView)
intermediate = activity!!.contentResolver.getType(uri)
} else if(requestCode== IMAGE_PICK_CODE) {
val imageView = view!!.findViewById<ImageView>(R.id.display_image)
// Get image URI From intent FOR UPLOADING
imageUri = data.data
intermediate = activity!!.contentResolver.getType(imageUri!!)
filePath = getImageFilePath(data)
if (filePath != null) {
mBitmap = BitmapFactory.decodeFile(filePath)
imageView.setImageBitmap(mBitmap)
cursor!!.close()
}
}
}
super.onActivityResult(requestCode, resultCode, data)
}
fun getImageFilePath(data: Intent): String {
return getImageFromFilePath(data)
}
private fun getImageFromFilePath(data: Intent?): String {
val isCamera = data == null || data.data == null
return if (isCamera)
getCaptureImageOutputUri()!!.path!!
else
getPathFromURI(data!!.data!!)
}
private fun getCaptureImageOutputUri(): Uri? {
val getImage = activity!!.getExternalFilesDir("")
if (getImage != null) {
outputFileUri = Uri.fromFile(File(getImage.path, "profile.png"))
}
return outputFileUri
}
private fun getImageUri(inContext: Context, inImage: Bitmap): Uri {
val bytes = ByteArrayOutputStream()
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
val path =
MediaStore.Images.Media.insertImage(inContext.contentResolver, inImage, "Title", null)
return Uri.parse(path)
}
fun getImageUriFromBitmap(activity: Activity, bitmap: Bitmap): Uri{
val bytes = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
val path = MediaStore.Images.Media.insertImage(activity.contentResolver, bitmap, "Title", null)
return Uri.parse(path.toString())
}
private fun getPathFromURI(contentUri: Uri): String {
val proj = arrayOf(MediaStore.Images.Media.DATA)
cursor = activity!!.contentResolver.query(contentUri, proj, null, null, null)
if(cursor!=null)
cursor!!.moveToFirst()
val column_index = cursor!!.getColumnIndex(proj[0])
return cursor!!.getString(column_index)
}
}

SignalR with paging using Groups

I am new to SignalR and in the learning process, I am trying to make Stock ticker. I have over 1000 stocks list and want to show paging and update on real-time changes that's why I am using Groups with SignalR. Problem is that when I open page 1 then everything works fine until I open page 2, then page 1 stop getting signals and page 2 start getting signals. What am I missing here in SignalR groups? Please help me, Thanks.
Hub
[HubName("stockTicker")]
public class StockTickerHub : Hub
{
private StockTicker _stockTicker;
public StockTickerHub()
: this(StockTicker.Instance)
{
}
public StockTickerHub(StockTicker stockTicker)
{
_stockTicker = stockTicker;
}
public void OpenMarket()
{
var page = this.Context.QueryString["page_no"];
int pageno = Convert.ToInt32(page);
_stockTicker.OpenMarket(pageno);
tryAddGroup(page);
}
public Task tryAddGroup(string page)
{
return Groups.Add(Context.ConnectionId, page);
}
}
StockTicker.cs
public class StockTicker
{
MainModel _model = new MainModel();
private static Lazy<StockTicker> _instance = new Lazy<StockTicker>(() => new StockTicker(GlobalHost.ConnectionManager.GetHubContext<StockTickerHub>().Clients));
private TimeSpan _updateInterval = TimeSpan.FromMilliseconds(3000);
private Timer _timer;
public volatile int pageno;
private StockTicker(IHubConnectionContext<dynamic> clients)
{
Clients = clients;
}
public static StockTicker Instance
{
get
{
return _instance.Value;
}
}
private IHubConnectionContext<dynamic> Clients
{
get;
set;
}
public void OpenMarket(int page_no)
{
pageno = page_no;
_timer = new Timer(UpdateStockPrices, pageno, _updateInterval, _updateInterval);
}
private void UpdateStockPrices(object state)
{
var latest_stocks = new List<StockViewModel>();
latest_stocks = _model.Get100Stocks(pageno);
foreach (var stock in latest_stocks)
{
BroadcastStockPrice(stock, pageno);
}
}
private void BroadcastStockPrice(StockViewModel stock, int pageno)
{
Clients.Group(pageno.ToString()).updateStockPrice(stock);
//Clients.All.updateStockPrice(stock);
}
}
(Updated Question)
StockTicker.js
if (!String.prototype.supplant) {
String.prototype.supplant = function (o) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};
}
jQuery.fn.flash = function (color, duration) {
var current = this.css('backgroundColor');
this.animate({ backgroundColor: 'rgb(' + color + ')' }, duration / 2)
.animate({ backgroundColor: current }, duration / 2);
};
$(function () {
var ticker = $.connection.stockTicker;
var $stockTable = $('#stockTable');
var $stockTableBody = $stockTable.find('tbody');
tdPrice = '<td data-rank-price="{currency_query}" data-sort="{currency_price_usd}"><div data-price-spn="{currency_query}">${currency_price_usd}</div></td>';
tdPercentage = '<td data-rank-perc="{currency_query}" data-sort="{currency_change_24h_usd}"><div data-change-spn="{currency_query}"><span class="{DirectionClass}">{currency_change_24h_usd}</span></div></td>';
tdVolume = '<td data-rank-volume="{currency_query}" data-sort="{currency_24h_volume_usd}"><div data-24-volume-spn="{currency_query}>${currency_24h_volume_usd}</div></td>';
tdMarketcap = '<td data-rank-cap="{currency_query}" data-sort="{currency_market_cap_usd}"><div data-mcap-spn="{currency_query}">${currency_market_cap_usd}</div></td>';
function formatStock(stock) {
return $.extend(stock, {
currency_price_usd: formatprices(stock.currency_price_usd),
currency_change_24h_usd: stock.currency_change_24h_usd == null ? '0.00%' : (stock.currency_change_24h_usd).toFixed(2) + '%',
currency_24h_volume_usd: stock.currency_24h_volume_usd == null ? '0' : nFormatter(stock.currency_24h_volume_usd, 2),
currency_market_cap_usd: stock.currency_market_cap_usd == null ? '0' : nFormatter(stock.currency_market_cap_usd, 2),
DirectionClass: stock.currency_change_24h_usd === 0 ? 'nochange' : stock.currency_change_24h_usd >= 0 ? 'green' : 'red'
});
}
function nFormatter(num, digits) {
var si = [
{ value: 1, symbol: "" },
{ value: 1E3, symbol: "K" },
{ value: 1E6, symbol: "M" },
{ value: 1E9, symbol: "B" },
{ value: 1E12, symbol: "T" },
{ value: 1E15, symbol: "P" },
{ value: 1E18, symbol: "E" }
];
var rx = /\.0+$|(\.[0-9]*[1-9])0+$/;
var i;
for (i = si.length - 1; i > 0; i--) {
if (num >= si[i].value) {
break;
}
}
return (num / si[i].value).toFixed(digits).replace(rx, "$1") + si[i].symbol;
}
function formatprices(n, curr) {
var sep = sep || ".";
var decimals;
if (n > 0.99999999) {
decimals = decimals || 2;
}
else {
decimals = decimals || 6;
}
return n.toLocaleString().split(sep)[0]
+ sep
+ n.toFixed(decimals).split(sep)[1];
}
$.extend(ticker.client, {
updateStockPrice: function (stock) {
var displayStock = formatStock(stock),
$tdprice = $(tdPrice.supplant(displayStock)),
$tdpercentage = $(tdPercentage.supplant(displayStock)),
$tdvolume = $(tdVolume.supplant(displayStock)),
$tdcap = $(tdMarketcap.supplant(displayStock));
if (stock.LastChange != 0.0) {
bgprice = stock.LastChange < 0.0
? '255,148,148'
: '154,240,117';
$stockTableBody.find('td[data-rank-price=' + stock.currency_query + ']').replaceWith($tdprice);
$tdpricespn = $stockTableBody.find('div[data-price-spn=' + stock.currency_query + ']');
$tdpricespn.flash(bgprice, 1500);
}
if (stock.LastChangePercentage != 0.0) {
bgper = stock.LastChangePercentage < 0.0
? '255,148,148'
: '154,240,117';
$stockTableBody.find('td[data-rank-perc=' + stock.currency_query + ']').replaceWith($tdpercentage);
$tdpercentagespn = $stockTableBody.find('div[data-change-spn=' + stock.currency_query + ']');
$tdpercentagespn.flash(bgper, 1500);
}
if (stock.LastChangeVolume != 0.0) {
bgvol = stock.LastChangeVolume < 0.0
? '255,148,148'
: '154,240,117';
$stockTableBody.find('td[data-rank-volume=' + stock.currency_query + ']').replaceWith($tdvolume);
$tdvolumespn = $stockTableBody.find('div[data-24-volume-spn=' + stock.currency_query + ']');
$tdvolumespn.flash(bgvol, 1500);
}
if (stock.LastChangeCap != 0.0) {
bgcap = stock.LastChangeCap < 0.0
? '255,148,148'
: '154,240,117';
$stockTableBody.find('td[data-rank-cap=' + stock.currency_query + ']').replaceWith($tdcap);
$tdcapspn = $stockTableBody.find('div[data-mcap-spn=' + stock.currency_query + ']');
$tdcapspn.flash(bgcap, 1500);
}
}
});
$.connection.hub.url = 'http://localhost:13429/signalr';
$.connection.hub.qs = { 'page_no': $("#page").val() };
$.connection.hub.start().done(function () {
console.log("connected");
}).then(function () {
return ticker.server.openMarket();
});
});
Looking at your code, your global variable pageno is always the last page that was requested:
public void OpenMarket(int page_no)
{
pageno = page_no;
_timer = new Timer(UpdateStockPrices, pageno, _updateInterval, _updateInterval);
}
You need another variable that tracks the max page.
public volatile int pageMax;
public void OpenMarket(int page_no)
{
pageno = page_no;
pageMax = pageno > pageMax
: pageno
? pageMax;
_timer = new Timer(UpdateStockPrices, pageno, _updateInterval, _updateInterval);
}
Then make sure to broadcast the correct stocks to the pages.

yalantis search filter in Fragment gets into background

I am using the Yalantis filter for android. I am having a Fragment rather than activity :
`class IncentiveActivity :Fragment() , FilterListener {
private var incentiveList = ArrayList<Incentive>()
var mAdapter: IncentiveListRecyclerAdapter? = null
val handler: Handler by lazy {
Handler()
}
private var mColors: IntArray? = null
private var mTitles: Array<String>? = null
private var mAllQuestions: List<Incentive>? = null
private var mFilter: Filter<FilterTag>? = null
val that :Context? = null
var fragment : View? =null
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
fragment = inflater!!.inflate(R.layout.activity_incentive_detail, container, false)
return fragment
}
override fun onStart() {
super.onStart()
setIncentiveAdapter()
mColors = getResources().getIntArray(R.array.colorslist);
mTitles = getResources().getStringArray(R.array.job_titles);
mFilter = this.filter as Filter<FilterTag>
mFilter!!.adapter =Adapter(getTags())
mFilter!!.listener = this
//the text to show when there's no selected items
mFilter!!.noSelectedItemText = getString(R.string.str_all_selected)
mFilter!!.build()
}
private fun getTags():List<FilterTag> {
val tags = ArrayList<FilterTag>()
for (i in 0..mTitles!!.size - 1) {
tags.add(FilterTag(mTitles!![i], mColors!![i]))
}
return tags
}
fun setIncentiveAdapter(){
//todo for salafi API call here and set adapter
val in1 = Incentive("Get 100p by completing 10","Description","D","Cash","100","ACTIVE",10,"id-vcxsdt","ACTIVE",8,6,9)
val in2 = Incentive("Get 100p by completing 10","Description","W","Cash","100","OPTED",10,"id-vcxsdt","OPTED",8,6,9)
val in3 = Incentive("Get 100p by completing 10","Description","Y","Cash","100","EXPIRED",10,"id-vcxsdt","EXPIRED",8,6,9)
val in4 = Incentive("Get 100p by completing 10","Description","Y","Cash","100","ACHIEVED",10,"id-vcxsdt","EXPIRED",8,6,9)
val in5 = Incentive("Get 100p by completing 10","Description","Y","Cash","100","NOT_OPTED",10,"id-vcxsdt","NOT_OPTED",8,6,9)
incentiveList.add(in1)
incentiveList.add(in2)
incentiveList.add(in3)
incentiveList.add(in4)
incentiveList.add(in5)
mAdapter = IncentiveListRecyclerAdapter(context, incentiveList)
incentiveListView.adapter = mAdapter
incentiveListView.layoutManager = LinearLayoutManager(context)
}
private fun calculateDiff(oldList: List<Incentive>, newList: List<Incentive >) {
DiffUtil.calculateDiff(object : DiffUtil.Callback() {
override fun getOldListSize(): Int {
return oldList.size
}
override fun getNewListSize(): Int {
return newList.size
}
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition].equals(newList[newItemPosition])
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition].equals(newList[newItemPosition])
}
}).dispatchUpdatesTo(mAdapter)
}
override fun onFilterDeselected(item: FilterTag) {
}
override fun onFilterSelected(item: FilterTag) {
Log.e("Item",item.getText())
if (item.getText().equals(mTitles!![0])) {
Log.e("mtitle",mTitles!![0])
mFilter!!.deselectAll();
mFilter!!.collapse();
}
}
/*private fun findByTags(tags: List<FilterTag>): List<Incentive> {
val questions = ArrayList<Incentive>()
for (question in mAllQuestions!!) {
for (tag in tags) {
if (question.hasTag(tag.getText()) && !questions.contains(question)) {
questions.add(question)
}
}
}
return questions
}*/
override fun onFiltersSelected(filters: java.util.ArrayList<FilterTag>) {
Log.e("filter",filters.size.toString())
/*val newQuestions = findByTags(filters)
val oldQuestions = mAdapter.getQuestions()
mAdapter.setQuestions(newQuestions)
calculateDiff(oldQuestions, newQuestions)*/
}
override fun onNothingSelected() {
if (this.incentiveListView != null) {
mFilter!!.adapter =Adapter(getTags())
incentiveListView.adapter = mAdapter
}
}
inner class Adapter(#NotNull items: List<FilterTag>) : FilterAdapter<FilterTag>(items) {
override fun createView(position: Int, item: FilterTag): FilterItem {
val filterItem = FilterItem(this#IncentiveActivity.activity)
filterItem.strokeColor = mColors!![0]
filterItem.textColor = mColors!![0]
filterItem.cornerRadius = 14f
filterItem.checkedTextColor = ContextCompat.getColor(this#IncentiveActivity.activity, android.R.color.white)
filterItem.color = ContextCompat.getColor(this#IncentiveActivity.activity, R.color.m_color2)
filterItem.checkedColor = mColors!![position]
filterItem.text = item.getText()
filterItem.deselect()
return filterItem
}
}
}`
i am facing problem when i expand the filter it comes in background of my list keeping my list visible .
this is my listView when i first open the fragment
this is the listview after i select the filter
also i am sorry if i have not provided all details and my question doesn't follow the SOF conditions thank you

maxRequestLength - behind the scene details needed!

What really happens to the currently executing request in IIS during a file upload, when the upload length exceed configured maxRequestLength.
Tried hard to find a decent article that talks about that, but there are none!!
Thanks
This is what exactly happens:
In class HttpRequest and in method GetEntireRawContent this condition is checked and will throw an exception:
if (length > maxRequestLengthBytes)
{
throw new HttpException(System.Web.SR.GetString("Max_request_length_exceeded"), null, 0xbbc);
}
Here is the whole of the method if you find useful:
private HttpRawUploadedContent GetEntireRawContent()
{
if (this._wr == null)
{
return null;
}
if (this._rawContent == null)
{
HttpRuntimeSection httpRuntime = RuntimeConfig.GetConfig(this._context).HttpRuntime;
int maxRequestLengthBytes = httpRuntime.MaxRequestLengthBytes;
if (this.ContentLength > maxRequestLengthBytes)
{
if (!(this._wr is IIS7WorkerRequest))
{
this.Response.CloseConnectionAfterError();
}
throw new HttpException(System.Web.SR.GetString("Max_request_length_exceeded"), null, 0xbbc);
}
int requestLengthDiskThresholdBytes = httpRuntime.RequestLengthDiskThresholdBytes;
HttpRawUploadedContent data = new HttpRawUploadedContent(requestLengthDiskThresholdBytes, this.ContentLength);
byte[] preloadedEntityBody = this._wr.GetPreloadedEntityBody();
if (preloadedEntityBody != null)
{
this._wr.UpdateRequestCounters(preloadedEntityBody.Length);
data.AddBytes(preloadedEntityBody, 0, preloadedEntityBody.Length);
}
if (!this._wr.IsEntireEntityBodyIsPreloaded())
{
int num3 = (this.ContentLength > 0) ? (this.ContentLength - data.Length) : 0x7fffffff;
HttpApplication applicationInstance = this._context.ApplicationInstance;
byte[] buffer = (applicationInstance != null) ? applicationInstance.EntityBuffer : new byte[0x2000];
int length = data.Length;
while (num3 > 0)
{
int size = buffer.Length;
if (size > num3)
{
size = num3;
}
int bytesIn = this._wr.ReadEntityBody(buffer, size);
if (bytesIn <= 0)
{
break;
}
this._wr.UpdateRequestCounters(bytesIn);
this.NeedToInsertEntityBody = true;
data.AddBytes(buffer, 0, bytesIn);
num3 -= bytesIn;
length += bytesIn;
if (length > maxRequestLengthBytes)
{
throw new HttpException(System.Web.SR.GetString("Max_request_length_exceeded"), null, 0xbbc);
}
}
}
data.DoneAddingBytes();
if ((this._installedFilter != null) && (data.Length > 0))
{
try
{
try
{
this._filterSource.SetContent(data);
HttpRawUploadedContent content2 = new HttpRawUploadedContent(requestLengthDiskThresholdBytes, data.Length);
HttpApplication application2 = this._context.ApplicationInstance;
byte[] buffer3 = (application2 != null) ? application2.EntityBuffer : new byte[0x2000];
while (true)
{
int num7 = this._installedFilter.Read(buffer3, 0, buffer3.Length);
if (num7 == 0)
{
break;
}
content2.AddBytes(buffer3, 0, num7);
}
content2.DoneAddingBytes();
data = content2;
}
finally
{
this._filterSource.SetContent(null);
}
}
catch
{
throw;
}
}
this._rawContent = data;
}
return this._rawContent;
}

Resources