Help with saving gestures! - Java for Android App Development

Currently, i'm making an application that involves using GestureOverlayView. I've already created some default gestures using the GestureBuilder and have copied them into my res/raw folder in my application. My application also does customization, meaning that the user can create his or her own gestures and save them. I've read that it's impossible for me to just save the additionally made gestures from the users to the res/raw folder. I was told that i have some optionals: ExternalStorage (to SD card), InternalStorage, and SharedPreferences. Which method is probably the more optimal choice?
I've tried using these codes:
gestureLib.addGesture(scName.getText().toString(), gesture);
gestureLib.save();
setResult(RESULT_OK);
in an attempt to save them. Even though the gestures do save, but when i restart the application, they're gone. Please help! Thanks so much!

rx24race said:
Currently, i'm making an application that involves using GestureOverlayView. I've already created some default gestures using the GestureBuilder and have copied them into my res/raw folder in my application. My application also does customization, meaning that the user can create his or her own gestures and save them. I've read that it's impossible for me to just save the additionally made gestures from the users to the res/raw folder. I was told that i have some optionals: ExternalStorage (to SD card), InternalStorage, and SharedPreferences. Which method is probably the more optimal choice?
I've tried using these codes:
gestureLib.addGesture(scName.getText().toString(), gesture);
gestureLib.save();
setResult(RESULT_OK);
in an attempt to save them. Even though the gestures do save, but when i restart the application, they're gone. Please help! Thanks so much!
Click to expand...
Click to collapse
I haven't used gestures so far but for the saving:
In your SharedPreferences you can only save the standard types like int or string. I'm guessing you don't want to convert the gesture to string and backwards, so I'd say external storage in a folder with the name of your app(so the user can manually delete it) but you could also save the file in your app directory.
Look at This question , he uses the gesture library and saves it to the file with
Code:
GestureLibrary store = GestureLibraries.fromFile(mStoreFile);
store.addGesture("Gesture Password", mGesture);
store.save();

My application successfully saves now, but there's still a consistent problem. When i restart the application, the saved gestures are gone. Why is that?

rx24race said:
My application successfully saves now, but there's still a consistent problem. When i restart the application, the saved gestures are gone. Why is that?
Click to expand...
Click to collapse
When you restart your app, everything in its ram will be gone, so you always need to load the saved file and then import the gestures to the library again probably.
You'd want to do that in the onCreate() or onRestart().
In the above example,
Code:
store.load();
Is used to do that

It works now. Thanks a lot. I'm assuming that these gestures are being saved in the application itself, since that i can't find them in the SD card. Thanks for your time, by the way.

It works now. Thanks a lot. I'm assuming that these gestures are being saved in the application itself, since that i can't find them in the SD card. Thanks for your time, by the way.
Click to expand...
Click to collapse
Glad I could help you

BUMP! I've been struggling with a problem that i newly encountered. What i want to do is, i want to create a folder in the external directory and save ALL the gestures that the user creates. But the thing is, every time i save the gesture, it overwrites the existing one. How do i create a folder and put the new ones in it? Any help or hints would be nice

rx24race said:
BUMP! I've been struggling with a problem that i newly encountered. What i want to do is, i want to create a folder in the external directory and save ALL the gestures that the user creates. But the thing is, every time i save the gesture, it overwrites the existing one. How do i create a folder and put the new ones in it? Any help or hints would be nice
Click to expand...
Click to collapse
You've got to use a different string for every gesture in that line:
Code:
store.addGesture("this should be a different string every time", mGesture);
Then you should be able to put them into one file.

nikwen said:
You've got to use a different string for every gesture in that line:
Code:
store.addGesture("this should be a different string every time", mGesture);
Then you should be able to put them into one file.
Click to expand...
Click to collapse
I definitely have a different name for the every gesture that i save
Here's the code:
Code:
package com.epicunlock.rx24race;
import java.io.File;
import java.util.ArrayList;
import android.app.Activity;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.gesture.GestureOverlayView.OnGesturePerformedListener;
import android.gesture.Prediction;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;
public class createShortcut extends Activity implements
OnGesturePerformedListener {
boolean found = false;
EditText scName;
GestureOverlayView gestures;
GestureLibrary lib;
File mStoreFile;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.createshortcutlayout);
scName = (EditText) findViewById(R.id.etName);
gestures = (GestureOverlayView) findViewById(R.id.gestures);
gestures.addOnGesturePerformedListener(this);
mStoreFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/com.epicunlock.rx24race");
if (!mStoreFile.exists()) {
mStoreFile.mkdirs();
}
lib = GestureLibraries.fromFile(mStoreFile);
lib.load();
}
[user=439709]@override[/user]
public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
// TODO Auto-generated method stub
found = false;
ArrayList<Prediction> predictions = lib.recognize(gesture);
for (String s : lib.getGestureEntries()) {
Log.v("GESTURE", s);
}
Log.v("TAG", "Gesture has been detected");
for (Prediction p : predictions) {
Log.v("TAG", p.toString());
Log.v("^ Score", "" + p.score);
}
for (Prediction p : predictions) {
if (p.score > 2.0) {
Toast.makeText(this, p.name, Toast.LENGTH_SHORT).show();
found = true;
}
}
if (!found) {
Log.v("TAG", "Gesture has been saved");
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
lib = GestureLibraries.fromFile(mStoreFile);
lib.addGesture(scName.getText().toString(), gesture);
lib.save();
setResult(RESULT_OK);
}
}
}
As you can see, i have every gesture named after its own unique scName (EditText).
What's happening right now is that i successfully creates a folder name "com.epicunlock.rx24race" inside Android/data, but nothing is ever saved in it

rx24race said:
I definitely have a different name for the every gesture that i save
Here's the code:
Code:
package com.epicunlock.rx24race;
import java.io.File;
import java.util.ArrayList;
import android.app.Activity;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.gesture.GestureOverlayView.OnGesturePerformedListener;
import android.gesture.Prediction;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;
public class createShortcut extends Activity implements
OnGesturePerformedListener {
boolean found = false;
EditText scName;
GestureOverlayView gestures;
GestureLibrary lib;
File mStoreFile;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.createshortcutlayout);
scName = (EditText) findViewById(R.id.etName);
gestures = (GestureOverlayView) findViewById(R.id.gestures);
gestures.addOnGesturePerformedListener(this);
mStoreFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/com.epicunlock.rx24race");
if (!mStoreFile.exists()) {
mStoreFile.mkdirs();
}
lib = GestureLibraries.fromFile(mStoreFile);
lib.load();
}
[user=439709]@override[/user]
public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
// TODO Auto-generated method stub
found = false;
ArrayList<Prediction> predictions = lib.recognize(gesture);
for (String s : lib.getGestureEntries()) {
Log.v("GESTURE", s);
}
Log.v("TAG", "Gesture has been detected");
for (Prediction p : predictions) {
Log.v("TAG", p.toString());
Log.v("^ Score", "" + p.score);
}
for (Prediction p : predictions) {
if (p.score > 2.0) {
Toast.makeText(this, p.name, Toast.LENGTH_SHORT).show();
found = true;
}
}
if (!found) {
Log.v("TAG", "Gesture has been saved");
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
lib = GestureLibraries.fromFile(mStoreFile);
lib.addGesture(scName.getText().toString(), gesture);
lib.save();
setResult(RESULT_OK);
}
}
}
As you can see, i have every gesture named after its own unique scName (EditText).
What's happening right now is that i successfully creates a folder name "com.epicunlock.rx24race" inside Android/data, but nothing is ever saved in it
Click to expand...
Click to collapse
As far as I know the file you save it to mustn't be a directory, but a file.
Try that:
Code:
mStoreFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/com.epicunlock.rx24race");
if (!mStoreFile.exists()) {
mStoreFile.mkdirs();
}
[COLOR="Red"]File gestureFile = new File(mStoreFile, "gestures");
lib = GestureLibraries.fromFile(gestureFile);[/COLOR]
lib.load();
and
Code:
if (!found) {
Log.v("TAG", "Gesture has been saved");
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
[COLOR="Red"]File gestureFile = new File(mStoreFile, "gestures");
lib = GestureLibraries.fromFile(gestureFile);[/COLOR]
lib.addGesture(scName.getText().toString(), gesture);
lib.save();
setResult(RESULT_OK);
}

nikwen said:
As far as I know the file you save it to mustn't be a directory, but a file.
Try that:
Code:
mStoreFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/com.epicunlock.rx24race");
if (!mStoreFile.exists()) {
mStoreFile.mkdirs();
}
[COLOR="Red"]File gestureFile = new File(mStoreFile, "gestures");
lib = GestureLibraries.fromFile(gestureFile);[/COLOR]
lib.load();
and
Code:
if (!found) {
Log.v("TAG", "Gesture has been saved");
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
[COLOR="Red"]File gestureFile = new File(mStoreFile, "gestures");
lib = GestureLibraries.fromFile(gestureFile);[/COLOR]
lib.addGesture(scName.getText().toString(), gesture);
lib.save();
setResult(RESULT_OK);
}
Click to expand...
Click to collapse
I've tried something similar to this before too, but the same problem still exists. it keeps overwriting the previous one. It's never able to save multiple gestures.
What i have:
Code:
package com.epicunlock.rx24race;
import java.io.File;
import java.util.ArrayList;
import android.app.Activity;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.gesture.GestureOverlayView.OnGesturePerformedListener;
import android.gesture.Prediction;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;
public class createShortcut extends Activity implements
OnGesturePerformedListener {
boolean found = false;
EditText scName;
GestureOverlayView gestures;
GestureLibrary lib, storage;
File path;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.createshortcutlayout);
scName = (EditText) findViewById(R.id.etName);
gestures = (GestureOverlayView) findViewById(R.id.gestures);
gestures.addOnGesturePerformedListener(this);
path = new File(Environment.getExternalStorageDirectory() + "/Android/data/com.epicunlock.rx24race/");
if (!path.exists()) {
path.mkdirs();
}
File gestureFile = new File(path, "gestures");
lib = GestureLibraries.fromFile(gestureFile);
lib.load();
}
[user=439709]@override[/user]
public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
// TODO Auto-generated method stub
found = false;
ArrayList<Prediction> predictions = lib.recognize(gesture);
for (String s : lib.getGestureEntries()) {
Log.v("GESTURE", s);
}
Log.v("TAG", "Gesture has been detected");
for (Prediction p : predictions) {
Log.v("TAG", p.toString());
Log.v("^ Score", "" + p.score);
}
for (Prediction p : predictions) {
if (p.score > 2.0) {
Toast.makeText(this, p.name, Toast.LENGTH_SHORT).show();
found = true;
}
}
if (!found) {
Log.v("TAG", "Gesture has been saved");
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
File gestureFile = new File(path, "gestures");
lib = GestureLibraries.fromFile(gestureFile);
lib.addGesture(scName.getText().toString(), gesture);
lib.save();
setResult(RESULT_OK);
}
}
}

I just fixed the problem: "Can't save multiple gestures."
This is how i fixed it. But can anyone tell me what difference it made?
Code:
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.createshortcutlayout);
scName = (EditText) findViewById(R.id.etName);
gestures = (GestureOverlayView) findViewById(R.id.gestures);
gestures.addOnGesturePerformedListener(this);
path = new File(Environment.getExternalStorageDirectory() + "/Android/data/com.epicunlock.rx24race/");
if (!path.exists()) {
path.mkdirs();
}
[B]if (lib == null) {
gestureFile = new File(path, "gestures");
lib = GestureLibraries.fromFile(gestureFile);
}[/B]
lib.load();
}

Related

Interested in toggling a value in the build.prop

So in my toolkit, id like to design an activity where I could point it towards certain lines in the build.prop to allow a user to easily toggle, for instance this line
qemu.hw.mainkeys=0
So, in the layout xml, lets say it had "Enable Nav Bar" and a "Toggle Button" for on/off
Where would i start in developing such a feature?
You create a ToggleButton and whenever it is clicked, you change the line.
What is your problem?
nikwen said:
You create a ToggleButton and whenever it is clicked, you change the line.
What is your problem?
Click to expand...
Click to collapse
My concerns are wouldnt I need to add ro permissions on the prop before toggling and a reboot action to apply
I think your device needs to be rooted to be able to write to the build.prop file. You do not need root access to read it though
I'm from mobile and i can't post some code but i will give you some hints
To edit build.prop programmatically first you ne ed to be rooted then you can use the shell command "sed" to exchange values. Take a look at AOKP settings source on github and look for density changer class
If you want to import various build properties you can use fileinputstream and read the file line by line then let the app create listview custom items for every line in the file (you need a custom adapter) .
Sorry if this post it's not really useful but i will edit this when at PC
Sent from my HTC One X using Tapatalk 4 Beta
Thankyou for the tip! The answer might of been infront of my face possibly...
Sent from my 9300 using xda app-developers app
xcesco89 said:
I'm from mobile and i can't post some code but i will give you some hints
To edit build.prop programmatically first you ne ed to be rooted then you can use the shell command "sed" to exchange values. Take a look at AOKP settings source on github and look for density changer class
If you want to import various build properties you can use fileinputstream and read the file line by line then let the app create listview custom items for every line in the file (you need a custom adapter) .
Sorry if this post it's not really useful but i will edit this when at PC
Sent from my HTC One X using Tapatalk 4 Beta
Click to expand...
Click to collapse
I Wrote something up but I keep getting force closes "Not a java code monkey yet, still learning" and Ill post here what I have when I get to my pc later. Maybe you can see what Im missing or did wrong. What I did is I have a preference screen similiar to AOKP density changer class. What Im going for is a PreferenceList that you click and your values are Enable or Disabled and another preference to reboot to apply settings. Im wanting to allow the user to enable and disable the Navigation Bar by toggling it through the build.prop. If this works, I want to add more toggles custom values like change your phone model, Screen Density, build number, ect; but figured Id start with something simpler first and see if it works.
Sent from my Alps9300 using Tapatalk
Nx Biotic said:
I Wrote something up but I keep getting force closes "Not a java code monkey yet, still learning" and Ill post here what I have when I get to my pc later. Maybe you can see what Im missing or did wrong. What I did is I have a preference screen similiar to AOKP density changer class. What Im going for is a PreferenceList that you click and your values are Enable or Disabled and another preference to reboot to apply settings. Im wanting to allow the user to enable and disable the Navigation Bar by toggling it through the build.prop. If this works, I want to add more toggles custom values like change your phone model, Screen Density, build number, ect; but figured Id start with something simpler first and see if it works.
Sent from my Alps9300 using Tapatalk
Click to expand...
Click to collapse
this is the method you need:
Code:
private void setLcdDensity(int newDensity) {
Helpers.getMount("rw");
new CMDProcessor().su.runWaitFor("busybox sed -i 's|ro.sf.lcd_density=.*|"
+ "ro.sf.lcd_density" + "=" + newDensity + "|' " + "/system/build.prop");
Helpers.getMount("ro");
}
( method took from here : https://github.com/TeamBAKED/packag...aked/romcontrol/fragments/DensityChanger.java )
newDensity is the int/string you let the user set ( you can use a seekbar or a dialog or what you prefer)
you have also CMDProcessor().su.runWaitFor : just use the classes you can find here : https://github.com/TeamBAKED/packag...11bca71808c9143/src/com/baked/romcontrol/util
just add these classes in your project ( these are to simplify your life when you need to use android terminal [ remember to give credits on your app! ] )
Now, you can use various types of views and methods to show to the user all the available props:
- manually add every view for every line in your build.prop ( this will probably limit the compatibility with other devices and make your app "laggy" due to "gazilions" views )
- use a blank linearLayout and inflate a "row view" for every line in build.prop:
read file line by line and import every line in an ArrayList:
Code:
ArrayList<String> Tokens = new ArrayList<String>();
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("/system/build.prop");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
strLine = strLine.trim();
if ((strLine.length()!=0)) {
String[] names = strLine.split("\\s+");
Tokens.add(names[0]);
}
}
for (String s : Tokens) {
//System.out.println(s);
//Log.d("NNNNNNNNNNNNNNNNNN", s);
}
// Close the input stream
in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
names = new String[Tokens.size()-1];
names = Tokens.toArray(names);
ArrayList<String> value = new ArrayList<String>();
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("/sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
strLine = strLine.trim();
if ((strLine.length()!=0)) {
String[] val = strLine.split("\\s+");
value.add(val[1]);
}
}
for (String s : value) {
//System.out.println(s);
//Log.d("NNNNNNNNNNNNNNNNNN", s);
}
// Close the input stream
in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
values = new String[value.size()-1];
values = value.toArray(values);
LineNumberReader lnr = null;
try {
lnr = new LineNumberReader(new FileReader(new File("/sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table")));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
lnr.skip(Long.MAX_VALUE);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int num = lnr.getLineNumber();
Log.d("LINES", ""+num);
int i = 0;
//now inflate a specific view for every line
// you can also filter every item for example by reading the string and inflating a different layout using an if statement
for (String s : names) {
LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View v = inflater.inflate(R.layout.uvrow, null, true);
TextView text0 = (TextView) v.findViewById(R.id.text0);
ImageButton back0 = (ImageButton) v.findViewById(R.id.back0);
final EditText edit0 = (EditText) v.findViewById(R.id.edit0);
ImageButton fwd0 = (ImageButton) v.findViewById(R.id.fwd0);
text0.setText(s);
parentGroup.addView(v);
edit0.setText(values[i]);
/*
* if you need to set listeners and actions insert them inside this loop!
*/
}
if you need more informations, take a look at my code on github ( was my first "really useful" app ): https://github.com/cesco89/CustomSettings/blob/master/src/com/cesco/customsettings/UVTable.java
it's not perfect, could be tricky, but i can't post all the code here
This Is what I put together...Excuse any errors in java...Im new at this. When I start this fragment, I get a force close. What did I do?
Code:
package com.bionx.res.catalyst;
import android.content.Context;
import android.os.Bundle;
import android.os.PowerManager;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceFragment;
import com.bionx.res.R;
import com.bionx.res.helpers.CMDProcessor;
import com.bionx.res.helpers.Helpers;
public abstract class Navbar extends PreferenceFragment implements OnPreferenceChangeListener {
Preference mReboot;
ListPreference mStockValue;
int newStockValue;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.navbarchanger);
mStockValue = (ListPreference) findPreference("stock_value");
mStockValue.setOnPreferenceChangeListener(this);
mReboot = findPreference("reboot");
}
public boolean onPreference(Preference preference) {
if (preference == mReboot) {
PowerManager pm = (PowerManager) getActivity()
.getSystemService(Context.POWER_SERVICE);
pm.reboot("Setting Navbar");
}
return false;
}
[user=439709]@override[/user]
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference == mStockValue) {
newStockValue = Integer.parseInt((String) newValue);
setNavbarValue(newStockValue);
mStockValue.setSummary(getResources().getString(R.string.navbar_changer) + newStockValue);
return true;
}
return false;
}
private void setNavbarValue(int newNavbar) {
Helpers.getMount("rw");
new CMDProcessor().su.runWaitFor("busybox sed -i 's|qemu.hw.mainkeys=.*|"
+ "qemu.hw.mainkeys" + "=" + newNavbar + "|' " + "/system/build.prop");
Helpers.getMount("ro");
}
}
Code:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<Preference
android:title="System Properties"
android:summary="User System Tweaks" />
<ListPreference
android:entries="@array/navbar_stock_entries"
android:entryValues="@array/navbar_stock_values"
android:key="stock_value"
android:title="NavBar Enabler"
android:summary="Toggle the system navbar" />
<Preference
android:key="reboot"
android:title="Reboot"
android:summary="Applies tweaks and reboots" />
</PreferenceScreen>
Where I launch the fragment.
Code:
...
<header
android:fragment="com.bionx.res.catalyst.Navbar"
android:icon="@drawable/ic_changelog"
android:title="System Ui Tweaks"
android:summary="Developers soup of the week" />
...
Nx Biotic said:
This Is what I put together...Excuse any errors in java...Im new at this. When I start this fragment, I get a force close. What did I do?
Code:
package com.bionx.res.catalyst;
import android.content.Context;
import android.os.Bundle;
import android.os.PowerManager;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceFragment;
import com.bionx.res.R;
import com.bionx.res.helpers.CMDProcessor;
import com.bionx.res.helpers.Helpers;
public abstract class Navbar extends PreferenceFragment implements OnPreferenceChangeListener {
Preference mReboot;
ListPreference mStockValue;
int newStockValue;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.navbarchanger);
mStockValue = (ListPreference) findPreference("stock_value");
mStockValue.setOnPreferenceChangeListener(this);
mReboot = findPreference("reboot");
}
public boolean onPreference(Preference preference) {
if (preference == mReboot) {
PowerManager pm = (PowerManager) getActivity()
.getSystemService(Context.POWER_SERVICE);
pm.reboot("Setting Navbar");
}
return false;
}
[user=439709]@override[/user]
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference == mStockValue) {
newStockValue = Integer.parseInt((String) newValue);
setNavbarValue(newStockValue);
mStockValue.setSummary(getResources().getString(R.string.navbar_changer) + newStockValue);
return true;
}
return false;
}
private void setNavbarValue(int newNavbar) {
Helpers.getMount("rw");
new CMDProcessor().su.runWaitFor("busybox sed -i 's|qemu.hw.mainkeys=.*|"
+ "qemu.hw.mainkeys" + "=" + newNavbar + "|' " + "/system/build.prop");
Helpers.getMount("ro");
}
}
Code:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<Preference
android:title="System Properties"
android:summary="User System Tweaks" />
<ListPreference
android:entries="@array/navbar_stock_entries"
android:entryValues="@array/navbar_stock_values"
android:key="stock_value"
android:title="NavBar Enabler"
android:summary="Toggle the system navbar" />
<Preference
android:key="reboot"
android:title="Reboot"
android:summary="Applies tweaks and reboots" />
</PreferenceScreen>
Where I launch the fragment.
Code:
...
<header
android:fragment="com.bionx.res.catalyst.Navbar"
android:icon="@drawable/ic_changelog"
android:title="System Ui Tweaks"
android:summary="Developers soup of the week" />
...
Click to expand...
Click to collapse
please post the Log you get on Eclipse !
the log will tell you exactly where the error is

[APP] Android transation helper script

If your application has different language versions and a lot of changess to strings.xml (strings added, IDs renamed, strings deleted), the translations will soon become a mess and people won't know anymore what is there left to be translated or if particular string needs translation at all. To fix that I've created a simple java proggy, that
1) loads English strings as a golden source for all other strings
2) compares each values-xx/strings.xml to the above
3) adds a XML comment <!-- PLEASE TRANSLATE --> to each missing value
4) outputs modified to values-xx/strings.xml_obr, sorted by ID
Fast and easy. Here's the code (note: requires jdom-2.x.x.jar)
Code:
package pl.qus.utility.ash;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import org.jdom2.Comment;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
public class AndroidStringsHelper {
private class KeyVal {
String key;
String value;
public KeyVal(String k, String v)
{
key=k;
value=v;
}
}
String resDir = "";
ArrayList<File> listaJęzyków = new ArrayList<File>();
HashMap<String, String> wzorcowaMapa = new HashMap<String, String>();
HashMap<String, String> obrabianaMapa = new HashMap<String, String>();
private static String trKey="!#---TRANSLATE---#!";
public AndroidStringsHelper(String resourceDir) {
String[] listaPlików;
resDir = resourceDir;
File katalog = new File(resDir);
listaPlików = katalog.list();
for (int i = 0; i < listaPlików.length; i++) {
File obr = new File(resourceDir,listaPlików[i]);
if (obr.getName().startsWith("values")) {
File plik=new File(obr, "strings.xml");
if (plik.exists()) {
System.out.println("Dodaję:" + obr.getName());
if (obr.getName().equals("values"))
{
}
else
listaJęzyków.add(plik);
}
}
}
obróbJęzyki();
}
private void obróbJęzyki() {
zaczytajPlik(new File(resDir,"values\\strings.xml"),wzorcowaMapa);
List<KeyVal> sortowanaMapa = new ArrayList<KeyVal>();
for(File plik:listaJęzyków) {
sortowanaMapa.clear();
System.out.println("==================================");
System.out.println("Obrabiam:"+plik.getPath());
obrabianaMapa.clear();
zaczytajPlik(plik,obrabianaMapa);
SortedSet<String> sorted=new TreeSet<String>(wzorcowaMapa.keySet());
Iterator<String> it = sorted.iterator();
while(it.hasNext()) {
String klucz=it.next();
if(obrabianaMapa.containsKey(klucz))
{
sortowanaMapa.add(new KeyVal(klucz, obrabianaMapa.get(klucz)));
}
else
{
System.out.println("Brak ["+klucz+"]");
sortowanaMapa.add(new KeyVal(klucz, trKey+wzorcowaMapa.get(klucz)));
}
}
zapiszPlik(new File(plik.getPath()+"_obr"),sortowanaMapa);
}
}
private void zapiszPlik(File plik, List<KeyVal> docel) {
FileOutputStream os;
Document profileDoc = new Document();
Element root=new Element("resources");
Iterator<KeyVal> it = docel.iterator();
while(it.hasNext()) {
KeyVal nast=it.next();
String klucz=(String) nast.key;
String wart=(String) nast.value;
Element nowy=new Element("string");
if(wart.startsWith(trKey))
{
wart=wart.substring(trKey.length());
root.addContent(new Comment("PLEASE TRANSLATE!"));
}
nowy.addContent(wart);
nowy.setAttribute("name", klucz);
root.addContent(nowy);
}
profileDoc.addContent(root);
try {
os = new FileOutputStream(plik);
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
outputter.output(profileDoc, os);
os.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void zaczytajPlik(File plik, HashMap<String, String> docel) {
SAXBuilder builder = new SAXBuilder();
try {
Document strings = builder.build(plik);
Element spis = strings.getRootElement();
List<Element> wszystkie = spis.getChildren();
for (Element e : wszystkie) {
docel.put(e.getAttributeValue("name"), e.getText());
}
} catch (JDOMException | IOException e) {
e.printStackTrace();
}
System.out.println("Zaczytane:"+docel.size());
}
}
To run it just pass a path to your resource directory:
Code:
public class Main {
public static void main(String arg[]) {
new AndroidStringsHelper("/path/to/your/workspace/project/res");
}
}

[Q] rmtp / mms player

hi friends
i can't play rtmp or mss protocol in android project (just audio live stream )
my code :
Code:
package sample.media.player;
import java.io.IOException;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
public class SampleMediaPlayerActivity extends Activity implements OnErrorListener, OnPreparedListener {
private MediaPlayer player;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
player.setDataSource("rtmp://199.103.63.202/live&file=irib3"); // rtmp link
player.setOnErrorListener(this);
player.setOnPreparedListener(this);
player.prepareAsync();
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IllegalStateException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
[user=439709]@override[/user]
public void onDestroy() {
super.onDestroy();
player.release();
player = null;
}
[user=439709]@override[/user]
public void onPrepared(MediaPlayer play) {
play.start();
}
[user=439709]@override[/user]
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
return false;
}
}
please help me / thanks:good:
Is it crashing or does it do nothing? Logcat?
LogCat:
Level : E
PID : 222
Application : Simple.Media.Player
Tag : MediaPlayer
Text : Error(1,-1)
help me plzzzzzzzzzzzz
nobodyyyyyy ????
takname said:
LogCat:
Level : E
PID : 222
Application : Simple.Media.Player
Tag : MediaPlayer
Text : Error(1,-1)
Click to expand...
Click to collapse
There should be more log code which is important. In every case there should be an Exception which is thrown.
I just found this library: http://www.aftek.com/afteklab/aftek-RTMP-library.shtml
Might be helpful.
(Both formats are not natively supported by the Android platform: http://developer.android.com/guide/appendix/media-formats.html)

Need help in saving data from app

Code:
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import java.io.*;
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}public void save(View view){
EditText e=(EditText) findViewById(R.id.editText1);
String a=String.valueOf(((e.getText().toString())));
try{FileOutputStream s=new FileOutputStream("/data/data/com.mycompany.myapp/first.sav");
ObjectOutputStream save= new ObjectOutputStream(s);
save.writeObject(a);}
catch(Exception f){e.setText(""+f);}
}
}
This code saves the entered data in first.sav file. But if i add different data again, it replaces the earlier saved data but i want both the older and newer saved. How to do it
Sent from my GT-S5570 using xda premium
You mean appending some new text to your existing file?
Code:
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("/data/data/com.mycompany.myapp/first.sav", true)));
out.println("the text");
out.close();
} catch (IOException e) {
e.setText(""+e);
}
you can use Filewriter like this
FileWriter fw = new FileWriter(filename,true);
Click to expand...
Click to collapse
the 2nd parameter will open file in append mode.
As per Developer's site:
Code:
FileOutputStream(String path, boolean append)
Constructs a new FileOutputStream that writes to path.
http://developer.android.com/reference/java/io/FileOutputStream.html
Using your current code, just add true to your FileOutputStream
mkrstudio said:
You mean appending some new text to your existing file?
Code:
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("/data/data/com.mycompany.myapp/first.sav", true)));
out.println("the text");
out.close();
} catch (IOException e) {
e.setText(""+e);
}
Click to expand...
Click to collapse
Thnxx guys my problem is solved now
wasim memon said:
you can use Filewriter like this
the 2nd parameter will open file in append mode.
Click to expand...
Click to collapse
zalez said:
As per Developer's site:
Code:
FileOutputStream(String path, boolean append)
Constructs a new FileOutputStream that writes to path.
http://developer.android.com/reference/java/io/FileOutputStream.html
Using your current code, just add true to your FileOutputStream
Click to expand...
Click to collapse
Sent from my GT-S5570 using xda premium

[Q] Copy Image from Gallery Share (Send To) menu

Moderators... It says I am breaking the rules by asking a question and to ask in the Q&A... But the title of this is "Coding Discussion, Q&A, and Educational Resources" I am not breaking the rules intentionally, I just don't know where else to put this. This is a Coding Question, not a General Question that I would think would get buried and or lost in the General Q&A forum. Please move if you feel I am incorrect.
Hello All, I was hoping someone could help me.
I am trying to create an app that will hide pictures. I want to be able to Pick my App from the Share (Send To) menu from the Users Gallery and have it copy the file to a Directory I have created on my SDCard and then ultimately delete the file from the current location.
Here is what I have so far, but when I pick my app from the Share menu, it crashes the Gallery app. So... I can't even see any errors in my LogCat to even try and troubleshoot my issue.
Can someone point me to a working example of how to do this (I have searched the internet until I am blue in the face) or... I hate to say it... Fix my Code?
Any Help would be appreciated... Thanks!!
Code:
package com.company.privitegallery;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
public class SendToDo extends Activity {
File sdCardLoc = Environment.getExternalStorageDirectory();
File intImagesDir = new File(sdCardLoc,"/DCIM/privgal/.nomedia");
private static final int CAMERA_REQUEST = 1888;
private String selectedImagePath;
String fileName = "capturedImage.jpg";
private static Uri mCapturedImageURI;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
// Get intent, action and MIME type
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
handleSendText(intent); // Handle text being sent
} else if (type.startsWith("image/")) {
handleSendImage(intent); // Handle single image being sent
try {
GetPhotoPath();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
if (type.startsWith("image/")) {
handleSendMultipleImages(intent); // Handle multiple images being sent
}
} else {
// Handle other intents, such as being started from the home screen
}
//...
}
void handleSendText(Intent intent) {
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
if (sharedText != null) {
// Update UI to reflect text being shared
}
}
void handleSendImage(Intent intent) {
Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (imageUri != null) {
// Update UI to reflect image being shared
}
}
void handleSendMultipleImages(Intent intent) {
ArrayList<Uri> imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
if (imageUris != null) {
// Update UI to reflect multiple images being shared
}
}
public void GetPhotoPath() throws IOException {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
copy(fileName, intImagesDir);
}
[user=439709]@override[/user]
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_REQUEST) {
selectedImagePath = getPath(mCapturedImageURI);
Log.v("selectedImagePath: ", ""+selectedImagePath);
//Save the path to pass between activities
try {
copy(selectedImagePath, intImagesDir);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public void copy(String scr, File dst) throws IOException {
InputStream in = new FileInputStream(scr);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
private void deleteLatest() {
// TODO Auto-generated method stub
File f = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera" );
//Log.i("Log", "file name in delete folder : "+f.toString());
File [] files = f.listFiles();
//Log.i("Log", "List of files is: " +files.toString());
Arrays.sort( files, new Comparator<Object>()
{
public int compare(Object o1, Object o2) {
if (((File)o1).lastModified() > ((File)o2).lastModified()) {
// Log.i("Log", "Going -1");
return -1;
} else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
// Log.i("Log", "Going +1");
return 1;
} else {
// Log.i("Log", "Going 0");
return 0;
}
}
});
//Log.i("Log", "Count of the FILES AFTER DELETING ::"+files[0].length());
files[0].delete();
}
}
What's the gallery log output?
Btw, you're not breaking the rules. This is the right forum for Java Q&A.
nikwen said:
What's the gallery log output?
Click to expand...
Click to collapse
How would I get the Logs for the Gallery? I am using and HTC ONE and it's the standard Gallery. Nothing shows up in LogCat so I'm stuck
nikwen said:
Btw, you're not breaking the rules. This is the right forum for Java Q&A.
Click to expand...
Click to collapse
Great, Thanks!!
StEVO_M said:
How would I get the Logs for the Gallery? I am using and HTC ONE and it's the standard Gallery. Nothing shows up in LogCat so I'm stuck
Great, Thanks!!
Click to expand...
Click to collapse
Do you view the logs on your computer?
There should be an error message in the logs.
nikwen said:
Do you view the logs on your computer?
There should be an error message in the logs.
Click to expand...
Click to collapse
Which Logs?? As I said before. LogCat does not give any errors.

Categories

Resources