I am doing python exercise with a book 'headfirst python'
and making android app by using python and sl4a
my code is
import android
import json
import time
from urllib import urlencode
from urllib2 import urlopen
hello_msg = "Welcome to Coach Kelly's Timing App"
list_title = 'Here is your list of athletes:'
quit_msg = "Quitting Coach Kelly's App."
web_server = 'http://127.0.0.1:8080'
get_names_cgi = '/cgi-bin/generate_name.py'
def send_to_server(url, post_data=None):
if post_data:
page = urlopen(url, urlencode(post_data))
else:
page = urlopen(url)
return(page.read().decode("utf8"))
app = android.Android()
def status_update(msg, how_long=2):
app.makeToast(msg)
time.sleep(how_long)
status_update(hello_msg)
athlete_names = sorted(json.loads(send_to_server(web_server + get_names_cgi)))
app.dialogCreateAlert(list_title)
app.dialogSetSingleChoiceItems(athlete_names)
app.dialogSetPositiveButtonText('Select')
app.dialogSetNegativeButtonText('Quit')
app.dialogShow()
resp = app.dialogGetResponse().result
status_update(quit_msg)
this is my code and the result is
what is the problem???
I can not figure out what the problem is...
Use 10.0.2.2:8080
because If you are running both server and emulator in you computer 127.0.0.1:(port) the local IP will refer to the emulator then you need another local IP for the server which will be automatically The 10.0.2.2
hope i clearified it well, glad i helped
Having followed #Coderji 's solution, I was finally able to solve this problem albeit with a different IP address; since the suggested 10.0.2.2 didn't work for me.
What worked for me was to access a terminal, ipconfig, and then used any of the provided ipv4 addresses provided by cmd (all of them seemed to work). Cheers.
Related
Searched everywhere but I fail to find an answer.
Scenario:
Automation script done for an Android application
Pre-req:
Click on a button from the Android application with a Mobile browser redirect
What I want the script to check:
If user was successfully redirected to the Mobile browser by checking if an element from the Mobile browser page is displayed (with a text or link or xpath)
The script is made for the Application but I fail to find the correct code for it to check an element from the browser page
I will post here a small part of code from my automation script for an Android app:
from appium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
import time
if __name__ == "__main__":
desired_cap = {
"platformName": "android",
"deviceName": "emulator-5554",
"appPackage": "com.project.ProjectName",
"appActivity": ".SplashActivity",
"automatorName": "UiAutomator2",
}
driver = webdriver.Remote ("http://localhost:4723/wd/hub",desired_cap)
#Get more gold button check
element =
driver.find_element_by_xpath("xpath here")
element.click()
print("Step 12. Get more gold button clicked")
pass
#??????Confirmation that Gold store was open IN BROWSER
wait = WebDriverWait(driver, 10)
element = driver.find_elements_by_xpath("//xpath here,*[text()='Choose your payment method']")
#wait.until(EC.visibility_of_any_elements_located((By.CLASS_NAME, "flx-j-c txt-up")))
for i in element:
if 'Choose your payment method' == i.text:
print('Step 13. User not on Me tab - PASS')
else: print('FAIL to redirect the user')
time.sleep(2)
driver.back()
pass
Error:
selenium.common.exceptions.TimeoutException: Message:
I tried to find the element by xpath, class, by text, there is no id to use for this.
I think the issue is here,
element = driver.find_elements_by_xpath("//xpath here,*[text()='Choose your payment method']")
if you pay attention then you have something like this xpath here in xpath("")
instead it should be :-
element = driver.find_elements_by_xpath("//*[text()='Choose your payment method']")
Now you will have a list here.
print(len(element))
print the size like this or do whatever you wanna do with the list. It's all upto you.
Update 1:
After seeing the HTML, I think this should work for you.
Xpath
//section[contains(#class,'gold-payment-methods')]/descendant::strong
In code :-
element = driver.find_element_by_xpath("//section[contains(#class,'gold-payment-methods')]/descendant::strong")
element.click()
I currently have the Droid cam Application installed on my android, it is being detected and is streaming on Skype through wifi (Droid Cam client). It is however not streaming to OpenCV, no matter what number I put in for the following.
cap=cv2.VideoCapture()
In addition to this, I have an IP address, so is there any way I can implement this so that OpenCV can read an process images wireless from my camera?
I know that it does not even begin to read the camera as I have tested it with the following code, which returns FALSE every time I run it.
cap=cv2.Videocapture(0) #Use default cam
i=0
while(i<50):
ret,frame=cap.read()
print ret
Keeps returning false, meaning camera isn't being recognized :L
You have to enter the ip address of the droidcam followed by the format.The following method worked flawlessly for me :
cap = cv2.VideoCapture('http://0.0.0.0:4747/mjpegfeed?640x480')
Make sure you open the client and do not access the camera feed elsewhere
Install Droid Cam
Enable USB Debugging
Connected camera via USB to your computer
Change IP address bellow
cap = cv2.VideoCapture('http://192.168.0.21:4747/mjpegfeed')
Its simple, droidcam app shows the url; just copy it and paste in the videocapture.
IP Cam Access:
http://192.168.29.201:4747/video
Paste the url like this :
import cv2
cap = cv2.VideoCapture('http://192.168.29.201:4747/video')
while True:
ret, frame = cap.read()
cv2.imshow("frame", frame)
cv2.waitKey(1)
Thats it. Opencv should take the feed from your droidcam.
DroidCam has an MJPEG endpoint you can try getting at,
http://ip:port/mjpegfeed
See: Reading stream from IP camera with cv2.VideoCapture()
Try
IP Webcam android app
and get frames from http://your-ip:8080/shot.jpg?
I just used the following instructions and worked for me.
Install Droidcam;
Enable USB Debugging
Connected camera via USB to your computer
Use the code:
cap = cv2.VideoCapture(0)
cap=cv2.Videocapture(0)
i=0
while(i<50):
ret,frame=cap.read() //change car -> cap
print ret
i=0
while(i<50):
#put this statement inside the loop to capture the frame returned by ip webcam or
#droidcam in every iteration
#put image address in the parameter
cap=cv2.VideoCapture('http://192.168.x.x:4747/shot.jpg?rnd=890215')
ret,frame=car.read()
print(ret)
here is the python code to do wirelessly stream video from android to opencv through droidcam
import numpy as np
import cv2
#go to the setting find ip cam username and password if it is not empty use
#first one
#cap = cv2.VideoCapture('http://username:password#ip:port/video')
cap = cv2.VideoCapture('http://ip:port/video')
while(cap.isOpened()):
ret, frame = cap.read()
#do some stuff
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Install droidcam app on PC and mobile and then write this code:
import cv2
cap =cv2.VideoCapture(1)
while True:
_, img = cap.read()
cv2.imshow("img", img)
cv2.waitKey(1)
This answer here worked for me, replacing the url with http://my-ip:8080/shot.jpg for IP Webcam app. Here is my code:
import cv2
import urllib.request
import numpy as np
my_ip = # ip given by ip-webcam
while True:
req = urllib.request.urlopen('http://'+my_ip+':8080/shot.jpg')
arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
img = cv2.imdecode(arr, -1) # 'Load it as it is'
if cv2.waitKey(1) == 27:
break
cv2.imshow('Its Me', img)
cv2.destroyAllWindows()
I have 2 laptops. One is windows and one is Linux(Ubuntu). On the windows machine I'm unable to run android emulator app. I have tried with http://localhost/, http://10.0.2.2/ and none working. On Linux machine everything is work just fine. What can be the problem?
I have use Eclipse. And on machine localhost WAMP.
Update:
I have this code which I try to open via app. When I run it on my local i.e. http://localhost/file.php obviously I get this error for deprecated mysql_* function but the result is displayed (on the web host I don't get this errors). I've tried to turn of display_errors in php.ini and I notice that the app doesn't crash anymore and all is running. Is it really possible this to cause the problem?
<?php
$objConnect = mysql_connect("localhost","database","");
$objDB = mysql_select_db("tableName");
$strSQL = "SELECT * FROM res";
$objQuery = mysql_query($strSQL);
$intNumField = mysql_num_fields($objQuery);
$resultArray = array();
while($obResult = mysql_fetch_array($objQuery))
{
$arrCol = array();
for($i=0;$i<$intNumField;$i++)
{
$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
}
array_push($resultArray,$arrCol);
}
mysql_close($objConnect);
echo json_encode($resultArray);
?>
Here's what I need to do. I have 2 devices which I need to test using monkeyrunner. It is an automated test using python and monkeyrunner. I want to execute the test simultaneously for the 2 devices so I thought of using thread.
here's the code
import threading
import datetime import os, sys
import ConfigParser from com.android.monkeyrunner
import MonkeyRunner, MonkeyDevice,MonkeyImage from datetime
import datetime import hashlib from java.net
import SocketException from com.ziclix.python.sql
import zxJDBC
def UseThread(data1, data2, data3, devID, Code, ScreenshotRef,
logFile):
device = MonkeyRunner.waitForConnection(10, devID)
'threaded code'
'initialization'
file = open(os.path.dirname(os.path.realpath(file)) +
'\Samples.txt','r') while 1:
while 1:
line = file.readline()
if not line:
print 'Done!'
break
else:
line
val=line.split('\t')
data1 = val[0]
data2 = val[1]
data3 = val[2]
threads = []
for Code in cp.options('p'):
devID = cp.get('product',Code).strip()
ScreenshotRef = cp.get('source','ScreenshotRef') + '\\' + prodCode.upper()
logFile = outputFolder + '\\' + prodCode.upper() + '\\logs.txt'
t=threading.Thread(target=UseThread,args=(data1, data2, data3, devID, prodCode, ScreenshotRef, logFile))
threads.append(t)
t.start()
for i in range(0,len(threads)):
threads[i].join()
The problem is this. When the while loops finish one run and proceed to 2nd run, the code hangs in the part when monkeyrunner is waiting for connection. To be exact, this is the part where it stops
device = MonkeyRunner.waitForConnection(10, devID)
the message says "Monkey command wake".
I assume that the problem has something to do with the connection, not with the thread because I tried to print something before that line which makes a connection and it works.
Is there an issue making a connection when you have already made one? do I need to close the previous connection first?
MonkeyRunner waitForConnection works only for one device. You cannot run this twice. You can run from another instance
Why Socket can be open on the android emulator and connect to the python server code and open a socket !! In other Hand When i run same android code on the mobile it doesn't run . didnt open a socket ..Any suggestion what is the problem and how to solve such thing
enter code here
import sys
from threading import Thread
import socket
import MySQLdb
allClients=[]
class Client(Thread):
def __init__(self,clientSocket):
Thread.__init__(self)
self.sockfd = clientSocket #socket client
self.name = ""
self.nickName = ""
def newClientConnect(self):
allClients.append(self.sockfd)
while True:
while True:
try:
rm= self.sockfd.recv(2048)
print rm
i=0
while (i<2):
if (rm) == row[i][0]:
reply="\n Welcome to our game %s: %s"%(rm,row[i][1])
self.sockfd.send(reply)
break
else:
i=i+1
if i==2:
reply="\n Error opaa ba2a"
self.sockfd.send(reply)
i=0
break
break
except ValueError:
self.sockfd.send("\n UNVAlied Comment ")
def run(self):
self.newClientConnect()
while True:
buff = self.sockfd.recv(2048)
if buff.strip() == 'quit':
self.sockfd.close()
break # Exit when break
else:
self.sendAll(buff)
#Main
if __name__ == "__main__":
#Server Connection to socket:
IP = '50.0.10.107'
PORT = 5807
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )
print ("Server Started")
try:
serversocket.bind(('',54633))
except ValueError,e:
print e
serversocket.listen(5)
db= MySQLdb.connect(host= "localhost",
user="root",
passwd="newpassword",
db="new_schema")
x=db.cursor()
x.execute("SELECT * FROM lolo")
row = x.fetchall()
print "Connected to the Database"
while True:
(clientSocket, address) = serversocket.accept()
print 'New connection from ', address
ct = Client(clientSocket)
ct.start()
__all__ = ['allClients','Client']
The python code and the server code it map and button when click on button connection start and it work great on the emulator
Could be a number of thing:
You don't have networking permissions enabled in your manifest file
Your wifi / 3G is disabled
If your server is on your personal computer and you're connected to the internet using a router then you need to redirect the port you're using for socket communication from the router to your machine.
If your code works on emulator but not on real phone, that could be a network issue. Emulator depends on LAN to access your server and phone access through 3G network. Is your server accessible through internet?