I'm trying to create the URI but my app crached.this is my code.
ContentValues values1 = new ContentValues(1);
values1.put(MediaStore.Audio.Media.DISPLAY_NAME, "My Song.mp3");
ContentResolver resolver = getApplicationContext().getContentResolver();
audiouri = resolver.insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values1);
And this is the error that i got.
2021-09-20 00:22:22.963 24197-24197/com.example.voicetest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.voicetest, PID: 24197
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.lastIndexOf(int)' on a null object reference
at android.os.Parcel.createException(Parcel.java:1956)
at android.os.Parcel.readException(Parcel.java:1918)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
at android.content.ContentProviderProxy.insert(ContentProviderNative.java:476)
at android.content.ContentResolver.insert(ContentResolver.java:1587)
at com.example.voicetest.MainActivity$1.onClick(MainActivity.java:148)
at android.view.View.performClick(View.java:7044)
at android.view.View.performClickInternal(View.java:7017)
at android.view.View.access$3200(View.java:784)
at android.view.View$PerformClick.run(View.java:26596)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6819)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:497)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:912)
UPDATE
I added this code and it's work fine, but getContentResolver().insert() return null
File directory = getExternalFilesDir(Environment.DIRECTORY_MUSIC);
values.put(MediaStore.Audio.AudioColumns.DATA, "${directory}${song?.title}");
File directory = getExternalFilesDir(Environment.DIRECTORY_MUSIC);
values.put(MediaStore.Audio.AudioColumns.DATA, "${directory}${song?.title}");
I added this code and it's work fine, but getContentResolver().insert() return null
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
My app won't launch and points to a Null Pointer Exception on my FileReader fr. I initialized it as null to prevent a "Variable may not have been initialized" error. I know the file I want it to use is there under downloads. The file is also inside the main project folder and putting just "academiccalendar.json" does not work either.
My main activity:
public class MainActivity extends AppCompatActivity {
Event[] mobileArray;
Gson gson = new Gson();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BufferedReader br;
FileReader fr = null;
try {
fr = new FileReader("C:/Users/Ali/Downloads/academiccalendar.json");
}
catch (FileNotFoundException e){
e.printStackTrace();
}
br = new BufferedReader(fr);
//br = new BufferedReader(new FileReader("C:/Users/Ali/Downloads/academiccalendar.json"));
mobileArray = gson.fromJson(br, Event[].class);
My logcat output:
12-31 20:06:37.368 9449-9449/com.example.test.testassigment E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test.testassigment/com.example.test.testassigment.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1967)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
at android.app.ActivityThread.access$600(ActivityThread.java:127)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4511)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:976)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:743)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:64)
at java.io.BufferedReader.<init>(BufferedReader.java:92)
at java.io.BufferedReader.<init>(BufferedReader.java:80)
at com.example.test.testassigment.MainActivity.onCreate(MainActivity.java:42)
at android.app.Activity.performCreate(Activity.java:4486)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1052)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1931)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
at android.app.ActivityThread.access$600(ActivityThread.java:127)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4511)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
"C:/Users/Ali/Downloads/academiccalendar.json"
That is a path on your Windows PC. Windows uses drive letters.
Your Android app cannot read files from your PC of course. Or from mine ;-).
I suppose your Android app wants to read a file which is on your Android device.
Try to determine the file on the file system of your Android device.
Because of your path defination. You can use this:
fr = new FileReader("C:\\Users\\Ali\\Downloads\\academiccalendar.json");
Any one can help me I can't find how I can fix this error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
import java.util.ArrayList;
import java.util.List;
/**
* Created by Ineza on 18/11/2016.
*/
public class DerpData extends Application {
private static Context mContext;
#Override
public void onCreate() {
super.onCreate();
mContext = this;
}
public static Context getContext(){
return mContext;
}
private static final String[] titles = DerpData.getContext().getResources().getStringArray(R.array.listArray);
private static final int[] icons =DerpData.getContext().getResources().getIntArray(R.array.imgs);
public static List<LisItem> getListData() {
List<LisItem> data = new ArrayList<>();
//Repeat process 4 times, so that we have enough data to demonstrate a scrollable
//RecyclerView
for (int x = 0; x < 4; x++) {
//create ListItem with dummy data, then add them to our List
for (int i = 0; i < titles.length && i < icons.length; i++) {
LisItem item = new LisItem();
item.setImageResId(icons[i]);
item.setTittle(titles[i]);
data.add(item);
}
}
return data;
}
}
Here is a part of logcat
11-19 06:07:42.188 6497-6497/com.example.ineza.assthree E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ineza.assthree, PID: 6497
java.lang.ExceptionInInitializerError
at com.example.ineza.assthree.RecyClerViewActivity.onCreate(RecyClerViewActivity.java:27)
at android.app.Activity.performCreate(Activity.java:6664)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at com.example.ineza.assthree.model.DerpData.<clinit>(DerpData.java:30)
at com.example.ineza.assthree.RecyClerViewActivity.onCreate(RecyClerViewActivity.java:27)
at android.app.Activity.performCreate(Activity.java:6664)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
11-19 06:07:42.223 1326-1337/system_process W/ActivityManager: Force finishing activity com.example.ineza.assthree/.RecyClerViewActivity
11-19 06:07:42.284 1326-1337/system_process W/ActivityManager: Force finishing activity com.example.ineza.assthree/.LVCustomActivity
11-19 06:07:42.348 1326-1326/system_process W/art: Long monitor contention with owner Binder:1326_1 (1337) at void com.android.server.am.AppErrors.crashApplicationInner(com.android.server.am.Proc essRecord, android.app.ApplicationErrorReport$CrashInfo)(AppErrors.java:328) waiters=0 in int com.android.server.am.ActivityManagerService.broadcastIntent(android.app.IApplicationThread, android.content.Intent, java.lang.String, android.content.IIntentReceiver, int, java.lang.String, android.os.Bundle, java.lang.String[], int, android.os.Bundle, boolean, boolean, int) for 144ms
11-19 06:07:42.561 1326-1343/system_process E/BatteryStatsService: power: Missing API
11-19 06:07:42.562 1326-1375/system_process D/WifiNative-HAL: Failing getSupportedFeatureset because HAL isn't started
11-19 06:07:42.569 1326-1343/system_process E/BluetoothAdapter: Bluetooth binder is null
11-19 06:07:42.571 1326-1343/system_process E/BatteryStatsService: no controller energy info supplied
11-19 06:07:42.620 1326-1343/system_process E/BatteryStatsService: modem info is invalid: ModemActivityInfo{ mTimestamp=0 mSleepTimeMs=0 mIdleTimeMs=0 mTxTimeMs[]=[0, 0, 0, 0, 0] mRxTimeMs=0 mEnergyUsed=0}
11-19 06:07:42.723 1326-2409/system_process I/OpenGLRenderer: Initialized EGL, version 1.4
The code is trying to access static variable from static context when initializing the class. The static initializers are executed before any instance of the class is created. The mContext is initialized after the instance creation during the lifecycle callback. Change your code like this (Updated according to comment below):
#Override
public void onCreate() {
super.onCreate();
mContext = this;
titles = mContext.getResources().getStringArray(R.array.listArray);
icons = mContext.getResources().getIntArray(R.array.imgs);
}
private static final String[] titles;
private static final int[] icons;
I've been using Gson to parse JSON in an API to use in my app. This is an example of the JSON output:
{"getdashboarddata":{"version":"1.0.0","runtime":492.3939704895,"data":{"raw":{"personal":{"hashrate":0},"pool":{"hashrate":1705841},"network":{"hashrate":41430764.301,"esttimeperblock":94.464466565347,"nextdifficulty":578.78109116,"blocksuntildiffchange":1}},"personal":{"hashrate":0,"sharerate":"0.0000","sharedifficulty":0,"shares":{"valid":0,"invalid":0,"invalid_percent":0,"unpaid":0},"estimates":{"block":0,"fee":0,"donation":0,"payout":0}},"pool":{"info":{"name":"RAPIDHASH","currency":"DOGE"},"workers":2199,"hashrate":1.705841,"shares":{"valid":1866290,"invalid":15564,"invalid_percent":0.83,"estimated":1866214,"progress":100},"price":"0.00000073","difficulty":32,"target_bits":21},"system":{"load":[0.1,0.25,0.29]},"network":{"hashrate":41.430764301,"difficulty":911.23745057,"block":235378,"esttimeperblock":94.46,"nextdifficulty":578.78109116,"blocksuntildiffchange":1}}}}
This is the logcat:
05-25 17:12:00.230 24143-24159/io.kd.figgycity50.mpos.mposchecker E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: io.kd.figgycity50.mpos.mposchecker, PID: 24143
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: com.google.gson.JsonSyntaxException: java.io.EOFException: End of input at line 1 column 501
at com.google.gson.Gson.fromJson(Gson.java:813)
at com.google.gson.Gson.fromJson(Gson.java:768)
at com.google.gson.Gson.fromJson(Gson.java:717)
at com.google.gson.Gson.fromJson(Gson.java:689)
at io.kd.figgycity50.mpos.mposchecker.MainActivity$DownloadWebpageTask.doInBackground(MainActivity.java:77)
at io.kd.figgycity50.mpos.mposchecker.MainActivity$DownloadWebpageTask.doInBackground(MainActivity.java:64)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.io.EOFException: End of input at line 1 column 501
at com.google.gson.stream.JsonReader.nextNonWhitespace(JsonReader.java:1377)
at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:471)
at com.google.gson.stream.JsonReader.skipValue(JsonReader.java:1209)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:170)
at com.google.gson.Gson.fromJson(Gson.java:803)
at com.google.gson.Gson.fromJson(Gson.java:768)
at com.google.gson.Gson.fromJson(Gson.java:717)
at com.google.gson.Gson.fromJson(Gson.java:689)
at io.kd.figgycity50.mpos.mposchecker.MainActivity$DownloadWebpageTask.doInBackground(MainActivity.java:77)
at io.kd.figgycity50.mpos.mposchecker.MainActivity$DownloadWebpageTask.doInBackground(MainActivity.java:64)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
This is the code that gets and parses the JSON:
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
String resp = null;
try {
resp = downloadUrl(urls[0]);
} catch (IOException e) {
resp = "{\"getdashboarddata\":{\"data\":{\"personal\":{\"hashrate\":0},\"pool\":{\"info\":{\"name\":\"SET POOL IN SETTINGS\",\"currency\":\"???\"},\"hashrate\":0,\"difficulty\":0},\"network\":{\"hashrate\":0,\"difficulty\":0}}}}";
}
Gson gson = new Gson();
Log.d("INFO", resp);
MPOSDashStruct data = gson.fromJson(resp, MPOSDashStruct.class);
TextView t = (TextView)findViewById(R.id.poolName);
TextView t2 = (TextView)findViewById(R.id.khashMe);
TextView t3 = (TextView)findViewById(R.id.khashPool);
TextView t4 = (TextView)findViewById(R.id.khashNet);
t.setText(data.getName());
t2.setText(data.getMyHash());
t3.setText(data.getPoolHash());
t4.setText(data.getNetHash());
return "Hello World. If you see this, you probably hack. Get out.";
}
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
}
}
Here's the class MPOSDashStruct:
package io.kd.figgycity50.mpos.mposchecker;
import com.google.gson.annotations.SerializedName;
/**
* Created by George on 25/05/2014.
*/
public class MPOSDashStruct {
public static class getdashboarddata {
public static class data {
public static class personal {
public static int hashrate;
}
public static class pool {
public static int hashrate;
public static int difficulty;
public static class info {
#SerializedName("name")
public static String poolName;
public static String currency;
}
}
public static class network {
public static int hashrate;
public static int difficulty;
}
}
}
public String getName() {
return getdashboarddata.data.pool.info.poolName;
}
public String getCurrency() {
return getdashboarddata.data.pool.info.currency;
}
public int getPoolHash() {
return getdashboarddata.data.pool.hashrate;
}
public int getPoolDiff() {
return getdashboarddata.data.pool.difficulty;
}
public int getMyHash() {
return getdashboarddata.data.personal.hashrate;
}
public int getNetHash() {
return getdashboarddata.data.network.hashrate;
}
}
The code is seemingly good, and Android Studio has no errors.
EDIT 2: contentAsString ouputs
05-25 17:30:12.976 29974-29988/io.kd.figgycity50.mpos.mposchecker D/INFO﹕ {"getdashboarddata":{"version":"1.0.0","runtime":632.7919960022,"data":{"raw":{"personal":{"hashrate":0},"pool":{"hashrate":1675289},"network":{"hashrate":38541151.201,"esttimeperblock":61.161346587453,"nextdifficulty":538.41366248,"blocksuntildiffchange":1}},"personal":{"hashrate":0,"sharerate":"0.0000","sharedifficulty":0,"shares":{"valid":0,"invalid":0,"invalid_percent":0,"unpaid":0},"estimates":{"block":0,"fee":0,"donation":0,"payout":0}},"pool":{"info":{"name":"RAPIDHASH","currency":"DOGE"}
using Log.d("INFO", contentAsString)
EDIT: After using getContentLength, the new logcat is this:
05-25 17:50:19.203 5143-5157/io.kd.figgycity50.mpos.mposchecker W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x41bd4ba8)
05-25 17:50:19.203 5143-5157/io.kd.figgycity50.mpos.mposchecker E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: io.kd.figgycity50.mpos.mposchecker, PID: 5143
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NegativeArraySizeException: -1
at io.kd.figgycity50.mpos.mposchecker.MainActivity$DownloadWebpageTask.readIt(MainActivity.java:120)
at io.kd.figgycity50.mpos.mposchecker.MainActivity$DownloadWebpageTask.downloadUrl(MainActivity.java:104)
at io.kd.figgycity50.mpos.mposchecker.MainActivity$DownloadWebpageTask.doInBackground(MainActivity.java:71)
at io.kd.figgycity50.mpos.mposchecker.MainActivity$DownloadWebpageTask.doInBackground(MainActivity.java:64)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
which points to this line of my code:
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len]; //this line, others added so you can understand
reader.read(buffer);
return new String(buffer);
}
EDIT 3: Directing Gson to handle the Reader worked well, but new errors arise again. Logcat:
05-26 09:17:52.459 11810-11810/io.kd.figgycity50.mpos.mposchecker E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: io.kd.figgycity50.mpos.mposchecker, PID: 11810
java.lang.RuntimeException: Unable to start activity ComponentInfo{io.kd.figgycity50.mpos.mposchecker/io.kd.figgycity50.mpos.mposchecker.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at io.kd.figgycity50.mpos.mposchecker.MainActivity.onCreate(MainActivity.java:49)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
which points to:
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String prefPool = sharedPref.getString("pref_pool", "https://doge.rapidhash.net/");
String prefKey = sharedPref.getString("pref_key", "XXXX");
new DownloadWebpageTask().execute(prefPool + "index.php?page=api&action=getdashboarddata&api_key=" + prefKey);
TextView t = (TextView)findViewById(R.id.poolName); // this line
TextView t2 = (TextView)findViewById(R.id.khashMe);
TextView t3 = (TextView)findViewById(R.id.khashPool);
TextView t4 = (TextView)findViewById(R.id.khashNet);
t.setText(dashStruct.getName());
t2.setText(dashStruct.getMyHash());
t3.setText(dashStruct.getPoolHash());
t4.setText(dashStruct.getNetHash());
}
I don't know why you do this
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
If your JSON is longer than that, you're breaking it into pieces that are not parseable by JSON parsers. Read the full JSON string.
Get the content length from the response.
int len = conn.getContentLength();
From Edit 3 above, the following line seems to be throwing the NullPointerException:
t.setText(dashStruct.getName());
I can tell that you declare dashStruct as a class level variable which is getting initialized in the AsyncTask DownloadWebpageTask.
By design, an AsyncTask will be executed off the main thread (to be precise, the AsyncTask#doInBackground(T) method). If DownloadWebpageTask hasn't finished initializing dashStruct when the main thread executes t.setText(dashStruct.getName()); - an NPE will be thrown - dashStruct is null.
To get past this exception, override onPostExecute() in DownloadWebpageTask and move the following code to it (remove it from onCreate(Bundle)):
#Override
protected void onPostExecute(String result) {
if (dashStruct != null) {
t.setText(dashStruct.getName());
t2.setText(dashStruct.getMyHash());
t3.setText(dashStruct.getPoolHash());
t4.setText(dashStruct.getNetHash());
} else {
// Deal with dashStruct being null
}
}
I notice that in your original posting, you are updating your UI (setting textview text) from the DownloadWebpageTask#doInBackground(String...). This will throw an IllegalStateException as doInBackground() is processed off the main thread - the only thread allowed to touch your UI. onPostExecute() is processed on the main thread. And that's where your UI logic should go.
I've added the following (http://loopj.com/android-async-http/) to my /libs folder and have also put it in the module settings as a library and ticked the export button. In the actual file there are no errors given that it can't find the class and when I do import com.loopj and so-forth it completes it for me and shows me the available options.
However, when I run it on my phone it gives the following errors:
12-02 23:00:08.943 8209-8209/mobi.vassilev.beam E/dalvikvm﹕ Could not find class 'com.loopj.android.http.AsyncHttpClient', referenced from method mobi.vassilev.beam.GoogleLoginActivity.requestAPIKeyFromOAuthToken
12-02 23:00:09.183 8209-8209/mobi.vassilev.beam E/﹕ file /data/data/com.nvidia.NvCPLSvc/files/driverlist.txt: not found!
12-02 23:00:10.453 8382-8382/? E/ObjectHelper﹕ Can't find method:setCompatibilityInfo
12-02 23:00:10.598 8209-8209/mobi.vassilev.beam E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NoClassDefFoundError: com.loopj.android.http.AsyncHttpClient
at mobi.vassilev.beam.GoogleLoginActivity.requestAPIKeyFromOAuthToken(GoogleLoginActivity.java:118)
at mobi.vassilev.beam.GoogleLoginActivity.access$200(GoogleLoginActivity.java:24)
at mobi.vassilev.beam.GoogleLoginActivity$OnTokenAcquired.run(GoogleLoginActivity.java:105)
at android.accounts.AccountManager$11.run(AccountManager.java:1335)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5751)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1083)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
at dalvik.system.NativeStart.main(Native Method)
12-02 23:00:10.633 513-548/? E/EmbeddedLogger﹕ App crashed! Process: mobi.vassilev.beam
and the extract of code (not complete obv as the URL is fake, but that shouldn't affect anything):
private void requestAPIKeyFromOAuthToken(String token) {
AsyncHttpClient client = new AsyncHttpClient(); // <-- this is line 118
RequestParams params = new RequestParams("token", token);
client.post("https://myrailsapp.com/api/v1/auth/verify", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Log.w("OAUTH", "Got API key from server: " + response);
finish();
}
#Override
public void onFailure(Throwable e) {
Log.w("OAUTH", "Error getting API key");
Toast.makeText(getApplicationContext(), R.string.connection_error_message, Toast.LENGTH_LONG).show();
e.printStackTrace();
}
});
}
Would anyone know a solution to this problem?
Thank you very much,
Daniel
In Android Studio, you have to add your jar into the lib folder, add the dependency into the build.gradle file and call gradlew clean from console. The gradlew is in your project directory.
Check this thread for more details: Android Studio: Add jar as library?