Bootstrap collapse button not working on smartphone - android

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.

Related

_casterror (null check operator used on a null value)

I have the follwing problem with my code. When I call a Int with SharedPreference then show the emulator the error "_casterror (null check operator used on a null value)". The error is showing only when I start the app.When starting, the value should be _pktH = 0.
...
int? _pktH;
...
void initState() {
super.initState();
_loadCounterH();
}
_loadCounterH() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_counterH = (prefs.getInt('counterH') ?? 1);
prefs.setInt('counterH', _counterH!);
_pktH = (prefs.getInt('pktH') ?? 0);
prefs.setInt('pktH', _pktH!);
print(Text("Save number is: $_counterH"));
print(Text("Save pkt is: $_pktH"));
});
}
String _abzeichenH;
if (_pktH! >= 2835) {
_abzeichenH = ' ' + ' \u{1F451}' + ' ' + 'Ingenieur/-in';
} else if (_pktH! >= 1890) {
_abzeichenH = ' ' + '\u2692' + '\u2692' + '\u2692' + ' ' + 'Arbeiter/-in';
} else if (_pktH! >= 1260) {
_abzeichenH = ' ' + '\u2692' + '\u2692' + ' ' + 'Azubi';
} else if (_pktH! >= 10) {
_abzeichenH = ' ' + '\u2692' + ' ' + 'Praktikant/-in';
} else {
_abzeichenH = '';
}
print('Dein Abzeichen ist $_abzeichenH');

Sliding image 4x4 with GridLayout

I want ask about sliding image puzzle.
below is code for slide to left or right.
but I have a problem.
if (i + 1 < imageviews.size) {
if (imageviews[i + 1]!!.drawable == null) {
mGridLayout.removeView(imageviews[i + 1])
mGridLayout.addView(imageviews[i + 1], i)
val temp = imageviews[i + 1]
imageviews[i + 1] = imageviews[i]
imageviews[i] = temp
}
}
if (i - 1 >= 0) {
if (imageviews[i - 1]!!.drawable == null) {
mGridLayout.removeView(imageviews[i - 1])
mGridLayout.addView(imageviews[i - 1], i)
val temp = imageviews[i - 1]
imageviews[i - 1] = imageviews[i]
imageviews[i] = temp
}
}
before do anything:
I have updated setOnClickListener() function and it seems to be working but I haven't solved it completely:
private fun setOnClickListener() {
Log.i(TAG, "${imageviews.size} ")
for (i in 0 until imageviews.size step 1) {
imageviews[i]!!.setOnClickListener {
Log.i(TAG, "${imageviews.size} $i")
val top: Int? = if (i - GRID_NO >= 0) i - GRID_NO else null
val bottom: Int? = if (i + GRID_NO < imageviews.size) i + GRID_NO else null
val left: Int? = if (i % GRID_NO > 0) i - 1 else null
val right: Int? = if (i % GRID_NO < GRID_NO - 1) i + 1 else null
// Log.i(TAG, "Top: $top Bottom: $bottom Left: $left Right: $right")
if (top != null && imageviews[top]!!.drawable == null) {
imageviews[top]!!.setImageDrawable(imageviews[i]!!.drawable)
mGridLayout.removeViewAt(i)
mGridLayout.addView(imageviews[i], i)
imageviews[i]!!.setImageDrawable(null)
} else if (bottom != null && imageviews[bottom]!!.drawable == null) {
imageviews[bottom]!!.setImageDrawable(imageviews[i]!!.drawable)
mGridLayout.removeViewAt(i)
mGridLayout.addView(imageviews[i], i)
imageviews[i]!!.setImageDrawable(null)
} else if (left != null && imageviews[left]!!.drawable == null) {
imageviews[left]!!.setImageDrawable(imageviews[i]!!.drawable)
mGridLayout.removeViewAt(i)
mGridLayout.addView(imageviews[i], i)
imageviews[i]!!.setImageDrawable(null)
} else if (right != null && imageviews[right]!!.drawable == null) {
imageviews[right]!!.setImageDrawable(imageviews[i]!!.drawable)
mGridLayout.removeViewAt(i)
mGridLayout.addView(imageviews[i], i)
imageviews[i]!!.setImageDrawable(null)
}
if (isSolved()) {
Toast.makeText(this, "Success , true", Toast.LENGTH_SHORT).show()
}
}
}
}
UPDATED isSolved() FUNCTION UPON REQUEST
Updated isSolved() looks like as follows:
private fun isSolved(): Boolean {
var solved = true
for (i in 0 until GRID_NO) {
for (j in 0 until GRID_NO) {
val index: Int = i * GRID_NO + j
if (imageviews[index]!!.drawable == null) {
continue
} else if (imageviews[index]!!.drawable != imageViews[i][j]!!.drawable) {
solved = false
break
}
}
}
return solved
}
Please note that this version returns true if all cells except the empty cell in correct place, meaning that empty cell can be any cell at the end. If these kind of puzzles normally have more restricted success rules, like the empty cell should be on the corners, it needs to be updated.

How to retrieve multi-line text from Edittext?

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?

Incompatible types error in EditText android

My java code is below and I get java.lang.NullPointerException from this line:
firstplayer = player1.getText().toString;
in OnCreate method , where player1 is a one of the EditText from previous activity.
How can I fix it ?
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
public class startwith2player extends ActionBarActivity {
private boolean playerone = true , playertwo = false ;
private Integer score1 = 0 , score2 = 0;
private Integer flag4 = 0 , flag5 = 0 , flag6 = 0 , flag7 = 0, flag8 = 0, flag9 = 0 , flag10 = 0, flag11 = 0, flag12 = 0;
private Integer counter1 = 0 , counter2 = 0;
TextView tex1 ;
TextView tex2 ;
String firstplayer = "";
String secondplayer = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_startwith2player);
tex1 = (TextView) findViewById(R.id.textView3);
tex2 = (TextView) findViewById(R.id.textView4);
EditText player1 = (EditText)findViewById(R.id.editText);
EditText player2 = (EditText)findViewById(R.id.editText2);
firstplayer = player1.getText().toString();
secondplayer = player2.getText().toString();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_startwith2player, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void refresh(){
BlueAllBoxes();
if(playerone){
playerone = false;
playertwo = true;
}
else{
playerone = true;
playertwo = false;
}
flag4 = 0 ; flag5 = 0 ; flag6 = 0 ; flag7 = 0; flag8 = 0; flag9 = 0 ; flag10 = 0; flag11 = 0; flag12 = 0;
counter1 = 0 ; counter2 = 0;
}
public void BlueAllBoxes(){
Button button4 = (Button) findViewById(R.id.button4);
button4.setBackgroundColor(0xFF4B4BFF);
Button button5 = (Button) findViewById(R.id.button5);
button5.setBackgroundColor(0xFF4B4BFF);
Button button6 = (Button) findViewById(R.id.button6);
button6.setBackgroundColor(0xFF4B4BFF);
Button button7 = (Button) findViewById(R.id.button7);
button7.setBackgroundColor(0xFF4B4BFF);
Button button8 = (Button) findViewById(R.id.button8);
button8.setBackgroundColor(0xFF4B4BFF);
Button button9 = (Button) findViewById(R.id.button9);
button9.setBackgroundColor(0xFF4B4BFF);
Button button10 = (Button) findViewById(R.id.button10);
button10.setBackgroundColor(0xFF4B4BFF);
Button button11 = (Button) findViewById(R.id.button11);
button11.setBackgroundColor(0xFF4B4BFF);
Button button12 = (Button) findViewById(R.id.button12);
button12.setBackgroundColor(0xFF4B4BFF);
}
public void button4(View view) {
if(counter1 == 3){
if(flag4 == 1) {
view.setBackgroundColor(0xFF67FF5A);
counter2++;
if(playerone) {
score1 = score1 + 30;
// tex1.setText(String.valueOf(score1));
tex1.setText(firstplayer + " : " + score1 );
}
else {
score2 = score2 + 30;
tex2.setText(secondplayer + " : " + score2 );
}
if(counter2 == 3)
refresh();
}
else{
view.setBackgroundColor(0xFFFF231E);
if(playerone) {
score1 = score1 - 10;
tex1.setText(firstplayer + " : " + score1 );
}
else {
score2 = score2 - 10;
tex2.setText(secondplayer + " : " + score2 );
}
}
}
else {
if (flag4 == 0) {
flag4 = 1;
view.setBackgroundColor(0xFF67FF5A);
counter1++;
if(counter1 == 3)
BlueAllBoxes();
}
}
}
public void button5(View view) {
if(counter1 == 3){
if(flag5 == 1) {
view.setBackgroundColor(0xFF67FF5A);
counter2++;
if(playerone) {
score1 = score1 + 30;
tex1.setText(firstplayer + " : " + score1 );
}
else {
score2 = score2 + 30;
tex2.setText(secondplayer + " : " + score2 );
}
if(counter2 == 3)
refresh();
}
else{
view.setBackgroundColor(0xFFFF231E);
if(playerone) {
score1 = score1 - 10;
tex1.setText(firstplayer + " : " + score1 );
}
else {
score2 = score2 - 10;
tex2.setText(secondplayer + " : " + score2 );
}
}
}
else {
if (flag5 == 0) {
flag5 = 1;
view.setBackgroundColor(0xFF67FF5A);
counter1++;
if(counter1 == 3)
BlueAllBoxes();
}
}
}
public void button6(View view) {
if(counter1 == 3){
if(flag6 == 1) {
view.setBackgroundColor(0xFF67FF5A);
counter2++;
if(playerone) {
score1 = score1 + 30;
tex1.setText(firstplayer + " : " + score1 );
}
else {
score2 = score2 + 30;
tex2.setText(secondplayer + " : " + score2 );
}
if(counter2 == 3)
refresh();
}
else{
view.setBackgroundColor(0xFFFF231E);
if(playerone) {
score1 = score1 - 10;
tex1.setText(firstplayer + " : " + score1 );
}
else {
score2 = score2 - 10;
tex2.setText(secondplayer + " : " + score2 );
}
}
}
else {
if (flag6 == 0) {
flag6 = 1;
view.setBackgroundColor(0xFF67FF5A);
counter1++;
if(counter1 == 3)
BlueAllBoxes();
}
}
}
public void button7(View view) {
if(counter1 == 3){
if(flag7 == 1) {
view.setBackgroundColor(0xFF67FF5A);
counter2++;
if(playerone) {
score1 = score1 + 30;
tex1.setText(firstplayer + " : " + score1 );
}
else {
score2 = score2 + 30;
tex2.setText(secondplayer + " : " + score2 );
}
if(counter2 == 3)
refresh();
}
else{
view.setBackgroundColor(0xFFFF231E);
if(playerone) {
score1 = score1 - 10;
tex1.setText(firstplayer + " : " + score1);
}
else {
score2 = score2 - 10;
tex2.setText(secondplayer + " : " + score2 );
}
}
}
else {
flag7 = 1;
view.setBackgroundColor(0xFF67FF5A);
counter1++;
if(counter1 == 3)
BlueAllBoxes();
}
}
public void button8(View view) {
if(counter1 == 3){
if(flag8 == 1) {
view.setBackgroundColor(0xFF67FF5A);
counter2++;
if(playerone) {
score1 = score1 + 30;
tex1.setText(firstplayer + " : " + score1 );
}
else {
score2 = score2 + 30;
tex2.setText(secondplayer + " : " + score2 );
}
if(counter2 == 3)
refresh();
}
else{
view.setBackgroundColor(0xFFFF231E);
if(playerone) {
score1 = score1 - 10;
tex1.setText(firstplayer + " : " + score1 );
}
else {
score2 = score2 - 10;
tex2.setText(secondplayer + " : " + score2 );
}
}
}
else {
flag8 = 1;
view.setBackgroundColor(0xFF67FF5A);
counter1++;
if(counter1 == 3)
BlueAllBoxes();
}
}
public void button9(View view) {
if(counter1 == 3){
if(flag9 == 1) {
view.setBackgroundColor(0xFF67FF5A);
counter2++;
if(playerone) {
score1 = score1 + 30;
tex1.setText(firstplayer + " : " + score1 );
}
else {
score2 = score2 + 30;
tex2.setText(secondplayer + " : " + score2 );
}
if(counter2 == 3)
refresh();
}
else{
view.setBackgroundColor(0xFFFF231E);
if(playerone) {
score1 = score1 - 10;
tex1.setText(firstplayer + " : " + score1 );
}
else {
score2 = score2 - 10;
tex2.setText(secondplayer + " : " + score2 );
}
}
}
else {
flag9 = 1;
view.setBackgroundColor(0xFF67FF5A);
counter1++;
if(counter1 == 3)
BlueAllBoxes();
}
}
public void button10(View view) {
if(counter1 == 3){
if(flag10 == 1) {
view.setBackgroundColor(0xFF67FF5A);
counter2++;
if(playerone) {
score1 = score1 + 30;
tex1.setText(firstplayer + " : " + score1 );
}
else {
score2 = score2 + 30;
tex2.setText(secondplayer + " : " + score2 );
}
if(counter2 == 3)
refresh();
}
else{
view.setBackgroundColor(0xFFFF231E);
if(playerone) {
score1 = score1 - 10;
tex1.setText(firstplayer + " : " + score1 );
}
else {
score2 = score2 - 10;
tex2.setText(secondplayer + " : " + score2 );
}
}
}
else {
flag10 = 1;
view.setBackgroundColor(0xFF67FF5A);
counter1++;
if(counter1 == 3)
BlueAllBoxes();
}
}
public void button11(View view) {
if(counter1 == 3){
if(flag11 == 1) {
view.setBackgroundColor(0xFF67FF5A);
counter2++;
if(playerone) {
score1 = score1 + 30;
tex1.setText(firstplayer + " : " + score1 );
}
else {
score2 = score2 + 30;
tex2.setText(secondplayer + " : " + score2 );
}
if(counter2 == 3)
refresh();
}
else{
view.setBackgroundColor(0xFFFF231E);
if(playerone) {
score1 = score1 - 10;
tex1.setText(firstplayer + " : " + score1 );
}
else {
score2 = score2 - 10;
tex2.setText(secondplayer + " : " + score2);
}
}
}
else {
flag11 = 1;
view.setBackgroundColor(0xFF67FF5A);
counter1++;
if(counter1 == 3)
BlueAllBoxes();
}
}
public void button12(View view) {
if(counter1 == 3){
if(flag12 == 1) {
view.setBackgroundColor(0xFF67FF5A);
counter2++;
if(playerone) {
score1 = score1 + 30;
tex1.setText(firstplayer + " : " + score1 );
}
else {
score2 = score2 + 30;
tex2.setText(secondplayer + " : " + score2);
}
if(counter2 == 3)
refresh();
}
else{
view.setBackgroundColor(0xFFFF231E);
if(playerone) {
score1 = score1 - 10;
tex1.setText(firstplayer + " : " + score1 );
}
else {
score2 = score2 - 10;
tex2.setText(secondplayer + " : " + score2);
}
}
}
else {
flag12 = 1;
view.setBackgroundColor(0xFF67FF5A);
counter1++;
if(counter1 == 3)
BlueAllBoxes();
}
}
}
You have to cast findViewById() method to your View type because it finds a view that was identified by the id attribute from the XML that was processed in. So you have to type cast view into your EditText view.
Try this:
EditText player1 = (EditText)findViewById(R.id.editText);
EditText playertwo = (EditText)findViewById(R.id.editText2);
you have to type cast findviewbyid
EditText player1 = (EditText)findViewById(R.id.editText);
EditText playertwo = (EditText)findViewById(R.id.editText2);
You are getting a NPE because your player1 is null
EditText player1 = (EditText)findViewById(R.id.editText);
firstplayer = player1.getText().toString();
You are saying that the player1 is in the previous Activity.
If the player1 isn't in the activity_startwith2player layout, you will always get a NPE.
If you have this value in the previous Activity, you can share this value using an Extra in your Intent.
Intent intent = new Intent(this, startwith2player.class);
EditText player1 = (EditText)findViewById(R.id.editText);
String message = player1.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
More info here.
By the way, I suggest you using a capital letter for your class.

Variable delay before updating an android textview

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);
}
}

Categories

Resources