Writing in the private area of other apps - Java for Android App Development

I'm trying to write a file (FlappyBird2.xml in this example) into the data directory of another app (/data/data/com.dotgears.flappybird/shared_prefs.xml in this example). But the code does literally nothing. It writes the file in the own private area, but doesn't move it. Superuser works perfectly. Here's my code:
Code:
Button btncheat = (Button) findViewById(R.id.button1);
btncheat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String path = "/data/data/com.dotgears.flappybird/shared_prefs/";
String filename = "FlappyBird2.xml";
String string = "test";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
final Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("su");
runtime.exec("mv " + Environment.getDataDirectory().toString() + filename + " " + path);
} catch (Exception e) {
e.printStackTrace();
}
}
});
Can anybody explain me why?

/data needs to be remounted as rw before doing that, it is mounted as ro by default
---------------------------------
Phone : Nexus 4
OS:
Pure KitKat 4.4.2 stock, no root, no mods
---------------------------------
4d 61 73 72 65 70 75 73 20 66 74 77
Gesendet von Tapatalk

That's incorrect, /data is always mounted as rw.

So what is then the error within his code if just toggling su enables you to modify /data, as you suggest
---------------------------------
Phone : Nexus 4
OS:
Pure KitKat 4.4.2 stock, no root, no mods
---------------------------------
4d 61 73 72 65 70 75 73 20 66 74 77
Gesendet von Tapatalk

An app is not allowed to edit other apps data unless it is working as root
Sent from my GT-S5570 using XDA Premium 4 mobile app

arpitkh96 said:
An app is not allowed to edit other apps data unless it is working as root
Sent from my GT-S5570 using XDA Premium 4 mobile app
Click to expand...
Click to collapse
That is right, of course, but if you have a closer look at the commands he executes, you will see the 'su' command being made before everything else
---------------------------------
Phone : Nexus 4
OS:
Pure KitKat 4.4.2 stock, no root, no mods
---------------------------------
4d 61 73 72 65 70 75 73 20 66 74 77
Gesendet von Tapatalk

an alternative solution :
use the chmod from busybox to change the permissions of the file to world writeable and then write to the file using standard java functions.
Sent from my GT-S5302 using Tapatalk 2

This may or may not help - I'm very new to Java and the whole Linux side of things (25 years Windows development means I know a LOT about that, but not much outside it).
Code:
runtime.exec(new string[] {"su", "mv " + Environment.getDataDirectory().toString() + filename + " " + path});
If I'm correct then you can't execute su and then make subsequent calls as superuser. If the above doesn't change that then make a shell script and run that instead so you only have one exec call.

Mh probably only one exec is really the thing that is needed in order to execute the following commands as su
---------------------------------
Phone : Nexus 4
OS:
Pure KitKat 4.4.2 stock, no root, no mods
---------------------------------
4d 61 73 72 65 70 75 73 20 66 74 77
Gesendet von Tapatalk

Masrepus said:
Mh probably only one exec is really the thing that is needed in order to execute the following commands as su
Click to expand...
Click to collapse
My thoughts exactly, since I expect each exec to run as a separate process, therefore granting SU rights with one will not mean you have them for the 2nd one. I'm not sure if the approach of passing an array of commands will work. I think creating a shell script and running that is probably the best method, but like I said, I'm no Java developer.

Ah i think i have read about executing an array of commands somewhere, so i guess this will work
Ya probably that is a more elegant solution
---------------------------------
Phone : Nexus 4
OS:
Pure KitKat 4.4.2 stock, no root, no mods
---------------------------------
4d 61 73 72 65 70 75 73 20 66 74 77
Gesendet von Tapatalk

I use this class to execute su commands(extracted from aokp rom control).
Code:
public class CMDProcessor {
private final String TAG = getClass().getSimpleName();
private static final boolean DEBUG = false;
private Boolean can_su;
public SH sh;
public SH su;
public CMDProcessor()
{ sh = new SH("sh"); su = new SH("su"); }
public SH suOrSH() { return canSU() ? su : sh; }
public boolean canSU() { return canSU(false); }
public class CommandResult { private final String resultTag = TAG + '.' + getClass().getSimpleName(); public final String stdout; public final String stderr; public final Integer exit_value;
CommandResult(final Integer exit_value_in) { this(exit_value_in, null, null); }
CommandResult(final Integer exit_value_in, final String stdout_in, final String stderr_in) { exit_value = exit_value_in; stdout = stdout_in; stderr = stderr_in; if (DEBUG) Log.d(TAG, resultTag + "( exit_value=" + exit_value + ", stdout=" + stdout + ", stderr=" + stderr + " )"); }
public boolean success() { return exit_value != null && exit_value == 0; }
}
public class SH { private String SHELL = "sh";
public SH(final String SHELL_in) { SHELL = SHELL_in; }
private String getStreamLines(final InputStream is) { String out = null; StringBuffer buffer = null; final DataInputStream dis = new DataInputStream(is); try { if (dis.available() > 0) { buffer = new StringBuffer(dis.readLine()); while (dis.available() > 0) { buffer.append("\n").append(dis.readLine()); } } dis.close(); } catch (final Exception ex) { Log.e(TAG, ex.getMessage()); } if (buffer != null) { out = buffer.toString(); } return out; }
public Process run(final String s) { Process process = null; try { process = Runtime.getRuntime().exec(SHELL); final DataOutputStream toProcess = new DataOutputStream( process.getOutputStream()); toProcess.writeBytes("exec " + s + "\n"); toProcess.flush(); } catch (final Exception e) { Log.e(TAG, "Exception while trying to run: '" + s + "' " + e.getMessage()); process = null; } return process; }
public CommandResult runWaitFor(final String s) { if (DEBUG) Log.d(TAG, "runWaitFor( " + s + " )"); final Process process = run(s); Integer exit_value = null; String stdout = null; String stderr = null; if (process != null) { try { exit_value = process.waitFor(); stdout = getStreamLines(process.getInputStream()); stderr = getStreamLines(process.getErrorStream()); } catch (final InterruptedException e) { Log.e(TAG, "runWaitFor " + e.toString()); } catch (final NullPointerException e) { Log.e(TAG, "runWaitFor " + e.toString()); } } return new CommandResult(exit_value, stdout, stderr); } }
public boolean canSU(final boolean force_check) { if (can_su == null || force_check) { final CommandResult r = su.runWaitFor("id"); final StringBuilder out = new StringBuilder(); if (r.stdout != null) { out.append(r.stdout).append(" ; "); } if (r.stderr != null) { out.append(r.stderr); } Log.d(TAG, "canSU() su[" + r.exit_value + "]: " + out); can_su = r.success(); } return can_su; }}
Sent from my GT-S5570 using XDA Premium 4 mobile app

I managed to solve it already. I'm using this class now:
Code:
public void RunAsRoot(String[] cmds){
Process p = null;
try {
p = Runtime.getRuntime().exec("su");
} catch (IOException e) {
e.printStackTrace();
}
DataOutputStream os = new DataOutputStream(p.getOutputStream());
for (String tmpCmd : cmds) {
try {
os.writeBytes(tmpCmd+"\n");
} catch (IOException e) {
e.printStackTrace();
}
}
try {
os.writeBytes("exit\n");
} catch (IOException e) {
e.printStackTrace();
}
try {
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
Then simply call it via
Code:
String[] commands = {"command1", "command2", "command3", ...};
RunAsRoot(commands);
Thanks anyways!

Oh okay that looks really nice :good:
---------------------------------
Phone : Nexus 4
OS:
Pure KitKat 4.4.2 stock, no root, no mods
---------------------------------
4d 61 73 72 65 70 75 73 20 66 74 77
Gesendet von Tapatalk

Related

csharp - exception was unhandeld

Hello,
I just started with developing in csharp for my mobile phone. The first project i'm working on is creating a GPS tracker program that will safe the current GPS location to a text file. This file i'll load to a website from where people can download an google earth file (i prefer php programming )
But to get to the point. The program worked fine untill i added some extra functionality (SystemIdleTimerReset and the date in the name of the datafile)
After adding this the program starts in the emulator, however after 30 seconds (when the trigger start for the first time) it comes with the exception (at the red comment):
Exception was unhandeld
The method or operation is not implemented
My code (i added everything from the main form, since i don't know where the error is)
Code:
using System;
using System.Collections;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.WindowsMobile.Samples.Location;
namespace GPS_Tracker
{
public partial class mainform : Form
{
GpsDeviceState device = null;
GpsPosition position = null;
Gps gps = new Gps();
int iTicker = 0;
int iCounter = 0;
string fileName;
private EventHandler updateDataHandler;
private EventHandler timerTicker;
DateTime currentTime = DateTime.Now;
public mainform()
{
InitializeComponent();
}
private void menuExit_Click(object sender, EventArgs e)
{
if (gps.Opened)
{
gps.Close();
}
Close();
}
private void menuStart_Click(object sender, EventArgs e)
{
if (!gps.Opened)
{
gps.Open();
}
menuStart.Enabled = false;
menuStop.Enabled = true;
}
private void menuStop_Click(object sender, EventArgs e)
{
if (gps.Opened)
{
gps.Close();
}
menuStart.Enabled = true;
menuStop.Enabled = false;
}
private void mainform_Load(object sender, EventArgs e)
{
timerTicker = new EventHandler(timerCheck);
updateDataHandler = new EventHandler(UpdateData);
gps.DeviceStateChanged += new DeviceStateChangedEventHandler(gps_DeviceStateChanged);
gps.LocationChanged += new LocationChangedEventHandler(gps_LocationChanged);
Status.Text = "";
}
protected void gps_LocationChanged(object sender, LocationChangedEventArgs args)
{
position = args.Position;
// call the UpdateData method via the updateDataHandler so that we
// update the UI on the UI thread
Invoke(timerTicker);
}
void gps_DeviceStateChanged(object sender, DeviceStateChangedEventArgs args)
{
device = args.DeviceState;
// call the UpdateData method via the updateDataHandler so that we
// update the UI on the UI thread
Invoke(timerTicker);[COLOR="Red"]// place where error comes[/COLOR]
}
void timerCheck(object sender, System.EventArgs args)
{
Invoke(updateDataHandler);
}
void UpdateData(object sender, System.EventArgs args)
{
if (iTicker == 1)
{
SystemIdleTimerReset();
if (gps.Opened)
{
string str = "";
if (device != null)
{
str = device.FriendlyName + " " + device.ServiceState + ", " + device.DeviceState + "\n";
}
if (position != null)
{
iCounter++;
if (position.SeaLevelAltitudeValid &&
position.EllipsoidAltitudeValid &&
position.SpeedValid &&
position.LatitudeValid &&
position.LongitudeValid &&
position.SatellitesInSolutionValid &&
position.SatellitesInViewValid &&
position.SatelliteCountValid &&
position.TimeValid)
{
fileName = "data_" + currentTime.ToString("yyyyMMdd") + ".txt";
StreamWriter output;
output = File.AppendText(fileName);
output.WriteLine(position.SeaLevelAltitude + ";" +
position.EllipsoidAltitude + ";" +
position.SpeedKmh + ";" +
position.Longitude + ";" +
position.Latitude + ";" +
position.GetSatellitesInSolution().Length + "/" +
position.GetSatellitesInView().Length + " (" +
position.SatelliteCount + ";" +
position.Time.ToString());
output.Close();
str += "Saving data to File \nEntry: " + iCounter + "\n";
str += "Current speed: " + position.SpeedKmh + "\n";
str += "Current height: " + position.SeaLevelAltitude + "\n";
}
}
Status.Text = str;
}
iTicker = 0;
}
}
private void SystemIdleTimerReset()
{
throw new Exception("The method or operation is not implemented.");
}
private void Ticker_Tick(object sender, EventArgs e)
{
iTicker = 1;
}
}
}
the error details:
Error details:
System.Exception was unhandled
Message="The method or operation is not implemented."
StackTrace:
at GPS_Tracker.mainform.SystemIdleTimerReset()
at GPS_Tracker.mainform.UpdateData()
at TASK.Invoke()
at System.Windows.Forms.Control._InvokeAll()
at System.Windows.Forms.Control.InvokeHelper()
at System.Windows.Forms.Control.Invoke()
at GPS_Tracker.mainform.timerCheck()
at TASK.Invoke()
at System.Windows.Forms.Control._InvokeAll()
at System.Windows.Forms.Control.WnProc()
at System.Windows.Forms.ContainerControl.WnProc()
at System.Windows.Forms.Form.WnProc()
at System.Windows.Forms.Control._InternalWnProc()
at Microsoft.AGL.Forms.EVL.EnterMainLoop()
at System.Windows.Forms.Application.Run()
at GPS_Tracker.Program.Main()
Click to expand...
Click to collapse
I hope anybody can help me.
Thanks in advance
StruiS
I removed (commented) the SystemIdleTimerReset function and it works again.
Can someone help me implement this function?
Thanks

Problems running Unix commands in native Android Java...

Hello,
I've been trying to do some android stuff on java for some time now, and i've come across a problem here: i can't get the app to execute linux stuff, as there is no system() method like on other platforms... so i searched some code and found this:
Code:
protected void system(String[] Commands){
e Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
DataInputStream osRes = new DataInputStream(process.getInputStream());
Vector<String> res = new Vector<String>();
for (String single : Commands) {
e os.writeBytes(single + "\n");
e os.flush();
e res.add(osRes.readLine());
// Log.e("CMDs", osRes.readLine());
}
e os.writeBytes("exit\n");
e os.flush();
process.waitFor();
}
However that won't work because of some errors i have in the marked lines:
"Unhandled exception type IOException"
and the process.waitFor(); line also gives me an error:
"Unhandled exception type InterruptedException"
Any ideas?
You need to add a try/catch block around that code which catches the IO exception and the interrupted exception.
deleted
So, first of all thanks to both of you it appears to be working now... i tried in on the emulator, and of course "su" didn't work there (broken pipe), so i replaced it by "sh", however this didn't seem to work well too. the application just locked up with a warning in android.... strange...
edit: tried using /system/bin/sh, didn't work, locked up again
What version of Android in the emulator? I've done it with 1.5 through 2.2 in the emulator, just by using "sh".
could you post the code you used please? would be AWESOME!
i'm trying to get this working on 2.1
Sure, I can post some more details later, but for now just the code.
Include the file in your project and use with:
Code:
ShellCommand cmd = new ShellCommand();
CommandResult r = cmd.sh.runWaitFor("ls -l");
if (!r.success()) {
Log.v(TAG, "Error " + r.stderr);
} else {
Log.v(TAG, "Success! " + r.stdout);
}
If you want su you can either use cmd.shOrSu().runWaitFor("..."); which will try su (by running "id", it just tests the status code but it's a nice entry in logcat for debugging) and fallback to sh. Or you can use cmd.su.runWaitFor("...");
Also at
teslacoilsw.com/files/ShellCommand.java
Code:
package com.teslacoilsw.quicksshd;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import android.util.Log;
public class ShellCommand {
private static final String TAG = "ShellCommand.java";
private Boolean can_su;
public SH sh;
public SH su;
public ShellCommand() {
sh = new SH("sh");
su = new SH("su");
}
public boolean canSU() {
return canSU(false);
}
public boolean canSU(boolean force_check) {
if (can_su == null || force_check) {
CommandResult r = su.runWaitFor("id");
StringBuilder out = new StringBuilder();
if (r.stdout != null)
out.append(r.stdout).append(" ; ");
if (r.stderr != null)
out.append(r.stderr);
Log.v(TAG, "canSU() su[" + r.exit_value + "]: " + out);
can_su = r.success();
}
return can_su;
}
public SH suOrSH() {
return canSU() ? su : sh;
}
public class CommandResult {
public final String stdout;
public final String stderr;
public final Integer exit_value;
CommandResult(Integer exit_value_in, String stdout_in, String stderr_in)
{
exit_value = exit_value_in;
stdout = stdout_in;
stderr = stderr_in;
}
CommandResult(Integer exit_value_in) {
this(exit_value_in, null, null);
}
public boolean success() {
return exit_value != null && exit_value == 0;
}
}
public class SH {
private String SHELL = "sh";
public SH(String SHELL_in) {
SHELL = SHELL_in;
}
public Process run(String s) {
Process process = null;
try {
process = Runtime.getRuntime().exec(SHELL);
DataOutputStream toProcess = new DataOutputStream(process.getOutputStream());
toProcess.writeBytes("exec " + s + "\n");
toProcess.flush();
} catch(Exception e) {
Log.e(QuickSSHD.TAG, "Exception while trying to run: '" + s + "' " + e.getMessage());
process = null;
}
return process;
}
private String getStreamLines(InputStream is) {
String out = null;
StringBuffer buffer = null;
DataInputStream dis = new DataInputStream(is);
try {
if (dis.available() > 0) {
buffer = new StringBuffer(dis.readLine());
while(dis.available() > 0)
buffer.append("\n").append(dis.readLine());
}
dis.close();
} catch (Exception ex) {
Log.e(TAG, ex.getMessage());
}
if (buffer != null)
out = buffer.toString();
return out;
}
public CommandResult runWaitFor(String s) {
Process process = run(s);
Integer exit_value = null;
String stdout = null;
String stderr = null;
if (process != null) {
try {
exit_value = process.waitFor();
stdout = getStreamLines(process.getInputStream());
stderr = getStreamLines(process.getErrorStream());
} catch(InterruptedException e) {
Log.e(TAG, "runWaitFor " + e.toString());
} catch(NullPointerException e) {
Log.e(TAG, "runWaitFor " + e.toString());
}
}
return new CommandResult(exit_value, stdout, stderr);
}
}
}
Thanks kevin The code you are using there is awesome Looking good so far, however it keeps returning permission denied... is it some setting in the android manifest?
Actually "Permission denied" often also means "no such file or directory" on android :-/ . It's very frustrating.
Try running something simple to start with like:
cmd.sh.runWaitFor("echo foo");
[email protected] said:
Actually "Permission denied" often also means "no such file or directory" on android :-/ . It's very frustrating.
Try running something simple to start with like:
cmd.sh.runWaitFor("echo foo");
Click to expand...
Click to collapse
yep, i tried running echo as i was confused by the "permission denied" although i had already set write permissions for the sdcard... didn't work, for some odd reason

[Q] Can I register a listener on process state?

I'm an experienced developer but new to Android development. I have an app that runs some native binaries, and I provide a status indicator to show when the native process is running and when it's not. Currently I poll the device to figure this out, using the ActivityManager API to determine if specific processes are running or not.
I'm hoping there is some way to register a listener on process state changes, so I can get notified when my process starts or stops. I looked through the API, and there doesn't seem to be such a thing. Does anyone know how I can keep track of process start and stop other than polling via ActivityManager?
MidnightJava said:
I'm an experienced developer but new to Android development. I have an app that runs some native binaries, and I provide a status indicator to show when the native process is running and when it's not. Currently I poll the device to figure this out, using the ActivityManager API to determine if specific processes are running or not.
I'm hoping there is some way to register a listener on process state changes, so I can get notified when my process starts or stops. I looked through the API, and there doesn't seem to be such a thing. Does anyone know how I can keep track of process start and stop other than polling via ActivityManager?
Click to expand...
Click to collapse
Afaik there's no way to accomplish that other than your way or being system/root app. See this similar question here for reference.
Can you show how you start the process?
EmptinessFiller said:
Can you show how you start the process?
Click to expand...
Click to collapse
Sure. Here's the class that manages starting, stopping, and statusing (running or not) the binary executable. In this case, it's the omniNames service of the omni ORB (CORBA broker).
Code:
public class RHManager {
private TimerTask task = new TimerTask() {
@Override
public void run() {
if (RHManager.this.listener != null) {
listener.running(isOmniNamesRunning());
}
}
};
private IStatusListener listener;
public RHManager() {
}
public void startOmniNames() {
final Exec exec = new Exec();
final String[] args = new String[]
{RhMgrConstants.INSTALL_LOCATION_OMNI_NAMES_SCRIPTS + "/" + RhMgrConstants.OMNI_NAMES_SCRIPT_FILE,
"start"};
final String[] env = new String[] {"LD_LIBRARY_PATH=/sdcard/data/com.axiosengineering.rhmanager/omniORB/lib"};
Thread t = new Thread() {
public void run() {
try {
int res = exec.doExec(args, env);
logMsg("omniNames start return code " + res);
} catch (IOException e) {
logMsg("Failed to start omniNames");
e.printStackTrace();
}
String std = exec.getOutResult();
logMsg("omniNames start: std out==> " + std );
String err = exec.getErrResult();
logMsg("omniNames start: err out==> " + err );
};
};
t.start();
logMsg("omniNames started");
}
private boolean isOmniNamesRunning() {
String pid_s = getOmniNamesPid();
Integer pid = null;
if (pid_s != null) {
try {
pid = Integer.parseInt(pid_s);
} catch (NumberFormatException e) {
return false;
}
}
if (pid != null) {
RunningAppProcessInfo activityMgr = new ActivityManager.RunningAppProcessInfo("omniNames", pid, null);
return activityMgr.processName != null ;
}
return false;
}
public void stopOmniNames() {
String pid = getOmniNamesPid();
android.os.Process.killProcess(Integer.parseInt(pid));
android.os.Process.sendSignal(Integer.parseInt(pid), android.os.Process.SIGNAL_KILL);
}
private String getOmniNamesPid() {
Exec exec = new Exec();
final String[] args = new String[]
{RhMgrConstants.INSTALL_LOCATION_OMNI_NAMES_SCRIPTS + "/" + RhMgrConstants.OMNI_NAMES_SCRIPT_FILE,
"pid"};
String pid = "";
try {
int res = exec.doExec(args, null);
logMsg("oniNames pid return code: " + res);
} catch (IOException e) {
logMsg("Failed to start omniNames");
e.printStackTrace();
return pid;
}
String std = exec.getOutResult();
logMsg("omniNames pid: std out ==> " + std);
String err = exec.getErrResult();
logMsg("omniNames pid: err out ==> " + err);
String[] parts = std.split("\\s+");
if (parts.length >= 2) {
pid = parts[1];
}
return pid;
}
//monitor omniNames status and report status periodically to an IStatusListener
public void startMonitorProcess(IStatusListener listener, String string) {
this.listener = listener;
Timer t = new Timer();
t.schedule(task, 0, 1000);
}
private void logMsg(String msg) {
if (RhMgrConstants.DEBUG) {
System.err.println(msg);
}
}
}
Here's the Exec class that handles invocation of Runtime#exec(), consumes std and err out, and reports those and process return status to the caller.
Code:
public class Exec {
private String outResult;
private String errResult;
private Process process;
private boolean failed = false;
StreamReader outReader;
StreamReader errReader;
public int doExec(String[] cmd, String[] envp) throws IOException{
Timer t = null;
try {
process = Runtime.getRuntime().exec(cmd, envp);
outReader = new StreamReader(process.getInputStream());
outReader.setPriority(10);
errReader = new StreamReader(process.getErrorStream());
outReader.start();
errReader.start();
t = new Timer();
t.schedule(task, 10000);
int status = process.waitFor();
outReader.join();
errReader.join();
StringWriter outWriter = outReader.getResult();
outResult = outWriter.toString();
outWriter.close();
StringWriter errWriter = errReader.getResult();
errResult = errWriter.toString();
errWriter.close();
return (failed ? -1: status);
} catch (InterruptedException e) {
return -1;
} finally {
if (t != null) {
t.cancel();
}
}
}
public int doExec(String[] cmd) throws IOException{
return doExec(cmd, null);
}
public String getOutResult(){
return outResult;
}
public String getErrResult(){
return errResult;
}
private static class StreamReader extends Thread {
private InputStream is;
private StringWriter sw;
StreamReader(InputStream is) {
this.is = is;
sw = new StringWriter(30000);
}
public void run() {
try {
int c;
while ((c = is.read()) != -1){
sw.write(c);
}
}
catch (IOException e) { ; }
}
StringWriter getResult() {
try {
is.close();
} catch (IOException e) {
System.err.println("Unable to close input stream in StreamReader");
}
return sw;
}
}
private TimerTask task = new TimerTask() {
@Override
public void run() {
failed = true;
process.destroy();
}
};
}
Here's the script that startOminNames() invokes. It's the shell script installed with omniORB with functions other than start and get_pid removed, since those are handled by Android classes. You can invoke any executable in place of the script, or wrap your executable in a script.
Code:
#
# omniNames init file for starting up the OMNI Naming service
#
# chkconfig: - 20 80
# description: Starts and stops the OMNI Naming service
#
exec="/sdcard/data/com.axiosengineering.rhmanager/omniORB/bin/omniNames"
prog="omniNames"
logdir="/sdcard/data/com.axiosengineering.rhmanager/omniORB/logs"
logfile="/sdcard/data/com.axiosengineering.rhmanager/omniORB/logs/omninames-localhost.err.log"
options=" -start -always -logdir $logdir -errlog $logfile"
start() {
#[ -x $exec ] || exit 5
echo -n $"Starting $prog: "
$exec $options
}
get_pid() {
ps | grep omniNames
}
case "$1" in
start)
start && exit 0
$1
;;
pid)
get_pid
;;
*)
echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
exit 2
esac
exit $?
And here's the IStatusListener interface
Code:
public interface IStatusListener {
public void running(boolean running);
}
Runtime.exec() has some pitfalls. See this helpful Runtime.exec tutorial for a nice explanation.
And you may also want to check out this post on loading native binaries in Android.

[Q] Game Crash at onCreate by database cursor?

Hi,
I have a problem with my Game App: On my device all is working fine, but at other Devices it crashes at the start. I get these errors: (Pic 1/2 sry for bad pics :S)
My Database Handler looks as following:
Code:
//...
public class SQLHandler extends SQLiteOpenHelper
{
// Database Version
private static final int DATABASE_VERSION = 6;
// Database Name
private static final String DATABASE_NAME = "MRPIGDB";
public SQLHandler(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
// SQL statement to create the table
String CREATE_MRPIG_TABLE = "CREATE TABLE IF NOT EXISTS mrpig ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"points INTEGER )"; // +
//"name" DATA-TYPE )";
// create table
db.execSQL(CREATE_MRPIG_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS mrpig");
// create fresh table
this.onCreate(db);
initDB(0);
}
//table name ***
private static final String TABLE_MRPIG = "mrpig";
//Table Columns names ***
private static final String KEY_ID = "id";
private static final String KEY_POINTS = "points";
//private static final String KEY_ = "";
private static final String[] COLUMNS = {KEY_ID, KEY_POINTS /*,KEY_*/};
public void initDB(int points)
{
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put(KEY_POINTS, points);
// 3. insert
db.insert(TABLE_MRPIG, // table
null, //nullColumnHack
values); // key/value -> keys = column names/ values = column values
// 4. close
db.close();
}
public int getpoints() //called at start to draw the highstore at screen
{
// 1. get reference to readable DB
SQLiteDatabase db = this.getReadableDatabase();
// 2. build query
Cursor cursor =
db.query(TABLE_MRPIG, // a. table
COLUMNS, // b. column names
" id = ?", // c. selections
new String[] { String.valueOf(1) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
// 3. if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
// 4. get points !!!!!!!!!!ERROR HERE!!!!!!!
int points = (Integer.parseInt(cursor.getString(1)));
// 5. return points
return points;
}
public int updatePoints(int points)
{
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put(KEY_POINTS, points);
// 3. updating row
int i = db.update(TABLE_MRPIG, //table
values, // column/value
KEY_ID + " = ?", // selections
new String[] { String.valueOf(1) }); //selection args
// 4. close
db.close();
return i;
}
}
I am sorry for so much code and i hOpe someone can help me.
Mfg
Lolxdfly
Try that, i hope it helps!
//...
// 3. if we got results get the first one
if (cursor != null) { //i dont know if you forgot the open bracket here after the if query, but if you did, then it always moved to first. I now put the whole thin inside that one if branch
cursor.moveToFirst();
// 4. get points
int points = null; //i declare it here already, this is better for later on
//you must try catch that as the value of getstring could be corrupt and not parseable to int
try {
points = (Integer.parseInt(cursor.getString(1)));
}
catch (Exception e) {
points = null;
}
// 5. return points (still in if-branch!
return points;
} //end of if
else {
return null; //if cursor = null return null
}
} // end of method
Click to expand...
Click to collapse
---------------------------------
Phone : Nexus 4
OS:
Pure KitKat 4.4.2 stock, no root, no mods
---------------------------------
4d 61 73 72 65 70 75 73 20 66 74 77
Gesendet von Tapatalk
Masrepus said:
Try that, i hope it helps!
---------------------------------
Phone : Nexus 4
OS:
Pure KitKat 4.4.2 stock, no root, no mods
---------------------------------
4d 61 73 72 65 70 75 73 20 66 74 77
Gesendet von Tapatalk
Click to expand...
Click to collapse
Thank you.
Now it works on other devices, but that dont fixed really. It dont crash. But there will be always shown 0 points, because getting the points is failing....
Mfg
Lolxdfly
Hmm... Well i have no idea about the sqlite stuff in android, but i have done a bit of dbs with microsoft access in sql and i think to remember that one has to explicitely format a specific column as int if you want to handle it as int later on. Do you have to do that in sqlite as well?
Also it would be good if you would debug my part and closely watch if:
1. The if branch or the else branch is being executed
2. If the if branch is being executed, does the try catch block exit via the catch section or runs without errors
---------------------------------
Phone : Nexus 4
OS:
Pure KitKat 4.4.2 stock, no root, no mods
---------------------------------
4d 61 73 72 65 70 75 73 20 66 74 77
Gesendet von Tapatalk
49965255 34
Masrepus said:
Hmm... Well i have no idea about the sqlite stuff in android, but i have done a bit of dbs with microsoft access in sql and i think to remember that one has to explicitely format a specific column as int if you want to handle it as int later on. Do you have to do that in sqlite as well?
Also it would be good if you would debug my part and closely watch if:
1. The if branch or the else branch is being executed
2. If the if branch is being executed, does the try catch block exit via the catch section or runs without errors
---------------------------------
Phone : Nexus 4
OS:
Pure KitKat 4.4.2 stock, no root, no mods
---------------------------------
4d 61 73 72 65 70 75 73 20 66 74 77
Gesendet von Tapatalk
Click to expand...
Click to collapse
Idk... i am new to do something with db :S
At my device he goes into the 1st if bracket and he excutes the try succesfully. At my friends phone he go also into the if bracket but he dont excutes the try succesfull and then he goes into the catch function...
So it returns 0..
Okay. Did you already try flooding the db with some random score data and then checking the output?
Another thing, at the try, the (cursor.getString(1))), what does the 1 mean there?
---------------------------------
Phone : Nexus 4
OS:
Pure KitKat 4.4.2 stock, no root, no mods
---------------------------------
4d 61 73 72 65 70 75 73 20 66 74 77
Gesendet von Tapatalk
Masrepus said:
Okay. Did you already try flooding the db with some random score data and then checking the output?
Another thing, at the try, the (cursor.getString(1))), what does the 1 mean there?
---------------------------------
Phone : Nexus 4
OS:
Pure KitKat 4.4.2 stock, no root, no mods
---------------------------------
4d 61 73 72 65 70 75 73 20 66 74 77
Gesendet von Tapatalk
Click to expand...
Click to collapse
Something crasy happend: i removed the try/catch. And i put initDB(0); at onCreate. He always inserts a 0 at start. But my friend said itvis working fine. It saves the right points and it works now.
Thank you for your ideas
Mfg
lolxdfly

Json html table parsing

Hi guys.
I've been working today on an app that will show all my blogposts which are created by Wordpress. Now, people are using both lists and tables when they are creating new blogposts which TextView and android HTML parser don't really like.
I found a workaround on the html lists (ul, ol, li) tags by kiutsi from stackoverflow (cant post outside urls)
Now im trying to make the same code from the li, ul workaround and also implement td,tr which works out great! But there's one small problem.
I have a json string that spits out (from logcat):
Code:
"content":"<table width=\"495\">\n<tbody>\n<tr>\n<td width=\"115\">GT-B2710<\/td>\n<td width=\"314\">Xcover 271<\/td>\n<td width=\"65\">15.2Q<\/td>\n<\/tr>\n
This code is printing out three columns with text, in my app there's no spaces between these three columns and I can't for my life figure this one out..
Code:
package com.X.X;
import org.xml.sax.XMLReader;
import android.text.Editable;
import android.text.Html.TagHandler;
public class TagHandler2 implements TagHandler {
boolean first = true;
String parent = null;
int index = 1;
public void handleTag(final boolean opening, final String tag,
final Editable output, final XMLReader xmlReader) {
if (tag.equals("ul")) {
parent = "ul";
index = 1;
} else if (tag.equals("ol")) {
parent = "ol";
index = 1;
} else if (tag.equals("tr")) {
parent = "tr";
index = 1;
} else if (tag.equals("td")) {
parent = "tr";
index = 1;
}
if (tag.equals("li")) {
char lastChar = 0;
if (output.length() > 0) {
lastChar = output.charAt(output.length() - 1);
}
if (parent.equals("ul")) {
if (first) {
if (lastChar == '\n') {
output.append("\t• ");
} else {
output.append("\n\t• ");
}
first = false;
} else {
first = true;
}
} else {
if (first) {
if (lastChar == '\n') {
output.append("\t" + index + ". ");
} else {
output.append("\n\t" + index + ". ");
}
first = false;
index++;
} else {
first = true;
}
}
}
if (tag.equals("tr")) {
char lastChar = 0;
if (output.length() > 0) {
lastChar = output.charAt(output.length() - 1);
}
if (parent.equals("tr")) {
if (first) {
if (lastChar == '\n') {
output.append("\t• ");
} else {
output.append("\n\t• ");
}
first = false;
} else {
first = true;
}
} else {
if (first) {
if (lastChar == '\n') {
output.append("\t" + index);
} else {
output.append("\n\t" + index);
}
first = false;
index++;
} else {
first = true;
}
}
}
}
}
Code:
If i try to swap out tr to td in this code, then there wont be any columns just new rows "\n"
if (tag.equals("tr")) {
char lastChar = 0;
if (output.length() > 0) {
lastChar = output.charAt(output.length() - 1);
}
I'm terribly sorry for this huge mess of a post that I have done but right now my mind is basically mush.
Well i find this way of working with the xmlreader looks quite complicated, if you dont mind about switching tools, try out Jsoup xml parser, there you can select a single table/list/etc object and just get all the element's children (which, in a table, are tr objects whose children are then td). It is far easier than doing it by hand
---------------------------------
Phone : Nexus 4
OS :
- KitKat 4.4.4 stock
- Xposed: 58(app_process); 54(bridge)
- SU: SuperSU
- no custom recovery
---------------------------------
4d 61 73 72 65 70 75 73 20 66 74 77
Gesendet von Tapatalk

Categories

Resources