Storing player data in Kivy - android

I've made a class to pickle and unpickle data from a dictionary. Its fairly standard: it tried to open the file, if the file's not present it creates it and it offers methods to read from the dictionary and write to the dictionary.
However, when packaged as an APK using buildozer (I made sure to delete the data file before compiling), sometimes data is randomly lost on the device, and if you update the app through the android updater all data is lost. I don't know where the data file is, but I'm presuming it's kept in the APK. Can anyone offer a solution to this?
I'm using Python 2 and Kivy 1.10 and the built-in pickle module. Thanks in advance
The code for my pickler is as below:
import pickle 
class Data(object):
def __init__(self,fname):
try:
f = open(fname,'r')
p = pickle.load(f)
f.close()
except IOError:
f = open(fname,'w')
pickle.dump({'highscore':0},f)
f.close() p = {'highscore':0}
self.fname = fname
self.data = p 
def rewrite(self,key,value):
new = self.data
new[key] = value
f = open(self.fname,'w')
pickle.dump(new,f)
f.close()
self.data = new
def grab(self,key):
with open(self.fname,'r') as f:
self.data = pickle.load(f) 
return self.data[key]

Related

Where do you store json files in a Xamarin forms app for ios and android apps

I'm new to Xamarin Forms and would like to include some read-only data in a json file to be deployed with the package that will be used as a local data store. How do you add this resource to the respective project types? ie iOS and Android.
You can put the json file in the Froms file directory, then click the file->Properties->Build Action to select Embedded resource.
You can get it using the code below:
var resourcePrefix = "MyApp.";//your project name.
var assembly = IntrospectionExtensions.GetTypeInfo(typeof(MainPage)).Assembly;
Stream stream = assembly.GetManifestResourceStream(resourcePrefix + "aaa.json");//your json file name
using(var streamReader = new StreamReader(stream))
{
var reader = streamReader.ReadToEnd();
}

Read APK file from URL in Python 2.7

I am working on a Python Script which reads the APK file which is stored in a folder on the same server on which the Script is running.
here is the code I am using:
apk_path = "/var/fibo-dev/public/uploads/apks/TvBox-release-signed-latest.apk"
apkf = APK(apk_path)
is_valid = apkf.is_valid_APK()
package = apkf.get_package()
version = apkf.androidversion
version = version['Name']
APK Parsing Package:
https://github.com/androguard/androguard
The Script reads the content of the APK like it's version, package name etc and then store the info in a csv.
As you can see the APK I am reading is stored on the same server on which the script is placed.
But now the thing is I want to read the APK which is placed on a different server. i.e. https://fibo.network/uploads/apks/18243602447plus_v4.3.4.apk
and when I try to do the same thing for the given url it doesn't work.
for example:
url = urllib2.urlopen("https://fibo.network/uploads/apks/18243602447plus_v4.3.4.apk")
apkf = APK(url.read())
It gives the error:
file() argument 1 must be encoded string without null bytes, not str
I tried to use a different methods like:
urlopen
,
requests.get
and more
But none of those worked for me.
So I am requesting you to help me to get this thing worked out.
Thanks.

Where is my file in Android application(Xamarin)?

I wrote a test Android app in Xamarin, where sample data was stored in a file. Somehow I copied test data file to emulator, successfully run the app and forgot about the project for couple of months.
Now I am resuscitating the project and - I can't find the file in Android Device Manager although it is still accessible in the emulator. It drives me nuts, I need to edit it!
Perhaps someone can point me to the right way to locate the file. Thanks!
Following is the code fragment that reads the file. I added debug output in the comments after each relevant line
var fileName = "NursePurse.jobjson1.txt";
var assembly = typeof(pageJobs).GetTypeInfo().Assembly;
//assembly.base.CodeBase = "file:///storage/emulated/0/Android/data/NursePurse.Droid/files/.__override__/NursePurse.dll"
String fname = assembly.FullName;
//fname = NursePurse, Version=1.0.6504.22050, Culture=neutral, PublicKeyToken=null
Stream stream = assembly.GetManifestResourceStream(fileName);
List<String> t = assembly.GetManifestResourceNames().ToList();
// there are two entries
// "NursePurse.AppResources.resources","NursePurse.jobjson1.txt"
// here is my file! But I don't see neither of these files in the android device manager.
Question - where is it?
Following is the screenshot of Android Dev.Manager View and Device definition with SIM card

Get Pretrained Inception v3 model from Open Images dataset working on Android

I tried a while to get the pretrained model working on android. The problem is, I only got the ckpt and meta file for the pretrained net. In my opinion I need the .pb for the android app. So I tried to convert the given files to an .pb file.
Therefore I tried the freeze_graph.py but without succes. So I used the example code from https://github.com/openimages/dataset/blob/master/tools/classify.py and modified it to store a pb. file after loading
if not os.path.exists(FLAGS.checkpoint):
tf.logging.fatal(
'Checkpoint %s does not exist. Have you download it? See tools/download_data.sh',
FLAGS.checkpoint)
g = tf.Graph()
with g.as_default():
input_image = tf.placeholder(tf.string)
processed_image = PreprocessImage(input_image)
with slim.arg_scope(inception.inception_v3_arg_scope()):
logits, end_points = inception.inception_v3(
processed_image, num_classes=FLAGS.num_classes, is_training=False)
predictions = end_points['multi_predictions'] = tf.nn.sigmoid(
logits, name='multi_predictions')
init_op = control_flow_ops.group(tf.global_variables_initializer(),
tf.global_variables_initializer(),
data_flow_ops.initialize_all_tables())
saver = tf_saver.Saver()
sess = tf.Session()
saver.restore(sess, FLAGS.checkpoint)
outpt_filename = 'output_graph.pb'
#output_graph_def = sess.graph.as_graph_def()
output_graph_def = graph_util.convert_variables_to_constants(sess, sess.graph.as_graph_def(), ["multi_predictions"])
with gfile.FastGFile(outpt_filename, 'wb') as f:
f.write(output_graph_def.SerializeToString())
Now my problem is that I have the .pb file but I don't have any opinion what is the input node name and I am not sure if multi_predictions is the right output name. In the example android app I have to specify both. And the android app crashed with:
tensorflow_inference_jni.cc:138 Could not create Tensorflow Graph: Invalid argument: No OpKernel was registered to support Op 'DecodeJpeg' with these attrs.
I don't know if there are more problem by trying to fix the .pb problem. Or if anyone knows a better way to port the ckpt and meta files to a .pd file in my case or knows a source for the final file with input and ouput names please give me a hint to complete this task.
Thanks
You'll need to use the optimize_for_inference.py script to strip out the unused nodes in your graph. "decodeJpeg" is not supported on Android -- pixel values should be fed in directly. ClassifierActivity.java has more detail about the specific nodes to use for inception v3.

How to serve dynamic pdf in Django on mobile device

Using pdftk I generate some dynamic temporary pdf files, which then Django serves to the user.
On a desktop, it works fine - the pdf file opens which then user can save, however on my android phone in all browsers (maybe the same on iOS but don't have and iOS device so can't test), the pdf does not download successfully. It starts the download but then always fails and I can't figure out why.
The following is a snippet of the view and the function which generates the pdf binary data:
def get_pdf():
fdf = {...}
t1 = tempfile.NamedTemporaryFile(delete=False)
t2 = tempfile.NamedTemporaryFile(delete=False)
t1.file.write(fdf)
# close temp files for pdftk to work properly
t1.close()
t2.close()
p = Popen('pdftk %s fill_form %s output %s flatten' %
('original.pdf', t1.name, t2.name), shell=True)
p.wait()
with open(t2.name, 'rb') as fid:
data = fid.read()
# delete t1 and t2 since they are temp files
# at this point the data is the binary of the pdf
return data
def get_pdf(request):
pdf = get_pdf()
response = HttpResponse(pdf, mimetype='application/pdf')
response['Content-Disposition'] = 'filename=foofile.pdf'
return response
Any ideas as to why this might be happening?
As per #Pascal comment, I added Content-Length and the downloads now work on mobile devices.
However it was not being downloaded with the filename I assign it in the view. Adding attachment fixes this but I don't want the attachment to be present for desktop browsers. Hence the following is my final solution which works.
# I am using the decorator from http://code.google.com/p/minidetector/
#detect_mobile
def event_pdf(request, event_id, variant_id):
pdf = get_pdf()
response = HttpResponse(pdf, mimetype='application/pdf')
response['Content-Disposition'] = '%sfilename=foofile.pdf' %
request.mobile and 'attachment; ' or ''
response['Content-Length'] = len(pdf)
return response

Categories

Resources