Remember Me button in android app - javascript

I have recently created a new plugin for an android app I've been working on. This plugin requires the use of a remember me function that I cant seem to get working properly. Within my code I've designated the use of shared properties at the top and the string pass.
View thisScreensView = null;
String errormessage = "";
String errormessageTextColor = "";
String errormessageText = "";
String rememberTextText = "";
String rememberTextTextColor = "";
String voucherTextfieldPlaceholder = "";
String voucherTextfieldSecureTextEntry = "";
boolean voucherTextfieldSecureTextEntryBool = false;
String iphoneImage = "";
String ipadImage = "";
String errormessageInvalid = "";
String errormessageRemember = "";
private TextView errormessageTextView = null;
private EditText voucherTextfieldEditText = null;
private ImageView imageView = null;
private Button submitButton = null;
private Switch rememberSwitch = null;
private Drawable myHeaderImageDrawable = null;
private String alphaImage = "", pass;
private static BT_item screenObjectToLoad = null;
SharedPreferences sharedpreferences;
I have it assigning the variable pass into the designated text box with this code:
voucherTextfieldEditText.setVisibility(View.VISIBLE);
rememberSwitch = (Switch) thisScreensView.findViewById(R.id.rememberSwitch);
// set the switch to ON
rememberSwitch.setText(errormessageRemember);
rememberSwitch.setChecked(true);
// attach a listener to check for changes in state
rememberSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
BT_debugger.showIt(fragmentName + ":rememberSwitch is ON");
// switchStatus.setText("Switch is currently ON");
//voucherTextfieldEditText.setText(pref.getString(pass, null));
} else {
BT_debugger.showIt(fragmentName + ":rememberSwitch is OFF");
// switchStatus.setText("Switch is currently OFF");
}
}
});
// check the current state before we display the screen
if (rememberSwitch.isChecked()) {
BT_debugger.showIt(fragmentName + ":rememberSwitch is ON");
// switchStatus.setText("Switch is currently ON");
//voucherTextfieldEditText.setText(pass);
if (voucherTextfieldEditText!=null) {
//voucherTextfieldEditText.setText(sharedPreferences.getString(pass, ""));
}
if (pass != null) {
String textfield = sharedpreferences.getString("PASS", pass);
//voucherTextfieldEditText.setText(sharedPreferences.getString("PASS", pass));
voucherTextfieldEditText.setText(textfield);
}
}
else {
BT_debugger.showIt(fragmentName + ":rememberSwitch is OFF");
// switchStatus.setText("Switch is currently OFF");
}
//
// submit click listener..
submitButton = (Button) thisScreensView.findViewById(R.id.submitButtonVoucher);
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
launchScreen(voucherTextfieldEditText.getText().toString());
}
});
// return the layout file as the view for this screen..
return thisScreensView;
}// onCreateView...
Then I set the shared preferences string "PASS" with this line of code:
if (loadScreenNickname.length() > 1 && !loadScreenNickname.equalsIgnoreCase("none")) {
// before we launch the next screen...
if (!rememberSwitch.isChecked()) {
voucherTextfieldEditText.setText("");
}
if (rememberSwitch.isChecked()){
//voucherTextfieldEditText.setText("");
//editor.putString(pass, voucherTextfieldEditText.getText().toString().trim());
//editor.apply();
pass = voucherTextfieldEditText.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("PASS", pass);
editor.apply();
}
errormessageTextView.setVisibility(View.GONE);
errormessageTextView.invalidate();
//loadScreenObject(null, thisScreen);
try {
loadScreenWithNickname(loadScreenNickname);
foundIt = 1;
} catch (Exception ex){
Log.e ("eTutorPrism Error", "Caught this exception " + ex);
ex.printStackTrace();
}
break;
}
}
However anything I exit and restart the application, even if the remember me button is checked, it doesn't remember the previous value and the app ends up crashing due to a null. Everything else in the code works except the Remember Me. If anyones got any ideas I could use them?

You are not initializing your sharedPreference. try to initialize it.
SharedPreferences sharedPreferences=getSharedPreferences("myPref",MODE_PRIVATE);

Related

Loading Images from URL Is Producing Unexpected Results

I am loading images from Wikipedia into a Grid view. For the most part this is working correctly. Because there could possible be up to 200 or more images being loaded I am try to run it in a new thread. I see a definite delay when scrolling from my Album tab to the Artist tab that is loading the images. I am also see some lag as images are still getting load while scrolling up and down the list. Also when I scroll back to the top of the list place holders that previously occupied by the default image because I am unable to get an image from Wikipedia are now occupied by images from another artist.
When I scroll back to the song list and then back to the artist list the view is reset but it still has a lot of delay when going into the artist tab.
This image is what the screen looks like when first entering the Artist tab.
This image is what the screen looks like after scrolling to the bottom of the list and back to the top.
As you can see the <unknow. and AJR have had their default image replaced.
Here is my code that I am calling to load the images from Wikipedia.
#Override
public void onBindViewHolder(#NonNull ARV holder, int position) {
Artist artist = artistList.get(position);
if(artist!=null) {
holder.artistName.setText(artist.artistName);
String bandName = artist.artistName;
bandName = bandName.replace(' ','_');
try {
String imageUrl = cutImg(getUrlSource("https://en.wikipedia.org/w/api.php?action=query&titles="+bandName+"&prop=pageimages&format=json&pithumbsize=250"));
URL url = new URL(imageUrl);
ImageLoader.getInstance().displayImage(imageUrl, holder.artistImage,
new DisplayImageOptions.Builder().cacheInMemory(true).showImageOnLoading(R.drawable.album)
.resetViewBeforeLoading(true).build());
} catch (IOException e) {
e.printStackTrace();
}
/*ImageLoader.getInstance().displayImage(getCoverArtPath(context,artist.id),holder.artistImage,
new DisplayImageOptions.Builder().cacheInMemory(true).showImageOnLoading(R.drawable.album)
.resetViewBeforeLoading(false).build());*/
}
}
private StringBuilder getUrlSource(String site) throws IOException {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
URL localUrl = null;
localUrl = new URL(site);
URLConnection conn = localUrl.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line = "";
String html;
StringBuilder ma = new StringBuilder();
while ((line = reader.readLine()) != null) {
ma.append(line);
Log.i(ContentValues.TAG, "StringBuilder " + ma);
}
Log.i(ContentValues.TAG, "Final StringBuilder " + ma);
return ma;
}
public static String cutImg(StringBuilder split){
int start=split.indexOf("\"source\":")+new String("\"source\":\"").length();
split.delete(0, start);
split.delete(split.indexOf("\""), split.length());
Log.i(ContentValues.TAG, "StringBuilder " + split);
return split.toString();
}
Here is the code that is call the Artist Fragment.
public class ArtistFragment extends Fragment {
int spanCount = 3; // 2 columns
int spacing = 20; // 20px
boolean includeEdge = true;
private RecyclerView recyclerView;
private ArtistAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_artist, container, false);
recyclerView = view.findViewById(R.id.artistFragment);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
Thread t = new Thread()
{
public void run()
{
// put whatever code you want to run inside the thread here.
new LoadData().execute("");
}
};
t.start();
return view;
}
public class LoadData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
if(getActivity()!=null) {
adapter=new ArtistAdapter(getActivity(),new ArtistLoader().artistList(getActivity()));
}
return "Executed";
}
#Override
protected void onPostExecute(String s) {
recyclerView.setAdapter(adapter);
if(getActivity()!=null) {
recyclerView.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
}
I have also tried this using Picasso using the following code:
bandName = artist.artistName;
bandName = bandName.replace(' ','_');
try {
String imageUrl = cutImg(getUrlSource("https://en.wikipedia.org/w/api.php?action=query&titles="+bandName+"&prop=pageimages&format=json&pithumbsize=250"));
URL url = new URL(imageUrl);
Picasso.get().load(imageUrl).placeholder(R.drawable.album)
.error(R.drawable.artistdefault).into(holder.artistImage);
} catch (IOException e) {
e.printStackTrace();
}
The results are pretty much the same as when I used Android-Universal-Image-Loader. I have been try for several days to fix this, I have tried several different examples that I found on Stack overflow but none of them seem to resolve the issues I am seeing. I am hoping that someone will be able to identify what I am doing incorrectly.
Thanks in advance.
ArtistFragmentconverted to Kotlin
class ArtistFragment : Fragment() {
var spanCount = 3 // 2 columns
var spacing = 20 // 20px
var includeEdge = true
var retrofit: Retrofit? = null
var wikiService: WikiService? = null
var adapter: ArtistAdapter? = null
private var recyclerView: RecyclerView? = null
private var viewModelJob = Job()
private val viewModelScope = CoroutineScope(Dispatchers.Main + viewModelJob)
private var progress_view: ProgressBar? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_artist, container, false)
recyclerView = view.findViewById(R.id.artistFragment)
recyclerView?.setLayoutManager(GridLayoutManager(activity, 3))
progress_view = view.findViewById(R.id.progress_view)
initWikiService()
initList()
//LoadData().execute("")
return view
}
override fun onDestroy() {
super.onDestroy()
viewModelJob.cancel()
}
private fun initList() {
recyclerView!!.addItemDecoration(GridSpacingItemDecoration(spanCount, spacing, includeEdge))
adapter = ArtistAdapter(this)
adapter?.items = ArrayList()
adapter?.listener = this
recyclerView?.adapter = adapter
viewModelScope.launch {
progress_view.visibility = View.VISIBLE
val wikiPages = getWikiPages()
adapter?.items = wikiPages
progress_view?.visibility = View.GONE
}
}
private suspend fun getWikiPages(): ArrayList<Artist> {
val newItems = ArrayList<Artist>()
withContext(Dispatchers.IO) {
ArtistData.artists.map { artist ->
async { wikiService?.getWikiData(artist) }
}.awaitAll().forEach { response ->
val pages = response?.body()?.query?.pages
pages?.let {
for (page in pages) {
val value = page.value
val id = value.pageid?.toLong() ?: value.title.hashCode().toLong()
val title = value.title ?: "Unknown"
val url = value.thumbnail?.source
newItems.add(Artist(id, title, albumCount = 0, songCount = 0, artistUrl = url!!))
}
}
}
}
return newItems
}
private fun initWikiService() {
retrofit = Retrofit.Builder()
.baseUrl("https://en.wikipedia.org/")
.addConverterFactory(GsonConverterFactory.create())
.build()
wikiService = retrofit?.create(WikiService::class.java)
}
I believe I have resolved most of the issues I was previously seeing I am now down to the following problems:
Artist.item.map { artist -> - Not sure how this should be called, Unresolved reference: item
}.awaitAll().forEach { response -> = forEach is telling me Overload resolution ambiguity. All these functions match.
public inline fun Iterable<TypeVariable(T)>.forEach(action: (TypeVariable(T)) → Unit): Unit defined in kotlin.collections
public inline fun <K, V> Map<out TypeVariable(K), TypeVariable(V)>.forEach(action: (Map.Entry<TypeVariable(K), TypeVariable(V)>) → Unit): Unit defined in kotlin.collections
newItems.add(Artist(id, title, url)) - I know that the variables for the Artist Model need to go here, but when I put them there they are unresolved.
I have reworked the ArtistAdapter not sure if it is correct though.
class ArtistAdapter(private val context: ArtistFragment, private val artistList: List<Artist>?) : RecyclerView.Adapter<ArtistAdapter.ARV>() {
private var dimension: Int = 64
init {
val density = context.resources.displayMetrics.density
dimension = (density * 64).toInt()
hasStableIds()
}
var items: MutableList<Artist> = ArrayList()
set(value) {
field = value
notifyDataSetChanged()
}
var listener: Listener? = null
interface Listener {
fun onItemClicked(item: Artist)
abstract fun ArtistAdapter(context: ArtistFragment): ArtistAdapter
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ARV {
return ARV(LayoutInflater.from(parent.context).inflate(R.layout.artist_gride_item, parent,
false))
}
override fun onBindViewHolder(holder: ARV, position: Int) {
holder.onBind(getItem(position))
}
private fun getItem(position: Int): Artist = items[position]
override fun getItemId(position: Int): Long = items[position].id
override fun getItemCount(): Int {
return artistList?.size ?: 0
}
inner class ARV(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
private val artistNameView: TextView = itemView.findViewById(R.id.artistName)
private val artistAlbumArtView: SquareCellView = itemView.findViewById(R.id.artistAlbumArt)
fun onBind(item: Artist) {
artistNameView.text=item.artistName
if(item.artistURL!=null) {
Picasso.get()
.load(item.artistURL)
.resize(dimension, dimension)
.centerCrop()
.error(R.drawable.artistdefualt)
.into(artistAlbumArtView)
} else {
artistAlbumArtView.setImageResource(R.drawable.artistdefualt)
}
itemView.setOnClickListener(this)
}
override fun onClick(view: View) {
val artistId = artistList!![bindingAdapterPosition].id
val fragmentManager = (context as AppCompatActivity).supportFragmentManager
val transaction = fragmentManager.beginTransaction()
val fragment: Fragment
transaction.setCustomAnimations(R.anim.layout_fad_in, R.anim.layout_fad_out,
R.anim.layout_fad_in, R.anim.layout_fad_out)
fragment = ArtistDetailsFragment.newInstance(artistId)
transaction.hide(context.supportFragmentManager
.findFragmentById(R.id.main_container)!!)
transaction.add(R.id.main_container, fragment)
transaction.addToBackStack(null).commit()
}
}
}
Logcat Snippet
java.lang.NoSuchMethodError: No static method metafactory(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite; in class Ljava/lang/invoke/LambdaMetafactory; or it
s super classes (declaration of 'java.lang.invoke.LambdaMetafactory' appears in /apex/com.android.art/javalib/core-oj.jar)
at okhttp3.internal.Util.<clinit>(Util.java:87)
at okhttp3.internal.Util.skipLeadingAsciiWhitespace(Util.java:321)
at okhttp3.HttpUrl$Builder.parse(HttpUrl.java:1313)
at okhttp3.HttpUrl.get(HttpUrl.java:917)
at retrofit2.Retrofit$Builder.baseUrl(Retrofit.java:506)
at com.rvogl.androidaudioplayer.fragments.ArtistFragment.initWikiService(ArtistFragment.kt:103)
at com.rvogl.androidaudioplayer.fragments.ArtistFragment.onCreateView(ArtistFragment.kt:43)
It looks to me as a known bug with Picasso.
Try to load default image manually so it won't be replaced with cached one.
Update 14.10.20:
I think the main problem is that you load network content in adapter in rather ineffective way. I suggest to form a list of all urls at first, leaving only image load in adapter.
Also reccomend you to use rerofit2 for network calls and something for async work instead of AsyncTask: rxJava, courutines, flow etc.
I created a sample project to load data async using retrofit2+coroutines.
In activity:
private val viewModelScope = CoroutineScope(Dispatchers.Main)
private fun initWikiService() {
retrofit = Retrofit.Builder()
.baseUrl("https://en.wikipedia.org/")
.addConverterFactory(GsonConverterFactory.create())
.build()
wikiService = retrofit?.create(WikiService::class.java)
}
private fun initList() {
viewModelScope.launch {
val wikiPages = getWikiPages()
adapter?.items = wikiPages
}
}
private val viewModelScope = CoroutineScope(Dispatchers.Main + viewModelJob)
private suspend fun getWikiPages(): ArrayList<Item> {
val newItems = ArrayList<Item>()
withContext(IO) {
ArtistData.artists.map { artist ->
async { wikiService?.getWikiData(artist) }
}.awaitAll().forEach { response ->
val pages = response?.body()?.query?.pages
pages?.let {
for (page in pages) {
val value = page.value
val id = value.pageid?.toLong() ?: value.title.hashCode().toLong()
val title = value.title ?: "Unknown"
val url = value.thumbnail?.source
newItems.add(Item(id, title, url))
}
}
}
}
return newItems
}
In viewHolder:
fun onBind(item: Item) {
if (item.url != null) {
Picasso.get()
.load(item.url)
.resize(dimension, dimension)
.centerCrop()
.error(R.drawable.ic_baseline_broken_image_24)
.into(pictureView)
} else {
pictureView.setImageResource(R.drawable.ic_baseline_image_24)
}
}
In adapter: add hasStableIds() to constructor and override getItemId method:
init {
hasStableIds()
}
override fun getItemId(position: Int): Long = items[position].id
Retrofit Service:
interface WikiService {
#GET("/w/api.php?action=query&prop=pageimages&format=json&pithumbsize=250")
suspend fun getWikiData(#Query("titles") band: String): Response<WikipediaResponse?>
}

CefSharp Javascript registration and execution is not working in Release 79.1.36

I tried to upgrade CefSharp from Version 69.0.0.0 to 79.1.36.
I could not get the Javascript interaction working.
The registration changed from
this.Browser.RegisterJsObject
to
this.Browser.JavascriptObjectRepository.Register
according to https://github.com/cefsharp/CefSharp/issues/2990.
When I execute EvaluateScriptAsync, I get a response back with Status Canceled.
Trying to understand how to implement it correctly, I examined the CefSharp.WpfExample and noticed that the Javascript functionality in the example WPF application does not work either.
The Execute Javascript (asynchronously) does not do anything when clicking the Run button.
The Evaluate Javascript (Async) returns:
Uncaught ReferenceError: bound is not defined # about:blank:1:0
Did the Javascript functionality break in the latest release?
Update
Here is how it is used in our code.
This is the registration
public void RegisterJavaScriptHandler(string name, object handler)
{
try
{
CefSharpSettings.LegacyJavascriptBindingEnabled = true;
this.Browser.JavascriptObjectRepository.Register(name, handler, false, new BindingOptions() { CamelCaseJavascriptNames = false });
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
This is the EvaluateScriptAsync part
public void InitializeLayers()
{
try
{
int count = _mapLogic.Layers.Count();
foreach (WMSLayer layer in _mapLogic.Layers)
{
if (!_loadedLayers.Contains(layer))
{
var script = string.Format("addWMSLayer('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}')",
layer.ProviderCode.Url, layer.AttributionText, layer.AttributionHref,
layer.Layer, layer.FormatCode.Format, layer.ServerType, layer.Res1, layer.Res2, layer.Res3, layer.Res4);
var response = this.ECBBrowser.Browser.EvaluateScriptAsync(script, new TimeSpan(0, 0, 1));
response.ContinueWith(t =>
{
count--;
if (count == 0) this.initializeMap();
});
_loadedLayers.Add(layer);
}
else
{
count--;
if(count == 0) this.initializeMap();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
Update II
I now believe something has changed with the resource loading.
This is what I have (unimportant parts are left out).
public class ECBSchemeHandler : IResourceHandler
{
private string _mimeType;
private Stream _stream;
public bool Open(IRequest request, out bool handleRequest, ICallback callback)
{
var result = open(request, callback);
handleRequest = result;
return result;
}
public bool Read(Stream dataOut, out int bytesRead, IResourceReadCallback callback)
{
return read(dataOut, out bytesRead, callback);
}
public bool ReadResponse(Stream dataOut, out int bytesRead, ICallback callback)
{
return read(dataOut, out bytesRead, callback);
}
private bool open(IRequest request, ICallback callback)
{
var u = new Uri(request.Url);
var file = u.Authority + u.AbsolutePath;
var ass = Assembly.GetExecutingAssembly();
var resourcePath = ECBConfiguration.DEFAULT_ASSEMBLY_NAMESPACE + "." + file.Replace("/", ".");
if (ass.GetManifestResourceInfo(resourcePath) != null)
{
Task.Run(() =>
{
using (callback)
{
_stream = ass.GetManifestResourceStream(resourcePath);
var fileExtension = Path.GetExtension(file);
_mimeType = ResourceHandler.GetMimeType(fileExtension);
callback.Continue();
}
});
return true;
}
else
{
callback.Dispose();
}
return false;
}
private bool read(Stream dataOut, out int bytesRead, IDisposable callback)
{
callback.Dispose();
if (_stream == null)
{
bytesRead = 0;
return false;
}
//Data out represents an underlying buffer (typically 32kb in size).
var buffer = new byte[dataOut.Length];
bytesRead = _stream.Read(buffer, 0, buffer.Length);
dataOut.Write(buffer, 0, buffer.Length);
return bytesRead > 0;
}
}
}
Using the built-in ResourceHandlers as pointed out by #amaitland solved the problem with the Javascript registration.

Comparing Selected DropDown with condition

i am creating a form which can be accessed based on condition in MVC. I have first view with dropdownlist and submit button, i want when the submit button is clicked, the value in dropdownlist is passed and compared with condition set for that value, and if the condition is not ok, it shows alert rather than processing to the form.
Here is my code:
public ActionResult ChooseType()
{
var x = DataAccess.GetEmployee(#User.Identity.Name);
var lists = new SelectList(RuleAccess.GetAllRule(), "ID", "TypeDetail");
ViewBag.CategoryId = lists;
/*rule*/
ViewBag.comp1 = Logic.AnnualToogle(#User.Identity.Name);
if (x.EmpSex == "F" && x.EmpMaritalSt == "NIKAH")
{ ViewBag.comp2 = 1; }
else ViewBag.comp2 = 0;
return View();
}
[HttpGet]
public ActionResult Create(int lv_type)
{
var type = RuleAccess.GetTypeByID(lv_type);
ViewBag.type = type;
var model = new LeaveApplicationViewModels();
model.X = DataAccess.GetEmployee(#User.Identity.Name);
model.C = DataAccess.GetLeaveApp(#User.Identity.Name);
/*disable*/
ViewBag.dis = DataAccess.GetDisabledDate(#User.Identity.Name);
/*max*/
var max= RuleAccess.GetMaxByID(lv_type);
ViewBag.c = max;
if (lv_type == 1)
{
var used = RuleAccess.CountUsedAnnual(#User.Identity.Name);
var rem = max - used;
ViewBag.a = used;
ViewBag.b = rem;
}
else
{
ViewBag.b = max;
}
return View(model);
}
I used the Viewbag.comp 1 & 2 in my view:
<script type="text/javascript">
var x = #ViewBag.comp1;
var y = #ViewBag.comp2;
function validatecreate()
{
var value= document.getElementById("lv_type").value;
if (value==1)
{
if(x==1)
document.getElementById('validatecreate').submit();
else { alert('Action cant be done. You either have another annual leave application in pending status or you have reach the limit of annual leave'); }
}
else if(value==2)
{
if(y==1)
document.getElementById('validatecreate').submit();
else { alert('Action cant be done. You either are Male or Not Married Yet'); }
}
else if(value==3)
{
document.getElementById('validatecreate').submit();
}
else {
document.getElementById('validatecreate').submit();
//alert('Http Not Found');
}
}
#Html.DropDownList(
"lv_type", (SelectList) ViewBag.CategoryId,
"--Select One--",
new{ //anonymous type
#class = "form-control input-sm"
}
)
I feel like im doing it wrong especially because if someone manually put the url with ?lv_type=2, they not validate and can go to the form directly. But i need the value of lv_type bcs i use that in my view. Please Helpp :(
Validation must always be done on the server, and client side validation should only be considered a nice bonus that minimizes the need for to a call to the server. And presenting options in a dropdownlist to a user and then telling them thay can't select that option is an awful user experience. Instead, you should be presenting only those options which are applicable to the user (and delete all the scripts you have shown).
Create an additional method in your RuleAccess class, say GetEmployeeRules(Employee employee) which returns only the rules that are applicable to that employee, for example
public static List<Rule> GetEmployeeRules(Employee employee)
{
// Get the list of all rules
if (employee.EmpSex == "F" && employee.EmpMaritalSt == "NIKAH")
{
// Remove the appropriate Rule from the list
}
.....
// Return the filtered list
}
In addition, you should be using a view model in the view
public class LeaveTypeVM
{
[Required(ErrorMessage = "Please select a leave type")]
public int SelectedLeaveType { get; set; }
public IEnumerable<SelectListItem> LeaveTypeList { get; set; }
}
Then in the ChooseType() method
public ActionResult ChooseType()
{
var employee = DataAccess.GetEmployee(#User.Identity.Name);
var rules = RuleAccess.GetEmployeeRules(employee);
var model = new LeaveTypeVM()
{
LeaveTypeList = new SelectList(rules, "ID", "TypeDetail")
};
return View(model);
}
and in the view
#model LeaveTypeVM
#using (Html.BeginForm())
{
#Html.DropDownListFor(m => m.SelectedLeaveType, Model.LeaveTypeList, "--Select One--", new { #class = "form-control input-sm" }
#Html.ValidationMessageFor(m => m.SelectedLeaveType)
<input type="submit" value="Submit" />
}
and submit to a POST method which allows you to easily return the view if its invalid, or to redirect to the Create method.
[HttpPost]
public ActionResult ChooseType(LeaveTypeVM model)
{
if (!ModelState.IsValid)
{
model.LeaveTypeList = .... // as per GET method
}
return RedirectToAction("Create", new { leaveType = model.SelectedLeaveType });
and in the Create() method
public ActionResult Create(int leaveType)
{
var employee = DataAccess.GetEmployee(#User.Identity.Name);
var rule = RuleAccess.GetEmployeeRules(employee).Where(x => x.ID == leaveType).FirstOrDefault();
if (rule == null)
{
// Throw exception or redirect to an error page
}
var model = new LeaveApplicationViewModels();
....
return View(model);
}
Note your LeaveApplicationViewModels should contain additional properties so that you can avoid all those ViewBag properties and generate a strongly typed view.

How to print jpanel with graphic components

Here i use just print the JPanel but i need to put graphics component for drawLine method. how to use it anyone please advice me. my sample code for print JPanel here.
public class Sample {
JPanel component_name = new JPanel();
public void printComponenet(){
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setJobName(" Print Component ");
pj.setPrintable (new Printable() {
public int print(Graphics pg, PageFormat pf, int pageNum){
if (pageNum > 0){
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2 = (Graphics2D) pg;
g2.translate(pf.getImageableX(), pf.getImageableY());
component_name.printAll(g2);
return Printable.PAGE_EXISTS;
}
});
if (pj.printDialog() == false)
return;
try {
pj.print();
} catch (PrinterException ex) {
// handle exception
}
}
Add
g2.drawLine(left,top,width,height);
Replacing ( or assigning to ) the four parameters with integer values you want to use. eg:
g2.drawLine(30,40,400,300);
Should work for most displays.
g2.setColor(r,g,b);
Before, if you want other than black.

Exist stringByEvaluatingJavaScriptFromString for Android

Exist stringByEvaluatingJavaScriptFromString method in Android like Iphone?.
Not with a simple code like this javascript:wave(). But with a complex Java Script function.
Thanks
You can use loadUrl instead,eg:
webView.loadUrl("javascript:PerformSimpleCalculation()");
It's effect similar to stringByEvaluatingJavaScriptFromString.The API description is not clear.
stringByEvaluatingJavaScriptFromString is a private method in Android API. But it is really useful.
You could retrive this API via Java reflection:
Method stringByEvaluatingJavaScriptFromString , sendMessageMethod;;
Object webViewCore , browserFrame;
private boolean hasIntercepted = true;
Object webViewObject = this;
Class webViewClass = WebView.class;
try {
Field mp = webViewClass.getDeclaredField("mProvider");
mp.setAccessible(true);
webViewObject = mp.get(this);
webViewClass = webViewObject.getClass();
Field wc = webViewClass.getDeclaredField("mWebViewCore");
wc.setAccessible(true);
webViewCore = wc.get(webViewObject);
if (webViewCore != null) {
sendMessageMethod = webViewCore.getClass().getDeclaredMethod("sendMessage", Message.class);
sendMessageMethod.setAccessible(true);
Field bf= webViewCore.getClass().getDeclaredField("mBrowserFrame");
bf.setAccessible(true);
browserFrame = bf.get(webViewCore);
stringByEvaluatingJavaScriptFromString = browserFrame.getClass().getDeclaredMethod("stringByEvaluatingJavaScriptFromString", String.class);
stringByEvaluatingJavaScriptFromString.setAccessible(true);
}
hasIntercepted = true;
} catch (Throwable e) {
hasIntercepted = false;
}
Then to use this method:
Object argument =(Object) ((String)"window.hitTest("+event.getX()+ ","+event.getY()+")");
try {
Object _tagName = stringByEvaluatingJavaScriptFromString.invoke(browserFrame, argument);
String tagName =(String)_tagName;
} catch (Exception e) {
e.printStackTrace();
}

Categories

Resources