问:
Optimize cube rendering in threejs
I have the following code:

https://github.com/CrizzzSombiii/laboratoryofsombiisbycrizz/blob/master/docs/maze2.htm

```

The code runs without errors. The trouble resides in the fps count. The html file is running only between 1 and 4 frames per second. I want to run the html file in at least 60 frames per second. Any help? Thanks anyway!

答:
Finally, I get the solution!

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/88/three.js"></script>
<script>
setTimeout(()=>{
s=1.5
k=[]
onmousedown=()=>{document.body.requestPointerLock()}
onmousemove=(e)=>{
if(document.pointerLockElement===document.body){
vector.xa-=0.01*e.movementX
vector.ya-=0.01*e.movementY
}}
onkeydown=onkeyup=function(e){k[e.keyCode]=e.type=="keydown"}
document.body.style.backgroundColor="black"
document.body.style.margin="0"
scene=new THREE.Scene()
camera=new THREE.PerspectiveCamera(75,1,0.1,16);vector={xs:0,ys:0,zs:0,xa:0,ya:0}
camera.position.set(0,0,0);renderer=new THREE.WebGLRenderer()
document.body.appendChild(renderer.domElement)
light=new THREE.PointLight("rgb(0,127,255)",1,8);light.position.set(0,0,0);scene.add(light)
function render(){
camera.aspect=window.innerWidth/window.innerHeight
camera.updateProjectionMatrix()
renderer.setSize(innerWidth,innerHeight)
requestAnimationFrame(render)
renderer.render(scene,camera)
}
setInterval(()=>{
if(vector.ya<-1){vector.ya=-1}
if(1<vector.ya){vector.ya=1}
if(k[37]){vector.xa+=0.1}
if(k[38]){if(vector.ya<1.2){vector.ya+=0.1}}
if(k[39]){vector.xa-=0.1}
if(k[40]){if(-1.2<vector.ya){vector.ya-=0.1}}
if(k[87]){vector.xs+=0.01*Math.sin(vector.xa)*Math.cos(vector.ya);vector.ys+=0.01*vector.ya;vector.zs+=0.01*Math.cos(vector.xa)*Math.cos(vector.ya)}
if(k[83]){vector.xs-=0.01*Math.sin(vector.xa)*Math.cos(vector.ya);vector.ys-=0.01*vector.ya;vector.zs-=0.01*Math.cos(vector.xa)*Math.cos(vector.ya)}
if(k[65]){vector.xs+=0.01*Math.sin(vector.xa+Math.PI/2)*Math.cos(vector.ya);vector.ys+=0.01*vector.ya;vector.zs+=0.01*Math.cos(vector.xa+Math.PI/2)*Math.cos(vector.ya)}
if(k[68]){vector.xs+=0.01*Math.sin(vector.xa-Math.PI/2)*Math.cos(vector.ya);vector.ys+=0.01*vector.ya;vector.zs+=0.01*Math.cos(vector.xa-Math.PI/2)*Math.cos(vector.ya)}
camera.position.x+=vector.xs;vector.xs=vector.xs*9/10
camera.position.y+=vector.ys;vector.ys=vector.ys*9/10
camera.position.z+=vector.zs;vector.zs=vector.zs*9/10
light.position.set(camera.position.x,camera.position.y,camera.position.z)
camera.lookAt(new THREE.Vector3(camera.position.x+Math.sin(vector.xa)*Math.cos(vector.ya),camera.position.y+vector.ya,camera.position.z+Math.cos(vector.xa)*Math.cos(vector.ya)))
if(s<Math.max(Math.pow(camera.position.x*camera.position.x,1/2),Math.pow(camera.position.y*camera.position.y,1/2),Math.pow(camera.position.z*camera.position.z,1/2))+12){sy=1.5
while(sy<s+1){sz=1.5;while(sz<sy+1){
gen(s,sy,sz,0,0,0);if(Math.random()*16<1){g(2,s+1.5,sy+1.5,sz+1.5)}
gen(s,sy,sz,1,0,0);gen(s,sy,sz,-1,0,0);gen(s,sy,sz,0,1,0);gen(s,sy,sz,0,-1,0);gen(s,sy,sz,0,0,1);gen(s,sy,sz,0,0,-1)
if(Math.random()*2<1){gen(s,sy,sz,1,1,0);gen(s,sy,sz,1,2,0);gen(s,sy,sz,2,1,0);gen(s,sy,sz,2,2,0)}
if(Math.random()*2<1){gen(s,sy,sz,0,1,1);gen(s,sy,sz,0,1,2);gen(s,sy,sz,0,2,1);gen(s,sy,sz,0,2,2)}
if(Math.random()*2<1){gen(s,sy,sz,1,0,1);gen(s,sy,sz,1,0,2);gen(s,sy,sz,2,0,1);gen(s,sy,sz,2,0,2)}
sz+=3};while(sz==sy){sz=0}sy+=3};while(sy==s){sy=0}s+=3}
for(i1 in obj1){
obj1[i1].obj.position.set(obj1[i1].x,obj1[i1].y,obj1[i1].z)
if(camera.position.x-0.5<obj1[i1].x+0.5){if(camera.position.x+0.5>obj1[i1].x-0.5){
if(camera.position.y-0.5<obj1[i1].y+0.5){if(camera.position.y+0.5>obj1[i1].y-0.5){
if(camera.position.z-0.5<obj1[i1].z+0.5){if(camera.position.z+0.5>obj1[i1].z-0.5){
vector.xs-=0.01*(obj1[i1].x-camera.position.x)/Math.pow(
(obj1[i1].x-camera.position.x)*(obj1[i1].x-camera.position.x)+
(obj1[i1].y-camera.position.y)*(obj1[i1].y-camera.position.y)+
(obj1[i1].z-camera.position.z)*(obj1[i1].z-camera.position.z),3/2)
vector.ys-=0.01*(obj1[i1].y-camera.position.y)/Math.pow(
(obj1[i1].x-camera.position.x)*(obj1[i1].x-camera.position.x)+
(obj1[i1].y-camera.position.y)*(obj1[i1].y-camera.position.y)+
(obj1[i1].z-camera.position.z)*(obj1[i1].z-camera.position.z),3/2)
vector.zs-=0.01*(obj1[i1].z-camera.position.z)/Math.pow(
(obj1[i1].x-camera.position.x)*(obj1[i1].x-camera.position.x)+
(obj1[i1].y-camera.position.y)*(obj1[i1].y-camera.position.y)+
(obj1[i1].z-camera.position.z)*(obj1[i1].z-camera.position.z),3/2)
}}}}}}
}
for(i2 in obj2){
obj2[i2].obj.position.set(obj2[i2].x,obj2[i2].y,obj2[i2].z)
obj2[i2].x+=obj2[i2].xs;if(0.1<obj2[i2].xs){obj2[i2].xs=obj2[i2].xs*7/8};if(obj2[i2].xs<-0.1){obj2[i2].xs=obj2[i2].xs*7/8}
obj2[i2].y+=obj2[i2].ys;if(0.1<obj2[i2].ys){obj2[i2].ys=obj2[i2].ys*7/8};if(obj2[i2].ys<-0.1){obj2[i2].ys=obj2[i2].ys*7/8}
obj2[i2].z+=obj2[i2].zs;if(0.1<obj2[i2].zs){obj2[i2].zs=obj2[i2].zs*7/8};if(obj2[i2].zs<-0.1){obj2[i2].zs=obj2[i2].zs*7/8}
if(camera.position.x-0.5<obj2[i2].x+0.5){if(camera.position.x+0.5>obj2[i2].x-0.5){
if(camera.position.y-0.5<obj2[i2].y+0.5){if(camera.position.y+0.5>obj2[i2].y-0.5){
if(camera.position.z-0.5<obj2[i2].z+0.5){if(camera.position.z+0.5>obj2[i2].z-0.5){
camera.position.x=1/0;alert("Moriste!")
}}}}}}
}
for(i1 in obj1){for(i2 in obj2){
if(obj1[i1].x-0.5<obj2[i2].x+0.5){if(obj1[i1].x+0.5>obj2[i2].x-0.5){
if(obj1[i1].y-0.5<obj2[i2].y+0.5){if(obj1[i1].y+0.5>obj2[i2].y-0.5){
if(obj1[i1].z-0.5<obj2[i2].z+0.5){if(obj1[i1].z+0.5>obj2[i2].z-0.5){
obj2[i2].xs+=0.01*(obj2[i2].x-obj1[i1].x)/Math.pow(
(obj2[i2].x-obj1[i1].x)*(obj2[i2].x-obj1[i1].x)+
(obj2[i2].y-obj1[i1].y)*(obj2[i2].y-obj1[i1].y)+
(obj2[i2].z-obj1[i1].z)*(obj2[i2].z-obj1[i1].z),3/2)
obj2[i2].ys+=0.01*(obj2[i2].y-obj1[i1].y)/Math.pow(
(obj2[i2].x-obj1[i1].x)*(obj2[i2].x-obj1[i1].x)+
(obj2[i2].y-obj1[i1].y)*(obj2[i2].y-obj1[i1].y)+
(obj2[i2].z-obj1[i1].z)*(obj2[i2].z-obj1[i1].z),3/2)
obj2[i2].zs+=0.01*(obj2[i2].z-obj1[i1].z)/Math.pow(
(obj2[i2].x-obj1[i1].x)*(obj2[i2].x-obj1[i1].x)+
(obj2[i2].y-obj1[i1].y)*(obj2[i2].y-obj1[i1].y)+
(obj2[i2].z-obj1[i1].z)*(obj2[i2].z-obj1[i1].z),3/2)
}}}}}}
}}
},1)
render()
obj1={};i1=0
obj2={};i2=0
g=function(obj,x,y,z){
if(obj==1){i1++;obj1[i1]={x:x,y:y,z:z,obj:new THREE.Mesh(new THREE.BoxGeometry(1,1,1),new THREE.MeshLambertMaterial({color:"rgb(255,255,255)",
transparent:true,opacity:1}))};scene.add(obj1[i1].obj)}
if(obj==2){i2++;obj2[i2]={x:x,y:y,z:z,xs:Math.random()*0.2-0.1,ys:Math.random()*0.2-0.1,zs:Math.random()*0.2-0.1,obj:new THREE.Mesh(new THREE.BoxGeometry(1,1,1),
new THREE.MeshLambertMaterial({color:"rgb(0,0,0)",transparent:true,opacity:1}))};scene.add(obj2[i2].obj)}
}
gen=function(x,y,z,a,b,c){
g(1,x+a,y+b,z+c);g(1,y+a,x+b,z+c);g(1,y+a,z+b,x+c);g(1,x+a,z+b,y+c);g(1,z+a,x+b,y+c);g(1,z+a,y+b,x+c)
g(1,-x+a,y+b,z+c);g(1,-y+a,x+b,z+c);g(1,-y+a,z+b,x+c);g(1,-x+a,z+b,y+c);g(1,-z+a,x+b,y+c);g(1,-z+a,y+b,x+c)
g(1,x+a,-y+b,z+c);g(1,y+a,-x+b,z+c);g(1,y+a,-z+b,x+c);g(1,x+a,-z+b,y+c);g(1,z+a,-x+b,y+c);g(1,z+a,-y+b,x+c)
g(1,-x+a,-y+b,z+c);g(1,-y+a,-s+b,z+c);g(1,-y+a,-z+b,x+c);g(1,-x+a,-z+b,y+c);g(1,-z+a,-x+b,y+c);g(1,-z+a,-y+b,x+c)
g(1,x+a,y+b,-z+c);g(1,y+a,x+b,-z+c);g(1,y+a,z+b,-x+c);g(1,x+a,z+b,-y+c);g(1,z+a,x+b,-y+c);g(1,z+a,y+b,-x+c)
g(1,-x+a,y+b,-z+c);g(1,-y+a,x+b,-z+c);g(1,-y+a,z+b,-x+c);g(1,-x+a,z+b,-y+c);g(1,-z+a,x+b,-y+c);g(1,-z+a,y+b,-x+c)
g(1,x+a,-y+b,-z+c);g(1,y+a,-x+b,-z+c);g(1,y+a,-z+b,-x+c);g(1,x+a,-z+b,-y+c);g(1,z+a,-x+b,-y+c);g(1,z+a,-y+b,-x+c)
g(1,-x+a,-y+b,-z+c);g(1,-y+a,-x+b,-z+c);g(1,-y+a,-z+b,-x+c);g(1,-x+a,-z+b,-y+c);g(1,-z+a,-x+b,-y+c);g(1,-z+a,-y+b,-x+c)
}
},1)
</script>
</code>```

It keeps running at 30 fps, but it's the first step to elaborating an answer. I will repair my code for finally get 60 fps.

Title: Optimize cube rendering in threejs

Body:
I have the following code:

https://github.com/CrizzzSombiii/laboratoryofsombiisbycrizz/blob/master/docs/maze2.htm

The code runs without errors. The trouble resides in the fps count. The html file is running only between 1 and 4 frames per second. I want to run the html file in at least 60 frames per second. Any help? Thanks anyway!

Body:
Finally, I get the solution!

<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/88/three.js"></script>
<script>
setTimeout(()=>{
s=1.5
k=[]
onmousedown=()=>{document.body.requestPointerLock()}
onmousemove=(e)=>{
if(document.pointerLockElement===document.body){
vector.xa-=0.01*e.movementX
vector.ya-=0.01*e.movementY
}}
onkeydown=onkeyup=function(e){k[e.keyCode]=e.type=="keydown"}
document.body.style.backgroundColor="black"
document.body.style.margin="0"
scene=new THREE.Scene()
camera=new THREE.PerspectiveCamera(75,1,0.1,16);vector={xs:0,ys:0,zs:0,xa:0,ya:0}
camera.position.set(0,0,0);renderer=new THREE.WebGLRenderer()
document.body.appendChild(renderer.domElement)
light=new THREE.PointLight("rgb(0,127,255)",1,8);light.position.set(0,0,0);scene.add(light)
function render(){
camera.aspect=window.innerWidth/window.innerHeight
camera.updateProjectionMatrix()
renderer.setSize(innerWidth,innerHeight)
requestAnimationFrame(render)
renderer.render(scene,camera)
}
setInterval(()=>{
if(vector.ya<-1){vector.ya=-1}
if(1<vector.ya){vector.ya=1}
if(k[37]){vector.xa+=0.1}
if(k[38]){if(vector.ya<1.2){vector.ya+=0.1}}
if(k[39]){vector.xa-=0.1}
if(k[40]){if(-1.2<vector.ya){vector.ya-=0.1}}
if(k[87]){vector.xs+=0.01*Math.sin(vector.xa)*Math.cos(vector.ya);vector.ys+=0.01*vector.ya;vector.zs+=0.01*Math.cos(vector.xa)*Math.cos(vector.ya)}
if(k[83]){vector.xs-=0.01*Math.sin(vector.xa)*Math.cos(vector.ya);vector.ys-=0.01*vector.ya;vector.zs-=0.01*Math.cos(vector.xa)*Math.cos(vector.ya)}
if(k[65]){vector.xs+=0.01*Math.sin(vector.xa+Math.PI/2)*Math.cos(vector.ya);vector.ys+=0.01*vector.ya;vector.zs+=0.01*Math.cos(vector.xa+Math.PI/2)*Math.cos(vector.ya)}
if(k[68]){vector.xs+=0.01*Math.sin(vector.xa-Math.PI/2)*Math.cos(vector.ya);vector.ys+=0.01*vector.ya;vector.zs+=0.01*Math.cos(vector.xa-Math.PI/2)*Math.cos(vector.ya)}
camera.position.x+=vector.xs;vector.xs=vector.xs*9/10
camera.position.y+=vector.ys;vector.ys=vector.ys*9/10
camera.position.z+=vector.zs;vector.zs=vector.zs*9/10
light.position.set(camera.position.x,camera.position.y,camera.position.z)
camera.lookAt(new THREE.Vector3(camera.position.x+Math.sin(vector.xa)*Math.cos(vector.ya),camera.position.y+vector.ya,camera.position.z+Math.cos(vector.xa)*Math.cos(vector.ya)))
if(s<Math.max(Math.pow(camera.position.x*camera.position.x,1/2),Math.pow(camera.position.y*camera.position.y,1/2),Math.pow(camera.position.z*camera.position.z,1/2))+12){sy=1.5
while(sy<s+1){sz=1.5;while(sz<sy+1){
gen(s,sy,sz,0,0,0);if(Math.random()*16<1){g(2,s+1.5,sy+1.5,sz+1.5)}
gen(s,sy,sz,1,0,0);gen(s,sy,sz,-1,0,0);gen(s,sy,sz,0,1,0);gen(s,sy,sz,0,-1,0);gen(s,sy,sz,0,0,1);gen(s,sy,sz,0,0,-1)
if(Math.random()*2<1){gen(s,sy,sz,1,1,0);gen(s,sy,sz,1,2,0);gen(s,sy,sz,2,1,0);gen(s,sy,sz,2,2,0)}
if(Math.random()*2<1){gen(s,sy,sz,0,1,1);gen(s,sy,sz,0,1,2);gen(s,sy,sz,0,2,1);gen(s,sy,sz,0,2,2)}
if(Math.random()*2<1){gen(s,sy,sz,1,0,1);gen(s,sy,sz,1,0,2);gen(s,sy,sz,2,0,1);gen(s,sy,sz,2,0,2)}
sz+=3};while(sz==sy){sz=0}sy+=3};while(sy==s){sy=0}s+=3}
for(i1 in obj1){
obj1[i1].obj.position.set(obj1[i1].x,obj1[i1].y,obj1[i1].z)
if(camera.position.x-0.5<obj1[i1].x+0.5){if(camera.position.x+0.5>obj1[i1].x-0.5){
if(camera.position.y-0.5<obj1[i1].y+0.5){if(camera.position.y+0.5>obj1[i1].y-0.5){
if(camera.position.z-0.5<obj1[i1].z+0.5){if(camera.position.z+0.5>obj1[i1].z-0.5){
vector.xs-=0.01*(obj1[i1].x-camera.position.x)/Math.pow(
(obj1[i1].x-camera.position.x)*(obj1[i1].x-camera.position.x)+
(obj1[i1].y-camera.position.y)*(obj1[i1].y-camera.position.y)+
(obj1[i1].z-camera.position.z)*(obj1[i1].z-camera.position.z),3/2)
vector.ys-=0.01*(obj1[i1].y-camera.position.y)/Math.pow(
(obj1[i1].x-camera.position.x)*(obj1[i1].x-camera.position.x)+
(obj1[i1].y-camera.position.y)*(obj1[i1].y-camera.position.y)+
(obj1[i1].z-camera.position.z)*(obj1[i1].z-camera.position.z),3/2)
vector.zs-=0.01*(obj1[i1].z-camera.position.z)/Math.pow(
(obj1[i1].x-camera.position.x)*(obj1[i1].x-camera.position.x)+
(obj1[i1].y-camera.position.y)*(obj1[i1].y-camera.position.y)+
(obj1[i1].z-camera.position.z)*(obj1[i1].z-camera.position.z),3/2)
}}}}}}
}
for(i2 in obj2){
obj2[i2].obj.position.set(obj2[i2].x,obj2[i2].y,obj2[i2].z)
obj2[i2].x+=obj2[i2].xs;if(0.1<obj2[i2].xs){obj2[i2].xs=obj2[i2].xs*7/8};if(obj2[i2].xs<-0.1){obj2[i2].xs=obj2[i2].xs*7/8}
obj2[i2].y+=obj2[i2].ys;if(0.1<obj2[i2].ys){obj2[i2].ys=obj2[i2].ys*7/8};if(obj2[i2].ys<-0.1){obj2[i2].ys=obj2[i2].ys*7/8}
obj2[i2].z+=obj2[i2].zs;if(0.1<obj2[i2].zs){obj2[i2].zs=obj2[i2].zs*7/8};if(obj2[i2].zs<-0.1){obj2[i2].zs=obj2[i2].zs*7/8}
if(camera.position.x-0.5<obj2[i2].x+0.5){if(camera.position.x+0.5>obj2[i2].x-0.5){
if(camera.position.y-0.5<obj2[i2].y+0.5){if(camera.position.y+0.5>obj2[i2].y-0.5){
if(camera.position.z-0.5<obj2[i2].z+0.5){if(camera.position.z+0.5>obj2[i2].z-0.5){
camera.position.x=1/0;alert("Moriste!")
}}}}}}
}
for(i1 in obj1){for(i2 in obj2){
if(obj1[i1].x-0.5<obj2[i2].x+0.5){if(obj1[i1].x+0.5>obj2[i2].x-0.5){
if(obj1[i1].y-0.5<obj2[i2].y+0.5){if(obj1[i1].y+0.5>obj2[i2].y-0.5){
if(obj1[i1].z-0.5<obj2[i2].z+0.5){if(obj1[i1].z+0.5>obj2[i2].z-0.5){
obj2[i2].xs+=0.01*(obj2[i2].x-obj1[i1].x)/Math.pow(
(obj2[i2].x-obj1[i1].x)*(obj2[i2].x-obj1[i1].x)+
(obj2[i2].y-obj1[i1].y)*(obj2[i2].y-obj1[i1].y)+
(obj2[i2].z-obj1[i1].z)*(obj2[i2].z-obj1[i1].z),3/2)
obj2[i2].ys+=0.01*(obj2[i2].y-obj1[i1].y)/Math.pow(
(obj2[i2].x-obj1[i1].x)*(obj2[i2].x-obj1[i1].x)+
(obj2[i2].y-obj1[i1].y)*(obj2[i2].y-obj1[i1].y)+
(obj2[i2].z-obj1[i1].z)*(obj2[i2].z-obj1[i1].z),3/2)
obj2[i2].zs+=0.01*(obj2[i2].z-obj1[i1].z)/Math.pow(
(obj2[i2].x-obj1[i1].x)*(obj2[i2].x-obj1[i1].x)+
(obj2[i2].y-obj1[i1].y)*(obj2[i2].y-obj1[i1].y)+
(obj2[i2].z-obj1[i1].z)*(obj2[i2].z-obj1[i1].z),3/2)
}}}}}}
}}
},1)
render()
obj1={};i1=0
obj2={};i2=0
g=function(obj,x,y,z){
if(obj==1){i1++;obj1[i1]={x:x,y:y,z:z,obj:new THREE.Mesh(new THREE.BoxGeometry(1,1,1),new THREE.MeshLambertMaterial({color:"rgb(255,255,255)",
transparent:true,opacity:1}))};scene.add(obj1[i1].obj)}
if(obj==2){i2++;obj2[i2]={x:x,y:y,z:z,xs:Math.random()*0.2-0.1,ys:Math.random()*0.2-0.1,zs:Math.random()*0.2-0.1,obj:new THREE.Mesh(new THREE.BoxGeometry(1,1,1),
new THREE.MeshLambertMaterial({color:"rgb(0,0,0)",transparent:true,opacity:1}))};scene.add(obj2[i2].obj)}
}
gen=function(x,y,z,a,b,c){
g(1,x+a,y+b,z+c);g(1,y+a,x+b,z+c);g(1,y+a,z+b,x+c);g(1,x+a,z+b,y+c);g(1,z+a,x+b,y+c);g(1,z+a,y+b,x+c)
g(1,-x+a,y+b,z+c);g(1,-y+a,x+b,z+c);g(1,-y+a,z+b,x+c);g(1,-x+a,z+b,y+c);g(1,-z+a,x+b,y+c);g(1,-z+a,y+b,x+c)
g(1,x+a,-y+b,z+c);g(1,y+a,-x+b,z+c);g(1,y+a,-z+b,x+c);g(1,x+a,-z+b,y+c);g(1,z+a,-x+b,y+c);g(1,z+a,-y+b,x+c)
g(1,-x+a,-y+b,z+c);g(1,-y+a,-s+b,z+c);g(1,-y+a,-z+b,x+c);g(1,-x+a,-z+b,y+c);g(1,-z+a,-x+b,y+c);g(1,-z+a,-y+b,x+c)
g(1,x+a,y+b,-z+c);g(1,y+a,x+b,-z+c);g(1,y+a,z+b,-x+c);g(1,x+a,z+b,-y+c);g(1,z+a,x+b,-y+c);g(1,z+a,y+b,-x+c)
g(1,-x+a,y+b,-z+c);g(1,-y+a,x+b,-z+c);g(1,-y+a,z+b,-x+c);g(1,-x+a,z+b,-y+c);g(1,-z+a,x+b,-y+c);g(1,-z+a,y+b,-x+c)
g(1,x+a,-y+b,-z+c);g(1,y+a,-x+b,-z+c);g(1,y+a,-z+b,-x+c);g(1,x+a,-z+b,-y+c);g(1,z+a,-x+b,-y+c);g(1,z+a,-y+b,-x+c)
g(1,-x+a,-y+b,-z+c);g(1,-y+a,-x+b,-z+c);g(1,-y+a,-z+b,-x+c);g(1,-x+a,-z+b,-y+c);g(1,-z+a,-x+b,-y+c);g(1,-z+a,-y+b,-x+c)
}
},1)
</script>

It keeps running at 30 fps, but it's the first step to elaborating an answer. I will repair my code for finally get 60 fps.


来源: stackexchange

问:
How to read a text file and insert into databse in php?
Basically what i am trying to do is to insert content of a file to my database table.To be more clear ill explain it in details.I have a folder named "filedata" in which text files are uploaded.and the movement the files are uploaded to filedata folder i want to read those file,insert its content to database and delete that file from filedata folder.I am in confusion from where to start.I know php basics not much knowledge of it.So please anyone suggest me where to start. </p>

答:
it goes something like this first you read the file then you encode it into base64 then you insert it into database hope it helps</p>

```<code><?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$file_content=file_get_contents(path_of_file)
$data=base64_encode ( $file )
$sql = "insert into table 'tablename' values($data)"

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
it goes something like this first you read the file then you encode it into base64 then you insert it into database hope it helps

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$file_content=file_get_contents(path_of_file)
$data=base64_encode ( $file )
$sql = "insert into table 'tablename' values($data)"

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>


问:
primefaces JSF: how to create a period picker?
I'd like to add a period picker on my website but I didn't find any option on PrimeFaces.

The idea is that I'd get a calendar where I can pick two dates and have the period between these two dates selected.

Is there an option to do that ?

答:
You did not find an option in PrimeFaces but did you check the PrimeFaces issue list for feature requests?

https://github.com/primefaces/primefaces/issues/2202

Up to 6.1 it is not available and I'm not sure it will be in 6.2. I, unfortunately, do not have the time to create a pull request myself (I'm going to need it in the not too distant future myself)


问:
How to add testCompile dependencies to IDE classpath
I have been struggling with unit-test-android problem for quite a long time. I have seen this, this and that, finally I found the gradle-android-test-plugin and even got it working. I can now run the tests with gradlew test command.

But, writing those tests in IDE (Android Studio or IntelliJ 13) is far from comfortable, because it does not see the junit & Robolectric dependencies added with testCompile dependency.

Is there any way to add these dependencies to the IDE classpath but still avoid to package them in the production app (thus, AFAIU compile dependency cannot be used)?

答:
In IntelliJ IDEA you need to configure couple things in your build.gradle

```<code>// add idea plugin
apply plugin: 'idea'
// make sure `configurations.testCompile` is added to idea.module
idea {
    module {
        scopes.TEST.plus += [ configurations.testCompile ]
    }
}
</code>```

For more info see:
http://www.gradle.org/docs/current/dsl/org.gradle.plugins.ide.idea.model.IdeaModule.html

Any dependency included with testCompile will be automatically imported into IDEA.

Body:
In IntelliJ IDEA you need to configure couple things in your build.gradle

// add idea plugin
apply plugin: 'idea'
// make sure `configurations.testCompile` is added to idea.module
idea {
    module {
        scopes.TEST.plus += [ configurations.testCompile ]
    }
}

For more info see:
http://www.gradle.org/docs/current/dsl/org.gradle.plugins.ide.idea.model.IdeaModule.html

Any dependency included with testCompile will be automatically imported into IDEA.


问:
[Swift]nil when loading scn files downloaded in runtime
I am working on a project to load a model into a ARKit powered app by scanning a qrCode. I have the qrCode working and .scn file downloaded into a .tmp file. However, when I tried to catch the scene by SCNScene(url:), all what returns is a nil.

I am wondering if it's because I copied the file too early --- before it finishes downloading, since the app freezes right after I scanned the qrCode.

Any suggestions would be appreciated. :D

2017-11-18 added download code

The template: http://www.jianshu.com/p/6ca4864b3600

```<code>func sessionSimpleDownload( scnurl: URL){
    let url = scnurl
    let request = URLRequest(url: url)
    let session = URLSession.shared
    var ls: String!

    let downloadTask = session.downloadTask(with: request,
    completionHandler: { (location:URL?, response:URLResponse?, error:Error?)
        -> Void in

        print("location:\(String(describing: location))")
        let locationPath = location!.path

        let documents:String = NSHomeDirectory() + "/Documents/max.scn"
        ls = NSHomeDirectory() + "/Documents"
        let fileManager = FileManager.default

        if (fileManager.fileExists(atPath: documents)){
            try! fileManager.removeItem(atPath: documents)
        }
        try! fileManager.moveItem(atPath: locationPath, toPath: documents)
        print("new location:\(documents)")

    })
    downloadTask.resume()

    self.Modelscene = SCNScene(named: "max.scn", inDirectory: ls)
}
</code>```

答:
Where is your download code?  You shouldn't attempt to load the file until the completion handler is called.  In any case you can check the file size with FileManager.default.attributesOfItem(atPath: ) and see if that matches what you expect.

EDIT:
Your problem is you call self.Modelscene = SCNScene(named: "max.scn", inDirectory: ls) right after downloadTask.resume().  That means you are opening the scene when the download has just started, not after it has finished.  You need to put the scene assignment inside the completion handler so it happens when the download is complete.

Body:
I am working on a project to load a model into a ARKit powered app by scanning a qrCode. I have the qrCode working and .scn file downloaded into a .tmp file. However, when I tried to catch the scene by SCNScene(url:), all what returns is a nil.

I am wondering if it's because I copied the file too early --- before it finishes downloading, since the app freezes right after I scanned the qrCode.

Any suggestions would be appreciated. :D

2017-11-18 added download code

The template: http://www.jianshu.com/p/6ca4864b3600

func sessionSimpleDownload( scnurl: URL){
    let url = scnurl
    let request = URLRequest(url: url)
    let session = URLSession.shared
    var ls: String!

    let downloadTask = session.downloadTask(with: request,
    completionHandler: { (location:URL?, response:URLResponse?, error:Error?)
        -> Void in

        print("location:\(String(describing: location))")
        let locationPath = location!.path

        let documents:String = NSHomeDirectory() + "/Documents/max.scn"
        ls = NSHomeDirectory() + "/Documents"
        let fileManager = FileManager.default

        if (fileManager.fileExists(atPath: documents)){
            try! fileManager.removeItem(atPath: documents)
        }
        try! fileManager.moveItem(atPath: locationPath, toPath: documents)
        print("new location:\(documents)")

    })
    downloadTask.resume()

    self.Modelscene = SCNScene(named: "max.scn", inDirectory: ls)
}


问:
Android fitsSystemWindows not working when replacing fragments
I have SingleFramgnetActivity whose purpose is only to hold and replace fragments inside it.

layout looks like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    tools:context=".SingleFragmentActivity"
    >

    <include layout="@layout/toolbar"/>

    <FrameLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</LinearLayout>
</code>```

I'm replacing the Fragments inside the FrameLayout. When I set the fitsSystemWindows to true on the Fragment layout, it is not responding. Actually it is working only when Activity is created, but once I replace the Fragment inside the FrameLayout, the fitsSystemWindows parameter is ignored and the layout is below the status bar and navigation bar.

I found some solution with custom FrameLayout which is using deprecated methods, but for some reason it is not working for me (same result as with normal FrameLayout) and I also do not like the idea to use deprecated methods.

答:
You could also build a custom WindowInsetsFrameLayout and use a OnHierarchyChangedListener to request applying the insets again:

```<code>public WindowInsetsFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    // Look for replaced fragments and apply the insets again.
    setOnHierarchyChangeListener(new OnHierarchyChangeListener() {
        @Override
        public void onChildViewAdded(View parent, View child) {
            requestApplyInsets();
        }

        @Override
        public void onChildViewRemoved(View parent, View child) {

        }
    });
}
</code>```

Check out this detailed answer: https://stackoverflow.com/a/47349880/3979479

Body:
I have SingleFramgnetActivity whose purpose is only to hold and replace fragments inside it.

layout looks like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    tools:context=".SingleFragmentActivity"
    >

    <include layout="@layout/toolbar"/>

    <FrameLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</LinearLayout>

I'm replacing the Fragments inside the FrameLayout. When I set the fitsSystemWindows to true on the Fragment layout, it is not responding. Actually it is working only when Activity is created, but once I replace the Fragment inside the FrameLayout, the fitsSystemWindows parameter is ignored and the layout is below the status bar and navigation bar.

I found some solution with custom FrameLayout which is using deprecated methods, but for some reason it is not working for me (same result as with normal FrameLayout) and I also do not like the idea to use deprecated methods.

Body:
You could also build a custom WindowInsetsFrameLayout and use a OnHierarchyChangedListener to request applying the insets again:

public WindowInsetsFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    // Look for replaced fragments and apply the insets again.
    setOnHierarchyChangeListener(new OnHierarchyChangeListener() {
        @Override
        public void onChildViewAdded(View parent, View child) {
            requestApplyInsets();
        }

        @Override
        public void onChildViewRemoved(View parent, View child) {

        }
    });
}

Check out this detailed answer: https://stackoverflow.com/a/47349880/3979479


问:
Printing very large BigIntegers to a file in Java
I'm trying to print a very large BigInteger to a .txt file, but when the number reaches a certain size, it prints nothing. Code:

```<code>BigInteger bi = new BigInteger("16777216");
int exponent = 1000000;
bi = bi.pow(exponent);

String txtToPrint = bi.toString();
sendToFile(txtToPrint, "output.txt");

private static void sendToFile(String txtToPrint, String fileName) {

        try {

            FileWriter fileWriter = new FileWriter(fileName);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(txtToPrint);

            bufferedWriter.close();
        }
        catch(IOException e) {
            System.out.println("Error writing to file '" + fileName + "'");
        }

}
</code>```

Whenever the exponent is greater than 566 the output file is empty, instead of containing the number. The goal is to have an exponent of 1 000 000, or even greater.

I thought BigInteger did not have a size limit, so my question is: What limit am I exceeding and is there a way to solve this problem?

EDIT: When trying to flush and close the filewriter, I got this exception:

```<code>java.io.IOException: Stream closed
at sun.nio.cs.StreamEncoder.ensureOpen(Unknown Source)
at sun.nio.cs.StreamEncoder.flush(Unknown Source)
at java.io.OutputStreamWriter.flush(Unknown Source)
at PrintInt.main(PrintInt.java:4
</code>```

EDIT: The problem only occurs when running the program in Eclipse, I tried exporting it to an external jar, and everything worked just fine. I am using Eclipse Mars.1 Release (4.5.1) and Java jre1.8.0_131 and Cp1252 encoding.

答:
I would say, the String size is maybe the limit.

You should be able to get a String of length Integer.MAX_VALUE (always 2147483647 (231 - 1) by the Java specification, the maximum size of an array, which the String class uses for internal storage) or half your maximum heap size (since each character is two bytes), whichever is smaller.

Body:
I'm trying to print a very large BigInteger to a .txt file, but when the number reaches a certain size, it prints nothing. Code:

BigInteger bi = new BigInteger("16777216");
int exponent = 1000000;
bi = bi.pow(exponent);

String txtToPrint = bi.toString();
sendToFile(txtToPrint, "output.txt");

private static void sendToFile(String txtToPrint, String fileName) {

        try {

            FileWriter fileWriter = new FileWriter(fileName);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(txtToPrint);

            bufferedWriter.close();
        }
        catch(IOException e) {
            System.out.println("Error writing to file '" + fileName + "'");
        }

}

Whenever the exponent is greater than 566 the output file is empty, instead of containing the number. The goal is to have an exponent of 1 000 000, or even greater.

I thought BigInteger did not have a size limit, so my question is: What limit am I exceeding and is there a way to solve this problem?

EDIT: When trying to flush and close the filewriter, I got this exception:

java.io.IOException: Stream closed
at sun.nio.cs.StreamEncoder.ensureOpen(Unknown Source)
at sun.nio.cs.StreamEncoder.flush(Unknown Source)
at java.io.OutputStreamWriter.flush(Unknown Source)
at PrintInt.main(PrintInt.java:4

EDIT: The problem only occurs when running the program in Eclipse, I tried exporting it to an external jar, and everything worked just fine. I am using Eclipse Mars.1 Release (4.5.1) and Java jre1.8.0_131 and Cp1252 encoding.


问:
NSTimer usage in Xamarin Ios
I am trying to build a App in IOS where I want UIButton to continuously change its background colour.
I tried using Timer was not able to do it properly.
I want the colour background to continuously change colour.
If anyone has any idea please suggest</p>

答:
```<code>void StartButton_TouchUpInside (object sender, EventArgs ea) {
_timer = NSTimer.CreateRepeatingScheduledTimer(TimeSpan.FromSeconds(1), () =>
{
    this.InvokeOnMainThread(()=>{
        //Your code goes here
    });
}
</code>```

To Start the Timer

```<code>_timer.Fire();
</code>```

To End The Timer

```<code>_timer.Invalidate();
</code>```

Title: NSTimer usage in Xamarin Ios

Body:
void StartButton_TouchUpInside (object sender, EventArgs ea) {
_timer = NSTimer.CreateRepeatingScheduledTimer(TimeSpan.FromSeconds(1), () =>
{
    this.InvokeOnMainThread(()=>{
        //Your code goes here
    });
}

To Start the Timer

_timer.Fire();

To End The Timer

_timer.Invalidate();


问:
Webview in Swift
I want to integrate webpage into an Ios application.
I have created a webpage using D3 js and SVG elements.
I am trying to display the webpage on Ipad Pro 12.9" 2nd generation.
But somehow it is showing only a 1/4 portion of my webpage in webView.

Here is the webpage URL -
http://ec2-54-198-148-171.compute-1.amazonaws.com/webapp/question

I got iPad pro-resolution from apple website which is 1366X1024 so I have created a webpage for the same resolution.

I have verified webpage on browsers like safari, chrome, firefox and it's looking perfect on it with 1366X1024 resolution.

Attached screenshot BrowserScreenCap taken with 1366 X 1024 on browser and IpadAppScreenCap took on iPad application.
I am using WKwebView on IOS side. I have verified webpage layout on simulator only.
How we make that webpage fullscreen?

答:
add the below tag into your html body

```<code><meta name=\"viewport\" content=\"width=device-width, initial-scale=1,user-scalable=no\">
</code>```

if you want you can enable user-scable=yes for zooming

Title: Webview in Swift

Body:
add the below tag into your html body

<meta name=\"viewport\" content=\"width=device-width, initial-scale=1,user-scalable=no\">

if you want you can enable user-scable=yes for zooming


问:
How do I write an arrow function in ES6 recursively?
Arrow functions in ES6 do not have an arguments property and therefore arguments.callee will not work and would anyway not work in strict mode even if just an anonymous function was being used.

Arrow functions cannot be named, so the named functional expression trick can not be used.

So... How does one write a recursive arrow function? That is an arrow function that recursively calls itself based on certain conditions and so on of-course?

答:
I found the provided solutions really complicated, and honestly couldn't understand any of them, so i thought out a simpler solution myself (I'm sure it's already known, but here goes my thinking process):

So you're making a factorial function

```<code>x => x < 2 ? x : x * (???)
</code>```

the (???) is where the function is supposed to call itself, but since you can't name it, the obvious solution is to pass it as an argument to itself

```<code>f => x => x < 2 ? x : x * f(x-1)
</code>```

This won't work though. because when we call f(x-1) we're calling this function itself, and we just defined it's arguments as 1) f: the function itself, again and 2) x the value. Well we do have the function itself, f remember? so just pass it first:

```<code>f => x => x < 2 ? x : x * f(f)(x-1)
                            ^ the new bit
</code>```

And that's it. We just made a function that takes itself as the first argument, producing the Factorial function! Just literally pass it to itself:

```<code>(f => x => x < 2 ? x : x * f(f)(x-1))(f => x => x < 2 ? x : x * f(f)(x-1))(5)
>120
</code>```

Instead of writing it twice, you can make another function that passes it's argument to itself:

```<code>y => y(y)
</code>```

and pass your factorial making function to it:

```<code>(y => y(y))(f => x => x < 2 ? x : x * f(f)(x-1))(5)
>120
</code>```

Boom. Here's a little formula:

```<code>(y => y(y))(f => x => endCondition(x) ? default(x) : operation(x)(f(f)(nextStep(x))))
</code>```

For a basic function that adds numbers from 0 to x, endCondition is when you need to stop recurring, so x => x == 0. default is the last value you give once endCondition is met, so x => x. operation is simply the operation you're doing on every recursion, like multiplying in Factorial or adding in Fibonacci: x1 => x2 => x1 + x2. and lastly nextStep is the next value to pass to the function, which is usually the current value minus one: x => x - 1. Apply:

```<code>(y => y(y))(f => x => x == 0 ? x : x + f(f)(x - 1))(5)
>15
</code>```

Body:
I found the provided solutions really complicated, and honestly couldn't understand any of them, so i thought out a simpler solution myself (I'm sure it's already known, but here goes my thinking process):

So you're making a factorial function

x => x < 2 ? x : x * (???)

the (???) is where the function is supposed to call itself, but since you can't name it, the obvious solution is to pass it as an argument to itself

f => x => x < 2 ? x : x * f(x-1)

This won't work though. because when we call f(x-1) we're calling this function itself, and we just defined it's arguments as 1) f: the function itself, again and 2) x the value. Well we do have the function itself, f remember? so just pass it first:

f => x => x < 2 ? x : x * f(f)(x-1)
                            ^ the new bit

And that's it. We just made a function that takes itself as the first argument, producing the Factorial function! Just literally pass it to itself:

(f => x => x < 2 ? x : x * f(f)(x-1))(f => x => x < 2 ? x : x * f(f)(x-1))(5)
>120

Instead of writing it twice, you can make another function that passes it's argument to itself:

y => y(y)

and pass your factorial making function to it:

(y => y(y))(f => x => x < 2 ? x : x * f(f)(x-1))(5)
>120

Boom. Here's a little formula:

(y => y(y))(f => x => endCondition(x) ? default(x) : operation(x)(f(f)(nextStep(x))))

For a basic function that adds numbers from 0 to x, endCondition is when you need to stop recurring, so x => x == 0. default is the last value you give once endCondition is met, so x => x. operation is simply the operation you're doing on every recursion, like multiplying in Factorial or adding in Fibonacci: x1 => x2 => x1 + x2. and lastly nextStep is the next value to pass to the function, which is usually the current value minus one: x => x - 1. Apply:

(y => y(y))(f => x => x == 0 ? x : x + f(f)(x - 1))(5)
>15

ContentLicense: CC BY-SA 4.0


问:
android settext for textview from relative weakreference
I have an Activity and an inner class with name InnerClass in it which its updateAfterDelay() method must update a TextView . I want to avoid memory leak. So I changed InnerClass to static and try to use WeakReference like this:

```<code>public class MainActivity extends Activity {

    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate ( savedInstanceState );
        setContentView ( R.layout.main );

        textView = (TextView) findViewById ( R.id.textView );
    }

    private static class InnerClass {

        private final WeakReference<TextView> targetTextView;

        public InnerClass(TextView targetTextView) {
            this.targetTextView = new WeakReference<TextView> ( targetTextView );
        }

        void updateAfterDelay() {
            targetTextView.setText ( "text" );
        }

    }

}
</code>```

But on targetTextView.setText ( "text" ); I get this compile error:

```<code>cannot resolve method 'setText(java.lang.String)'
</code>```

How I can solve above problem?

答:
Get TextView and set text.</p>

```<code>targetTextView.get().setText ( "text" );
</code>```

Body:
I have an Activity and an inner class with name InnerClass in it which its updateAfterDelay() method must update a TextView . I want to avoid memory leak. So I changed InnerClass to static and try to use WeakReference like this:

public class MainActivity extends Activity {

    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate ( savedInstanceState );
        setContentView ( R.layout.main );

        textView = (TextView) findViewById ( R.id.textView );
    }

    private static class InnerClass {

        private final WeakReference<TextView> targetTextView;

        public InnerClass(TextView targetTextView) {
            this.targetTextView = new WeakReference<TextView> ( targetTextView );
        }

        void updateAfterDelay() {
            targetTextView.setText ( "text" );
        }

    }

}

But on targetTextView.setText ( "text" ); I get this compile error:

cannot resolve method 'setText(java.lang.String)'

How I can solve above problem?

Body:
Get TextView and set text.

targetTextView.get().setText ( "text" );


问:
Polymer routes not working Polymer starter kit
I cloned polymer starter kit and its working perfectly fine.

So in the placeholder route there is a page called
http://localhost:5000/users/Rob.
The above url works if I move from users page to Rob page by clicking on the rob link.

but if I directly paste on http://localhost:5000/users/Rob on browser and press enter, it does not work.

I assume the above might be resolved by using htaccess. but couldn't figure out how.

Below is my .htaccess code

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* /index.html [L,R=302]
</code>```

答:
Removing [L,R=302] did the trick for me!

.htaccess:

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* /
</code>```

index.html:

<app-route
route="{{route}}"
pattern="/users/:id"
data="{{usersRouteData}}"
tail="{{usersSubroute}}"
active="{{usersActive}}"
></app-route>
```

Body:
I cloned polymer starter kit and its working perfectly fine.

So in the placeholder route there is a page called
http://localhost:5000/users/Rob.
The above url works if I move from users page to Rob page by clicking on the rob link.

but if I directly paste on http://localhost:5000/users/Rob on browser and press enter, it does not work.

I assume the above might be resolved by using htaccess. but couldn't figure out how.

Below is my .htaccess code

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* /index.html [L,R=302]

Body:
Removing [L,R=302] did the trick for me!

.htaccess:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* /

index.html:

<app-route
route="{{route}}"
pattern="/users/:id"
data="{{usersRouteData}}"
tail="{{usersSubroute}}"
active="{{usersActive}}"
></app-route>


问:
Amazon S3 - Images sometimes 404
I'm using Amazon S3 for images and randomly images 404 when loading from Amazon S3?

Why? How can I fix this bug?

Thanks

答:
Actually this is no bug.

S3 has been designed to only come close to a 0% error rate. Some requests will always fail.

Because of this you will need to implement a method on your side to try multiple times to load an image before you give up.

ContentLicense: CC BY-SA 2.5

Title: Amazon S3 - Images sometimes 404


问:
How to use SearchView.OnQueryTextListener() in searchable spinner?
I'm creating a searchable spinner using third party library. I have added library classes(SearchableListDialog, SearchableSpinner) in my app. Everything is working fine but still one problem I'm facing for example, In search-view widget if I search Abc, I'm not getting the result filtered as Abc but when clicking on the list-view items, results is showing item as Abc. It is like the position is change for the items but the list is not showing the searchable result. I'm not getting where is I'm wrong. I modified code many times but didn't get desirable result.

Searchable Spinner xml code:

```<code> <com.example.my.currencyconverterapp.activity.SearchableSpinner
                    android:id="@+id/spinner"
                    android:layout_below="@+id/rl_currency_converterted_data"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
</code>```

This is my Fragment code where I'm setting a adapter to searchable spinner.

```<code>countriesCustomAdapterInr = new CountriesCustomAdapterInr(getActivity(), R.layout.custom_spinner_items, arrayList,res);
        spinner.setAdapter(countriesCustomAdapterInr);
        assert spinner != null;
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(getActivity(), ""+arrayList.get(i).getFull_name()+i, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {}
        });
</code>```

This is third party SearchableSpinner class:

```<code>public class SearchableSpinner extends android.support.v7.widget.AppCompatSpinner implements View.OnTouchListener,
        SearchableListDialog.SearchableItem {

    public static final int NO_ITEM_SELECTED = -1;
    private Context _context;
    private List _items;
    private SearchableListDialog _searchableListDialog;

    private boolean _isDirty;
    private ArrayAdapter _arrayAdapter;
    private String _strHintText;
    private boolean _isFromInit;

    public SearchableSpinner(Context context) {
        super(context);
        this._context = context;
        init();
    }

    public SearchableSpinner(Context context, AttributeSet attrs) {
        super(context, attrs);
        this._context = context;
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SearchableSpinner);
        final int N = a.getIndexCount();
        for (int i = 0; i < N; ++i) {
            int attr = a.getIndex(i);
            if (attr == R.styleable.SearchableSpinner_hintText) {
                _strHintText = a.getString(attr);
            }
        }
        a.recycle();
        init();
    }

    public SearchableSpinner(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this._context = context;
        init();
    }

    private void init() {
        _items = new ArrayList();
        _searchableListDialog = SearchableListDialog.newInstance
                (_items);
        _searchableListDialog.setOnSearchableItemClickListener(this);
        setOnTouchListener(this);

        _arrayAdapter = (ArrayAdapter) getAdapter();
        if (!TextUtils.isEmpty(_strHintText)) {
            ArrayAdapter arrayAdapter = new ArrayAdapter(_context, android.R.layout
                    .simple_list_item_1, new String[]{_strHintText});
            _isFromInit = true;
            setAdapter(arrayAdapter);
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {

            if (null != _arrayAdapter) {

                // Refresh content #6
                // Change Start
                // Description: The items were only set initially, not reloading the data in the
                // spinner every time it is loaded with items in the adapter.
                _items.clear();
                for (int i = 0; i < _arrayAdapter.getCount(); i++) {
                    _items.add(_arrayAdapter.getItem(i));
                }
                // Change end.

                _searchableListDialog.show(scanForActivity(_context).getFragmentManager(), "TAG");
            }
        }
        return true;
    }

    @Override
    public void setAdapter(SpinnerAdapter adapter) {

        if (!_isFromInit) {
            _arrayAdapter = (ArrayAdapter) adapter;
            if (!TextUtils.isEmpty(_strHintText) && !_isDirty) {
                ArrayAdapter arrayAdapter = new ArrayAdapter(_context, android.R.layout
                        .simple_list_item_1, new String[]{_strHintText});
                super.setAdapter(arrayAdapter);
            } else {
                super.setAdapter(adapter);
            }

        } else {
            _isFromInit = false;
            super.setAdapter(adapter);
        }
    }

    @Override
    public void onSearchableItemClicked(Object item, int position) {
        setSelection(_items.indexOf(item));

        if (!_isDirty) {
            _isDirty = true;
            setAdapter(_arrayAdapter);
            setSelection(_items.indexOf(item));
        }
    }

    public void setTitle(String strTitle) {
        _searchableListDialog.setTitle(strTitle);
    }

    public void setPositiveButton(String strPositiveButtonText) {
        _searchableListDialog.setPositiveButton(strPositiveButtonText);
    }

    public void setPositiveButton(String strPositiveButtonText, DialogInterface.OnClickListener onClickListener) {
        _searchableListDialog.setPositiveButton(strPositiveButtonText, onClickListener);
    }

    public void setOnSearchTextChangedListener(SearchableListDialog.OnSearchTextChanged onSearchTextChanged) {
        _searchableListDialog.setOnSearchTextChangedListener(onSearchTextChanged);
    }

    private Activity scanForActivity(Context cont) {
        if (cont == null)
            return null;
        else if (cont instanceof Activity)
            return (Activity) cont;
        else if (cont instanceof ContextWrapper)
            return scanForActivity(((ContextWrapper) cont).getBaseContext());

        return null;
    }

    @Override
    public int getSelectedItemPosition() {
        if (!TextUtils.isEmpty(_strHintText) && !_isDirty) {
            return NO_ITEM_SELECTED;
        } else {
            return super.getSelectedItemPosition();
        }
    }

    @Override
    public Object getSelectedItem() {
        if (!TextUtils.isEmpty(_strHintText) && !_isDirty) {
            return null;
        } else {
            return super.getSelectedItem();
        }
    }
}
</code>```

This is third party SearchableListDialog class:

```<code>public class SearchableListDialog extends DialogFragment implements
        SearchView.OnQueryTextListener, SearchView.OnCloseListener {

    private static final String ITEMS = "items";

    private CountriesCustomAdapterInr listAdapter;

    private ListView _listViewItems;

    private SearchableItem _searchableItem;

    private OnSearchTextChanged _onSearchTextChanged;

    private SearchView _searchView;

    private String _strTitle;

    private String _strPositiveButtonText;

    private DialogInterface.OnClickListener _onClickListener;

    public SearchableListDialog() {

    }

    public static SearchableListDialog newInstance(List items) {
        SearchableListDialog multiSelectExpandableFragment = new
                SearchableListDialog();

        Bundle args = new Bundle();
        args.putSerializable(ITEMS, (Serializable) items);

        multiSelectExpandableFragment.setArguments(args);

        return multiSelectExpandableFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams
                .SOFT_INPUT_STATE_HIDDEN);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        // Getting the layout inflater to inflate the view in an alert dialog.
        LayoutInflater inflater = LayoutInflater.from(getActivity());

        // Crash on orientation change #7
        // Change Start
        // Description: As the instance was re initializing to null on rotating the device,
        // getting the instance from the saved instance
        if (null != savedInstanceState) {
            _searchableItem = (SearchableItem) savedInstanceState.getSerializable("item");
        }
        // Change End

        View rootView = inflater.inflate(R.layout.searchable_list_dialog, null);
        setData(rootView);

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
        alertDialog.setView(rootView);

        String strPositiveButton = _strPositiveButtonText == null ? "CLOSE" : _strPositiveButtonText;
        alertDialog.setPositiveButton(strPositiveButton, _onClickListener);

//        String strTitle = _strTitle == null ? "Select Country" : _strTitle;
//        alertDialog.setTitle(strTitle);

        final AlertDialog dialog = alertDialog.create();
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams
                .SOFT_INPUT_STATE_HIDDEN);
        return dialog;
    }

    // Crash on orientation change #7
    // Change Start
    // Description: Saving the instance of searchable item instance.
    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putSerializable("item", _searchableItem);
        super.onSaveInstanceState(outState);
    }
    // Change End

    public void setTitle(String strTitle) {
        _strTitle = strTitle;
    }

    public void setPositiveButton(String strPositiveButtonText) {
        _strPositiveButtonText = strPositiveButtonText;
    }

    public void setPositiveButton(String strPositiveButtonText, DialogInterface.OnClickListener onClickListener) {
        _strPositiveButtonText = strPositiveButtonText;
        _onClickListener = onClickListener;
    }

    public void setOnSearchableItemClickListener(SearchableItem searchableItem) {
        this._searchableItem = searchableItem;
    }

    public void setOnSearchTextChangedListener(OnSearchTextChanged onSearchTextChanged) {
        this._onSearchTextChanged = onSearchTextChanged;
    }

    private void setData(View rootView) {
        SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);

        _searchView = (SearchView) rootView.findViewById(R.id.search);
        _searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName
                ()));
        _searchView.setIconifiedByDefault(false);
        _searchView.setOnQueryTextListener(this);
        _searchView.setOnCloseListener(this);
        _searchView.setQueryHint("Search Country");
        _searchView.clearFocus();
        InputMethodManager mgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        mgr.hideSoftInputFromWindow(_searchView.getWindowToken(), 0);

        List items = (List) getArguments().getSerializable(ITEMS);

        _listViewItems = (ListView) rootView.findViewById(R.id.listItems);

        //create the adapter by passing your ArrayList data
//        listAdapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, items);
listAdapter = new CountriesCustomAdapterInr(getActivity(), R.layout.custom_spinner_items, arrayList, getResources());
//

        //attach the adapter to the list
        _listViewItems.setAdapter(listAdapter);

        _listViewItems.setTextFilterEnabled(true);

        _listViewItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                _searchableItem.onSearchableItemClicked(listAdapter.getItem(position), position);
                getDialog().dismiss();
            }
        });
    }

    @Override
    public boolean onClose() {
        return false;
    }

    @Override
    public boolean onQueryTextSubmit(String s) {
        _searchView.clearFocus();
        return true;
    }

    @Override
    public boolean onQueryTextChange(String s) {
//        listAdapter.filterData(s);
        if (TextUtils.isEmpty(s)) {
//                _listViewItems.clearTextFilter();
            ((ArrayAdapter) _listViewItems.getAdapter()).getFilter().filter(null);
        } else {
            ((ArrayAdapter) _listViewItems.getAdapter()).getFilter().filter(s);
        }
        if (null != _onSearchTextChanged) {
            _onSearchTextChanged.onSearchTextChanged(s);
        }
        return true;
    }

    public interface SearchableItem<T> extends Serializable {
        void onSearchableItemClicked(T item, int position);
    }

    public interface OnSearchTextChanged {
        void onSearchTextChanged(String strText);
    }
}
</code>```

Here OnQueryTextListener() not working fine. Please help me. I tried but didn't any solution. Can anyone please help me. Above, I have mentioned my query. Thanks

答:
you can search in your adapter... i didn't see your adapter
you can look my adapter
https://github.com/kenmeidearu/SearchableSpinner/blob/master/searchablespinnerlibrary/src/main/java/com/kenmeidearu/searchablespinnerlibrary/ListAdapterSpinner.java

i give you example

Body:
I'm creating a searchable spinner using third party library. I have added library classes(SearchableListDialog, SearchableSpinner) in my app. Everything is working fine but still one problem I'm facing for example, In search-view widget if I search Abc, I'm not getting the result filtered as Abc but when clicking on the list-view items, results is showing item as Abc. It is like the position is change for the items but the list is not showing the searchable result. I'm not getting where is I'm wrong. I modified code many times but didn't get desirable result.

Searchable Spinner xml code:

 <com.example.my.currencyconverterapp.activity.SearchableSpinner
                    android:id="@+id/spinner"
                    android:layout_below="@+id/rl_currency_converterted_data"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

This is my Fragment code where I'm setting a adapter to searchable spinner.

countriesCustomAdapterInr = new CountriesCustomAdapterInr(getActivity(), R.layout.custom_spinner_items, arrayList,res);
        spinner.setAdapter(countriesCustomAdapterInr);
        assert spinner != null;
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(getActivity(), ""+arrayList.get(i).getFull_name()+i, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {}
        });

This is third party SearchableSpinner class:

public class SearchableSpinner extends android.support.v7.widget.AppCompatSpinner implements View.OnTouchListener,
        SearchableListDialog.SearchableItem {

    public static final int NO_ITEM_SELECTED = -1;
    private Context _context;
    private List _items;
    private SearchableListDialog _searchableListDialog;

    private boolean _isDirty;
    private ArrayAdapter _arrayAdapter;
    private String _strHintText;
    private boolean _isFromInit;

    public SearchableSpinner(Context context) {
        super(context);
        this._context = context;
        init();
    }

    public SearchableSpinner(Context context, AttributeSet attrs) {
        super(context, attrs);
        this._context = context;
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SearchableSpinner);
        final int N = a.getIndexCount();
        for (int i = 0; i < N; ++i) {
            int attr = a.getIndex(i);
            if (attr == R.styleable.SearchableSpinner_hintText) {
                _strHintText = a.getString(attr);
            }
        }
        a.recycle();
        init();
    }

    public SearchableSpinner(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this._context = context;
        init();
    }

    private void init() {
        _items = new ArrayList();
        _searchableListDialog = SearchableListDialog.newInstance
                (_items);
        _searchableListDialog.setOnSearchableItemClickListener(this);
        setOnTouchListener(this);

        _arrayAdapter = (ArrayAdapter) getAdapter();
        if (!TextUtils.isEmpty(_strHintText)) {
            ArrayAdapter arrayAdapter = new ArrayAdapter(_context, android.R.layout
                    .simple_list_item_1, new String[]{_strHintText});
            _isFromInit = true;
            setAdapter(arrayAdapter);
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {

            if (null != _arrayAdapter) {

                // Refresh content #6
                // Change Start
                // Description: The items were only set initially, not reloading the data in the
                // spinner every time it is loaded with items in the adapter.
                _items.clear();
                for (int i = 0; i < _arrayAdapter.getCount(); i++) {
                    _items.add(_arrayAdapter.getItem(i));
                }
                // Change end.

                _searchableListDialog.show(scanForActivity(_context).getFragmentManager(), "TAG");
            }
        }
        return true;
    }

    @Override
    public void setAdapter(SpinnerAdapter adapter) {

        if (!_isFromInit) {
            _arrayAdapter = (ArrayAdapter) adapter;
            if (!TextUtils.isEmpty(_strHintText) && !_isDirty) {
                ArrayAdapter arrayAdapter = new ArrayAdapter(_context, android.R.layout
                        .simple_list_item_1, new String[]{_strHintText});
                super.setAdapter(arrayAdapter);
            } else {
                super.setAdapter(adapter);
            }

        } else {
            _isFromInit = false;
            super.setAdapter(adapter);
        }
    }

    @Override
    public void onSearchableItemClicked(Object item, int position) {
        setSelection(_items.indexOf(item));

        if (!_isDirty) {
            _isDirty = true;
            setAdapter(_arrayAdapter);
            setSelection(_items.indexOf(item));
        }
    }

    public void setTitle(String strTitle) {
        _searchableListDialog.setTitle(strTitle);
    }

    public void setPositiveButton(String strPositiveButtonText) {
        _searchableListDialog.setPositiveButton(strPositiveButtonText);
    }

    public void setPositiveButton(String strPositiveButtonText, DialogInterface.OnClickListener onClickListener) {
        _searchableListDialog.setPositiveButton(strPositiveButtonText, onClickListener);
    }

    public void setOnSearchTextChangedListener(SearchableListDialog.OnSearchTextChanged onSearchTextChanged) {
        _searchableListDialog.setOnSearchTextChangedListener(onSearchTextChanged);
    }

    private Activity scanForActivity(Context cont) {
        if (cont == null)
            return null;
        else if (cont instanceof Activity)
            return (Activity) cont;
        else if (cont instanceof ContextWrapper)
            return scanForActivity(((ContextWrapper) cont).getBaseContext());

        return null;
    }

    @Override
    public int getSelectedItemPosition() {
        if (!TextUtils.isEmpty(_strHintText) && !_isDirty) {
            return NO_ITEM_SELECTED;
        } else {
            return super.getSelectedItemPosition();
        }
    }

    @Override
    public Object getSelectedItem() {
        if (!TextUtils.isEmpty(_strHintText) && !_isDirty) {
            return null;
        } else {
            return super.getSelectedItem();
        }
    }
}

This is third party SearchableListDialog class:

public class SearchableListDialog extends DialogFragment implements
        SearchView.OnQueryTextListener, SearchView.OnCloseListener {

    private static final String ITEMS = "items";

    private CountriesCustomAdapterInr listAdapter;

    private ListView _listViewItems;

    private SearchableItem _searchableItem;

    private OnSearchTextChanged _onSearchTextChanged;

    private SearchView _searchView;

    private String _strTitle;

    private String _strPositiveButtonText;

    private DialogInterface.OnClickListener _onClickListener;

    public SearchableListDialog() {

    }

    public static SearchableListDialog newInstance(List items) {
        SearchableListDialog multiSelectExpandableFragment = new
                SearchableListDialog();

        Bundle args = new Bundle();
        args.putSerializable(ITEMS, (Serializable) items);

        multiSelectExpandableFragment.setArguments(args);

        return multiSelectExpandableFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams
                .SOFT_INPUT_STATE_HIDDEN);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        // Getting the layout inflater to inflate the view in an alert dialog.
        LayoutInflater inflater = LayoutInflater.from(getActivity());

        // Crash on orientation change #7
        // Change Start
        // Description: As the instance was re initializing to null on rotating the device,
        // getting the instance from the saved instance
        if (null != savedInstanceState) {
            _searchableItem = (SearchableItem) savedInstanceState.getSerializable("item");
        }
        // Change End

        View rootView = inflater.inflate(R.layout.searchable_list_dialog, null);
        setData(rootView);

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
        alertDialog.setView(rootView);

        String strPositiveButton = _strPositiveButtonText == null ? "CLOSE" : _strPositiveButtonText;
        alertDialog.setPositiveButton(strPositiveButton, _onClickListener);

//        String strTitle = _strTitle == null ? "Select Country" : _strTitle;
//        alertDialog.setTitle(strTitle);

        final AlertDialog dialog = alertDialog.create();
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams
                .SOFT_INPUT_STATE_HIDDEN);
        return dialog;
    }

    // Crash on orientation change #7
    // Change Start
    // Description: Saving the instance of searchable item instance.
    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putSerializable("item", _searchableItem);
        super.onSaveInstanceState(outState);
    }
    // Change End

    public void setTitle(String strTitle) {
        _strTitle = strTitle;
    }

    public void setPositiveButton(String strPositiveButtonText) {
        _strPositiveButtonText = strPositiveButtonText;
    }

    public void setPositiveButton(String strPositiveButtonText, DialogInterface.OnClickListener onClickListener) {
        _strPositiveButtonText = strPositiveButtonText;
        _onClickListener = onClickListener;
    }

    public void setOnSearchableItemClickListener(SearchableItem searchableItem) {
        this._searchableItem = searchableItem;
    }

    public void setOnSearchTextChangedListener(OnSearchTextChanged onSearchTextChanged) {
        this._onSearchTextChanged = onSearchTextChanged;
    }

    private void setData(View rootView) {
        SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);

        _searchView = (SearchView) rootView.findViewById(R.id.search);
        _searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName
                ()));
        _searchView.setIconifiedByDefault(false);
        _searchView.setOnQueryTextListener(this);
        _searchView.setOnCloseListener(this);
        _searchView.setQueryHint("Search Country");
        _searchView.clearFocus();
        InputMethodManager mgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        mgr.hideSoftInputFromWindow(_searchView.getWindowToken(), 0);

        List items = (List) getArguments().getSerializable(ITEMS);

        _listViewItems = (ListView) rootView.findViewById(R.id.listItems);

        //create the adapter by passing your ArrayList data
//        listAdapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, items);
listAdapter = new CountriesCustomAdapterInr(getActivity(), R.layout.custom_spinner_items, arrayList, getResources());
//

        //attach the adapter to the list
        _listViewItems.setAdapter(listAdapter);

        _listViewItems.setTextFilterEnabled(true);

        _listViewItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                _searchableItem.onSearchableItemClicked(listAdapter.getItem(position), position);
                getDialog().dismiss();
            }
        });
    }

    @Override
    public boolean onClose() {
        return false;
    }

    @Override
    public boolean onQueryTextSubmit(String s) {
        _searchView.clearFocus();
        return true;
    }

    @Override
    public boolean onQueryTextChange(String s) {
//        listAdapter.filterData(s);
        if (TextUtils.isEmpty(s)) {
//                _listViewItems.clearTextFilter();
            ((ArrayAdapter) _listViewItems.getAdapter()).getFilter().filter(null);
        } else {
            ((ArrayAdapter) _listViewItems.getAdapter()).getFilter().filter(s);
        }
        if (null != _onSearchTextChanged) {
            _onSearchTextChanged.onSearchTextChanged(s);
        }
        return true;
    }

    public interface SearchableItem<T> extends Serializable {
        void onSearchableItemClicked(T item, int position);
    }

    public interface OnSearchTextChanged {
        void onSearchTextChanged(String strText);
    }
}

Here OnQueryTextListener() not working fine. Please help me. I tried but didn't any solution. Can anyone please help me. Above, I have mentioned my query. Thanks


问:
Responsive HTML email - Gmail adding classes
I am testing a very basic responsive HTML email template and Gmail (Android) is ignoring the media query.

Here's my very basic test markup:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <meta name="format-detection" content="telephone=no">
  <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;">
  <meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />
  <style type="text/css">@media screen and (max-width:580px) {
    *[class="mob-column"] {float: none!important; width: 100%!important;}
    *[class="hide"] {display:none!important;}
    *[class="100p"] {width:100%!important; height:auto!important;}
  }</style>
  <title>Website</title>
</head>

<body>
  <table class="100p" width="100%" cellpadding="10" cellspacing="0" bgcolor='#ffffff'>
    <tr>
      <td valign="top" align="center">
        <table class="100p" width="650" cellpadding="0" cellspacing="0" bgcolor="#ffffff">
          <tr>
            <td class="mob-column" width="325" align="left" valign="middle">
              <img src="https://www.website.com/img/logo.png" alt="website" width="200" height="26" border="0"/></td>
            <td class="hide" width="325" valign="middle" align="right">
              <span style="font-size:12px;color:#c5c5c5;font-family:Helvetica,Arial,sans-serif;">Having trouble viewing this email? <a style="color:#666666; text-decoration:none;" href="#">click here</a></span>
            </td>
          </tr>
          <tr>
            <td class="mob-column" align="left" valign="middle" colspan="2" height="30" style="padding-left: 15px;">
              <span style="font-size:12px; font-family:Helvetica,Arial,sans-serif;"><a style="color:#c5c5c5; text-decoration:none;" href="tel:111111111">111111111</a><span style="color: #c5c5c5;"> | </span><a style="color:#c5c5c5; text-decoration:none;" href="tel:111111111">111111111</a></span>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>
</code>```

So class mob-column should stack the table cells, and hide should hide the table cell. Yet this is being completely ignored in Gmail on Android.

When I inspect the HTML in Gmail on desktop I can see that the classes have been altered like so:

mob-column is changed to m_1371211720454434058mob-column
hide is changed to m_1371211720454434058hide

I've followed a tutorial on Litmus (https://litmus.com/community/learning/24-how-to-code-a-responsive-email-from-scratch) and I am using https://putsmail.com for testing.

Where am I going wrong with this?

答:
As far as I know, Gmail Android app does not support media query https://litmus.com/help/email-clients/media-query-support/

I highly recommend that you use inline CSS code, maybe you should try using CSS inliner by mailChimp https://templates.mailchimp.com/resources/inline-css/

Body:
I am testing a very basic responsive HTML email template and Gmail (Android) is ignoring the media query.

Here's my very basic test markup:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <meta name="format-detection" content="telephone=no">
  <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;">
  <meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />

  <title>Website</title>

              Having trouble viewing this email? click here

              111111111 | 111111111

So class mob-column should stack the table cells, and hide should hide the table cell. Yet this is being completely ignored in Gmail on Android.

When I inspect the HTML in Gmail on desktop I can see that the classes have been altered like so:

mob-column is changed to m_1371211720454434058mob-column
hide is changed to m_1371211720454434058hide

I've followed a tutorial on Litmus (https://litmus.com/community/learning/24-how-to-code-a-responsive-email-from-scratch) and I am using https://putsmail.com for testing.

Where am I going wrong with this?


问:
RecyclerView is not showing all items in the list
I am using RecyclerView in my app. Every time I open my screen I can see only one item but when I debug it is coming every time to onBindViewHolder method.

Here is my adapter:

```<code>@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.tourist_details_info, parent, false);

    return new ViewHolder(itemView);
}

@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
    try {
            holder.displayName.setText(list.get(position).toUpperCase());
    }catch (Exception e){
       AxeltaLogger.err("error>>>"+e);
    }
}
@Override
public int getItemCount() {
    return list.size();
}
</code>```

and this my RecyclerView:

```<code> RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setHasFixedSize(true);
touristAdapter=new TouristInfoAdapter(list);
recyclerView.setAdapter(touristAdapter);
</code>```

答:
This is the most common mistake everyone makes while using a recyclerView. Instead of using position in the onBindViewHolder you have to use

```<code>holder.getAdapterPosition()
</code>```

while fetching data from a list. The position that you are using in onBindViewHolder is the position of the item on the screen which will be limited to maximum number of items on your current screen.

```<code>@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
    try {
        holder.displayName.setText(list.get(holder.getAdapterPosition().toUpperCase());
    }
    catch (Exception e) {
        AxeltaLogger.err("error>>>" + e);
    }
}
</code>```

Hope this helps.

Body:
I am using RecyclerView in my app. Every time I open my screen I can see only one item but when I debug it is coming every time to onBindViewHolder method.

Here is my adapter:

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.tourist_details_info, parent, false);

    return new ViewHolder(itemView);
}

@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
    try {
            holder.displayName.setText(list.get(position).toUpperCase());
    }catch (Exception e){
       AxeltaLogger.err("error>>>"+e);
    }
}
@Override
public int getItemCount() {
    return list.size();
}

and this my RecyclerView:

 RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setHasFixedSize(true);
touristAdapter=new TouristInfoAdapter(list);
recyclerView.setAdapter(touristAdapter);

Body:
This is the most common mistake everyone makes while using a recyclerView. Instead of using position in the onBindViewHolder you have to use

holder.getAdapterPosition()

while fetching data from a list. The position that you are using in onBindViewHolder is the position of the item on the screen which will be limited to maximum number of items on your current screen.

@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
    try {
        holder.displayName.setText(list.get(holder.getAdapterPosition().toUpperCase());
    }
    catch (Exception e) {
        AxeltaLogger.err("error>>>" + e);
    }
}

Hope this helps.


答:
In Java 8, some information was added to the BigInteger javadoc, giving a minimum supported range and the actual limit of the current implementation:

```<code>BigInteger must support values in the range -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive) and may support values outside of that range.
</code>```

Implementation note: BigInteger constructors and operations throw ArithmeticException when the result is out of the supported range of -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive).

Title: Printing very large BigIntegers to a file in Java

Body:
In Java 8, some information was added to the BigInteger javadoc, giving a minimum supported range and the actual limit of the current implementation:

BigInteger must support values in the range -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive) and may support values outside of that range.

Implementation note: BigInteger constructors and operations throw ArithmeticException when the result is out of the supported range of -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive).


问:
Resource not found in ResourceDictionary for external control
PROBLEM

I would like to style control that is defined in Project B, but used on page in Project A using styles from Project A. I decided to do it by defining Merged Dictionary with styles dictionary that contains keys used in MyCtrl.xaml.

I thought that MyCtrl that is used in MainPage will go up the XAML tree to find the right style if it didn't find it in own xaml (broader scope), but I get exceptions that name/key was not found. Am I doing something wrong, or this idea is incorrect and I should find another solution?

Here is the structure:

I have a 2 projects:

Project A - main application with MainPage page and all styles/resources.

Project B - contains user controls

Project A references Project B.

(Project A) MainPage.xaml

```<code><Page
   xmlns:ext="using:ProjB.Ctrls">
  <Page.Resources>
    <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
         <ResourceDictionary Source="ms-appx:///SomeDir/MyCtrlStyles.xaml" />
         <ResourceDictionary Source="ms-appx:///SomeDir/MainPageStyles.xaml" />
      </ResourceDictionary.MergedDictionaries>
  </Page.Resources>
  …
  <ext: MyCtrl x:Id="myCtrlA" />
  …
</Page>
</code>```

(Project A) MainPageStyles.xaml

```<code><ResourceDictionary>
  <Style x:Key="StyleAAA" />
</ResourceDictionary>
</code>```

(Project A) MainPageStyles.xaml

```<code><ResourceDictionary>
  <Style x:Key="StyleBBB" BasedOn="{StaticResource BodyTextBlockStyle}" TargetType="TextBlock">
    <Setter Property="Margin" Value="24 13 12 0" />
  </Style>
</ResourceDictionary>
</code>```

(Project B) MyCtrl.xaml

```<code><UserControl>
  <TextBlock x:Name="txtA" Style="{StaticResource StyleBBB}" Text="Text A" />
</ UserControl>
</code>```

答:
The correct syntax for the source path should be:

ms-appx:///[Assembly]/[Path]/[Resource File]

So you should add the assembly name to the referenced assembly, like this:

<Page
   xmlns:ext="using:ProjB.Ctrls">
  <Page.Resources>
    <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
         <ResourceDictionary Source="ms-appx:///MyCtrl/SomeDir/MyCtrlStyles.xaml" />
         <ResourceDictionary Source="ms-appx:///SomeDir/MainPageStyles.xaml" />
      </ResourceDictionary.MergedDictionaries>
  </Page.Resources>
  …
  <ext: MyCtrl x:Id="myCtrlA" />
  …
</Page>
```

Body:
PROBLEM

I would like to style control that is defined in Project B, but used on page in Project A using styles from Project A. I decided to do it by defining Merged Dictionary with styles dictionary that contains keys used in MyCtrl.xaml.

I thought that MyCtrl that is used in MainPage will go up the XAML tree to find the right style if it didn't find it in own xaml (broader scope), but I get exceptions that name/key was not found. Am I doing something wrong, or this idea is incorrect and I should find another solution?

Here is the structure:

I have a 2 projects:

Project A - main application with MainPage page and all styles/resources.

Project B - contains user controls

Project A references Project B.

(Project A) MainPage.xaml

<Page
   xmlns:ext="using:ProjB.Ctrls">
  <Page.Resources>
    <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
         <ResourceDictionary Source="ms-appx:///SomeDir/MyCtrlStyles.xaml" />
         <ResourceDictionary Source="ms-appx:///SomeDir/MainPageStyles.xaml" />
      </ResourceDictionary.MergedDictionaries>
  </Page.Resources>
  …
  <ext: MyCtrl x:Id="myCtrlA" />
  …
</Page>

(Project A) MainPageStyles.xaml

<ResourceDictionary>

</ResourceDictionary>

(Project B) MyCtrl.xaml

<UserControl>
  <TextBlock x:Name="txtA" Style="{StaticResource StyleBBB}" Text="Text A" />
</ UserControl>


问:
Fragment Not Replaced In ViewPager
I am trying to replace a fragment displayed in a tab using TabLayout and ViewPager as shown below:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="in.netstreamtech.phonebuylogin.LoginRegisterActivity"
    android:paddingLeft="32.5dp"
    android:paddingTop="27dp"
    android:paddingRight="30dp">
    <LinearLayout
        android:id="@+id/main_layout"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/signInReOtpHeader"
            android:layout_width="268dp"
            android:layout_height="122dp"
            android:includeFontPadding="true"
            android:maxLines="2"
            android:text="Welcome \nback."
            android:layout_gravity="center_vertical"
            android:textColor="#1aa4b8"
            android:textSize="35sp" />
        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="wrap_content"
            android:layout_height="47dp"
            android:minHeight="?attr/actionBarSize"
            android:elevation="6dp" />
        <!-- View pager to swipe views -->
        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>
</android.support.constraint.ConstraintLayout>
</code>```

From my Fragment:

```<code>@Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof RegisterMainToActivity) {
            listener = (RegisterMainToActivity) context;
        }
    }
</code>```

Then later in the same fragment:

```<code>listener.passData(userRegistration);
</code>```

The Interface:

```<code>public interface RegisterMainToActivity {
    void passData(UserRegistration data);
}
</code>```

In My Activity(LoginRegisterActivity):

```<code>public class LoginRegisterActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener, RegisterMainToActivity {

    //This is our tablayout
    private TabLayout tabLayout;

    //This is our viewPager
    private ViewPager viewPager;

    private LoginPager adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_register);

        //Initializing viewPager
        viewPager = (ViewPager) findViewById(R.id.pager);
        createViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        tabLayout.setupWithViewPager(viewPager);
        createTabIcons();

    }

    private void createTabIcons() {

        TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.login_cutom_tab_view, null);
        tabOne.setText("SIGN IN");
        tabLayout.getTabAt(0).setCustomView(tabOne);

        TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.login_cutom_tab_view, null);
        tabTwo.setText("REGISTER");
        tabLayout.getTabAt(1).setCustomView(tabTwo);

    }

    private void createViewPager(ViewPager viewPager) {
        adapter = new LoginPager(getSupportFragmentManager());
        adapter.addFrag(new Login(), "SIGN IN");
        adapter.addFrag(new RegisterMain(), "REGISTER");
        viewPager.setAdapter(adapter);
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            //tabLayout.setBackground(getResources().getDrawable(R.drawable.login_tab_selected));
        }
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            //tabLayout.setBackground(getResources().getDrawable(R.drawable.login_tab_unselected));
        }
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    @Override
    public void passData(UserRegistration data) {
        RegisterOtp registerOtpFrag = new RegisterOtp();
        adapter.replaceFragment(registerOtpFrag, 1, "REGISTER");
        //adapter = new LoginPager(getSupportFragmentManager());
        //adapter.addFrag(new Login(), "SIGN IN");
        //adapter.addFrag(new RegisterOtp(), "REGISTER");
        //adapter.clearFragments();
        //adapter.addFrag(new Login(), "SIGN IN");
        //adapter.addFrag(new RegisterOtp(), "REGISTER");
        //viewPager.setAdapter(adapter);

        createTabIcons();
    }

//    public void attemptRegister(View v){
//        TextView registerName = (TextView) v.getContext()findViewById(R.id.register_name);
//        Toast.makeText(
//                getApplicationContext(),
//                registerName.getText(),
//                Toast.LENGTH_SHORT
//        ).show();
//    }

}
</code>```

In the function passData , I am trying to replace a fragment. I want this added to the backstack.

In my adapter class:

```<code>public class LoginPager extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public LoginPager(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {

        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFrag(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    public void replaceFragment(Fragment fragment, int index, String title) {
        mFragmentList.remove(index);
        mFragmentList.add(index, fragment);
        mFragmentTitleList.add(title);
        notifyDataSetChanged();
    }

    public void  clearFragments()
    {
        mFragmentList.clear();
        notifyDataSetChanged();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }

    @Override
    public int getItemPosition(Object object) {
        return this.POSITION_NONE;
    }
}
</code>```

I have tried many variations, including trying to clear the adapter and recreate the fragments. Whatever I do I am not able to replace the desired Fragment(RegisterMain with RegisterOtp). Ideally I should just be able to replace it... Please help!!!

答:
FragmentStatePagerAdapter works for me.

```<code>public class LoginPager extends FragmentStatePagerAdapter {...}
</code>```

FragmentPagerAdapter.notifyDataSetChanged() didn't clear those already committed fragments.

FragmentPagerAdapter is best for use when there are a handful of
typically more static fragments to be paged.

Title: Fragment Not Replaced In ViewPager

Body:
I am trying to replace a fragment displayed in a tab using TabLayout and ViewPager as shown below:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="in.netstreamtech.phonebuylogin.LoginRegisterActivity"
    android:paddingLeft="32.5dp"
    android:paddingTop="27dp"
    android:paddingRight="30dp">
    <LinearLayout
        android:id="@+id/main_layout"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/signInReOtpHeader"
            android:layout_width="268dp"
            android:layout_height="122dp"
            android:includeFontPadding="true"
            android:maxLines="2"
            android:text="Welcome \nback."
            android:layout_gravity="center_vertical"
            android:textColor="#1aa4b8"
            android:textSize="35sp" />
        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="wrap_content"
            android:layout_height="47dp"
            android:minHeight="?attr/actionBarSize"
            android:elevation="6dp" />

        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>
</android.support.constraint.ConstraintLayout>

From my Fragment:

@Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof RegisterMainToActivity) {
            listener = (RegisterMainToActivity) context;
        }
    }

Then later in the same fragment:

listener.passData(userRegistration);

The Interface:

public interface RegisterMainToActivity {
    void passData(UserRegistration data);
}

In My Activity(LoginRegisterActivity):

public class LoginRegisterActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener, RegisterMainToActivity {

    //This is our tablayout
    private TabLayout tabLayout;

    //This is our viewPager
    private ViewPager viewPager;

    private LoginPager adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_register);

        //Initializing viewPager
        viewPager = (ViewPager) findViewById(R.id.pager);
        createViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        tabLayout.setupWithViewPager(viewPager);
        createTabIcons();

    }

    private void createTabIcons() {

        TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.login_cutom_tab_view, null);
        tabOne.setText("SIGN IN");
        tabLayout.getTabAt(0).setCustomView(tabOne);

        TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.login_cutom_tab_view, null);
        tabTwo.setText("REGISTER");
        tabLayout.getTabAt(1).setCustomView(tabTwo);

    }

    private void createViewPager(ViewPager viewPager) {
        adapter = new LoginPager(getSupportFragmentManager());
        adapter.addFrag(new Login(), "SIGN IN");
        adapter.addFrag(new RegisterMain(), "REGISTER");
        viewPager.setAdapter(adapter);
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            //tabLayout.setBackground(getResources().getDrawable(R.drawable.login_tab_selected));
        }
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            //tabLayout.setBackground(getResources().getDrawable(R.drawable.login_tab_unselected));
        }
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    @Override
    public void passData(UserRegistration data) {
        RegisterOtp registerOtpFrag = new RegisterOtp();
        adapter.replaceFragment(registerOtpFrag, 1, "REGISTER");
        //adapter = new LoginPager(getSupportFragmentManager());
        //adapter.addFrag(new Login(), "SIGN IN");
        //adapter.addFrag(new RegisterOtp(), "REGISTER");
        //adapter.clearFragments();
        //adapter.addFrag(new Login(), "SIGN IN");
        //adapter.addFrag(new RegisterOtp(), "REGISTER");
        //viewPager.setAdapter(adapter);

        createTabIcons();
    }

//    public void attemptRegister(View v){
//        TextView registerName = (TextView) v.getContext()findViewById(R.id.register_name);
//        Toast.makeText(
//                getApplicationContext(),
//                registerName.getText(),
//                Toast.LENGTH_SHORT
//        ).show();
//    }

}

In the function passData , I am trying to replace a fragment. I want this added to the backstack.

In my adapter class:

public class LoginPager extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public LoginPager(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {

        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFrag(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    public void replaceFragment(Fragment fragment, int index, String title) {
        mFragmentList.remove(index);
        mFragmentList.add(index, fragment);
        mFragmentTitleList.add(title);
        notifyDataSetChanged();
    }

    public void  clearFragments()
    {
        mFragmentList.clear();
        notifyDataSetChanged();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }

    @Override
    public int getItemPosition(Object object) {
        return this.POSITION_NONE;
    }
}

I have tried many variations, including trying to clear the adapter and recreate the fragments. Whatever I do I am not able to replace the desired Fragment(RegisterMain with RegisterOtp). Ideally I should just be able to replace it... Please help!!!

Body:
FragmentStatePagerAdapter works for me.

public class LoginPager extends FragmentStatePagerAdapter {...}

FragmentPagerAdapter.notifyDataSetChanged() didn't clear those already committed fragments.

FragmentPagerAdapter is best for use when there are a handful of
typically more static fragments to be paged.


问:
How to resolve 'Emulator: PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT'
I created an AVD with 8.0. when I'm starting the AVD, it crashes and gives this error:

Emulator: PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT

I tried to resolve it by a previous answers available here, but none of them are working. I also tried defining AVD path in system settings, but that also didn't worked.

I'm using Android Studio 3.0 and system image for AVD 8.0 (Oreo)(API level 26).

答:
I solved my issue like this...

Go to 'My Computer'-> 'Properties' ->'Advance System Settings' -> 'Environment Variables' -> inside 'System Variables' add "ANDROID_SDK_ROOT" or "ANDROID_HOME" and inside this set the path of your AVD.

After that Restart your Computer. You must Restart your computer, otherwise it won't work.

This method worked for me, situations may be different in other cases.
Look here for more information.


问:
StringFormat in XAML, WPF : Currency Formatting
How can i obtain currency formatting according to my country i.e indian rupee, INR or Rs ??

Please tell me the way to achieve this ??
Right now when i use StringFormat="{}{0:C}", "$" is being used

I have gone through this link and i am able to achieve the desired result but i am worried about using this in my project. Is this code safe ??

What does this line mean in the above link "when you test functionality related to settings change it’s important you start the program directly from a folder window, if you run it from within Visual Studio or any other program you may get incorrect results."

答:
You can specify the culture in your binding like this:

```<code>TextBlock Text="{Binding Value, StringFormat=C, ConverterCulture=nl-BE}"
</code>```

nl-BE is belgian culture, you can exchange it with Indian culture info, I don't know that ;-)

Body:
You can specify the culture in your binding like this:

TextBlock Text="{Binding Value, StringFormat=C, ConverterCulture=nl-BE}"

nl-BE is belgian culture, you can exchange it with Indian culture info, I don't know that ;-)


问:
field 'info' must be a network type
I'm a beginner and I try to create a struct in nesc for a tinyos app, but i have this error that i don't know how to fix.
Any ideas?
The code of the struct is:</p>

```<code>typedef nx_struct Message
{
nx_uint16_t ID
float info;
} messaget;
</code>```

答: I think you're just missing a semicolon after ID. Also, the name you are giving your type is very close to message_t which is already used by TinyOS - I would recommend giving it a more descriptive name, like MyInformationMessage_t.

Title: field 'info' must be a network type

Body:
I'm a beginner and I try to create a struct in nesc for a tinyos app, but i have this error that i don't know how to fix.
Any ideas?
The code of the struct is:

typedef nx_struct Message
{
nx_uint16_t ID
float info;
} messaget;