Android Calendar getting the current day not working - android
I need help again.
I´m trying to get the current day, and set some specific text to textviews.
But my IF statement is not working correctly.
Actually, it sets the MONDAY-s texts for everyday and writes "Reede" (FRIDAY) on everyday.
So, it´s quite confusing to me, as I´m newbie for Android.
What I am doing wrong?
CODE:
private void setupTunniplaan() {
TextView paev = (TextView) findViewById(R.id.esmasp);
String[] tunnidesmasp = {"Matemaatika", "Bioloogia", "Füüsika", "Kehaline", "Geograafia", "Inglise keel", "Ajalugu","",""};
String[] tunnidteisip = {"Inglise keel", "Vene keel", "Karjääri õpetus", "Karjääri õpetus", "Matemaatika", "Eesti keel", "Kirjandus","", ""};
String[] tunnidkolmap = {"Füüsika", "Kehaline", "Keemia", "Matemaatika", "Kirjandus", "Kirjandus", "Kirjandus", "Inglise keel", "", ""};
String[] tunnidneljap = {"Inglise keel", "Ajalugu", "Matemaatika", " Muusika", "Geograafia", "Bioloogia", "Geograafia", "", ""};
String[] tunnidreede = {"Keemia", "UTA", "Eesti keel", "Matemaatika", "Vene keel", "Bioloogia", "Soome keel", "", ""};
Calendar kal = Calendar.getInstance();
int day = kal.get(Calendar.DAY_OF_WEEK);
if (day == Calendar.MONDAY); {
tunnid(tunnidesmasp[0], tunnidesmasp[1], tunnidesmasp[2],tunnidesmasp[3], tunnidesmasp[4], tunnidesmasp[5],
tunnidesmasp[6],tunnidesmasp[7], tunnidesmasp[8] );
paev.setText("Esmaspäev");
}
if (day == Calendar.TUESDAY); {
tunnid(tunnidteisip[0], tunnidteisip[1], tunnidteisip[2],tunnidteisip[3], tunnidteisip[4], tunnidteisip[5],
tunnidteisip[6],tunnidteisip[7], tunnidteisip[8] );
paev.setText("Teisipäev");
}
if (day == Calendar.WEDNESDAY); {
tunnid(tunnidkolmap[0], tunnidkolmap[1], tunnidkolmap[2],tunnidkolmap[3], tunnidkolmap[4], tunnidkolmap[5],
tunnidkolmap[6],tunnidkolmap[7], tunnidkolmap[8] );
paev.setText("Kolmapäev");
}
if (day == Calendar.THURSDAY); {
tunnid(tunnidneljap[0], tunnidneljap[1], tunnidneljap[2],tunnidneljap[3], tunnidneljap[4], tunnidneljap[5],
tunnidneljap[6],tunnidneljap[7], tunnidneljap[8] );
paev.setText("Neljapäev");
}
if (day == Calendar.FRIDAY); {
tunnid(tunnidreede[0], tunnidreede[1], tunnidreede[2],tunnidreede[3], tunnidreede[4], tunnidreede[5],
tunnidreede[6],tunnidreede[7], tunnidreede[8]);
paev.setText("Reede");
}
if (day == Calendar.SATURDAY); {
tunnid(tunnidesmasp[0], tunnidesmasp[1], tunnidesmasp[2],tunnidesmasp[3], tunnidesmasp[4], tunnidesmasp[5],
tunnidesmasp[6],tunnidesmasp[7], tunnidesmasp[8] );
}
if (day == Calendar.SUNDAY); {
tunnid(tunnidesmasp[0], tunnidesmasp[1], tunnidesmasp[2],tunnidesmasp[3], tunnidesmasp[4], tunnidesmasp[5],
tunnidesmasp[6],tunnidesmasp[7], tunnidesmasp[8] );
}
return;
}
//Sorry if I´m asking dumb questions.
EDIT: Thanks. The TextView paev is working correctly now.
But tunnid() is still not working correctly. You can see it in every if-statement as a first thing to do. My code still works through in every case MONDAY-s "tunnid()". So, the paev.setText() is working correctly, but tunnid() is not.
CODE of tunnid():
public void tunnid(String esimenetund, String teinetund, String kolmastund, String neljastund, String viiestund,
String kuuestund, String seitsmestund, String kaheksastund, String yheksastund) {
TextView tund1 = (TextView) findViewById(R.id.tund1);
TextView tund2 = (TextView) findViewById(R.id.tund2);
TextView tund3 = (TextView) findViewById(R.id.tund3);
TextView tund4 = (TextView) findViewById(R.id.tund4);
TextView tund5 = (TextView) findViewById(R.id.tund5);
TextView tund6 = (TextView) findViewById(R.id.tund6);
TextView tund7 = (TextView) findViewById(R.id.tund7);
TextView tund8 = (TextView) findViewById(R.id.tund8);
TextView tund9 = (TextView) findViewById(R.id.tund9);
TextView ylesanne1 = (TextView) findViewById(R.id.yl1);
TextView ylesanne2 = (TextView) findViewById(R.id.yl2);
TextView ylesanne3 = (TextView) findViewById(R.id.yl3);
TextView ylesanne4 = (TextView) findViewById(R.id.yl4);
TextView ylesanne5 = (TextView) findViewById(R.id.yl5);
TextView ylesanne6 = (TextView) findViewById(R.id.yl6);
TextView ylesanne7 = (TextView) findViewById(R.id.yl7);
TextView ylesanne8 = (TextView) findViewById(R.id.yl8);
TextView ylesanne9 = (TextView) findViewById(R.id.yl9);
tund1.setText(esimenetund);
tund2.setText(teinetund);
tund3.setText(kolmastund);
tund4.setText(neljastund);
tund5.setText(viiestund);
tund6.setText(kuuestund);
tund7.setText(seitsmestund);
tund8.setText(kaheksastund);
tund9.setText(yheksastund);
ylesanne1.setText("");
ylesanne2.setText("");
ylesanne3.setText("");
ylesanne4.setText("");
ylesanne5.setText("");
ylesanne6.setText("");
ylesanne7.setText("");
ylesanne8.setText("");
ylesanne9.setText("");
}
you have semicolon (;) after each one of your if statements:
if (day == Calendar.TUESDAY);
that means the if statement doesn't have a block to execute.
your application will execute each block after each if statement.
remove the semicolon (;)
Related
how to add the three values of textview and to store in one texview
String s1 = (getIntent().getStringExtra("Value1")); String s3 = (getIntent().getStringExtra("value2")); String s2 = (getIntent().getStringExtra("value3")); id1 = (TextView) findViewById(R.id.id1); id2 = (TextView) findViewById(R.id.id2); id3 = (TextView) findViewById(R.id.id3); id4 = (TextView) findViewById(R.id.id4); id1.setText((s1)); id2.setText((s2)); id3.setText((s3)); How to add the values of the tex view set text values and to store the value as integer in one text view
id1.setText((s1)); id2.setText((s2)); id3.setText((s3)); then your question, add the three values of textview and to store in one texview int first = Integer.parseInt(id1.getText().toString()); int second = Integer.parseInt(id2.getText().toString()); int third = Integer.parseInt(id3.getText().toString()); int final = first+second+third; id4.setText(""+final);
Do calculations on numbers in 1 multiline textView and return result replacing numbers
I am very new to android programming and am trying to complete my first app. It is a recipe converter. I have stored my recipe details in a SQLite DB and the text for ingredients is just one multiline string separated by carriage returns. I have used a cursor to get the ingredient data into a textview which returns text like (could be numerous variants): 100ml Water 500 g Mince 2 x 400g can crushed tomatoes etc. I originally had each Qty, Unit and Ingredient Description stored separately in the database which made life easy when converting but I chose to store it in a multiline string to allow copying and pasting of ingredients from the internet or another source. I am attempting to extract the numbers and then multiply them by a percentage, then return the new converted numbers, and the corresponding unit and description to get something like this: (multiplied by 200%) 200ml Water 1000g Mince 4 x 400g can crushed tomatoes I just don't know how to do it though. Can anyone help please? Thanks UPDATE: I have tried to do something like this to get the numbers. public void Split() { TextView tvSplit = (TextView) findViewById(R.id.tvSplit); final TextView tvTest = (TextView) findViewById(R.id.tvTest); String s = tvTest.getText().toString(); for (int i =0;i <= tvTest.getLineCount();i++){ tvSplit.setText(""); String text = s.replaceAll("\\D+", ","); tvSplit.append(text); tvSplit.append("\n"); } That shows me all of the numbers with a "," between them but it also includes all numbers in the string like in the above example prior to conversion it would show 100,500,2,400 when I only need 100,500,2. Then from that point I'm not sure how I would convert them all. My "fresh to programming mind" thought that I could store these in a temp SQL table by INSERT INTO tablename (id, originalvalues) VALUES (my string ie 100,500,2). I could then pull them back out, do the calculation, update the table, then add them back into my textview with the remaining string. I haven't got that far yet, so I'm just wondering what the correct way to do it is. UPDATE 2: As per my comments, this is the code I used to show an alert dialog with each item listed on a separate line, I then used the selected line to find the number before any " " to then display the text on the screen. public void PopUpSpinnerDialogue() { final TextView tvTest = (TextView) findViewById(R.id.tvTest); final TextView tv2 = (TextView) findViewById(R.id.tvTest2); String s = tvTest.getText().toString(); final ArrayAdapter myAdapter = new ArrayAdapter<String>(this, R.layout.my_dropdown_style, s.split("\n")); android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this); builder.setTitle("Please choose the key ingredient you need to scale your recipe by.") .setCancelable(false) .setAdapter(myAdapter, new DialogInterface.OnClickListener() { #Override public void onClick(DialogInterface dialog, int which) { try { String itemName = myAdapter.getItem(which).toString(); String[] parts = itemName.split(" "); String itemNumStr = parts[0]; TextView tvLineName = (TextView) findViewById(R.id.tvIngredientSelect); EditText et1 = (EditText) findViewById(R.id.etRecipeQtyConvert); EditText et2 = (EditText) findViewById(R.id.etQtyHave); tvLineName.setText(itemName); String b4Space = itemNumStr.replaceAll("\\D+", ""); tv2.setText(b4Space); et1.setText(b4Space); et2.setText(b4Space); calculateKeyIngredientPercent(); } catch (Exception e) { Toast.makeText(SelectConvertMethod.this, "Your ingredient must have a QTY. eg. 100ml.", Toast.LENGTH_SHORT).show(); } } }); android.app.AlertDialog alert = builder.create(); alert.show(); } It is this idea that I think I can use but I don't know how to code it and then display the results. UPDATE 3: The code or at least the idea of the code I am trying to use is this. TextView tvSplit = (TextView) findViewById(R.id.tvSplit); final TextView tvTest = (TextView) findViewById(R.id.tvTest); String s = tvTest.getText().toString(); for (int i =0;i <= tvTest.getLineCount();i++){ String[] ingreds = s.split("\n"); tvSplit.setText(""); String[] parts = ingreds.split(" "); String Qty = parts[0]; String Units = parts[1]; String Ingredients = parts[2]; Integer QtyInt = Integer.parseInt(Qty);} ingreds.split doesn't work and also, I don't know how to specify splitting the parts for each i.
I ended up using regex. It allowed the data to be entered with or without a space. So I ended up using this code to pull out the Qty of each line, multiply it by a percentage, append the text (units,ingredient description) to the line, then add it to a string array, to add to my alert dialog. Code is here. public void Split() { final TextView tv2 = (TextView) findViewById(R.id.tvTest2); TextView tvTest = (TextView) findViewById(R.id.tvTest); TextView tvPercent = (TextView) findViewById(R.id.tvPercent); String tvP = tvPercent.getText().toString(); String tvNumOnly = tvP.replaceAll("\\D+", ""); Integer PercentVal = Integer.parseInt(tvNumOnly); String s = tvTest.getText().toString(); StringBuilder sb = new StringBuilder(); Pattern p = Pattern.compile("((\\d*) ?(.*)(?:\\n*))"); Matcher m = p.matcher(s); while (m.find()) { String Qty = m.group(2) + ".00"; String Ingred = m.group(3); Float QtyFloat = Float.parseFloat(Qty); Float newQTY = (QtyFloat * PercentVal) / 100; String newQTYstr = newQTY.toString(); sb.append(newQTYstr + " " + Ingred + "\n"); } String[] lines = sb.toString().split("\n"); String[] IngredArray = Arrays.copyOfRange(lines, 0, lines.length - 1); final ArrayAdapter myAdapter = new ArrayAdapter<String>(this, R.layout.my_dropdown_style, IngredArray); android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this); builder.setTitle("Please choose the key ingredient you need to scale your recipe by.") .setCancelable(false) .setAdapter(myAdapter, new DialogInterface.OnClickListener() { #Override public void onClick(DialogInterface dialog, int which) { try { String itemName = myAdapter.getItem(which).toString(); String[] parts = itemName.split(" "); String itemNumStr = parts[0]; TextView tvLineName = (TextView) findViewById(R.id.tvIngredientSelect); EditText et1 = (EditText) findViewById(R.id.etRecipeQtyConvert); EditText et2 = (EditText) findViewById(R.id.etQtyHave); tvLineName.setText(itemName); String b4Space = itemNumStr.replaceAll("\\D.\\D+", ""); tv2.setText(b4Space); et1.setText(b4Space); et2.setText(b4Space); calculateKeyIngredientPercent(); } catch (Exception e) { Toast.makeText(SelectConvertMethod.this, "Your ingredient must have a QTY. eg. 100ml.", Toast.LENGTH_SHORT).show(); } } }); android.app.AlertDialog alert = builder.create(); alert.show(); // Toast.makeText(SelectConvertMethod.this, sb, Toast.LENGTH_LONG).show(); }
Number range on an edittext - only want numbers between 1 and 10
I'm trying to make an app that only allows a user to enter between 1 and 10, I've tried writing my own method where if the number is out of that range, it changes the text views to ERROR and clears what's in the edit text, however it crashes the app. Does anyone know what's wrong with it? New to android. Code: public void buttonClick (View v) { TextView tvNum = (TextView) findViewById(R.id.tvNumEnt); TextView tvName = (TextView) findViewById(R.id.tvNumEnt); TextView tvNameEnt = (TextView) findViewById(R.id.NameEnt); TextView tvNumEnt = (TextView) findViewById(R.id.NumEnt); EditText num = (EditText) findViewById(R.id.ETnumber); EditText name = (EditText) findViewById(R.id.ETname); String nameContent = name.getText().toString(); String numContent = num.getText().toString(); tvName.setText(nameContent); int value = Integer.parseInt(num.getText().toString()); if (value > 10) { tvNum.setText("ERROR"); num.getText().clear(); name.getText().clear(); } else if (value < 1) { tvNum.setText("ERROR"); num.getText().clear(); name.getText().clear(); } else { tvNum.setText(numContent); tvNameEnt.setVisibility(View.VISIBLE); tvNumEnt.setVisibility(View.VISIBLE); tvName.setVisibility(View.VISIBLE); tvNum.setVisibility(View.VISIBLE); } }
You have issue on this line int value = Integer.parseInt(num.toString()); change to: int value = Integer.parseInt(num.getText().toString()); Now you call toString() method from Object for EditText object. You have to call getText() method for it as first and after then call toString() method for CharSequence UPDATE: You find two times the same view with the same ids. Look at the code below: TextView tvNum = (TextView) findViewById(R.id.tvNumEnt); TextView tvName = (TextView) findViewById(R.id.tvNumEnt); there should be R.id.tvNumEnt in the second time, I think so... TextView tvNum = (TextView) findViewById(R.id.tvNumEnt); TextView tvName = (TextView) findViewById(R.id.tvNumEnt);
The main problem here is that you are trying to get the number in the edittext with: num.toString(), instead you have to use: num.getText().toString()
Improve swap image code
Is there a way to make this code simpler? It seems repeating The code is for two ImageViews that swap and change skin onClick, changing some labels at the same time. Thanks! public void imgChangeUnit(View v) { TextView lbl_unT = (TextView) findViewById(R.id.unT); TextView lbl_unOD = (TextView) findViewById(R.id.unOD); TextView lbl_unID = (TextView) findViewById(R.id.unID); TextView lbl_unit_res = (TextView) findViewById(R.id.lbl_unit_res); ImageView myImg_mm = (ImageView)findViewById(R.id.imgMetric); ImageView myImg_in = (ImageView)findViewById(R.id.imgImperial); if (isUnit(lbl_unit_res)) { lbl_unT.setText("inch"); lbl_unOD.setText("inch"); lbl_unID.setText("inch"); lbl_unit_res.setText("Feet"); myImg_in.setImageDrawable(getResources().getDrawable(R.drawable.img_but_imperial_on)); myImg_mm.setImageDrawable(getResources().getDrawable(R.drawable.img_but_metric_off)); } else { lbl_unT.setText("mm"); lbl_unOD.setText("mm"); lbl_unID.setText("mm"); lbl_unit_res.setText("Meters"); myImg_mm.setImageDrawable(getResources().getDrawable(R.drawable.img_but_metric_on)); myImg_in.setImageDrawable(getResources().getDrawable(R.drawable.img_but_imperial_off)); } }
This already looks a bit better. At least you don´t have variable repetition any more. You might want to create method like setToImperial() and setToMetric(), that would know what to get and set. It would even be better. Also, note that you shouldn´t hardcode Strings in android, but use the string resources file. public void imgChangeUnit(View v) { TextView lbl_unT = (TextView) findViewById(R.id.unT); TextView lbl_unOD = (TextView) findViewById(R.id.unOD); TextView lbl_unID = (TextView) findViewById(R.id.unID); TextView lbl_unit_res = (TextView) findViewById(R.id.lbl_unit_res); ImageView myImg_mm = (ImageView)findViewById(R.id.imgMetric); ImageView myImg_in = (ImageView)findViewById(R.id.imgImperial); String unit; String unit2; Drawable d1; Drawable d2; if (isUnit(lbl_unit_res)) { unit = "inch"; unit2 = "Feet"; d1 = getResources().getDrawable(R.drawable.img_but_imperial_on); d2 = getResources().getDrawable(R.drawable.img_but_metric_off); } else { unit = "mm"; unit2 = "Meters"; d1 = getResources().getDrawable(R.drawable.img_but_metric_on); d2 = getResources().getDrawable(R.drawable.img_but_imperial_off); } lbl_unT.setText(unit); lbl_unOD.setText(unit); lbl_unID.setText(unit); lbl_unit_res.setText(unit2); myImg_mm.setImageDrawable(d1); myImg_in.setImageDrawable(d2); }
Bunch of Records displaying in Custom View android but Very Time Consuming
I am developing Android Application which is Syncing data from Server. Server has thousands of records that i have stored in SQLite Database. But now i am displaying records in custom TableView Successfully, but its very time consuming and i got black screen for 10 to 20 seconds. My code is: /**** FILL ALL DATA OF PRODUCT WHICH IS AVAILABLE IN THIS COMPANY ****/ dbHelper.open(); productCursor = dbHelper.getProduct(companyid, isDistributor); if(productCursor.getCount() > 0) { productTable.setVisibility(View.VISIBLE); (view.findViewById(R.id.productIfNoAvailable)).setVisibility(View.GONE); TableRow row= null; com.salesman.library.ImageLoader mImageLoader = new com.salesman.library.ImageLoader(context); ImageView prodImage; TextView prodName; EditText prodRate = null; EditText prodQty = null; EditText prodDisc = null; /** For every time add new row in Table Layout **/ productTable.removeAllViews(); rowid = 0; int catid = 0; while (productCursor.moveToNext()) { final View childView = inflater.inflate(R.layout.list_product_view, null); row = new TableRow(context); catid = productCursor.getInt(productCursor.getColumnIndex(DatabaseHelper.PRODUCT_CATEGORY_ID)); int concatid = Integer.parseInt(catid+""+rowid++); row.setId(concatid); row.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); double productRateValue; double productDiscountValue; productRateValue = productCursor.getDouble(productCursor.getColumnIndex("rate")); productDiscountValue = productCursor.getDouble(productCursor.getColumnIndex("discount")); /*** Image ***/ prodImage = (ImageView) childView.findViewById(R.id.productImage); String path = productCursor.getString(productCursor.getColumnIndex(DatabaseHelper.PRODUCT_IMAGES)); mImageLoader.DisplayImage(path, prodImage); prodName = (TextView) childView.findViewById(R.id.productName); prodName.setText(productCursor.getString(productCursor.getColumnIndex(DatabaseHelper.PRODUCT_NAME))); prodQty = (EditText) childView.findViewById(R.id.productQuantityValue); prodQty.setText(""); prodRate = (EditText) childView.findViewById(R.id.productRateValue); prodRate.setText(String.valueOf(productRateValue)); prodDisc = (EditText) childView.findViewById(R.id.productDiscountValue); prodDisc.setText(String.valueOf(productDiscountValue)); prodRate.setFocusable(isRateEditable); prodRate.setEnabled(isRateEditable); prodDisc.setFocusable(isDiscountEditable); prodDisc.setEnabled(isDiscountEditable); row.addView(childView); productTable.addView(row); if(productSharedPref.getBoolean("saved", false)) { View rowView = productTable.findViewById(concatid); String prodRatePrefValue = productSharedPref.getString("rate"+concatid, ""); String prodQtyPrefValue = productSharedPref.getString("qty"+concatid, ""); String prodDiscPrefValue = productSharedPref.getString("discount"+concatid, ""); if(!prodQtyPrefValue.equals("") || prodQtyPrefValue != null) ((EditText)rowView.findViewById(R.id.productQuantityValue)).setText(prodQtyPrefValue); if(!prodRatePrefValue.equals("")) ((EditText)rowView.findViewById(R.id.productRateValue)).setText(prodRatePrefValue); if(!prodDiscPrefValue.equals("")) ((EditText)rowView.findViewById(R.id.productDiscountValue)).setText(prodDiscPrefValue); } } How to reduce this time. Please Help.
You can use async task.....what it does is loads a few items and displays the screen...and then it will keep updating the list with the new items,when they are processed