Hi, I really need help, i want to extract some .png and .jpg from the assets of the app 'Hyperdimension Neptunia The App'
after 3 month of research i found out that the assets are probably "encrypted" i wanted the textures for the live2D model files, and wanted to replace the sounds with the English versions from the iOS app that i extracted.
Audio was .caf in iOS but in Android it says its .mp3
This Line in a class says something about the audio: localEditor.putString("alarm_voice", bw.a(str, "caf", "mp3"));
The .caf opens and runs fine so whats the problem and anyone help me decrypt it? :fingers-crossed:
Full "AlarmActivity.class"
Code:
package jp.co.ideaf.neptune.nepkamijigenapp;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Handler;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.NumberPicker;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;
import java.util.Calendar;
import java.util.Timer;
import jp.co.ideaf.neptune.nepkamijigenapp.a.a;
import jp.co.ideaf.neptune.nepkamijigenapp.a.d;
import jp.co.ideaf.neptune.nepkamijigenapp.a.f;
import jp.co.ideaf.neptune.nepkamijigenapp.a.h;
import jp.co.ideaf.neptune.nepkamijigenapp.d.z;
public class AlarmActivity extends Activity
{
private a a = null;
private d b = null;
private Timer c = null;
private ee d = null;
private eg e = null;
private Handler f = new Handler();
private LinearLayout g = null;
private static int a(Context paramContext, a parama, long paramLong)
{
h localh = KamijigenApplication.c();
z localz = localh.b(parama.c().f());
int i = localh.a();
String str = localz.g();
Object[] arrayOfObject = new Object[1];
arrayOfObject[0] = Long.valueOf(paramLong / 1000L);
jp.co.ideaf.neptune.nepkamijigenapp.d.k.a(String.format("アラーム発生時間 : %d秒", arrayOfObject), new Object[0]);
f localf = new f(paramLong + Calendar.getInstance().getTimeInMillis());
SharedPreferences.Editor localEditor = paramContext.getSharedPreferences(bw.a(paramContext, 2131034117), 0).edit();
localEditor.putString("alarm_voice", bw.a(str, "caf", "mp3"));
localEditor.putBoolean("snooze", parama.b);
localEditor.putInt("snooze_time", parama.c);
localEditor.commit();
Intent localIntent = new Intent(paramContext, AlarmDialogActivity.class);
localIntent.addFlags(268435456);
PendingIntent localPendingIntent = PendingIntent.getActivity(paramContext, 0, localIntent, 0);
((AlarmManager)paramContext.getSystemService("alarm")).set(0, localf.b(), localPendingIntent);
return i;
}
private void a()
{
TimePicker localTimePicker = (TimePicker)findViewById(2131165202);
if (localTimePicker == null);
while (true)
{
return;
localTimePicker.setIs24HourView(Boolean.valueOf(true));
localTimePicker.setCurrentHour(Integer.valueOf(this.a.c().f()));
localTimePicker.setCurrentMinute(Integer.valueOf(this.a.c().g()));
}
}
private void a(int paramInt)
{
TextView localTextView = (TextView)findViewById(2131165196);
if (localTextView != null)
{
localTextView.setText(Integer.toString(paramInt));
localTextView.append(bw.a(this, 2131034215));
}
}
private void a(int paramInt1, int paramInt2)
{
TextView localTextView1 = (TextView)findViewById(2131165194);
if (localTextView1 != null)
{
localTextView1.setText(Integer.toString(paramInt1));
localTextView1.append(bw.a(this, 2131034211));
}
TextView localTextView2 = (TextView)findViewById(2131165195);
if (localTextView2 != null)
{
localTextView2.setText(Integer.toString(paramInt2));
localTextView2.append(bw.a(this, 2131034212));
}
}
public static void a(Context paramContext, a parama)
{
d locald = KamijigenApplication.a();
locald.b(paramContext, false);
c(paramContext, parama);
parama.a = true;
locald.p().a(parama);
locald.c(paramContext);
}
private void b()
{
CheckBox localCheckBox = (CheckBox)findViewById(2131165197);
if (localCheckBox != null)
{
if (KamijigenApplication.a().p().a)
break label38;
localCheckBox.setEnabled(false);
localCheckBox.setChecked(false);
}
while (true)
{
return;
label38: localCheckBox.setChecked(true);
}
}
private static void c(Context paramContext, a parama)
{
f localf1 = new f(Calendar.getInstance().getTimeInMillis());
int i = localf1.f();
int j = localf1.g();
int k;
int m;
int n;
f localf2;
long l;
if ((i < parama.c().f()) || ((i == parama.c().f()) && (j < parama.c().g())))
{
k = localf1.c();
m = localf1.d();
n = localf1.e();
localf2 = new f(k, m, n, parama.c().f(), parama.c().g(), 0);
jp.co.ideaf.neptune.nepkamijigenapp.d.k.a("targetDate : " + localf2.toString(), new Object[0]);
jp.co.ideaf.neptune.nepkamijigenapp.d.k.a("nowDate : " + localf1.toString(), new Object[0]);
l = localf2.b() - localf1.b();
if (parama.c <= 0)
break label300;
}
label300: for (parama.b = true; ; parama.b = false)
{
int i1 = a(paramContext, parama, l);
parama.c().a(k);
parama.c().b(m);
parama.c().c(n);
parama.d = i1;
return;
f localf3 = new f(86400000L + localf1.b());
k = localf3.c();
m = localf3.d();
n = localf3.e();
localf2 = new f(k, m, n, parama.c().f(), parama.c().g(), 0);
break;
}
}
public void onClickBackButton(View paramView)
{
finish();
}
public void onClickDecideButton(View paramView)
{
CheckBox localCheckBox = (CheckBox)findViewById(2131165197);
if (((RadioButton)findViewById(2131165199)).isChecked())
{
findViewById(2131165201).setVisibility(8);
findViewById(2131165203).setVisibility(0);
findViewById(2131165201).setVisibility(0);
findViewById(2131165203).setVisibility(8);
if (localCheckBox != null)
break label127;
}
while (true)
{
return;
findViewById(2131165201).setVisibility(0);
findViewById(2131165203).setVisibility(8);
findViewById(2131165201).setVisibility(8);
findViewById(2131165203).setVisibility(0);
break;
label127: d locald = KamijigenApplication.a();
if (!locald.p().a)
showDialog(0);
else if ((locald.p().a) && (localCheckBox.isChecked()))
showDialog(2);
else
showDialog(3);
}
}
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
setRequestedOrientation(1);
setContentView(2130903041);
d locald = KamijigenApplication.a();
this.a = new a();
this.a.a(locald.p());
a(this.a.c().f(), this.a.c().g());
a();
b();
TimePicker localTimePicker = (TimePicker)findViewById(2131165202);
if (localTimePicker != null)
{
localTimePicker.setVisibility(0);
localTimePicker.setOnTimeChangedListener(new j(this));
}
userNumberPicker localuserNumberPicker = (userNumberPicker)findViewById(2131165204);
a(this.a.c);
if ((Build.VERSION.SDK_INT < 11) && (localuserNumberPicker != null))
{
localuserNumberPicker.a(0, 59);
localuserNumberPicker.a(this.a.c);
localuserNumberPicker.a(new l(this));
}
if (Build.VERSION.SDK_INT >= 11)
{
FrameLayout localFrameLayout = (FrameLayout)findViewById(2131165203);
localuserNumberPicker.setEnabled(false);
localuserNumberPicker.setVisibility(8);
this.g = new LinearLayout(this);
this.g.setOrientation(0);
NumberPicker localNumberPicker = new NumberPicker(this);
localNumberPicker.setMinValue(0);
localNumberPicker.setMaxValue(59);
localNumberPicker.setValue(this.a.c);
localNumberPicker.setOnValueChangedListener(new m(this));
this.g.addView(localNumberPicker, 0, new LinearLayout.LayoutParams(-2, -2, 1.0F));
localFrameLayout.addView(this.g, new FrameLayout.LayoutParams(-2, -2, 17));
}
findViewById(2131165201).setVisibility(0);
findViewById(2131165203).setVisibility(8);
((RadioGroup)findViewById(2131165198)).setOnCheckedChangeListener(new n(this));
this.b = KamijigenApplication.a();
String str = getResources().getText(2131034115).toString();
LinearLayout localLinearLayout = (LinearLayout)findViewById(2131165191);
Button localButton = (Button)findViewById(2131165205);
if (str.equals(this.b.d(this.b.k())))
{
localLinearLayout.setBackgroundResource(2130837540);
localButton.setBackgroundResource(2130837513);
}
while (true)
{
if (locald.p().a)
showDialog(4);
return;
localLinearLayout.setBackgroundResource(2130837541);
localButton.setBackgroundResource(2130837514);
}
}
protected Dialog onCreateDialog(int paramInt)
{
AlertDialog localAlertDialog;
if (paramInt == 0)
localAlertDialog = new AlertDialog.Builder(this).setTitle(2131034216).setMessage(2131034217).setPositiveButton(2131034218, new q(this)).setNegativeButton(2131034219, null).create();
while (true)
{
return localAlertDialog;
if (paramInt == 1)
{
localAlertDialog = new AlertDialog.Builder(this).setMessage(2131034220).setPositiveButton(2131034221, new r(this)).create();
}
else if (paramInt == 2)
{
localAlertDialog = new AlertDialog.Builder(this).setTitle(2131034222).setMessage(2131034223).setPositiveButton(2131034224, new s(this)).setNegativeButton(2131034225, null).create();
}
else if (paramInt == 3)
{
localAlertDialog = new AlertDialog.Builder(this).setTitle(2131034226).setMessage(2131034227).setPositiveButton(2131034228, new t(this)).setNegativeButton(2131034229, null).create();
}
else
{
localAlertDialog = null;
if (paramInt == 4)
localAlertDialog = new AlertDialog.Builder(this).setMessage(2131034304).setPositiveButton(2131034228, new k(this)).setNegativeButton(2131034229, null).create();
}
}
}
protected void onPause()
{
super.onPause();
if (this.d != null)
this.d.b();
this.c.cancel();
this.c.purge();
}
protected void onResume()
{
super.onResume();
this.d = new ee(this);
this.d.a();
this.c = new Timer(true);
this.c.scheduleAtFixedRate(new o(this), 100L, 100L);
Display localDisplay = ((WindowManager)getSystemService("window")).getDefaultDisplay();
if (localDisplay.getWidth() > localDisplay.getHeight());
for (int i = localDisplay.getHeight(); ; i = localDisplay.getWidth())
{
float f1 = i / 480.0F;
LinearLayout localLinearLayout = (LinearLayout)findViewById(2131165193);
getResources().getDrawable(2130837742);
localLinearLayout.getLayoutParams().height = ((int)(90.0F * f1));
localLinearLayout.getLayoutParams().width = ((int)(f1 * 172.0F));
localLinearLayout.requestLayout();
this.e = new eg(this, 0);
return;
}
}
}
well if it is encrypted, what type ? and if it\s something like AES CBC how do you intend to get the cypher ?
That's the problem, im kinda new to this thing so im not sure how to get the cypher and i think its AES encrypted but not 100% certain. Sorry for being a noob.
Related
Hi.
I'm currently working on a wakeup-app (alarm) that plays your favorite radio-station via shoutcast-stream.
It looked really easy:
Code:
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(PATH_TO_FILE);
mp.prepare();
mp.start();
Then I found out Eclair doesn't support shoutcast's ICY protocol. Grmbl.
So for 2.1 (and earlier versions) it is required to handle the shoutcast-stream seperatly and pass it to MediaPlayer via http.
I even found an example:
http://code.google.com/p/npr-android-app/source/browse/trunk/Npr/src/org/npr/android/news/StreamProxy.java
Problem is that it's all a bit too advanced for me, so I was wondering if anyone has a really simple example of how to do this?
Something like:
"Add 'this file' to your project (where 'this file' would be a class similarly to StreamProxy) and then add this to your application:"
Code:
StreamProxy sp = new StreamProxy();
sp.setDataSource( SHOUTCAST_URL );
MediaPlayer mp = new MediaPlayer();
mp.setDataSource( sp.getProxyUrl );
mp.prepare();
mp.start();
(Pardon my english
fixed!
Will post how I did it soon.
Here's the app:
http://android.rejh.nl/fmalarm
Just got reminded by someone that I never posted the solution. Here goes:
Code:
// Streamurl
String streamUrl = "[Path-to-audio-stream-or-file]";
// Prepare Proxy (for Android 2.1 en lower (sdk<8))
sdkVersion = 0;
try { sdkVersion = Integer.parseInt(Build.VERSION.SDK); } // Note: Build.VERSION.SDK is deprecated..
catch (NumberFormatException e) {}
if (sdkVersion<8) {
if (proxy==null) {
try {
proxy = new StreamProxy();
proxy.init();
proxy.start();
streamUrl = String.format("http://127.0.0.1:%d/%s", proxy.getPort(), url);
} catch(IllegalStateException e) { Log.e(LOGTAG," -> IllStateException: "+e, e); }
}
}
// Create mediaplayer and set stream (proxied if needed)
mp = new MediaPlayer();
mp.setDataSource(streamUrl);
UPDATE!! Forgot the StreamProxy code
Code:
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Minor changes by REJH Gadellaa 2010/2011
package org.npr.android.news;
import android.util.Log;
import org.apache.http.Header;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.ParseException;
import org.apache.http.ProtocolVersion;
import org.apache.http.RequestLine;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionOperator;
import org.apache.http.conn.OperatedClientConnection;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.impl.conn.DefaultClientConnectionOperator;
import org.apache.http.impl.conn.DefaultResponseParser;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.io.HttpMessageParser;
import org.apache.http.io.SessionInputBuffer;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicLineParser;
import org.apache.http.message.ParserCursor;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.CharArrayBuffer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.StringTokenizer;
public class StreamProxy implements Runnable {
private static final String LOG_TAG = "FMA2Proxy";
private int port = 5050;
public int getPort() {
return port;
}
private boolean isRunning = true;
private ServerSocket socket;
private Thread thread;
public void init() {
try {
socket = new ServerSocket(port, 0, InetAddress.getByAddress(new byte[] {127,0,0,1}));
socket.setSoTimeout(5000);
port = socket.getLocalPort();
Log.d(LOG_TAG, "port " + port + " obtained");
} catch (UnknownHostException e) {
Log.e(LOG_TAG, "Error initializing server", e);
} catch (IOException e) {
Log.e(LOG_TAG, "Error initializing server", e);
}
}
public void start() {
if (socket == null) {
throw new IllegalStateException("Cannot start proxy; it has not been initialized.");
}
thread = new Thread(this);
thread.start();
}
public void stop() {
isRunning = false;
if (thread == null) {
throw new IllegalStateException("Cannot stop proxy; it has not been started.");
}
if (socket!=null) { try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
thread.interrupt();
try {
thread.join(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// @Override
public void run() {
Log.d(LOG_TAG, "running");
while (isRunning) {
try {
Socket client = socket.accept();
if (client == null) {
continue;
}
Log.d(LOG_TAG, "client connected");
HttpRequest request = readRequest(client);
processRequest(request, client);
} catch (SocketTimeoutException e) {
// Do nothing
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to client", e);
}
}
Log.d(LOG_TAG, "Proxy interrupted. Shutting down.");
}
private HttpRequest readRequest(Socket client) {
HttpRequest request = null;
InputStream is;
String firstLine;
try {
is = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
firstLine = reader.readLine();
} catch (IOException e) {
Log.e(LOG_TAG, "Error parsing request", e);
return request;
}
if (firstLine == null) {
Log.i(LOG_TAG, "Proxy client closed connection without a request.");
return request;
}
StringTokenizer st = new StringTokenizer(firstLine);
String method = st.nextToken();
String uri = st.nextToken();
Log.d(LOG_TAG, uri);
String realUri = uri.substring(1);
Log.d(LOG_TAG, realUri);
request = new BasicHttpRequest(method, realUri);
return request;
}
private HttpResponse download(String url) {
DefaultHttpClient seed = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
registry.register(
new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
SingleClientConnManager mgr = new MyClientConnManager(seed.getParams(),
registry);
DefaultHttpClient http = new DefaultHttpClient(mgr, seed.getParams());
HttpGet method = new HttpGet(url);
HttpResponse response = null;
try {
Log.d(LOG_TAG, "starting download");
response = http.execute(method);
Log.d(LOG_TAG, "downloaded");
} catch (ClientProtocolException e) {
Log.e(LOG_TAG, "Error downloading", e);
} catch (IOException e) {
Log.e(LOG_TAG, "Error downloading", e);
}
return response;
}
private void processRequest(HttpRequest request, Socket client)
throws IllegalStateException, IOException {
if (request == null) {
return;
}
Log.d(LOG_TAG, "processing");
String url = request.getRequestLine().getUri();
HttpResponse realResponse = download(url);
if (realResponse == null) {
return;
}
Log.d(LOG_TAG, "downloading...");
InputStream data = realResponse.getEntity().getContent();
StatusLine line = realResponse.getStatusLine();
HttpResponse response = new BasicHttpResponse(line);
response.setHeaders(realResponse.getAllHeaders());
Log.d(LOG_TAG, "reading headers");
StringBuilder httpString = new StringBuilder();
httpString.append(response.getStatusLine().toString());
httpString.append("\n");
for (Header h : response.getAllHeaders()) {
httpString.append(h.getName()).append(": ").append(h.getValue()).append(
"\n");
}
httpString.append("\n");
Log.d(LOG_TAG, "headers done");
try {
byte[] buffer = httpString.toString().getBytes();
int readBytes = -1;
Log.d(LOG_TAG, "writing to client");
client.getOutputStream().write(buffer, 0, buffer.length);
// Start streaming content.
byte[] buff = new byte[1024 * 50];
while (isRunning && (readBytes = data.read(buff, 0, buff.length)) != -1) {
client.getOutputStream().write(buff, 0, readBytes);
}
} catch (Exception e) {
Log.e("", e.getMessage(), e);
} finally {
if (data != null) {
data.close();
}
client.close();
}
}
private class IcyLineParser extends BasicLineParser {
private static final String ICY_PROTOCOL_NAME = "ICY";
private IcyLineParser() {
super();
}
@Override
public boolean hasProtocolVersion(CharArrayBuffer buffer,
ParserCursor cursor) {
boolean superFound = super.hasProtocolVersion(buffer, cursor);
if (superFound) {
return true;
}
int index = cursor.getPos();
final int protolength = ICY_PROTOCOL_NAME.length();
if (buffer.length() < protolength)
return false; // not long enough for "HTTP/1.1"
if (index < 0) {
// end of line, no tolerance for trailing whitespace
// this works only for single-digit major and minor version
index = buffer.length() - protolength;
} else if (index == 0) {
// beginning of line, tolerate leading whitespace
while ((index < buffer.length()) &&
HTTP.isWhitespace(buffer.charAt(index))) {
index++;
}
} // else within line, don't tolerate whitespace
if (index + protolength > buffer.length())
return false;
return buffer.substring(index, index + protolength).equals(ICY_PROTOCOL_NAME);
}
@Override
public Header parseHeader(CharArrayBuffer buffer) throws ParseException {
return super.parseHeader(buffer);
}
@Override
public ProtocolVersion parseProtocolVersion(CharArrayBuffer buffer,
ParserCursor cursor) throws ParseException {
if (buffer == null) {
throw new IllegalArgumentException("Char array buffer may not be null");
}
if (cursor == null) {
throw new IllegalArgumentException("Parser cursor may not be null");
}
final int protolength = ICY_PROTOCOL_NAME.length();
int indexFrom = cursor.getPos();
int indexTo = cursor.getUpperBound();
skipWhitespace(buffer, cursor);
int i = cursor.getPos();
// long enough for "HTTP/1.1"?
if (i + protolength + 4 > indexTo) {
throw new ParseException
("Not a valid protocol version: " +
buffer.substring(indexFrom, indexTo));
}
// check the protocol name and slash
if (!buffer.substring(i, i + protolength).equals(ICY_PROTOCOL_NAME)) {
return super.parseProtocolVersion(buffer, cursor);
}
cursor.updatePos(i + protolength);
return createProtocolVersion(1, 0);
}
@Override
public RequestLine parseRequestLine(CharArrayBuffer buffer,
ParserCursor cursor) throws ParseException {
return super.parseRequestLine(buffer, cursor);
}
@Override
public StatusLine parseStatusLine(CharArrayBuffer buffer,
ParserCursor cursor) throws ParseException {
StatusLine superLine = super.parseStatusLine(buffer, cursor);
return superLine;
}
}
class MyClientConnection extends DefaultClientConnection {
@Override
protected HttpMessageParser createResponseParser(
final SessionInputBuffer buffer,
final HttpResponseFactory responseFactory, final HttpParams params) {
return new DefaultResponseParser(buffer, new IcyLineParser(),
responseFactory, params);
}
}
class MyClientConnectionOperator extends DefaultClientConnectionOperator {
public MyClientConnectionOperator(final SchemeRegistry sr) {
super(sr);
}
@Override
public OperatedClientConnection createConnection() {
return new MyClientConnection();
}
}
class MyClientConnManager extends SingleClientConnManager {
private MyClientConnManager(HttpParams params, SchemeRegistry schreg) {
super(params, schreg);
}
@Override
protected ClientConnectionOperator createConnectionOperator(
final SchemeRegistry sr) {
return new MyClientConnectionOperator(sr);
}
}
}
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");
}
}
I've made a class called SendToWear with a static method called sendMessage(Context context, String path, @nullable String data) which finds all connected nodes and sends data to any found nodes.
This class is identical to another class I used in an Android Wear device called SendToPhone which works successfully and will send a fire-and-forget message to my connected mobile phone, but SendToWear (a class with identical code, as stated) will not.
The problem is at this section:
Code:
GoogleApiClient sClient = new GoogleApiClient.Builder(context)
.addApi(Wearable.API)
.build();
ConnectionResult connectionResult =
sClient.blockingConnect(5, TimeUnit.SECONDS);
if (!connectionResult.isSuccess()) {
Log.e(TAG, "Failed to connect to sClient.");
return 0;
} else Log.d(TAG, "sClient connected!");
The handheld device always return 'Failed to connect to sClient'. Can anybody explain this?
Thanks.
Full code below:
Code:
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.MessageApi;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.Wearable;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
public class SendToPhone {
public static int sendMessage(Context context, String path, [user=3869344]@nullable[/user] String data){
Log.d(TAG, "Path: " + path + "\tData: " + data);
ArrayList<String> nodes;
int sent; // amount of nodes which received the message
if(context == null || path == null){
Log.d(TAG, "Context or Path is null.");
return 0;
}
GoogleApiClient sClient = new GoogleApiClient.Builder(context)
.addApi(Wearable.API)
.build();
ConnectionResult connectionResult =
sClient.blockingConnect(5, TimeUnit.SECONDS);
if (!connectionResult.isSuccess()) {
Log.e(TAG, "Failed to connect to sClient.");
return 0;
} else Log.d(TAG, "sClient connected!");
nodes = getNodes(sClient);
if(nodes.size() == 0) return 0;
for(int i = sent = 0; i < nodes.size(); i++) {
MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(
sClient, nodes.get(i), path, data.getBytes()).await();
// was not able to send message
if(result.getStatus().isSuccess())
++sent;
}
sClient.disconnect();
Log.d(TAG, "SENT: " + sent);
return sent;
}
private static ArrayList<String> getNodes(GoogleApiClient client) {
ArrayList<String> results = new ArrayList<String>();
NodeApi.GetConnectedNodesResult nodes =
Wearable.NodeApi.getConnectedNodes(client).await(3, TimeUnit.SECONDS);
if(nodes == null || !nodes.getStatus().isSuccess())
return results;
for (Node node : nodes.getNodes()) {
results.add(node.getId());
}
return results;
}
}
Dear all , How are you
I have an Android application , the Developer of it chose to stop the support for it.
Any way i want to fix the bug,
I am not that expert with Java so i am seeking for help
The error that the app return when it get data from the database is :
Code:
11-14 15:42:26.420 W/SQLiteConnectionPool(15763): A SQLiteConnection object for database '/data/data/com.bookscars.src.v65/databases/AppDbStoreroot7' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
Now i did decompile the APK , search for the class who call AppDbStoreroot7 database to see what we can do for it ! and i found it,
Please note that i need to edit on the Smali code
what i need to know , where i need to put the close commad since i am not a JAVA expert
here is the code :
Code:
package com.studio.sm.root.utility;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.Iterator;
import java.util.Vector;
import org.json.JSONArray;
import org.json.JSONObject;
public class RootLogsStorage
{
private static final String DATABASE_NAME = "AppDbStoreroot7";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_BOOKS = "books";
public static final String TABLE_CARS = "cars";
private static final String TAG = "RootLogsStorage";
private DatabaseHelper DBHelper;
private final Context context;
private SQLiteDatabase db;
private RootLogsStorage(Context paramContext)
{
this.context = paramContext;
this.DBHelper = new DatabaseHelper(this.context, null);
}
public static void clearStorage(Context paramContext)
{
RootLogsStorage localRootLogsStorage = getWritable(paramContext);
localRootLogsStorage.emptyLogTable("books");
localRootLogsStorage.emptyLogTable("cars");
localRootLogsStorage.close();
}
private boolean emptyLogTable(String paramString)
{
return this.db.delete(paramString, null, null) > 0;
}
private static String getCreateStringFor(String paramString)
{
return "create table " + paramString + " (_id integer primary key autoincrement, " + "contents text not null);";
}
private Cursor getCursorOf(String paramString)
{
Cursor localCursor = this.db.query(paramString, new String[] { "_id", "contents" }, null, null, null, null, null);
if ((localCursor == null) || (localCursor.getCount() <= 0) || (!localCursor.moveToFirst()))
{
if (localCursor != null) {
localCursor.close();
}
localCursor = null;
}
return localCursor;
}
public static RootLogsStorage getReadable(Context paramContext)
{
return new RootLogsStorage(paramContext).openToRead();
}
public static RootLogsStorage getWritable(Context paramContext)
{
return new RootLogsStorage(paramContext).openToWrite();
}
private RootLogsStorage openToRead()
throws SQLException
{
this.db = this.DBHelper.getReadableDatabase();
return this;
}
private RootLogsStorage openToWrite()
throws SQLException
{
this.db = this.DBHelper.getWritableDatabase();
return this;
}
public void close()
{
this.db.close();
this.DBHelper.close();
}
public JSONArray getLogContentsOf(String paramString)
throws Exception
{
JSONArray localJSONArray = new JSONArray();
Cursor localCursor = getCursorOf(paramString);
if (localCursor == null) {
return localJSONArray;
}
while (!localCursor.isAfterLast())
{
localJSONArray.put(new JSONObject(localCursor.getString(1)));
localCursor.moveToNext();
}
localCursor.close();
return localJSONArray;
}
public void insertLogs(String paramString, Vector<String> paramVector)
{
Log.e("RootLogsStorage INSERT", paramString + "/" + paramVector.size());
Iterator localIterator = paramVector.iterator();
for (;;)
{
if (!localIterator.hasNext()) {
return;
}
String str = (String)localIterator.next();
ContentValues localContentValues = new ContentValues();
localContentValues.put("contents", str);
this.db.insert(paramString, null, localContentValues);
}
}
private static class DatabaseHelper
extends SQLiteOpenHelper
{
private DatabaseHelper(Context paramContext)
{
super("AppDbStoreroot7", null, 1);
}
public void onCreate(SQLiteDatabase paramSQLiteDatabase)
{
paramSQLiteDatabase.execSQL(RootLogsStorage.getCreateStringFor("books"));
paramSQLiteDatabase.execSQL(RootLogsStorage.getCreateStringFor("cars"));
}
public void onUpgrade(SQLiteDatabase paramSQLiteDatabase, int paramInt1, int paramInt2) {}
}
}
Please advice where to put the close command , please note i will edit on smali !
I'm trying to get the result of the asynctask by using an interface but when I've tried to use the methods on that interface my app keeps on crashing.
This project has 4 java files: MainActivity.java , SigninActivity.java , GetAvailableExam.java , AsyncResponse.java
I'm pretty sure the error is not on the GetAvailableExam.java because it is just an activity that prints hello world so I'm not going to post it's code here.
MainActivity.java
Code:
package com.it4.anexsysclient;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements AsyncResponse {
private EditText usernameField,passwordField;
private TextView status,role,method;
SigninActivity signinactivity = new SigninActivity();
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameField = (EditText)findViewById(R.id.editText1);
passwordField = (EditText)findViewById(R.id.editText2);
status = (TextView)findViewById(R.id.textView6);
role = (TextView)findViewById(R.id.textView7);
method = (TextView)findViewById(R.id.textView9);
signinactivity.delegate = this;
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
usernameField.setText("stud");
passwordField.setText("stud");
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void login(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Get Method");
new SigninActivity(this,status,role,0).execute(username,password);
}
public void loginPost(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Post Method");
new SigninActivity(this,status,role,1).execute(username,password);
}
public void processFinish(String output){
//Toast.makeText(getApplicationContext(), output, Toast.LENGTH_LONG).show();
}
}
SigninActivity.java
Code:
package com.it4.anexsysclient;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
public class SigninActivity extends AsyncTask<String,Void,String>{
private TextView statusField,roleField;
private Context context;
private int byGetOrPost = 0;
private String server_ip;
private ProgressDialog progress;
public AsyncResponse delegate=null;
public SigninActivity() {
}
//flag 0 means get and 1 means post.(By default it is get.)
public SigninActivity(Context context,TextView statusField,
TextView roleField,int flag) {
this.context = context;
this.statusField = statusField;
this.roleField = roleField;
byGetOrPost = flag;
this.progress = new ProgressDialog(context);
}
protected void onPreExecute(){
server_ip = "http://192.168.0.101/anexsys/examination-manager.php";
this.progress.setMessage("Logging in");
this.progress.show();
}
[user=439709]@override[/user]
protected String doInBackground(String... arg0) {
if(byGetOrPost == 0){ //means by Get Method
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link = "http://myphpmysqlweb.hostei.com/login.php?username="
+username+"&password="+password;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
else{
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link=server_ip;
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter
(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
}
[user=439709]@override[/user]
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
this.progress.dismiss();
delegate.processFinish(result);
//Log.d("ADebugTag", "Value: " + result);
//if(result.toString()=="student") {
//context.startActivity(new Intent(context, GetAvailableExam.class));
//}
}
}
AsyncResponse.java
Code:
package com.it4.anexsysclient;
public interface AsyncResponse {
void processFinish(String output);
}
Code:
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
this.progress.dismiss();
delegate.processFinish(result);
//Log.d("ADebugTag", "Value: " + result);
//if(result.toString()=="student") {
//context.startActivity(new Intent(context, GetAvailableExam.class));
//}
}
The delegate.processFinish(result) is the one causing the crash, The app works fine if I try to remove/comment out it.
Would be helpfull with some more information, for instance: what exception is it you get?
My guess is a nullpointer? Which by a quick glance i'd suspect is that you never set "delegate" in your signinactivity.
You create signinactivity during creation of mainactivity.
Code:
[B]SigninActivity signinactivity = new SigninActivity();[/B]
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameField = (EditText)findViewById(R.id.editText1);
passwordField = (EditText)findViewById(R.id.editText2);
status = (TextView)findViewById(R.id.textView6);
role = (TextView)findViewById(R.id.textView7);
method = (TextView)findViewById(R.id.textView9);
[B]signinactivity.delegate = this;[/B]
}
However that instance is later never used from what i can tell? You create new instances later in code when its used, where delegate won't be set.
Code:
public void login(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Get Method");
[B]new SigninActivity(this,status,role,0).execute(username,password);[/B]
}
public void loginPost(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Post Method");
[B] new SigninActivity(this,status,role,1).execute(username,password);[/B]
}