I have been trying to solve this problem for 9 hours straight, but nothing seems to work. I am building an app that captures values for all the available sensors in an Android phone over a certain time period, and stores these values in a remote database.
Two things should be kept in mind:
Each sensor has its own capture frequency (i.e. accelerometer each 10 seconds, gyroscope each 5 seconds, proximity each 60 seconds etc...).
This process doesn't go indefinitely, so there is a variable called duration, that specifies the total time spent capturing values. For example, if acctime = 10 and duration = 60, then we'll end up with 7 values captured at the 0s, 10s, 20s, 30s, 40s, 50s and 60s marks.
OK now for the code:
public void onSensorChanged(SensorEvent event) {
Sensor s = event.sensor;
if (s.getType() == Sensor.TYPE_ACCELEROMETER)
{
acc1 = event.values[0];
acc2 = event.values[1];
acc3 = event.values[2];
accm = (float) Math.sqrt(acc1 * acc1 + acc2 * acc2 + acc3 * acc3);
}
}
In the code above, the values are stored into their respective variables successfully.
Next, I want to display these variables in a textview, and update the textview as specified before (according to the frequency and total duration):
public void capture(View view) {
DecimalFormat df = new DecimalFormat("#.###");
for (i = 0; i < duration; i++) {
if ((i+1) % acctime == 0) {
acc1 = Float.valueOf(df.format(acc1));
acc2 = Float.valueOf(df.format(acc2));
acc3 = Float.valueOf(df.format(acc3));
accm = Float.valueOf(df.format(accm));
acctext.setText("i: " + i + "\nAccelerometer:\n\nX: " + acc1
+ "\nY: " + acc2 + "\nZ: " + acc3 + "\nMagnitude: "
+ accm);
}
}
}
Here, the test if (i % acctime == 0) guarantees that the textview is updated whenever i is a multiple of acctime, which is precisely what we want: so for example if acctime = 10, the textview is updated when i = 0, 10, 20, 30, 40, 50 and 60.
However, for the life of me, I couldn't figure out how pause the loop for 1 second before proceeding (assign to i a time value of 1 second means that the loop makes sense, going from 0 to duration), so all that's left is pause the loop for 1 second.
I tried Thread.Sleep(1000) between a try/catch block, but it didn't work (it crashed).
The same happened for android.os.SystemClock.sleep(1000); .
I also found some code that looks like
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//insert code here
}
}, 1000);
Either it didn't work, or I am implementing something incorrectly.
Please, any help would be greatly appreciated.
Below is the full version of the function, and it's the version that makes sense the most to me. Please point out any errors that you can find:
public void capture(View view) {
DecimalFormat df = new DecimalFormat("#.###");
int i = 1;
while (i <= duration) {
if (acctime != -1 && (i % acctime == 0 || i == 1)) {
acc1 = Float.valueOf(df.format(acc1));
acc2 = Float.valueOf(df.format(acc2));
acc3 = Float.valueOf(df.format(acc3));
accm = Float.valueOf(df.format(accm));
acctext.setText("Accelerometer:\n\nX: " + acc1 + "\nY: " + acc2
+ "\nZ: " + acc3 + "\nMagnitude: " + accm);
}
if (magtime != -1 && (i % magtime == 0 || i == 1)) {
mag1 = Float.valueOf(df.format(mag1));
mag2 = Float.valueOf(df.format(mag2));
mag3 = Float.valueOf(df.format(mag3));
magm = Float.valueOf(df.format(magm));
magtext.setText("Magnetometer\n\nX: " + mag1 + "\nY: " + mag2
+ "\nZ: " + mag3 + "\nMagnitude: " + magm);
}
if (proxtime != -1 && (i % proxtime == 0 || i == 1)) {
prox = Float.valueOf(df.format(prox));
proxtext.setText("Proximity\n\nMagnitude: " + prox);
}
if (lighttime != -1 && (i % lighttime == 0 || i == 1)) {
light = Float.valueOf(df.format(light));
lighttext.setText("Light:\n\nMagnitude: " + light);
}
if (presstime != -1 && (i % presstime == 0 || i == 1)) {
pressure = Float.valueOf(df.format(pressure));
presstext.setText("Pressure:\n\nMagnitude: " + pressure);
}
if (gyrotime != -1 && (i % gyrotime == 0 || i == 1)) {
gyro1 = Float.valueOf(df.format(gyro1));
gyro2 = Float.valueOf(df.format(gyro2));
gyro3 = Float.valueOf(df.format(gyro3));
gyrom = Float.valueOf(df.format(gyrom));
gyrotext.setText("Gyroscope:\n\nX: " + gyro1 + "\nY: " + gyro2
+ "\nZ: " + gyro3 + "\nMagnitude: " + gyrom);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i++;
}
}
Apply Handler as follows to delay for 1sec.
int i = 1;
public void capture(View view) {
final DecimalFormat df = new DecimalFormat("#.###");
Handler handler = new Handler();
while (i <= duration) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (acctime != -1 && (i % acctime == 0 || i == 1)) {
acc1 = Float.valueOf(df.format(acc1));
acc2 = Float.valueOf(df.format(acc2));
acc3 = Float.valueOf(df.format(acc3));
accm = Float.valueOf(df.format(accm));
acctext.setText("Accelerometer:\n\nX: " + acc1
+ "\nY: " + acc2 + "\nZ: " + acc3
+ "\nMagnitude: " + accm);
}
if (magtime != -1 && (i % magtime == 0 || i == 1)) {
mag1 = Float.valueOf(df.format(mag1));
mag2 = Float.valueOf(df.format(mag2));
mag3 = Float.valueOf(df.format(mag3));
magm = Float.valueOf(df.format(magm));
magtext.setText("Magnetometer\n\nX: " + mag1 + "\nY: "
+ mag2 + "\nZ: " + mag3 + "\nMagnitude: "
+ magm);
}
if (proxtime != -1 && (i % proxtime == 0 || i == 1)) {
prox = Float.valueOf(df.format(prox));
proxtext.setText("Proximity\n\nMagnitude: " + prox);
}
if (lighttime != -1 && (i % lighttime == 0 || i == 1)) {
light = Float.valueOf(df.format(light));
lighttext.setText("Light:\n\nMagnitude: " + light);
}
if (presstime != -1 && (i % presstime == 0 || i == 1)) {
pressure = Float.valueOf(df.format(pressure));
presstext
.setText("Pressure:\n\nMagnitude: " + pressure);
}
if (gyrotime != -1 && (i % gyrotime == 0 || i == 1)) {
gyro1 = Float.valueOf(df.format(gyro1));
gyro2 = Float.valueOf(df.format(gyro2));
gyro3 = Float.valueOf(df.format(gyro3));
gyrom = Float.valueOf(df.format(gyrom));
gyrotext.setText("Gyroscope:\n\nX: " + gyro1 + "\nY: "
+ gyro2 + "\nZ: " + gyro3 + "\nMagnitude: "
+ gyrom);
}
i++;
}
}, 1000);
}
}
Related
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.
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.
I am able to draw a polyline from start position dynamically while driving or walking and i just need to calculate the speed of the current ride for certain intervals.
Please suggest me how to calculate the speed with GPS/Network services.
Speed: Distance traveled divided by the time of travel.
So to calculate the current speed, calculate the distance between the two last locations you've got (by Location.distanceTo()) and divide by the time needed for that distance, which is the difference of the time-stamps of the locations.
Or, simply use Location.getSpeed()
Check below code, done by me, and its working well. In this lots of code related your stuff, because I have did exactly same as your requirement. So you can use all the code given below. And if you find it unncessory, then dont use it.
#Override
public void onLocationChanged(Location location) {
try {
if (location != null) {
if (current_lat != null && current_lat > 0) {
latitude = current_lat;
}
if (current_long != null && current_long > 0) {
longitude = current_long;
}
current_lat = location.getLatitude();
current_long = location.getLongitude();
distanceBetweenTwoPoint = getDistance(latitude, longitude, current_lat, current_long);
if ((current_lat > 0 && current_long > 0) && distanceBetweenTwoPoint > IjoomerApplicationConfiguration.track_DistanceBetweenPoints_IN_METERS) {
if (location.hasSpeed()) {
speedInKm = location.getSpeed() * 3.6;
} else {
speedInKm = 0.0;
}
row = new HashMap<String, String>();
row.put(TRACKID, IN_TRACKID + "");
row.put(LATITUDE, current_lat.toString());
row.put(LONGITUDE, current_long.toString());
row.put(SPEED, speedInKm + "");
row.put(TIMESTAMP, System.currentTimeMillis() + "");
row.put(STATUS, status);
distance = distance + (distanceBetweenTwoPoint / 1000);
row.put(DISTANCE, "" + distance);
dataProvider.InsertRow("TrackDetail", row);
row.put(LASTKNOWNLATITUDE, latitude.toString());
row.put(LASTKNOWNLONGITUDE, longitude.toString());
int seconds = (int) ((System.currentTimeMillis() - trackStartTime) / 1000) % 60;
int minutes = (int) (((System.currentTimeMillis() - trackStartTime) / (1000 * 60)) % 60);
int hours = (int) (((System.currentTimeMillis() - trackStartTime) / (1000 * 60 * 60)) % 24);
row.put(DURATION, String.valueOf(hours) + " : " + String.valueOf(minutes) + " : " + String.valueOf(seconds));
setNotification(speedInKm, String.valueOf(hours) + " : " + String.valueOf(minutes) + " : " + String.valueOf(seconds));
if (status.equalsIgnoreCase("1")) {
builder.append("|" + current_lat + "," + current_long);
trackDuration = String.valueOf(hours) + " : " + String.valueOf(minutes) + " : " + String.valueOf(seconds);
if (speedInKm > maxSpeed) {
maxSpeed = speedInKm;
}
totalSpeed = totalSpeed + speedInKm;
++totalTrackPoint;
sendBrodcastToActivity();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
I'm coding a method that solve various kind of equation. Now I want that the method receives a String equation that could be in the forms:
ax^2+bx+c=0
or
*ax^2+c=0*
or
bx+c=0
etc. and the order shouldn't matter.
My problem is: How could I parse the equation according the "x" grade?
The eq could contains more values of the same grade for example 2x^2+4x^2+3x+8=2 (max grade x^3).
My method should assign the a value to double a[] if on the left or on the right of a there is x^2, double b[], if on the left or on the right there is x, and double c[] if there isn't any x variable near the value (and should change the value sign if the therms is after the =).
Convert a String number in a double is simple but I don't know how I could disassemble the input String according the x grade as described.
Tested for -2x + 3x^2 - 2 + 3x = 3 - 2x^2
public Double[] parseEquation(String equation)
{
Log.d(TAG, "equation: " + equation);
// Remove all white spaces
equation = equation.replaceAll("[ ]", "");
// Get the left and right sides of =
String[] sides = equation.split("[=]"); // should be of size 2
boolean leftNegative = false;
boolean rightNegative = false;
if (sides.length != 2)
{
// There is no = or more than one = signs.
}
else
{
// if sides i starts with + remove the +
// if - we remove and put it back later
for (int i = 0; i < 2; i++)
{
if (sides[i].charAt(0) == '+')
{
sides[i] = sides[i].substring(1);
}
}
if (sides[0].charAt(0) == '-')
{
leftNegative = true;
sides[0] = sides[0].substring(1);
}
if (sides[1].charAt(0) == '-')
{
rightNegative = true;
sides[1] = sides[1].substring(1);
}
}
Log.d(TAG, "left side:" + sides[0] + " right side: " + sides[1]);
// Terms without signs need to find out later
String[] leftTerms = sides[0].split("[+-]");
String[] rightTerms = sides[1].split("[+-]");
int length = leftTerms[0].length();
if (leftNegative)
{
leftTerms[0] = "-" + leftTerms[0];
}
// put in the minus sign for the rest of the terms
for (int i = 1; i < leftTerms.length; i++)
{
Log.d(TAG, "length = " + length + " " + sides[0].charAt(length));
if (sides[0].charAt(length) == '-')
{
leftTerms[i] = "-" + leftTerms[i];
length += leftTerms[i].length();
}
else
{
length += leftTerms[i].length() + 1;
}
}
length = rightTerms[0].length();
if (rightNegative)
{
rightTerms[0] = "-" + rightTerms[0];
}
for (int i = 1; i < rightTerms.length; i++)
{
Log.d(TAG, "length = " + length + " " + sides[1].charAt(length));
if (sides[1].charAt(length) == '-')
{
rightTerms[i] = "-" + rightTerms[i];
length += rightTerms[i].length();
}
else
{
length += rightTerms[i].length() + 1;
}
}
// Now we put all the factors and powers in a list
List<ContentValues> leftLists = new ArrayList<ContentValues>();
// left side
for (int i = 0; i < leftTerms.length; i++)
{
Log.d(TAG, "leftTerm: " + leftTerms[i]);
ContentValues contentValues = new ContentValues();
int indexOfX = leftTerms[i].indexOf('x');
if (indexOfX == -1)
{
// no x mean a constant term
contentValues.put("factor", leftTerms[i]);
contentValues.put("power", "0");
}
else
{
int indexOfHat = leftTerms[i].indexOf('^');
if (indexOfHat == -1)
{
// no hat mean power = 1
contentValues.put("power", "1");
String factor = leftTerms[i].substring(0, indexOfX).trim();
contentValues.put("factor", factor);
}
else
{
String power = leftTerms[i].substring(indexOfX + 2).trim();
String factor = leftTerms[i].substring(0, indexOfX).trim();
contentValues.put("factor", factor);
contentValues.put("power", power);
}
}
Log.d(TAG, contentValues.toString());
leftLists.add(contentValues);
}
List<ContentValues> rightLists = new ArrayList<ContentValues>();
for (int i = 0; i < rightTerms.length; i++)
{
Log.d(TAG, "rightTerm: " + rightTerms[i]);
ContentValues contentValues = new ContentValues();
int indexOfX = rightTerms[i].indexOf('x');
if (indexOfX == -1)
{
// no hat mean a constant term
contentValues.put("factor", rightTerms[i]);
contentValues.put("power", "0");
}
else
{
int indexOfHat = rightTerms[i].indexOf('^');
if (indexOfHat == -1)
{
// no hat mean power = 1
contentValues.put("power", "1");
String factor = rightTerms[i].substring(0, indexOfX).trim();
contentValues.put("factor", factor);
}
else
{
String power = rightTerms[i].substring(indexOfX + 2).trim();
String factor = rightTerms[i].substring(0, indexOfX).trim();
contentValues.put("factor", factor);
contentValues.put("power", power);
}
}
Log.d(TAG, contentValues.toString());
rightLists.add(contentValues);
}
// Now add the factors with same powers.
// Suppose we solve for cubic here the end result will be
// 4 terms constant, x, x^2 and x^3
// Declare a double array of dim 4 the first will hold constant
// the second the x factor etc...
// You can allow arbitrary power by looping through the lists and get the max power
Double[] result = new Double[]{0.0, 0.0, 0.0, 0.0};
for (ContentValues c : leftLists)
{
switch (c.getAsInteger("power"))
{
case 0:
//Log.d(TAG, "power = 0, factor = " + c.toString());
result[0] += c.getAsDouble("factor");
break;
case 1:
result[1] += c.getAsDouble("factor");
break;
case 2:
result[2] += c.getAsDouble("factor");
break;
case 3:
result[3] += c.getAsDouble("factor");
break;
}
}
for (ContentValues c : rightLists)
{
switch (c.getAsInteger("power"))
{
case 0:
//Log.d(TAG, "power = 0, factor = " + c.toString());
result[0] -= c.getAsDouble("factor");
break;
case 1:
result[1] -= c.getAsDouble("factor");
break;
case 2:
result[2] -= c.getAsDouble("factor");
break;
case 3:
result[3] -= c.getAsDouble("factor");
break;
}
}
Log.d(TAG, "constant term = " + result[0] + ", x^1 = " + result[1]
+ ", x^2 = " + result[2] + ", x^3 = " + result[3]);
return result;
}
If you weren't limited by Android, I'd suggest using a lexer and parser. These are code generators, so they can work anywhere the base language works, but they tend to produce bloated code. Android might not appreciate that.