My app works fine in an emulator, but when I install it on a real device it crashes.
After some debugging I found the error was in the sub-string function.
Here's the code that I think is causing problem.
if(text.indexOf(" ")>0 && text.indexOf("d")>0) {
a = text.indexOf(" ");
b = text.indexOf("d");
}
ccs = text.substring(0,a);
crs = text.substring(a+1,b);
days = text.substring(b + 1);
For example, if text = "30 100d27";
ccs = "30", crs = "100" and days = "27"
Why would something like this work as expected on an emulator but crash on a real device?
I'll try this code in lenovo k900 its working fine.
if you have a doubt then put it into the try block like this.
try {
text = "30 100d27";
if (text.indexOf(" ") > 0 && text.indexOf("d") > 0) {
a = text.indexOf(" ");
b = text.indexOf("d");
}
ccs = text.substring(0, a);
crs = text.substring(a + 1, b);
days = text.substring(b + 1);
} catch (Exception e) {
Log.e("mye", "exception " + e);
}
and if your data is like this text = "30100d27" than its gives you java.lang.StringIndexOutOfBoundsException so ultimatly check your input.
I don't know the exact crash-cause since you haven't provided any error-logs or equal
But i can give you this:
Image a string "dexample01 " (a space at the end).
Now run your code an you will run into an exception:
text = "dexample01 ";
if (text.indexOf(" ") > 0 && text.indexOf("d") > 0) {
a = text.indexOf(" "); //a = 9
b = text.indexOf("d");
}
ccs = text.substring(0,a);
crs = text.substring(a+1,b); // a+1 = 10 -> 10 causes INDEX OUT OF BOUNDS
days = text.substring(b + 1);
Maybe you run into this exact special case and because of that your app crashes.
Try this as an example (It uses split() not indexof()):
public class Demo3 extends AppCompatActivity {
private EditText edt;
private Button b;
private TextView tv;
private String ccs;
private String crs;
private String days;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo3);
edt = (EditText) findViewById(R.id.edt);
tv = (TextView) findViewById(R.id.tv);
b = (Button) findViewById(R.id.b);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!edt.getText().toString().isEmpty()){
String[] split_space = edt.getText().toString().split(" ");
if(split_space.length==2){
ccs = split_space[0];//TODO: check ccs is a number
if(!split_space[1].isEmpty()){
String[] split_d = split_space[1].split("d");
if(split_d.length ==2 ){
crs = split_d[0];//TODO: check crs is a number
days = split_d[1];//TODO: check days is a number
}else{
crs = "null";
days = "null";
}
}else{
crs = "null";
days = "null";
}
}else{
ccs = "null";
crs = "null";
days = "null";
}
}else{
ccs = "null";
crs = "null";
days = "null";
}
tv.setText("ccs = " + ccs +"---" + "crs = " + crs + "---" + "days = " + days);
}
});
}
}
demo3.xml:----
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/edt"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="null"
android:id="#+id/tv"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Check"
android:layout_marginTop="50dp"
android:id="#+id/b"/>
</LinearLayout>
Related
I've been struggling a couple days now attempting to write this code. Basically,we have to perform a binarySearch based on the SSN of Comparable "Student" objects in a Student array. After performing the binarySearch on the SSN, the student who is associated with that SSN's first and last name should print out. I am finding difficulty in writing the binarySearch.
Here's my code so far:
my Student class:
public class Student implements Comparable<Student>{
private String firstName, lastName, SSN, bankAccount;
public Student(String first, String last, String ssn, String bkacct) {
this.firstName = first;
this.lastName = last;
this.SSN = ssn;
this.bankAccount = bkacct;
}
//toString method
public String toString() {
return "Employee: [FirstName = " + firstName + ", LastName = " + lastName + ", SSN = " + SSN + ", BankAccount = "
+ bankAccount + "]";
}
public boolean equals(Object other) {
return (lastName.equals(((Student)other).getLastName()) &&
firstName.equals(((Student)other).getFirstName())&&
SSN.equals(((Student)other).getSSN()) &&
bankAccount.equals(((Student)other).getBankAccount()));
}
//Sorting the array based on SSN
public int compareTo(Student target) {
int result;
if (lastName.equals(target.getLastName()))
result = SSN.compareTo((String) target.getSSN());
else
result = SSN.compareTo((String) target.getSSN());
return result;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Object getSSN() {
return SSN;
}
public String getBankAccount() {
return bankAccount;
}
and my class where i perform my binarySearch
public class ObjectBubbleSortTest {
//setting up binarySearch to find Array
public static <Student extends Comparable<Student>> int binarySearch(Student[] student, Student target) {
int low = 0;
int high = student.length - 1;
int middle = (low+high + 1)/2;
int location = -1;
while((low <= high) && (location == -1)) {
if (student[middle].compareTo(target) == 0 ) {
location = middle;
}
else if (student[middle].compareTo(target) < 0) { //middle element too high
high = middle - 1;
}
else {
low = middle + 1;
}
middle = (low + high + 1)/2;
}
return location;
}
public static void main(String[] args) {
//EMPLOYEES OF BURGER KING
Student[] student = new Student[5];
//order: First Name, Last Name, SSN, Bank_Account_Number
student[0] = new Student("Adam", "Sarrone", "1234567", "9022345");
student[1] = new Student("Ryan", "Petrowvoksi", "4345123", "0120345");
student[2] = new Student("Jenn", "Henderson", "8124512", "564214");
student[3] = new Student("Ricky", "Jean", "3512345", "612345");
student[4] = new Student("Dare", "Ogun", "421451", "198213");
System.out.println("Original array order: \n");
for (Student element : student)
System.out.print(element + "\n");
ObjectBubbleSorter.bubbleSort(student);
System.out.println();
System.out.println("\nSorted array order: \n");
for (Student element : student)
System.out.print(element + "\n");
System.out.println();
//need helping figuring out why the binary search is not printing out
int studentName = binarySearch(student, "421451");
System.out.print(studentName);
}
}
I am also getting an error on "int studentName = binarySearch" stating The method binarySearch(Student[], Student) in the type ObjectBubbleSortTest is not applicable for the arguments (Student[], String). I understand what it means but struggling to make my binarySearch adaptable to fix that error.
Any help would be greatly appreciated. Thank you.
It would be clear if you read the error message once again carefully.
"int studentName = binarySearch" stating The method binarySearch(Student[], Student) in the type ObjectBubbleSortTest is not applicable for the arguments (Student[], String).
So basically the method signature you have is int binarySearch(Student[] student, Student target), but when you call it in main() it's binarySearch(student, "421451");
You may want to instead call the method like binarySearch(student, student[4]);
In the OnClickListener, addFood needs the date and time input from the datepicker fragment.
How can i make it wait till the input is done by the user?
Button breakfastAdd = findViewById(R.id.breakFastButton);
breakfastAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (breakfastSearch.getCount() == 0) {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast,
(ViewGroup) findViewById(R.id.emptySelectionLayout));
TextView text = layout.findViewById(R.id.toastText);
text.setText(R.string.selectedIsEmpty);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
Log.d("list is", "empty");
} else {
new datePickerFragment().show(getSupportFragmentManager(), "datePicker");
addFood(context, breakfastDate, breakfastSearch, 1);
}
}
});
You should call your addFood(context, breakfastDate, breakfastSearch, 1); as an onChange in datePickerFragment instead.
You can put this code in you OnClickListener it will create DatePickerDialog and you will get date after you can put rest of the code:
Calendar calendar = Calendar.getInstance();
DatePickerDialog datePickerDialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
int getMonth = month + 1;
int getDay = dayOfMonth;
String setMonth;
String setDay;
if (getMonth < 10)
setMonth = "0" + String.valueOf(getMonth);
else
setMonth = String.valueOf(getMonth);
if (getDay < 10)
setDay = "0" + String.valueOf(getDay);
else
setDay = String.valueOf(getDay);
String getDate = setMonth + "/" + setDay + "/" + year;
//You have date which user picked here you can continue with rest of your code, Inflate layout etc.
}
}, calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_WEEK));
datePickerDialog.show();
I have a jquery events calendar (e-calendar) in the front end and retrieving the events from SharePoint calendar (c#), how can I convert this c# code to be displayed in the jquery e-calendar events?
Jquery events calendar:
https://github.com/jhonis/e-calendar
C# code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SPListItemCollection corporateCalendarListItems = GetCorporateCalendarItems();
if (corporateCalendarListItems != null) { AddCorporateCalendarEventsToUI(corporateCalendarListItems); }
}
}
private SPListItemCollection GetCorporateCalendarItems()
{
using (SPSite wadiSite = SPContext.Current.Site)
{
using (SPWeb wadiWeb = wadiSite.OpenWeb())
{
wadiWeb.AllowUnsafeUpdates = true;
// Fetch the List
SPList corporateCalendarList = wadiWeb.Lists.TryGetList("Corporate Calendar");
// Return the last item
if (corporateCalendarList != null)
{
DateTime todayDate = DateTime.Now;
string month = todayDate.ToString("MM");
string year = todayDate.ToString("yyyy");
string endOfMonthDate = year + "-" + month + "-30";
string startOfMonthDate = year + "-" + month + "-01";
SPQuery qry = new SPQuery();
qry.Query = #"<Where><And><And><Eq><FieldRef Name='Category' /><Value Type='Choice'>Holiday</Value></Eq><Geq><FieldRef Name='EventDate' /><Value Type='DateTime'>"+startOfMonthDate+"</Value></Geq></And><Leq><FieldRef Name='EventDate' /><Value Type='DateTime'>" + endOfMonthDate + "T12:00:00Z</Value></Leq></And></Where><OrderBy><FieldRef Name='EventDate' /></OrderBy>";
qry.ViewFields = #"<FieldRef Name='Title' /><FieldRef Name='EventDate' /><FieldRef Name='FileRef' /><FieldRef Name='EndDate' /><FieldRef Name='Category' />";
SPListItemCollection corporateCalendarListItems = corporateCalendarList.GetItems(qry);
return corporateCalendarListItems;
}
return null;
}
}
}
private void AddCorporateCalendarEventsToUI(SPListItemCollection corporateCalendarListItems)
{
List<CalendarEvent> calendarEvents = new List<CalendarEvent>();
foreach (SPListItem corporateCalendarListItem in corporateCalendarListItems)
{
CalendarEvent calendarEvent = new CalendarEvent();
calendarEvent.Title = corporateCalendarListItem["Title"].ToString();
if(corporateCalendarListItem["EventDate"] != null)
{
calendarEvent.StartDate = DateTime.Parse(corporateCalendarListItem["EventDate"].ToString());
}
if (corporateCalendarListItem["EndDate"] != null)
{
calendarEvent.EndDate = DateTime.Parse(corporateCalendarListItem["EndDate"].ToString());
}
calendarEvent.Category = "Test";
calendarEvent.AllDay = false;
calendarEvents.Add(calendarEvent);
}
}
this is my programmatically button, there is the error null pointer exception in logcat.
This is my way to loop the button.But the disable button for the button cannot function.When i click on "save" button the programmatically button will disable. is it my way to disable button is incorrect?
String CountQuery = "SELECT * FROM Category";
db = new DBController(getActivity());
SQLiteDatabase db2 = db.getReadableDatabase();
Cursor cursor1 = db2.rawQuery(CountQuery, null);
{
int num = cursor1.getCount();
Button[] valueB = new Button[num];
for (int i = 1; i < num; i++) {
String SelectQuery = "SELECT * FROM Category where CategoryID='" + i + "'";
db = new DBController(getActivity());
SQLiteDatabase db1 = db.getReadableDatabase();
Cursor cursor = db1.rawQuery(SelectQuery, null);
if (cursor.moveToNext()) {
String categoryName = cursor.getString(1);
String coordinateX = cursor.getString(2);
String coordinateY = cursor.getString(3);
valueB[i] = new Button(getActivity());
valueB[i].setText("" + categoryName);
valueB[i].setId(i);
valueB[i].setOnTouchListener(this);
params = new RelativeLayout.LayoutParams(300, 100);
params.leftMargin = Integer.parseInt(coordinateX);
params.topMargin = Integer.parseInt(coordinateY);
final int finalI = i;
valueB[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "asdasd" + finalI, Toast.LENGTH_SHORT).show();
viewPager = (ViewPager) getActivity().findViewById(R.id.pager);
viewPager.setCurrentItem(finalI);
}
});
mRrootLayout.addView(valueB[i],params);
}
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (i[0] = 1; i[0] < num; i[0]++) {
valueB[i[0]].setOnTouchListener(null);
}
}
});
}
}
You can disable the onclick listener by using valueB[i].setOnClickListener(null);
you can disable the button by using setClickable method.
valueB[i].setClickable(false);
or you can user setEnabled method also like
valueB[i].setEnabled(false);
I'm trying to have a hide and show button
Whenever i click on the button, it works but also refreshes the page at the same time. I'm not sure what is causing the refresh. This is on aspx:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#buttontest").click(function () {
$("#hello").toggle();
});
});</script>
<button id="buttontest">test</button>
<div id="hello">hello</div>
Not sure if its the aspx.cs is causing the refreshing:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection myConnect = new SqlConnection(_connStr);
acct = new Account();
acct = (Account)Session["Account"];
if (!IsPostBack)
{
LoadCart();
DataBind();
string strCommandText = "SELECT * From Customer where Cust_Id = #Cust_Id";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
cmd.Parameters.AddWithValue("#Cust_Id", 1);
//open connection and retrieve data by calling ExecuteReader
myConnect.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Lbl_FName.Text = dr["First_Name"].ToString();
Lbl_LName.Text = dr["Last_Name"].ToString();
Lbl_CNo.Text = dr["Contact_No"].ToString();
string addr1 = dr["Address"].ToString();
string addr2 = dr["Address2"].ToString();
address = new List<string>();
address.Add(dr["Address"].ToString() + " " + "Singapore " + dr["Postal_Code"].ToString());
address.Add(dr["Address2"].ToString() + " " + "Singapore " + dr["Postal_Code"].ToString());
//Ddl_Address.Text = dr["Address"].ToString() + " " + "Singapore " + dr["Postal_Code"].ToString();
//Ddl_Address.Text = dr["Address2"].ToString() + " " + "Singapore " + dr["Postal_Code"].ToString();
ddl_Addr.DataSource = address;
ddl_Addr.DataBind();
}
dr.Dispose();
dr.Close();
myConnect.Close();
//page load box retrieve
SqlConnection myConnect2 = new SqlConnection(_connStr);
string strCommandText2 = "SELECT * From Card_Details where Card_Id = #Card_Id";
myConnect2.Open();
SqlCommand cmd2 = new SqlCommand(strCommandText2, myConnect2);
cmd2.Parameters.AddWithValue("#Card_Id", 1);
////open connection and retrieve data by calling ExecuteReader
SqlDataReader dr2 = cmd2.ExecuteReader();
if (dr2.Read())
{
CNo1 = dr2["Card_Number"].ToString();
CNo2 = dr2["Card_Number2"].ToString();
Session["CardNo1"] = CNo1;
Session["CardNo2"] = CNo2;
CNo = new List<string>();
CNo.Add(CNo1);
CNo.Add(CNo2);
ddl_CNo.DataSource = CNo;
ddl_CNo.DataBind();
//display when first run
Lbl_CardName.Text = dr2["Name_On_Card"].ToString();
Lbl_CardType.Text = dr2["Card_Type"].ToString();
Lbl_EDate.Text = dr2["Expired_Date"].ToString();
dr2.Dispose();
dr2.Close();
myConnect2.Close();
}
}
}
protected void ddl_CNo_SelectedIndexChanged(object sender, EventArgs e)
{
string cardNum1 = Session["CardNo1"].ToString();
string cardNum2 = Session["CardNo2"].ToString();
if (ddl_CNo.SelectedIndex == 0)
{
SqlConnection myConnect2 = new SqlConnection(_connStr);
string strCommandText2 = "SELECT Name_On_Card, Card_Type, Expired_Date From Card_Details where Card_Number = #Card_Number";
myConnect2.Open();
SqlCommand cmd2 = new SqlCommand(strCommandText2, myConnect2);
cmd2.Parameters.AddWithValue("#Card_Number", cardNum1);
SqlDataReader dr2 = cmd2.ExecuteReader();
if (dr2.Read())
{
Lbl_CardName.Text = dr2["Name_On_Card"].ToString();
Lbl_CardType.Text = dr2["Card_Type"].ToString();
Lbl_EDate.Text = dr2["Expired_Date"].ToString();
}
dr2.Dispose();
dr2.Close();
// DataBind();
myConnect2.Close();
}
else if (ddl_CNo.SelectedIndex == 1)
{
SqlConnection myConnect3 = new SqlConnection(_connStr);
string strCommandText3 = "SELECT Name_On_Card2, Card_Type2, Expired_Date2 From Card_Details where Card_Number2 = #Card_Number2";
myConnect3.Open();
SqlCommand cmd3 = new SqlCommand(strCommandText3, myConnect3);
cmd3.Parameters.AddWithValue("#Card_Number2", cardNum2);
SqlDataReader dr3 = cmd3.ExecuteReader();
if (dr3.Read())
{
Lbl_CardName.Text = dr3["Name_On_Card2"].ToString();
Lbl_CardType.Text = dr3["Card_Type2"].ToString();
Lbl_EDate.Text = dr3["Expired_Date2"].ToString();
}
dr3.Dispose();
dr3.Close();
// DataBind();
myConnect3.Close();
}
}
protected void LoadCart()
{
gv_CartView.DataSource = ShoppingCart.Instance.Items;
gv_CartView.DataBind();
decimal total = 0.0m;
foreach (ShoppingCartItem item in ShoppingCart.Instance.Items)
{
total = total + item.TotalPrice;
}
decimal a = 2.0m;
decimal totalP = a + total;
Lbl_Subtotal.Text = total.ToString("C");
Lbl_TotalPrice.Text = totalP.ToString("C");
}
I'm still unfamiliar with all these, any help would be appreciated
EDIT: I've edited the button and javascript, it still caused a refresh
this looks like you might have button type as submit other wise this is not possible to happen
please make sure you added button as button not as submit button
Also please try to avoid
$("button").click(function () {
used specific button id
$("#btn_toggle").click(function () {
And you can also do.. in case if your button type is submit but you need to do return false.
$("#btn_toggle").click(function () {
$("#hello").toggle();
return false;
});
but make sure this will stop submit your from at server.
Replace server button with html button. i.e.
Replace
<asp:Button />
With
<input type="button" />
OR
do this:
$("button").click(function () {
$("#hello").toggle();
return false;
});
Try this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("button").click(function () {
$("#hello").toggle();
});
});</script>
<button>hello</button>
<div id="hello">hello</div>