Related
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
I want to get a text(Multi-line) from Edittext same as given Screenshot.
I want below output when getText() from Edittext.
Output:
Lorem Ipsum is simply dummy
text of the printing and
typesetting industry. Lorem
Ipsum has been the industry
standard dummy text.
I have tried below solution but, it doesn't work
etMessage.getText().toString().replaceAll("\\n", "<br />")
By default all the EditText widgets in Android are multi-lined. And you can configure the number of lines and the characters types. By setting the input type to multiline do the trick.
<EditText
...
android:inputType="textMultiLine" <!-- Multiline input -->
...
android:lines="8" <!-- Total Lines prior display -->
android:minLines="6" <!-- Minimum lines -->
android:gravity="top|left" <!-- Cursor Position -->
android:maxLines="10" <!-- Maximum Lines -->
android:layout_height="wrap_content" <!-- Height determined by content -->
android:layout_width="match_parent" <!-- Fill entire width -->
android:scrollbars="vertical" <!-- Vertical Scroll Bar -->
/>
After too much searching and waiting for an answer to this question. I have resolved this issue.
Solution:
I have measured each and every line & words for preserve this as Multiline text, you can use below function for that.
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
float density = metrics.density;
String result = fitString(ipText, ipText.getText().toString());
private String fitString(EditText editText, String message) {
Log.i(TAG, "fitString: Default String : " + message);
StringBuilder finalMessage = new StringBuilder();
if (isTooLarge(editText, message)) {
Log.i(TAG, "fitString: isTooLarge 1 : " + true);
List<String> lineList = Arrays.asList(message.split("\n"));
Log.i(TAG, "fitString: stringList" + lineList);
if (lineList != null && lineList.size() > 0) {
for (int i = 0; i < lineList.size(); i++) {
if (lineList.get(i) != null && !lineList.get(i).isEmpty()) {
if (isTooLarge(editText, lineList.get(i))) {
Log.i(TAG, "fitString: isTooLarge 2 : " + lineList.get(i) + " == " + true);
List<String> wordList = Arrays.asList(lineList.get(i).split(" "));
Log.i(TAG, "fitString: wordList" + wordList);
if (wordList != null && wordList.size() > 0) {
Log.i(TAG, "fitString: wordList : " + wordList.size());
StringBuilder temp = new StringBuilder();
String lastWord = "";
for (int j = 0; j < wordList.size(); j++) {
if (wordList.get(j) != null && !wordList.get(j).isEmpty()) {
if (isTooLarge(editText, wordList.get(j))) {
Log.i(TAG, "fitString: isTooLarge 3 : " + wordList.get(j) + " == " + true);
String newString = fitCharacter(editText, wordList.get(j));
Log.i(TAG, "fitString: fitCharacter == " + newString);
if (j == (wordList.size() - 1) && i == (lineList.size() - 1)) {
finalMessage.append(newString);
} else {
finalMessage.append(newString + "\n");
}
} else {
if (j == 0) {
lastWord = wordList.get(j);
} else {
lastWord = " " + wordList.get(j);
}
temp.append(lastWord);
Log.i(TAG, "fitString: temp : " + temp);
Log.i(TAG, "fitString: lastWord : " + lastWord);
if (isTooLarge(editText, temp.toString())) {
temp.setLength(0); // clear String Builder, new StringBuilder()
temp.append(lastWord);
if (j == (wordList.size() - 1) && i != (lineList.size() - 1)) {
Log.i(TAG, "fitString: ###### 1");
finalMessage.append("\n" + lastWord.trim() + "\n");
} else {
Log.i(TAG, "fitString: ###### 2");
finalMessage.append("\n" + lastWord.trim());
}
} else {
if (j == (wordList.size() - 1) && i != (lineList.size() - 1)) {
Log.i(TAG, "fitString: ###### 3");
finalMessage.append(lastWord + "\n");
} else {
Log.i(TAG, "fitString: ###### 4");
finalMessage.append(lastWord);
}
}
Log.i(TAG, "fitString: finalMessage : " + finalMessage);
}
} else {
Log.e(TAG, "fitString: Word is Null or Empty.");
finalMessage.append(" ");
}
}
} else {
Log.e(TAG, "fitString: wordList is Null or Empty.");
}
} else {
Log.i(TAG, "fitString: isTooLarge 2 : " + lineList.get(i) + " == " + false);
if (i == (lineList.size() - 1)) {
finalMessage.append(lineList.get(i));
} else {
finalMessage.append(lineList.get(i) + "\n");
}
}
} else {
Log.e(TAG, "fitString: Line is Null or Empty.");
finalMessage.append(lineList.get(i) + "\n");
}
}
} else {
Log.e(TAG, "fitString: stringList is Null or Empty.");
finalMessage.append("");
}
return finalMessage.toString();
} else {
Log.i(TAG, "fitString: isTooLarge : " + false);
return message;
}
}
public String fitCharacter(EditText editText, String message) {
Log.i(TAG, "fitCharacter2: Default Word : " + message);
StringBuilder finalWord = new StringBuilder();
int startIndex = 0;
int endIndex = 1;
for (; ; ) {
String tempSplitWord = message.substring(startIndex, endIndex);
Log.i(TAG, "fitCharacter2: startIndex : " + startIndex + " endIndex : " + endIndex + " tempSplitWord : " + tempSplitWord);
if (!isTooLarge(editText, tempSplitWord)) { // isTooLarge
if (endIndex < message.length()) {
endIndex = endIndex + 1;
Log.i(TAG, "IF fitCharacter2: endIndex < message.length() " + endIndex + " < " + message.length());
} else {
String result = finalWord.append(tempSplitWord).toString();
Log.i(TAG, "IF RETURN RESULT : " + result);
return result;
}
} else {
endIndex = endIndex - 1;
String splitWord = message.substring(startIndex, endIndex);
Log.i(TAG, "ELSE fitCharacter2: startIndex : " + startIndex + " endIndex : " + endIndex + " splitWord : " + splitWord);
boolean isTooLarge = isTooLarge(editText, splitWord);
if (!isTooLarge) {
finalWord.append(splitWord + "\n");
}
startIndex = endIndex;
endIndex = endIndex + 1;
Log.i(TAG, "ELSE fitCharacter2: startIndex : " + startIndex + " endIndex : " + endIndex);
}
}
}
private boolean isTooLarge(EditText editText, String newText) {
if (editText != null && editText.getPaint() != null) {
float textWidth = editText.getPaint().measureText(newText);
return (textWidth >= (editText.getMeasuredWidth() - (12 * density))); // editText.getMeasuredWidth();
} else {
return false;
}
}
For next comers, I find the accepted answer overcomplicated for the task. Here is a nice extension code in Kotlin that uses Paint.breakText(). That said, it can probably be simplified further...
fun EditText.getMultilineText(): String {
val maxWidth = (width - paddingLeft - paddingRight).toFloat()
val original = text.toString().trim()
val len = original.length
val multiline = mutableListOf<String>()
var p = 0
var count = -1
while (count != 0) {
count = paint.breakText(original, p, len, true, maxWidth, null)
if (p + count < len) {
var tmp = count
while (tmp > 0 && original[p + tmp - 1] != ' ') {
tmp -= 1
}
if (tmp > 0) {
count = tmp
}
}
val tmp = original.substring(p, p + count).trim()
if (tmp.isNotBlank()) {
multiline.add(tmp)
}
p += count
}
return multiline.joinToString("\r\n")
}
did you try this one
message = etMessage.getText().toString().replaceAll("\\n", "<br />")
please see this also How can I preserve line breaks from EditText?
Hi in the below am not getting any response from server. I am localhost ip address it is not taking.
I am trying to check my ipconfig and using local ip address and not working
I am getting the error while calling an api gateway.
if condition only checking and else condition is not working
I/>>>SchedulerActivity: Sending---http://192.168.0.30retrofit2.Retrofit$1#b357456
light_id:01
intensity:android.support.v7.widget.AppCompatTextView{1fb8ecd7 V.ED.... ........ 30,0-41,28 #7f08010f app:id/txt_bottom61}
cct:8
W/System.err: java.net.ConnectException: Failed to connect to /192.168.0.30:80
W/System.err: at okhttp3.internal.io.RealConnection.connectSocket(RealConnection.java:187)
at okhttp3.internal.io.RealConnection.buildConnection(RealConnection.java:170)
at okhttp3.internal.io.RealConnection.connect(RealConnection.java:111)
at okhttp3.internal.http.StreamAllocation.findConnection(StreamAllocation.java:187)
at okhttp3.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:123)
at okhttp3.internal.http.StreamAllocation.newStream(StreamAllocation.java:93)
at okhttp3.internal.http.HttpEngine.connect(HttpEngine.java:296)
at okhttp3.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at okhttp3.RealCall.getResponse(RealCall.java:243)
at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:201)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:163)
at okhttp3.RealCall.access$100(RealCall.java:30)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:127)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
private void getCCTAndIntensityValuesForPreset () {
url = "http://192.168.0.30:9000";
Retrofit retrofit = null;
Log.d("123", "retrofit");
if (retrofit == null) {
retrofit = new Retrofit.Builder().baseUrl(url).addConverterFactory(GsonConverterFactory.create()).build();
Log.d("123", "build();");
}
API1 service = retrofit.create(API1.class);
Call<GetScheduler> call = service.getSchedulerData();
Log.i(TAG, "Sending---" + url + service + "\n" + "light_id:" + lightid + "\n" + "intensity:" + dValue1 + "\n" + "cct:" + dayvalue3);
call.enqueue(new Callback<GetScheduler>() {
#Override
public void onResponse(Call<GetScheduler> call, Response<GetScheduler> response) {
if (response != null && response.isSuccessful()) {
String getLightId = response.body().getData().getLight_id();
if (getLightId == "00") {
simpleSwitch.setOn(false);
} else {
simpleSwitch.setOn(true);
}
Toast.makeText(getApplicationContext(), "Light Id" + getLightId, Toast.LENGTH_LONG).show();
//String light_id=response.body()
if(simpleSwitch1.isOn()){
int[] getIntensty = response.body().getData().getCct();
for (int i : getIntensty) {
if(dayvalue1==6){
mIntenisty1.setProgress(getIntensty[0]);
mIntensityTitle1.setText(getIntensty[0] + " %");
}
if(dayvalue2 == 7) {
mIntenisty2.setProgress(getIntensty[1]);
mIntensityTitle2.setText(getIntensty[1] + " %");
}if(dayvalue3==8){
mIntenisty3.setProgress(getIntensty[2]);
mIntensityTitle3.setText(getIntensty[2] + " %");
}
if(dayvalue4==9){
mIntenisty4.setProgress(getIntensty[3]);
mIntensityTitle4.setText(getIntensty[3] + " %");
}
if(dayvalue5==10){
mIntenisty5.setProgress(getIntensty[4]);
mIntensityTitle5.setText(getIntensty[4] + " %");
}
if(dayvalue6==11){
mIntenisty6.setProgress(getIntensty[5]);
mIntensityTitle6.setText(getIntensty[5] + " %");
}
if(dayvalue7==12){
mIntenisty7.setProgress(getIntensty[6]);
mIntensityTitle7.setText(getIntensty[6] + " %");
}
if(dayvalue8==13){
mIntenisty8.setProgress(getIntensty[7]);
mIntensityTitle8.setText(getIntensty[7] + " %");
}
if(dayvalue9==14){
mIntenisty9.setProgress(getIntensty[8]);
mIntensityTitle9.setText(getIntensty[8] + " %");
}
if(dayvalue10==15){
mIntenisty10.setProgress(getIntensty[9]);
mIntensityTitle10.setText(getIntensty[9] + " %");
}
if(dayvalue11==16){
mIntenisty11.setProgress(getIntensty[10]);
mIntensityTitle11.setText(getIntensty[10] + " %");
}
if(dayvalue12==17) {
mIntenisty12.setProgress(getIntensty[11]);
mIntensityTitle12.setText(getIntensty[11] + " %");
}
}
int[] getCCT = response.body().getData().getIntensity();
for (int i : getCCT) {
if (dayvalue1 == 6) {
mCCT1.setProgress(getCCT[0]);
mCCTTitle1.setText(getCCT[0] + " % ");
} if (dayvalue2 == 7) {
mCCT2.setProgress(getCCT[1]);
mCCTTitle2.setText(getCCT[1] + " % ");
} if (dayvalue3 == 8) {
mCCT3.setProgress(getCCT[2]);
mCCTTitle3.setText(getCCT[2] + " % ");
} if (dayvalue4 == 9) {
mCCT4.setProgress(getCCT[3]);
mCCTTitle4.setText(getCCT[3] + " % ");
} if (dayvalue5 == 10) {
mCCT5.setProgress(getCCT[4]);
mCCTTitle5.setText(getCCT[4] + " % ");
} if (dayvalue6 == 11) {
mCCT6.setProgress(getCCT[5]);
mCCTTitle6.setText(getCCT[5] + " % ");
} if (dayvalue7 == 12) {
mCCT7.setProgress(getCCT[6]);
mCCTTitle7.setText(getCCT[6] + " % ");
} if (dayvalue8 == 13) {
mCCT8.setProgress(getCCT[7]);
mCCTTitle8.setText(getCCT[7] + " % ");
} if (dayvalue9 == 14) {
mCCT9.setProgress(getCCT[8]);
mCCTTitle9.setText(getCCT[8] + " % ");
} if (dayvalue10 == 15) {
mCCT10.setProgress(getCCT[9]);
mCCTTitle10.setText(getCCT[9] + " % ");
} if (dayvalue11 == 16) {
mCCT11.setProgress(getCCT[10]);
mCCTTitle11.setText(getCCT[10] + " % ");
} if (dayvalue12 == 17) {
mCCT12.setProgress(getCCT[11]);
mCCTTitle12.setText(getCCT[11] + " % ");
}
}
}
else{
int[] getIntensty = response.body().getData().getCct();
for (int i : getIntensty) {
if(dayvalue1==18){
mIntenisty1.setProgress(getIntensty[0]);
mIntensityTitle1.setText(getIntensty[0] + " %");
}
if(dayvalue2 == 19) {
mIntenisty2.setProgress(getIntensty[1]);
mIntensityTitle2.setText(getIntensty[1] + " %");
}if(dayvalue3==20){
mIntenisty3.setProgress(getIntensty[2]);
mIntensityTitle3.setText(getIntensty[2] + " %");
}
if(dayvalue4==21){
mIntenisty4.setProgress(getIntensty[3]);
mIntensityTitle4.setText(getIntensty[3] + " %");
}
if(dayvalue5==22){
mIntenisty5.setProgress(getIntensty[4]);
mIntensityTitle5.setText(getIntensty[4] + " %");
}
if(dayvalue6==23){
mIntenisty6.setProgress(getIntensty[5]);
mIntensityTitle6.setText(getIntensty[5] + " %");
}
if(dayvalue7==24){
mIntenisty7.setProgress(getIntensty[6]);
mIntensityTitle7.setText(getIntensty[6] + " %");
}
if(dayvalue8==1){
mIntenisty8.setProgress(getIntensty[7]);
mIntensityTitle8.setText(getIntensty[7] + " %");
}
if(dayvalue9==2){
mIntenisty9.setProgress(getIntensty[8]);
mIntensityTitle9.setText(getIntensty[8] + " %");
}
if(dayvalue10==3){
mIntenisty10.setProgress(getIntensty[9]);
mIntensityTitle10.setText(getIntensty[9] + " %");
}
if(dayvalue11==4){
mIntenisty11.setProgress(getIntensty[10]);
mIntensityTitle11.setText(getIntensty[10] + " %");
}
if(dayvalue12==5) {
mIntenisty12.setProgress(getIntensty[11]);
mIntensityTitle12.setText(getIntensty[11] + " %");
}
}
int[] getCCT = response.body().getData().getIntensity();
for (int i : getCCT) {
if (dayvalue1 == 18) {
mCCT1.setProgress(getCCT[0]);
mCCTTitle1.setText(getCCT[0] + " % ");
} if (dayvalue2 == 19) {
mCCT2.setProgress(getCCT[1]);
mCCTTitle2.setText(getCCT[1] + " % ");
} if (dayvalue3 == 20) {
mCCT3.setProgress(getCCT[2]);
mCCTTitle3.setText(getCCT[2] + " % ");
} if (dayvalue4 == 21) {
mCCT4.setProgress(getCCT[3]);
mCCTTitle4.setText(getCCT[3] + " % ");
} if (dayvalue5 == 22) {
mCCT5.setProgress(getCCT[4]);
mCCTTitle5.setText(getCCT[4] + " % ");
} if (dayvalue6 == 23) {
mCCT6.setProgress(getCCT[5]);
mCCTTitle6.setText(getCCT[5] + " % ");
} if (dayvalue7 == 24) {
mCCT7.setProgress(getCCT[6]);
mCCTTitle7.setText(getCCT[6] + " % ");
} if (dayvalue8 == 1) {
mCCT8.setProgress(getCCT[7]);
mCCTTitle8.setText(getCCT[7] + " % ");
} if (dayvalue9 == 2) {
mCCT9.setProgress(getCCT[8]);
mCCTTitle9.setText(getCCT[8] + " % ");
} if (dayvalue10 == 3) {
mCCT10.setProgress(getCCT[9]);
mCCTTitle10.setText(getCCT[9] + " % ");
} if (dayvalue11 == 4) {
mCCT11.setProgress(getCCT[10]);
mCCTTitle11.setText(getCCT[10] + " % ");
} if (dayvalue12 == 5) {
mCCT12.setProgress(getCCT[11]);
mCCTTitle12.setText(getCCT[11] + " % ");
}
}
}
}
}
#Override
public void onFailure(Call<GetScheduler> call, Throwable t) {
t.printStackTrace();
}
});
}
If your server is running on localhost, you need to use the adress http://10.0.2.2 from your android code. Android Emulates a virtual machine, which is different from your regular day to day operating system, thus, it can not access the machine in a regular way. This address was reserved for the android os to communicate with your hosting os through localhost.
In my Android Project, I try to use Transform API and Javasist to make an AOP framework.
But some class is transformed to an empty class and then I got the build error :
/build/intermediates/transforms/jarMerging/debug/jars/1/1f/combined.jar] (Can't process class xxx/xxx/xxx/ABC.class
because the ABC.class get empty after javasist handle(I just load it with javasiit and then write back).
The code I write to modify class is :
public void weave(String path) {
println("Begin to weave androidClassPath = " + androidClassPath)
println("Begin to weave path = " + path)
pool.appendClassPath(path)
pool.appendClassPath(androidClassPath)
pool.importPackage("android.util.Log");
File dir = new File(path)
int indexOfPackage = path.length() + 1;
if (dir.isDirectory()) {
dir.eachFileRecurse { File file ->
String filePath = file.absolutePath
if (isWeavableClass(filePath)) {
println("Begin to inject filePath " + filePath)
int end = filePath.length() - 6 // .class = 6
String className = filePath.substring(indexOfPackage, end).replace(File.separator, '.')
CtClass clazz = pool.getCtClass(className)
if (clazz.isFrozen()) {
clazz.defrost()
}
boolean timeDebugClass = false;
boolean parameterDebugClass = false;
if(clazz.hasAnnotation(TimingDebug.class)) {
timeDebugClass = true;
}
if(clazz.hasAnnotation(ParameterDebug.class)) {
parameterDebugClass = true;
}
println "timeDebugClass = "+ timeDebugClass + " parameterDebugClass = " + parameterDebugClass
CtMethod[] methods = clazz.getDeclaredMethods();
for (CtMethod method : methods) {
boolean emptyMethod = method.isEmpty()
boolean isNativeMethod = Modifier.isNative(method.getModifiers());
println("method name = " + method + " emptyMethod " + emptyMethod + " isNativeMethod = " + isNativeMethod)
if (!emptyMethod && !isNativeMethod) {
if (method.hasAnnotation(ParameterDebug.class) || parameterDebugClass) {
weaveParameterDebugMethod(clazz, method)
}
if (method.hasAnnotation(TimingDebug.class) || timeDebugClass) {
weaveTimingDebugMethod(clazz, method)
}
}
}
CtConstructor[] constructors = clazz.getDeclaredConstructors();
for(CtConstructor constructor: constructors){
boolean emptyMethod = constructor.isEmpty()
println("constructor name = " + constructor + " emptyMethod " + emptyMethod)
if (!emptyMethod) {
if (constructor.hasAnnotation(ParameterDebug.class) || parameterDebugClass) {
weaveParameterDebugMethod(clazz, constructor)
}
if (constructor.hasAnnotation(TimingDebug.class) || timeDebugClass) {
weaveTimingDebugMethod(clazz, constructor)
}
}
}
clazz.writeFile(path)
clazz.detach()
}
}
}
}
Im trying to display a div using the bootstrap collapse class. It works smoothly, but when I try to use the button on an iPhone, iPad or any other 'smart device', the div is not displayed.
Here is my code:
<button type="button" class="btn btn-primary facts-button" data-toggle="collapse" data-target="#watch-facts"> Lees meer </button>
<div id="watch-facts" class="collapse out extras-facts">
<ul>
<li>One.</li>
<li>Two and two again</li>
<li>3</li>
</ul>
</div>
When i disable this .js script, it seems to work on a mobile phone. Don't know where the problem is.
!function($){
$.support.transition = (function(){
var thisBody = document.body || document.documentElement,
thisStyle = thisBody.style,
support = thisStyle.transition !== undefined || thisStyle.WebkitTransition !== undefined || thisStyle.MozTransition !== undefined || thisStyle.MsTransition !== undefined || thisStyle.OTransition !== undefined;
return support;
})();
var defaults = {
sectionContainer: "section",
easing: "ease",
animationTime: 1000,
pagination: true,
updateURL: false,
keyboard: true,
beforeMove: null,
afterMove: null,
loop: false
};
$.fn.swipeEvents = function() {
return this.each(function() {
var startX,
startY,
$this = $(this);
$this.bind('touchstart', touchstart);
function touchstart(event) {
var touches = event.originalEvent.touches;
if (touches && touches.length) {
startX = touches[0].pageX;
startY = touches[0].pageY;
$this.bind('touchmove', touchmove);
}
event.preventDefault();
}
function touchmove(event) {
var touches = event.originalEvent.touches;
if (touches && touches.length) {
var deltaX = startX - touches[0].pageX;
var deltaY = startY - touches[0].pageY;
if (deltaX >= 50) {
$this.trigger("swipeLeft");
}
if (deltaX <= -50) {
$this.trigger("swipeRight");
}
if (deltaY >= 50) {
$this.trigger("swipeUp");
}
if (deltaY <= -50) {
$this.trigger("swipeDown");
}
if (Math.abs(deltaX) >= 50 || Math.abs(deltaY) >= 50) {
$this.unbind('touchmove', touchmove);
}
}
event.preventDefault();
}
});
};
$.fn.onepage_scroll = function(options){
var settings = $.extend({}, defaults, options),
el = $(this),
sections = $(settings.sectionContainer)
total = sections.length,
status = "off",
topPos = 0,
lastAnimation = 0,
quietPeriod = 500,
paginationList = "";
$.fn.transformPage = function(settings, pos, index) {
if ( ! $.support.transition ) {
$(this).animate({
'top': pos + '%'
},400);
return;
}
$(this).css({
"-webkit-transform": "translate3d(0, " + pos + "%, 0)",
"-webkit-transition": "all " + settings.animationTime + "ms " + settings.easing,
"-moz-transform": "translate3d(0, " + pos + "%, 0)",
"-moz-transition": "all " + settings.animationTime + "ms " + settings.easing,
"-ms-transform": "translate3d(0, " + pos + "%, 0)",
"-ms-transition": "all " + settings.animationTime + "ms " + settings.easing,
"transform": "translate3d(0, " + pos + "%, 0)",
"transition": "all " + settings.animationTime + "ms " + settings.easing
});
$(this).one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(e) {
if (typeof settings.afterMove == 'function') settings.afterMove(index);
});
}
$.fn.jumpTo = function(newIndex) {
var el = $(this)
index = $(settings.sectionContainer +".active").data("index");
current = $(settings.sectionContainer + "[data-index='" + index + "']");
next = $(settings.sectionContainer + "[data-index='" + (newIndex+1) + "']");
if(next.length < 1) {
if (settings.loop == true) {
pos = 0;
next = $(settings.sectionContainer + "[data-index='" + (newIndex) + "']");
} else {
return
}
}else {
pos = (newIndex * 100) * -1;
}
current.removeClass("active")
next.addClass("active");
if(settings.pagination == true) {
$(".onepage-pagination li a" + "[data-index='" + index + "']").removeClass("active");
$(".onepage-pagination li a" + "[data-index='" + next.data("index") + "']").addClass("active");
}
$("body")[0].className = $("body")[0].className.replace(/\bviewing-page-\d.*?\b/g, '');
$("body").addClass("viewing-page-"+next.data("index"))
if (history.replaceState && settings.updateURL == true) {
var href = window.location.href.substr(0,window.location.href.indexOf('#')) + "#" + (index + 1);
history.pushState( {}, document.title, href );
}
el.transformPage(settings, pos, newIndex);
}
$.fn.moveDown = function() {
var el = $(this)
index = $(settings.sectionContainer +".active").data("index");
current = $(settings.sectionContainer + "[data-index='" + index + "']");
next = $(settings.sectionContainer + "[data-index='" + (index + 1) + "']");
if(next.length < 1) {
if (settings.loop == true) {
pos = 0;
next = $(settings.sectionContainer + "[data-index='1']");
} else {
return
}
}else {
pos = (index * 100) * -1;
}
if (typeof settings.beforeMove == 'function') settings.beforeMove( current.data("index"));
current.removeClass("active")
next.addClass("active");
if(settings.pagination == true) {
$(".onepage-pagination li a" + "[data-index='" + index + "']").removeClass("active");
$(".onepage-pagination li a" + "[data-index='" + next.data("index") + "']").addClass("active");
}
$("body")[0].className = $("body")[0].className.replace(/\bviewing-page-\d.*?\b/g, '');
$("body").addClass("viewing-page-"+next.data("index"))
if (history.replaceState && settings.updateURL == true) {
var href = window.location.href.substr(0,window.location.href.indexOf('#')) + "#" + (index + 1);
history.pushState( {}, document.title, href );
}
el.transformPage(settings, pos, index);
}
$.fn.moveUp = function() {
var el = $(this)
index = $(settings.sectionContainer +".active").data("index");
current = $(settings.sectionContainer + "[data-index='" + index + "']");
next = $(settings.sectionContainer + "[data-index='" + (index - 1) + "']");
if(next.length < 1) {
if (settings.loop == true) {
pos = ((total - 1) * 100) * -1;
next = $(settings.sectionContainer + "[data-index='"+total+"']");
}
else {
return
}
}else {
pos = ((next.data("index") - 1) * 100) * -1;
}
if (typeof settings.beforeMove == 'function') settings.beforeMove(current.data("index"));
current.removeClass("active")
next.addClass("active")
if(settings.pagination == true) {
$(".onepage-pagination li a" + "[data-index='" + index + "']").removeClass("active");
$(".onepage-pagination li a" + "[data-index='" + next.data("index") + "']").addClass("active");
}
$("body")[0].className = $("body")[0].className.replace(/\bviewing-page-\d.*?\b/g, '');
$("body").addClass("viewing-page-"+next.data("index"))
if (history.replaceState && settings.updateURL == true) {
var href = window.location.href.substr(0,window.location.href.indexOf('#')) + "#" + (index - 1);
history.pushState( {}, document.title, href );
}
el.transformPage(settings, pos, index);
}
function init_scroll(event, delta) {
deltaOfInterest = delta;
var timeNow = new Date().getTime();
// Cancel scroll if currently animating or within quiet period
if(timeNow - lastAnimation < quietPeriod + settings.animationTime) {
event.preventDefault();
return;
}
if (deltaOfInterest < 0) {
el.moveDown()
} else {
el.moveUp()
}
lastAnimation = timeNow;
}
// Prepare everything before binding wheel scroll
el.addClass("onepage-wrapper").css("position","relative");
$.each( sections, function(i) {
$(this).css({
position: "absolute",
top: topPos + "%"
}).addClass("section").attr("data-index", i+1);
topPos = topPos + 100;
if(settings.pagination == true) {
paginationList += "<li><a data-index='"+(i+1)+"' href='#" + (i+1) + "'></a></li>"
}
});
el.swipeEvents().bind("swipeDown", function(){
el.moveUp();
}).bind("swipeUp", function(){
el.moveDown();
});
// Create Pagination and Display Them
if(settings.pagination == true) {
$("<ul class='nav navbar-nav navbar-right onepage-pagination'>" + paginationList + "</ul>").prependTo(".navbar-collapse");
posTop = (el.find(".onepage-pagination").height() / 2) * -1;
el.find(".onepage-pagination").css("margin-top", posTop);
}
if(window.location.hash != "" && window.location.hash != "#1") {
init_index = window.location.hash.replace("#", "")
$(settings.sectionContainer + "[data-index='" + init_index + "']").addClass("active")
$("body").addClass("viewing-page-"+ init_index)
if(settings.pagination == true) $(".onepage-pagination li a" + "[data-index='" + init_index + "']").addClass("active");
next = $(settings.sectionContainer + "[data-index='" + (init_index) + "']");
if(next) {
next.addClass("active")
if(settings.pagination == true) $(".onepage-pagination li a" + "[data-index='" + (init_index) + "']").addClass("active");
$("body")[0].className = $("body")[0].className.replace(/\bviewing-page-\d.*?\b/g, '');
$("body").addClass("viewing-page-"+next.data("index"))
if (history.replaceState && settings.updateURL == true) {
var href = window.location.href.substr(0,window.location.href.indexOf('#')) + "#" + (init_index);
history.pushState( {}, document.title, href );
}
}
pos = ((init_index - 1) * 100) * -1;
el.transformPage(settings, pos, init_index);
}else{
$(settings.sectionContainer + "[data-index='1']").addClass("active")
$("body").addClass("viewing-page-1")
if(settings.pagination == true) $(".onepage-pagination li a" + "[data-index='1']").addClass("active");
}
if(settings.pagination == true) {
$(".onepage-pagination li a").click(function (){
var page_index = $(this).data("index");
if (!$(this).hasClass("active")) {
current = $(settings.sectionContainer + ".active")
next = $(settings.sectionContainer + "[data-index='" + (page_index) + "']");
if(next) {
current.removeClass("active")
next.addClass("active")
$(".onepage-pagination li a" + ".active").removeClass("active");
$(".onepage-pagination li a" + "[data-index='" + (page_index) + "']").addClass("active");
$("body")[0].className = $("body")[0].className.replace(/\bviewing-page-\d.*?\b/g, '');
$("body").addClass("viewing-page-"+next.data("index"))
}
pos = ((page_index - 1) * 100) * -1;
el.transformPage(settings, pos, page_index);
}
if (settings.updateURL == false) return false;
});
}
$(document).bind('mousewheel DOMMouseScroll', function(event) {
event.preventDefault();
var delta = event.originalEvent.wheelDelta || -event.originalEvent.detail;
init_scroll(event, delta);
});
if(settings.keyboard == true) {
$(document).keydown(function(e) {
var tag = e.target.tagName.toLowerCase();
switch(e.which) {
case 38:
if (tag != 'input' && tag != 'textarea') el.moveUp()
break;
case 40:
if (tag != 'input' && tag != 'textarea') el.moveDown()
break;
default: return;
}
e.preventDefault();
});
}
return false;
}
}(window.jQuery);
Ahh finally. Now that I had your complete code. I could find the issue. :-)
I fetched all your website resources and assets locally on my machine and tested and the error seems to be due to this - event.preventDefault(); on the .js file you mentioned (onepage-scroll.js) on line number 54.
Explanation : event.preventDefault method is used to prevent(not trigger) the default action of the event is called within. Because of this the default action of your touch event on any tablet or smaller device will be prevented and hence did not work on native devices.
Answer : Remove the event.preventDefault(); from the touchstart function (line 54) and it should work just fine even in your native devices. Tested and it works fine.
Hope it helped.