Trying to get balance with web3j (Android), geting nullpointer exception - java

Struggling getting anything to work in web3j on android, trying this example (I have replaced token and addr) the address I used does have some rinkeby ETH in it. Testing on phone, application crashes when I load up this class/activity, code is in the oncreate method. Have internet permission turned on in the manifest, and compile android web3j in the build gradle.
Web3j web3 = Web3jFactory.build(new
HttpService("https://rinkeby.infura.io/token"));
EthGetBalance ethGetBalance = null;
try {
ethGetBalance = web3
.ethGetBalance("addr",DefaultBlockParameterName.LATEST)
.sendAsync()
.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
BigInteger wei = ethGetBalance.getBalance();
The error
06-30 02:15:47.115 18904-18904/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.test.user.test, PID: 18904
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.user.test/com.test.user.test.balance}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2607)
at android.app.ActivityThread.access$900(ActivityThread.java:174)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1325)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5756)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.test.user.test.balance.onCreate(balance.java:43)
at android.app.Activity.performCreate(Activity.java:5619)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2512)
Line 43 referenced in error is the last line of code in my submitted code. When I comment out that line app doesn't crash and just get a few (what I assume are all) warnings.

Your ethGetBalance return a null value .i think you put a invalid address. thats why method
web3j.ethGetBalance failes. try this with valid address.
Web3j web3 = Web3jFactory.build(new HttpService("https://ropsten.infura.io/your-token"));
String strAddress="0x24b********************"; //strAddress is your wallet address
EthGetBalance ethGetBalance=
web3.ethGetBalance(strAddress,DefaultBlockParameterName.LATEST).sendAsync().get();
BigInteger wei = ethGetBalance.getBalance();
ethGetBalance.getBalance() is used to get your ether balance in wei.
To get actual token in your wallet use this Conversion method.
java.math.BigDecimal tokenValue = Convert.fromWei(String.valueOf(wei), Convert.Unit.ETHER);
String strTokenAmount = String.valueOf(tokenValue);

ethGetBalance = web3.ethGetBalance(public_address, DefaultBlockParameterName.LATEST).sendAsync().get();
BigInteger wei = ethGetBalance.getBalance();
Log.e("ether balance", "wei" + wei);
This is working fine in my app which is available on playstore
https://play.google.com/store/apps/details?id=multi.erc20.devgenesis.token.wallet

The problem is that the ethGetBalance is null, when you want to access it, because the method web3j.ethGetBalance fails.
You are sending "addr" as an address, this is not a valid Ethereum address.
A valid Ethereum address has a format similar that begins with: 0x and then has 40 elements (digits 0-9 or letters A to F).
To see if your address exists, just try to find it in the website https://etherscan.io/
Try with a correct Ethereum address and it should work.
EthGetBalance ethGetBalance = web3j
.ethGetBalance(userAddress, DefaultBlockParameterName.LATEST)
.sendAsync()
.get();
BigInteger wei = ethGetBalance.getBalance();

Related

Application crash when delete digits (redmarobot input mask)

I am using redmadrobot:inputmask to use card number input mask. Input mask is working properly, but when I try to delete digits from my input, the application crashes.
Here is my code.
ArrayList<String> affineFormats = new ArrayList<>();
affineFormats.add("[0000] [000] [000] [000]");
affineFormats.add("[0000] [000000] [00000]");
affineFormats.add("[0000] [0000] [0000] [0000]");
String format = "[0000] [000] [000] [000]";
MaskedTextChangedListener listener = new MaskedTextChangedListener(
format,
affineFormats,
AffinityCalculationStrategy.CAPACITY,
true,
etCardNumber,
null,
new MaskedTextChangedListener.ValueListener() {
#Override
public void onTextChanged(boolean b, String s, String s1) {
//here some code
}
});
etCardNumber.addTextChangedListener(listener);
Error Log:
java.lang.IndexOutOfBoundsException: setSpan (21 ... 21) ends beyond length 20
at android.text.SpannableStringBuilder.checkRange(SpannableStringBuilder.java:1108)
at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:680)
at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:673)
at android.text.Selection.setSelection(Selection.java:76)
at android.text.Selection.setSelection(Selection.java:87)
at android.widget.EditText.setSelection(EditText.java:104)
at com.redmadrobot.inputmask.MaskedTextChangedListener.afterTextChanged(MaskedTextChangedListener.kt:192)
at android.widget.TextView.sendAfterTextChanged(TextView.java:8366)
at android.widget.TextView$ChangeWatcher.afterTextChanged(TextView.java:10557)
at android.text.SpannableStringBuilder.sendAfterTextChanged(SpannableStringBuilder.java:1061)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:573)
at android.text.SpannableStringBuilder.delete(SpannableStringBuilder.java:233)
at android.text.SpannableStringBuilder.delete(SpannableStringBuilder.java:229)
at android.view.inputmethod.BaseInputConnection.deleteSurroundingText(BaseInputConnection.java:252)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:389)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:78)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5763)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:749)
Please help me resolve this issue.
Make sure you defined
<EditText
...
android:digits="0123456789 "
...
/>
for you input field, including space, as allowed symbol, because it is allowed in your mask.
You can do the same programmatically
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
editText.setKeyListener(DigitsKeyListener.getInstance("0123456789 "));
Worked for me.

How to fix mismatch processor architecture, unexpected e_machine, due to a .so file

I have a Xamarin android project and am currently using Visual Studio 2015.
Inside of my MainActivity.cs, I have the following code:
Com.Alk.Sdk.SharedLibraryLoader.LoadLibrary("alksdk", this);
which then goes into:
// Metadata.xml XPath method reference: path="/api/package[#name='com.alk.sdk']/class[#name='SharedLibraryLoader']/method[#name='loadLibrary' and count(parameter)=2 and parameter[1][#type='java.lang.String'] and parameter[2][#type='android.content.Context']]"
[Register ("loadLibrary", "(Ljava/lang/String;Landroid/content/Context;)Z", "")]
public static unsafe bool LoadLibrary (string p0, global::Android.Content.Context p1)
{
if (id_loadLibrary_Ljava_lang_String_Landroid_content_Context_ == IntPtr.Zero)
id_loadLibrary_Ljava_lang_String_Landroid_content_Context_ = JNIEnv.GetStaticMethodID (class_ref, "loadLibrary", "(Ljava/lang/String;Landroid/content/Context;)Z");
IntPtr native_p0 = JNIEnv.NewString (p0);
try {
JValue* __args = stackalloc JValue [2];
__args [0] = new JValue (native_p0);
__args [1] = new JValue (p1);
bool __ret = JNIEnv.CallStaticBooleanMethod (class_ref, id_loadLibrary_Ljava_lang_String_Landroid_content_Context_, __args);
return __ret;
} finally {
JNIEnv.DeleteLocalRef (native_p0);
}
}
The problem I am having is that when it calls the JNIEnv.CallStaticBooleanMethod, it throws this exception:
[ERROR] FATAL UNHANDLED EXCEPTION: Java.Lang.UnsatisfiedLinkError: dlopen failed: "/data/data/com.pai.rp/app_lib/libalksdk.so" has unexpected e_machine: 3
--- End of managed Java.Lang.UnsatisfiedLinkError stack trace ---
java.lang.UnsatisfiedLinkError: dlopen failed: "/data/data/com.pai.rp/app_lib/libalksdk.so" has unexpected e_machine: 3
at java.lang.Runtime.load0(Runtime.java:908)
at java.lang.System.load(System.java:1542)
at com.alk.sdk.SharedLibraryLoader.loadLibrary(SharedLibraryLoader.java:44)
at com.pai.rp.MainActivity.n_onCreate(Native Method)
at com.pai.rp.MainActivity.onCreate(MainActivity.java:30)
at android.app.Activity.performCreate(Activity.java:6973)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3064)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1659)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6823)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1557)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)
From what I've been able to research I've found that
e_machine: 3 indicates the expected arch is Intel 80386 (ELF Headers).
When using a Google Nexus 10 emulator it seems to work, however when
I use the Galaxy Tab E (ARM) through USB debugging, it crashes and gives me
this error.
So the question is, how do I correct this?

Android SQLiteDiskIOException disk I/O error (code 522)

Yesterday from Crashlytics I noticed disk I/O error (code 522) while opening the database. Problem is that this crashed already has been reported from 16 users 36 times. Sadly I can't reproduce this error. Here's the code fragment where error occurs
SessionDbManager(Context context, String tripDbFileName) {
this.context = context;
this.tripDbFileName = tripDbFileName;
this.tripDbHelper = new SessionDbHelper(this.context, tripDbFileName);
SQLiteDatabase database = null;
int attempt = 1;
while (database == null) {
try {
database = this.tripDbHelper.getWritableDatabase(); // here's the error
} catch (android.database.sqlite.SQLiteException e) {
Crashlytics.logException(e);
XLog.e("Failed to load history data from database ", e);
if (attempt == 5) throw e;
}
attempt++;
}
db = database;
}
And here's the stack trace
Fatal Exception: android.database.sqlite.SQLiteDiskIOException: disk I/O error (code 522): , while compiling: PRAGMA journal_mode
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(SQLiteConnection.java)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:932)
at android.database.sqlite.SQLiteConnection.executeForString(SQLiteConnection.java:677)
at android.database.sqlite.SQLiteConnection.setJournalMode(SQLiteConnection.java:363)
at android.database.sqlite.SQLiteConnection.setWalModeFromConfiguration(SQLiteConnection.java:337)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:251)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:195)
at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:808)
at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:793)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:696)
at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:737)
at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:289)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at eu.fishingapp.data.sql.session.SessionDbManager.(SourceFile:51)
at eu.fishingapp.data.sql.session.SessionContentProvider.update(SourceFile:753)
at android.content.ContentProvider$Transport.update(ContentProvider.java:384)
at android.content.ContentResolver.update(ContentResolver.java:1412)
at eu.fishingapp.data.sql.session.SessionDbHelper.renameSessionDb(SourceFile:584)
at eu.fishingapp.data.network.synchronization.FileSyncServiceImpl.uploadFile(SourceFile:462)
at eu.fishingapp.data.network.synchronization.FileSyncServiceImpl.uploadSessions(SourceFile:221)
at eu.fishingapp.data.network.synchronization.FileSyncServiceImpl.uploadSessionsFiles(SourceFile:243)
at eu.fishingapp.data.network.synchronization.FileSyncIntentService.onHandleIntent(SourceFile:116)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:67)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.os.HandlerThread.run(HandlerThread.java:61)
I have read about I/O error and found two possible answers I was thinking that this is because users ran out of free space on their devices. But here's some images from two app users
So this is definitely not storage issue :( Any ideas how to solve this problem?
EDIT: targetSdk version 22

Logcat error message - Attempted to destroy barrier with non zero count

I'm making an android app in Android Studio, integrating ParseCloud and when I try to retrieve some JSONObject from the cloud, I get this error message after step-debugging:
12-13 13:32:34.857 25631-25638/com.parse.starter A/art: art/runtime/barrier.cc:90] Check failed: count_ == 0 (count_=-1, 0=0) Attempted to destroy barrier with non zero count
12-13 13:32:34.858 25631-25638/com.parse.starter A/art: art/runtime/runtime.cc:366] Runtime aborting --- recursively, so no thread-specific detail!
12-13 13:32:34.863 25631-25638/com.parse.starter A/art: art/runtime/runtime.cc:366]
12-13 13:32:34.882 25631-25638/com.parse.starter A/libc: Fatal signal 6 (SIGABRT), code -6 in tid 25638 (JDWP)
Problem arises in this piece of code in ParseDecoder.java, precisely on the while line:
Map<String, Object> convertJSONObjectToMap(JSONObject object) {
Map<String, Object> outputMap = new HashMap<>();
Iterator<String> it = object.keys();
while (it.hasNext()) {
String key = it.next();
Object value = object.opt(key);
outputMap.put(key, decode(value));
}
return outputMap;
}
As I've seen while debugging, the object I wait for is created and is filled with one entry, but then this happens and I'm little bit lost... Any guidance will be great, thank you very much!
I've solved the problem. I was using an old version of Parse library and it was interfering with the new one. I've just changed the Parse.initialize() lines to:
Parse.initialize(new Parse.Configuration.Builder(this)
.applicationId("MY_APP_ID")
.clientKey("MY_CLIENT_KEY")
.server("MY_SERVER_URL")
.build()
);
and it worked!

Strange runtime exception on Android 4.4.4

I've got this strange stack trace from Flurry Analytics and I have no idea where it comes from. All the classes are from android system and not a single line that tells me where it comes from.
This error happened 3 times on a same device with android 4.4.4
Any ideas? Thanks.
java.lang.RuntimeException
android.app.ActivityThread.performResumeActivity(ActivityThread.java:2836)
android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2865)
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2291)
android.app.ActivityThread.access$800(ActivityThread.java:144)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
android.os.Handler.dispatchMessage(Handler.java:102)
android.os.Looper.loop(Looper.java:212)
android.app.ActivityThread.main(ActivityThread.java:5135)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:515)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:877)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
dalvik.system.NativeStart.main(Native Method)
Caused by: android.app.ActivityThread.deliverResults(ActivityThread.java:3455)
android.app.ActivityThread.performResumeActivity(ActivityThread.java:2823)
android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2865)
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2291)
android.app.ActivityThread.access$800(ActivityThread.java:144)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
android.os.Handler.dispatchMessage(Handler.java:102)
android.os.Looper.loop(Looper.java:212)
android.app.ActivityThread.main(ActivityThread.java:5135)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:515)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:877)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
dalvik.system.NativeStart.main(Native Method)
Part of the problem here seems to be that Flurry error reporting is leaving out important information.
Anyhow, this is where I think the exception is coming from:
private void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
final int N = results.size();
for (int i=0; i<N; i++) {
ResultInfo ri = results.get(i);
try {
if (ri.mData != null) {
ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
}
if (DEBUG_RESULTS) Slog.v(TAG,
"Delivering result to activity " + r + " : " + ri);
r.activity.dispatchActivityResult(ri.mResultWho,
ri.mRequestCode, ri.mResultCode, ri.mData);
} catch (Exception e) {
if (!mInstrumentation.onException(r.activity, e)) {
throw new RuntimeException(
"Failure delivering result " + ri + " to activity "
+ r.intent.getComponent().toShortString()
+ ": " + e.toString(), e);
}
}
}
}
(This code isn't from Android 4.4.4, but this particular method is identical in the versions I looked at ...)
It would seem that deliverResults is catching some exception it got further up the stack, and wrapping / resthoring it as a RuntimeException. At the point that the exception is constructed, it has a message, and cause. Whatever is generating the stacktrace has removed that information, and that is going to make diagnosis hard.

Categories

Resources