I have google this and searched here but I have hit a wall.
I have a function which is to return an Int. It tells me I need to add another return expression to the overall function but I can't figure out where it needs to go to be done correctly, i have tried a few variations including adding the same return I use within the if statements but before the closing tag which throws up errors within the rest of the code
I call the function like this;
var ans = GetQuestion(1)
fun GetQuestion(cat:Int): Int {
val btn1 = findViewById(R.id.button1) as Button
val btn2 = findViewById(R.id.button2) as Button
val btn3 = findViewById(R.id.button3) as Button
val btn4 = findViewById(R.id.button4) as Button
btn1.setVisibility(View.VISIBLE)
btn2.setVisibility(View.VISIBLE)
btn3.setVisibility(View.VISIBLE)
btn4.setVisibility(View.VISIBLE)
val initialimageview = findViewById(R.id.imageview_Qresponse) as ImageView
initialimageview.setBackgroundResource(R.drawable.question_2);
val viewQ = findViewById(R.id.textview_question) as TextView
if (cat==1) { // Multiplication
var a = rand(5,80)
var b = rand(2,50)
val ans = a * b
var opType = " X "
viewQ.text = ("" + a + " " + opType + " " + b + "?");
val listOfAns = mutableListOf(ans,ans-a,ans-b,ans+a)
listOfAns.shuffle()
btn1.text=("" + listOfAns.elementAt(0))
btn2.text=("" + listOfAns.elementAt(1))
btn3.text=("" + listOfAns.elementAt(2))
btn4.text=("" + listOfAns.elementAt(3))
return ans
listOfAns.clear()
}
if (cat==2) { // Addition
var a = rand(5,250)
var b = rand(2,140)
val ans = a + b
var opType = " + "
viewQ.text = ("" + a + " " + opType + " " + b + "?");
val listOfAns = mutableListOf(ans,ans+rand(2,4),ans+rand(5,10),ans-rand(2,10))
listOfAns.shuffle()
btn1.text=("" + listOfAns.elementAt(0))
btn2.text=("" + listOfAns.elementAt(1))
btn3.text=("" + listOfAns.elementAt(2))
btn4.text=("" + listOfAns.elementAt(3))
return ans
listOfAns.clear()
}
if (cat==3) { // Subtraction
var a = rand(80,150)
var b = rand(2,79)
var ans = a - b
var opType = " - "
viewQ.text = ("" + a + " " + opType + " " + b + "?");
val listOfAns = mutableListOf(ans,ans+rand(2,5),ans+rand(6,10),ans-rand(2,10))
listOfAns.shuffle()
btn1.text=("" + listOfAns.elementAt(0))
btn2.text=("" + listOfAns.elementAt(1))
btn3.text=("" + listOfAns.elementAt(2))
btn4.text=("" + listOfAns.elementAt(3))
return ans
listOfAns.clear()
}
if (cat==4) { // Division
var safedivision = rand(3,16)
var b = rand(2,20)
var a = b * safedivision
var ans = a / b
var opType = " / "
viewQ.text = ("" + a + " " + opType + " " + b + "?");
val listOfAns = mutableListOf(ans,ans+rand(2,5),ans+rand(6,10),ans-rand(2,10))
listOfAns.shuffle()
btn1.text=("" + listOfAns.elementAt(0))
btn2.text=("" + listOfAns.elementAt(1))
btn3.text=("" + listOfAns.elementAt(2))
btn4.text=("" + listOfAns.elementAt(3))
return ans
listOfAns.clear()
}
}
As a side note I wasn't sure if I have to use var of val when writing var ans = GetQuestion(1) however both methods throw up the same return error so I can amend that later if required
You can keep variable ans at the top of the function as below -
var ans = 0
and replace val ans from the all if conditions with ans. Before the last }
add return statement
return ans
If your function body doesn't have return keyword, then both sides of if-else must have return in them, for example:
fun dummyFunc(Int a):Int{
if (a > 0){
return 5
}else{
return -5
}
}
In this case, you don't need to add another return at the end of your code. But in your code, you don't have else block, so either you will do like the above answer by Priyanka Rajput or you will ad else statement. And after all, your code has reused code in if blocks, you can extract them and add after all the ifs you have written:
fun GetQuestion(cat:Int): Int {
val btn1 = findViewById(R.id.button1) as Button
val btn2 = findViewById(R.id.button2) as Button
val btn3 = findViewById(R.id.button3) as Button
val btn4 = findViewById(R.id.button4) as Button
btn1.setVisibility(View.VISIBLE)
btn2.setVisibility(View.VISIBLE)
btn3.setVisibility(View.VISIBLE)
btn4.setVisibility(View.VISIBLE)
val initialimageview = findViewById(R.id.imageview_Qresponse) as ImageView
initialimageview.setBackgroundResource(R.drawable.question_2);
val viewQ = findViewById(R.id.textview_question) as TextView
var a = 0
var b = 0
var ans = 0
var opType = ""
var viewQText = ""
var listOfAns = mutableListOf()
if (cat==1) { // Multiplication
var a = rand(5,80)
var b = rand(2,50)
val ans = a * b
var opType = " X "
viewQText = ("" + a + " " + opType + " " + b + "?");
val listOfAns = mutableListOf(ans,ans-a,ans-b,ans+a)
}
if (cat==2) { // Addition
a = rand(5,250)
b = rand(2,140)
ans = a + b
opType = " + "
viewQText = ("" + a + " " + opType + " " + b + "?");
listOfAns = mutableListOf(ans,ans+rand(2,4),ans+rand(5,10),ans-rand(2,10))
}
if (cat==3) { // Subtraction
a = rand(80,150)
b = rand(2,79)
ans = a - b
opType = " - "
viewQText = ("" + a + " " + opType + " " + b + "?");
listOfAns = mutableListOf(ans,ans+rand(2,5),ans+rand(6,10),ans-rand(2,10))
}
if (cat==4) { // Division
safedivision = rand(3,16)
b = rand(2,20)
a = b * safedivision
ans = a / b
opType = " / "
viewQText = ("" + a + " " + opType + " " + b + "?");
listOfAns = mutableListOf(ans,ans+rand(2,5),ans+rand(6,10),ans-rand(2,10))
}
viewQ.text = viewQText
listOfAns.shuffle()
btn1.text=("" + listOfAns.elementAt(0))
btn2.text=("" + listOfAns.elementAt(1))
btn3.text=("" + listOfAns.elementAt(2))
btn4.text=("" + listOfAns.elementAt(3))
return ans
listOfAns.clear()
}
While doing this, I have realized that you have a lot of style and coding problems. First, you mustn't call findViewById method too much, it's expensive. You must declare your Views as global variables and initialize them in your onCreate method. Second, you don't use listOfAns, maybe you have other plans for it, you will later use, I don't know, but all I know is, your code runs till the line with return keyword, which means listofAns.clear() will not be executed. And it would be better if you used when instead of if-else
Related
After Reading from a Gatt Characteristic i have a Problem getting the right Float Value from Result (part).
The Result for Measurement is a 4 byte value (result1-4), represented as single-precision0
floating point number (IEEE 754-2008)
This is my Function:
private fun getMeasurementData(data: ByteArray?, results: Int?) {
mDebugInfo!!.append("Read Measurements!\n")
if (data != null && results != null && results > 0) {
var r = results
var i = 1
while (r > 0) {
var resultId1 = data[i]
var resultId2 = data[i + 1]
var measureType = data[i + 2]
var measureStatus = data[i + 3]
var datetime1 = data[i + 4]
var datetime2 = data[i + 5]
var datetime3 = data[i + 6]
var datetime4 = data[i + 7]
var result1 = data[i + 8]
var result2 = data[i + 9]
var result3 = data[i + 10]
var result4 = data[i + 11]
val bytes = byteArrayOf(result1, result2, result3, result4)
val buffer = ByteBuffer.wrap(bytes, 0, 4).order(ByteOrder.LITTLE_ENDIAN)
val float = buffer.getFloat()
mDebugInfo!!.append(resultId1.toString() + " | " + resultId2.toString() + " | " + measureType.toString() + " | " + measureStatus.toString() + " | " + datetime1.toString() + " | " + datetime2.toString() + " | " + datetime3.toString() + " | " + datetime4.toString() + " | " + result1.toString() + " | " + result2.toString() + " | " + result3.toString() + " | " + result4.toString() + float +"\n")
i = i + 16
r--
}
}
}
The Output (mDebugInfo) from Byte.toString of result 1-4 & val float is:
result1
result2
result3
result4
float from ByteBuffer
96
-14
-13
-14
647.5922785
The right Value for Measurement is 7.59 - this Value is "included" in the float Result: 647.59 22785
How do I get this value only?
This Solution works for me:
var resultBytes = byteArrayOf(result4, result3, result2, result1)
private fun getMeasurementValue(ba: ByteArray): String {
var resultHex = ba.toHexString()
var iRes = resultHex.toLong(16)
var fRes = java.lang.Float.intBitsToFloat(iRes.toInt()) // This is the FLOAT Value (fRes)
return String.format("%.2f", fRes)
}
having js function in string:
val strFormat_elmLocation = "(function() { \n" +
"var elementId = '%s';\n" +
"try {\n" +
" var elm = document.getElementById(elementId);\n" +
" var width = window.innerWidth;\n" +
" var height = window.innerHeight;\n" +
"\n" +
" var rect = document.getElementById(elm.id).getBoundingClientRect();\n" +
"\n" +
// here it returns seems a json object,
// but in the evaluateJavascript's callback it receives a string,
// how does it work?
" return {\n" +
" 'elmId': elm.id,\n" +
" 'left': Math.floor(rect.left),\n" +
" 'top': Math.floor(rect.top),\n" +
" 'width': Math.floor(width),\n" +
" 'height': Math.floor(height)\n" +
" };\n" +
"} catch (e) {\n" +
"}\n" +
"return '';})()"
private fun doEvaluateJavascript(webview: WebView, elementId: String) {
val strJs = String.format(strFormat_elmLocation, elementId)
webview.evaluateJavascript(strJs) { data -> // data returned from javascript, here it is a string, not json object ??
if (!data.isNullOrBlank() && data.isNotEmpty()) {
try {
val obj: JSONObject = JSONObject(data)
val moduleId = obj.optString("elmId")
val left = obj.optInt("left")
val top = obj.optInt("top")
val htmlWindowWidth = obj.optInt("width")
val htmlWindowHeight = obj.optInt("height")
// do something
} catch (ex: Throwable) {
}
}
}
}
the evaluateJavascript is as below and the callback interface is taking a String.
public void evaluateJavascript(String script, #Nullable ValueCallback<String> resultCallback) {
throw new RuntimeException("Stub!");
}
How does the javascript returns a json object but a string is received in the callback?
this post may help:
The main thing to note is that the String returned in OnReceiveValue is either a JSON Value, JSON Object or JSON Array depending on what you return.
Things to note about this is if you return a single value, you need to use setLenient(true) on a JSON reader for it to work.
and
The method also handles Javascript objects:
webView1.evaluateJavascript("(function() { return { var1: \"variable1\", var2: \"variable2\" }; })();", new ValueCallback<String>() {
#Override
public void onReceiveValue(String s) {
Log.d("LogName", s); // Prints: {"var1":"variable1","var2":"variable2"}
}
});
I am new to Android. I am creating a native MobilePOS Android application for printng by using Bluetooth. This is my code:
private void showandadd() {
/*String num="";
num=num+String.valueOf(number);*/
String string1="";
String string2="";
String string3="";
if(num==""){
Toast.makeText(this,"Wrong input!! try again", Toast.LENGTH_LONG).show();
}
if(flag==1) {
getItem(directadd);
if(blankflag!=1) {
int updatedPrice = Integer.parseInt(this.price);
int data = Integer.parseInt(this.num);
if(data==0){
Toast.makeText(this,"Wrong input!! insert different quantity number", Toast.LENGTH_LONG).show();
}else {
int d = updatedPrice * data;
this.price = d + "";
// String str = itemName + " \t" + num + " No" + " \t" + "Rs " + price;
printdetailsnew.add(itemName);
quantitynum.add(num);
amount.add(price);
num = "";
directadd = "";
flag = 0;
blankflag = 0;
}
}
num = "";
directadd = "";
flag = 0;
blankflag = 0;
}else {
getItem(directadd);
if(blankflag!=1) {
//String str = itemName + " \t" + num + " No" + " \t" + "Rs " + price;
printdetailsnew.add(itemName);
quantitynum.add("1");
amount.add(price);
num = "";
}
directadd="";
blankflag=0;
}
for(int i=0;i<printdetailsnew.size();i++){
string1=string1+ printdetailsnew.get(i)+"\t"+"\n";
string2=string2 +"No."+ quantitynum.get(i)+"\t"+"\n";
string3= string3 + amount.get(i)+"\n";
result = printdetailsnew.get(i)+"\t" + "No."+ quantitynum.get(i)+"\t"+ amount.get(i)+"\n";
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"+result);
}
this.selection.setText(string1);
this.selection2.setText(string2);
this.selection3.setText(string3);
num="";
}
There are 3 strings assigned to result.
I am getting result twice when I am press second item.
when I am select first item getting "Itemname Quantity ampount" format like
Tea 1qty 10rs...when I enter second item output will came first item+first item+second item show like this:
Tea 1qty 10rs
Tea 1qty 10rs
Coffee 1qty 12rs
I want to get result
Tea 1qty 10rs
Coffee 1qty 12rs
like this...please any one can help me
A simple example would be to use one label and append to it each time you add a new item.
Instead of this:
for(int i=0;i<printdetailsnew.size();i++){
string1=string1+ printdetailsnew.get(i)+"\t"+"\n";
string2=string2 +"No."+ quantitynum.get(i)+"\t"+"\n";
string3= string3 + amount.get(i)+"\n";
result = printdetailsnew.get(i)+"\t" + "No."+ quantitynum.get(i)+"\t"+ amount.get(i)+"\n";
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"+result);
}
this.selection.setText(string1);
this.selection2.setText(string2);
this.selection3.setText(string3);
num="";
Change it to this:
str = this.selection.getText().toString();
str += printdetailsnew.get(i)+"\t" + "No."+ quantitynum.get(i)+"\t"+ amount.get(i)+"\n";
this.selection.setText(str);
num="";
code :
editor.putString("linkid",a);
editor.apply();
final Intent intent1 = new Intent(getActivity(), thirdreq.class);
startActivity(intent1);
for(int d=0;d<Integer.valueOf(dcountpeople[myid]);d++){
did2[d] = pref.getString("did2" + "[" + d + "]",null);
dformname2[d] = pref.getString("dformname2" + "[" + d + "]", null);
dregdate2[d] = pref.getString("dregdate2" + "[" + d + "]", null);
Log.i("Res:", did2[d] + ":" + dformname2[d] + ":" + dregdate2[d]);
txtshowpeoplearray[d].setVisibility(View.VISIBLE);
txtpeopleshowdatearray[d].setVisibility(View.VISIBLE);
btnpeopleviewarray[d].setVisibility(View.VISIBLE);
btnpeopledeletearray[d].setVisibility(View.VISIBLE);
txtshowpeoplearray[d].setText(dformname2[d]);
txtpeopleshowdatearray[d].setText(dregdate2[d]);
}
these codes into a Button click listener and
pref.getstrings works Properly when runs for 2 times(button clicked for 2 times) !
This is the code i am using to retreive a list of searched videos using the youtube data api.
if(detailed) {
YouTubeMediaGroup mediaGroup = videoEntry.getMediaGroup();
System.out.println("Uploaded by: " + mediaGroup.getUploader());
System.out.println("Video ID: " + mediaGroup.getVideoId());
System.out.println("Description: " +
mediaGroup.getDescription().getPlainTextContent());
MediaPlayer mediaPlayer = mediaGroup.getPlayer();
System.out.println("Web Player URL: " + mediaPlayer.getUrl());
MediaKeywords keywords = mediaGroup.getKeywords();
System.out.print("Keywords: ");
for(String keyword : keywords.getKeywords()) {
System.out.print(keyword + ",");
}
GeoRssWhere location = videoEntry.getGeoCoordinates();
if(location != null) {
System.out.println("Latitude: " + location.getLatitude());
System.out.println("Longitude: " + location.getLongitude());
}
Rating rating = videoEntry.getRating();
if(rating != null) {
System.out.println("Average rating: " + rating.getAverage());
}
YtStatistics stats = videoEntry.getStatistics();
if(stats != null ) {
System.out.println("View count: " + stats.getViewCount());
}
System.out.println();
System.out.println("\tThumbnails:");
for(MediaThumbnail mediaThumbnail : mediaGroup.getThumbnails()) {
System.out.println("\t\tThumbnail URL: " + mediaThumbnail.getUrl());
System.out.println("\t\tThumbnail Time Index: " +
mediaThumbnail.getTime());
System.out.println();
}
How could i convert this information to the use of a text view for the title, a ImageView for the thumbnail??