This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am new to Java and android development. I am interested to build an app that can sync a folder from my android phone (Nexus5) to Amazon Web service (AWS). I am trying to build based on an open source project. But, I get the following error for this snippet and unable to locate my mistake. Your feedback will be highly useful at this point.
private void loadFileList(File path) {
this.currentPath = path;
List<String> r = new ArrayList<String>();
if (path.exists()) {
if (path.getParentFile() != null) r.add(PARENT_DIR);
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
if (!sel.canRead()) return false;
if (selectDirectoryOption) return sel.isDirectory();
else {
boolean endsWith = fileEndsWith != null ? filename.toLowerCase().endsWith(fileEndsWith) : true;
return endsWith || sel.isDirectory();
}
}
{
FileDialog a = FileDialog.this;
//a.super();
}
};
String[] fileList1 = path.list(filter);
for (String file : fileList1) { <-- Error in this line
r.add(file);
}
}
fileList = (String[]) r.toArray(new String[0]);
}
Error:
11-30 01:03:23.880 24102-24102/pavan.syncfile E/AndroidRuntime: FATAL EXCEPTION: main
11-30 01:03:23.880 24102-24102/pavan.syncfile E/AndroidRuntime: Process: pavan.syncfile, PID: 24102
11-30 01:03:23.880 24102-24102/pavan.syncfile E/AndroidRuntime: java.lang.NullPointerException: Attempt to get length of null array
11-30 01:03:23.880 24102-24102/pavan.syncfile E/AndroidRuntime: at pavan.syncfile.FileDialog.loadFileList(FileDialog.java:149)
11-30 01:03:23.880 24102-24102/pavan.syncfile E/AndroidRuntime: at pavan.syncfile.FileDialog.<init>(FileDialog.java:45)
11-30 01:03:23.880 24102-24102/pavan.syncfile E/AndroidRuntime: at pavan.syncfile.SendFile$1.onClick(SendFile.java:56)
11-30 01:03:23.880 24102-24102/pavan.syncfile E/AndroidRuntime: at android.view.View.performClick(View.java:5198)
11-30 01:03:23.880 24102-24102/pavan.syncfile E/AndroidRuntime: at android.view.View$PerformClick.run(View.java:21147)
11-30 01:03:23.880 24102-24102/pavan.syncfile E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:739)
11-30 01:03:23.880 24102-24102/pavan.syncfile E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
11-30 01:03:23.880 24102-24102/pavan.syncfile E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
11-30 01:03:23.880 24102-24102/pavan.syncfile E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
11-30 01:03:23.880 24102-24102/pavan.syncfile E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
11-30 01:03:23.880 24102-24102/pavan.syncfile E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
11-30 01:03:23.880 24102-24102/pavan.syncfile E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
The intent of this line
String[] fileList1 = path.list(filter); is to list the subfiles in the directory.
Here you are getting fileList1[] are null as there is not subfiles in the path folder matching the filter.
You can add a null check before this line
for (String file : fileList1) { <-- Error in this line
r.add(file);
}
i.e
if(fileList1!=null)
{
for (String file : fileList1) { <-- Error in this line
r.add(file);
}
}
Related
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
I get the following error:
java.lang.IllegalArgumentException: Volume external_primary not found
But this only happens on 1 emulator I am running. It works fine on other emulators or my physical android phone.
Here is the code I am trying to run that causes the issue:
private fun listRingtones(): LinkedHashMap<String, String> {
var manager = RingtoneManager(this)
manager.setType(RingtoneManager.TYPE_NOTIFICATION)
var cursor: Cursor = manager.cursor
var list = LinkedHashMap<String, String>()
while (cursor.moveToNext()) {
var title: String = cursor.getString(RingtoneManager.TITLE_COLUMN_INDEX)
var ringtoneURI: Uri = manager.getRingtoneUri(cursor.position)
// Place the title and uri into a hashMap
list.put(title, ringtoneURI.toString())
}
return list
}
Specifically the debugger craps out on this line:
var cursor: Cursor = manager.cursor
Anyone seen anything like this or what could be the cause?
Here is the full error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.package.mypackage, PID: 7370
java.lang.IllegalArgumentException: Volume external_primary not found
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:170)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:140)
at android.content.ContentProviderProxy.query(ContentProviderNative.java:423)
at android.content.ContentResolver.query(ContentResolver.java:944)
at android.content.ContentResolver.query(ContentResolver.java:880)
at android.content.ContentResolver.query(ContentResolver.java:836)
at android.app.Activity.managedQuery(Activity.java:3111)
at android.media.RingtoneManager.query(RingtoneManager.java:646)
at android.media.RingtoneManager.getMediaRingtones(RingtoneManager.java:579)
at android.media.RingtoneManager.getMediaRingtones(RingtoneManager.java:571)
at android.media.RingtoneManager.getCursor(RingtoneManager.java:437)
at com.package.mypackage.NewReminderActivity.listRingtones(NewReminderActivity.kt:899)
at com.package.mypackage.NewReminderActivity.access$listRingtones(NewReminderActivity.kt:61)
at com.package.mypackage.NewReminderActivity$showSoundMenuAlert$2.onClick(NewReminderActivity.kt:1120)
at android.view.View.performClick(View.java:7140)
at android.view.View.performClickInternal(View.java:7117)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27351)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
The exception occurs randomly and then its hard to get rid of. I am tired of this error and despite the fact that I have tried almost everything on stackoverflow from changing url to respective IP address, using real device, adding internet permissions as mentioned or checking wifi connection. Everything is all right except the error which keeps coming back. Yes I also added checking connection code as below :
try {
ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm.getActiveNetworkInfo().isConnectedOrConnecting()) {
URL url = new URL(urlx);
HttpURLConnection urlc = (HttpURLConnection) url
.openConnection();
urlc.setConnectTimeout(1000); // mTimeout is in seconds
urlc.connect();
if (urlc.getResponseCode() == 200) {
runOnUiThread(new Runnable() {
public void run() {
//Do something on UiThread
upsuccess = true;
}
});
} else {
runOnUiThread(new Runnable() {
public void run() {
//Do something on UiThread
upsuccess = false;
}
});
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and System.setProperty("http.proxyHost", "myurl.com");
System.setProperty("http.proxyPort", "8080");
but each of them separately as well as together did not fetch me any useful results. Can you suggest me what to do?
I am basically doing this : I am uploading a pdf file on my server and loading the google docs viewer url with that url. I however see the following exception several times. I also added retrying in case I find the exception but the exception randomly happens and is not easy to get out of if you encounter it.
Exception :
java.net.UnknownHostException: Unable to resolve host "myurl.com": No
address associated with hostname 07-20 01:12:11.554
24907-24997/securitymsg.listmydocs W/System.err: at
java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:95)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at java.net.InetAddress.getAllByName(InetAddress.java:752) 07-20
01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err: at
okhttp3.Dns$1.lookup(Dns.java:39) 07-20 01:12:11.554
24907-24997/securitymsg.listmydocs W/System.err: at
okhttp3.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:173)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
okhttp3.internal.http.RouteSelector.nextProxy(RouteSelector.java:139)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at okhttp3.internal.http.RouteSelector.next(RouteSelector.java:81)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
okhttp3.internal.http.StreamAllocation.findConnection(StreamAllocation.java:172)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
okhttp3.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:123)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
okhttp3.internal.http.StreamAllocation.newStream(StreamAllocation.java:93)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at okhttp3.internal.http.HttpEngine.connect(HttpEngine.java:296) 07-20
01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err: at
okhttp3.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at okhttp3.RealCall.getResponse(RealCall.java:243) 07-20 01:12:11.554
24907-24997/securitymsg.listmydocs W/System.err: at
okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:201)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:163)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at okhttp3.RealCall.execute(RealCall.java:57) 07-20 01:12:11.554
24907-24997/securitymsg.listmydocs W/System.err: at
securitymsg.listmydocs.CloudViewer$UploadFileAsync.doInBackground(CloudViewer.java:678)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
securitymsg.listmydocs.CloudViewer$UploadFileAsync.doInBackground(CloudViewer.java:650)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at android.os.AsyncTask$2.call(AsyncTask.java:305) 07-20 01:12:11.554
24907-24997/securitymsg.listmydocs W/System.err: at
java.util.concurrent.FutureTask.run(FutureTask.java:237) 07-20
01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err: at
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 07-20
01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err: at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
07-20 01:12:11.554 24907-24997/securitymsg.listmydocs W/System.err:
at java.lang.Thread.run(Thread.java:761) 07-20 01:12:13.016
24907-24907/securitymsg.listmydocs W/cr_BindingManager: Cannot call
determinedVisibility() - never saw a connection for the pid: 24907
07-20 01:12:13.677 24907-24907/securitymsg.listmydocs
W/cr_BindingManager: Cannot call determinedVisibility() - never saw a
connection for the pid: 24907 07-20 01:12:13.678
24907-24907/securitymsg.listmydocs W/cr_BindingManager: Cannot call
determinedVisibility() - never saw a connection for the pid: 24907
My Permissions in manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
My code to upload file :
*PHP :
<?php
$file_path = "images/";
$neran = $_GET['neran'];
$ext = pathinfo(basename( $_FILES['uploaded_file']['name']), PATHINFO_EXTENSION);
$file_path = "images/".$neran.".".$ext;
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path) ){
echo "success";
} else{
echo "fail";
}
?>
Android side (I use Retrofit) : The following code is in doinbackground block of AsyncTask
String file_path = f.getAbsolutePath();
OkHttpClient client = new OkHttpClient();
RequestBody file_body = RequestBody.create(MediaType.parse(content_type),f);
Log.e("msh", content_type);
RequestBody request_body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("type",content_type)
.addFormDataPart("uploaded_file",file_path.substring(file_path.lastIndexOf("/")+1), file_body)
.build();
Request request = new Request.Builder()
.url("http://reviewitapp.co/retrofit_example/save_file.php?neran="+neran)
.post(request_body)
.build();
response = client.newCall(request).execute();
} catch (UnknownHostException e) {
e.printStackTrace();
/*uploadFile(selectedFilePath);*/
upsuccess = false;
} catch (IOException e) {
e.printStackTrace();
upsuccess = false;
} catch (NullPointerException e) {
e.printStackTrace();
/*uploadFile(selectedFilePath);*/
upsuccess = false;
}
if(response!=null) {
if (response.isSuccessful()) {
upsuccess = true;
}
response.body().close();
}
I have uploaded file and when I try to get the shared link then it gives NullPointerException.
FileInputStream fis = new FileInputStream(mFile);
String path = mPath + mFile.getName();
DropboxAPI.Entry response = mApi.putFile(path, fis,
mFile.length(), null, new ProgressListener() {
#Override
public long progressInterval() {
// Update the progress bar every half-second or so
return 500;
}
#Override
public void onProgress(long bytes, long total) {
publishProgress(bytes);
}
});
Log.i("DbExampleLog", "The uploaded file's rev is: " + response.rev);
if (response != null) {
mErrorMsg=response.path;
Log.e("DbExampleLog", "*****"+response.path+" The uploaded file's rev is: " + response.rev);
DropboxAPI.DropboxLink shareLink = mApi.share(response.path);
Log.e("DbExampleLog", "*****"+shareLink+" The uploaded file's rev is: " + response.rev);
if(shareLink!=null) {
if(shareLink.url!=null) {
Log.e("Null error URL*****",""+shareLink.url);
Log.e("Null error URL*****",""+getShareURL(shareLink.url));
String shareAddress = getShareURL(shareLink.url).toString();
Log.e("DbExampleLog", "URL -" + shareAddress + "*****" + response.path + " The uploaded file's rev is: " + response.rev);
}
else
Log.e("Null error URL*****",""+shareLink.url);
}
else{
Log.e("Null error*****",""+shareLink);
}
return true;
}
It returns like -
12-05 12:09:09.207 7335-7502/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/DbExampleLog: *****/1480919937073.jpg The uploaded file's rev is: 2ef4a7ca38e
12-05 12:09:10.966 7335-7502/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/DbExampleLog: *****com.dropbox.client2.DropboxAPI$DropboxLink#d9d5da1 The uploaded file's rev is: 2ef4a7ca38e
12-05 12:09:10.966 7335-7502/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/Null error URL*****: https://db.tt/ru6e39XK0
12-05 12:09:12.457 7335-7502/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/Null error URL*****: null
12-05 12:09:13.520 7335-7502/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.trucker.gtd.satyaki.dropboxintegrationapiv1, PID: 7335
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:318)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
at com.trucker.gtd.satyaki.dropboxintegrationapiv1.UploadFile.doInBackground(UploadFile.java:147)
at com.trucker.gtd.satyaki.dropboxintegrationapiv1.UploadFile.doInBackground(UploadFile.java:63)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
12-05 12:09:13.645 1248-1248/? E/EGL_emulation: tid 1248: eglCreateSyncKHR(1641): error 0x3004 (EGL_BAD_ATTRIBUTE)
12-05 12:09:13.796 2071-2205/com.android.launcher3 E/EGL_emulation: tid 2205: eglSurfaceAttrib(1146): error 0x3009 (EGL_BAD_MATCH)
12-05 12:09:14.006 1530-1640/system_process E/EGL_emulation: tid 1640: eglSurfaceAttrib(1146): error 0x3009 (EGL_BAD_MATCH)
12-05 12:09:14.304 7335-7335/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/WindowManager: android.view.WindowLeaked: Activity com.trucker.gtd.satyaki.dropboxintegrationapiv1.Main has leaked window DecorView#3bf9cac[] that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:417)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:331)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at android.app.Dialog.show(Dialog.java:316)
at android.app.AlertDialog$Builder.show(AlertDialog.java:1112)
at com.dropbox.client2.android.AuthActivity.checkAppBeforeAuth(AuthActivity.java:284)
at com.dropbox.client2.android.AndroidAuthSession.startAuthentication(AndroidAuthSession.java:213)
at com.trucker.gtd.satyaki.dropboxintegrationapiv1.Main.onActivityResult(Main.java:132)
at android.app.Activity.dispatchActivityResult(Activity.java:6915)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4049)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516)
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)
12-05 12:09:14.310 7335-7335/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/WindowManager: android.view.WindowLeaked: Activity com.trucker.gtd.satyaki.dropboxintegrationapiv1.Main has leaked window DecorView#e8ad10a[] that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:417)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:331)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at android.app.Dialog.show(Dialog.java:316)
at com.trucker.gtd.satyaki.dropboxintegrationapiv1.UploadFile.<init>(UploadFile.java:98)
at com.trucker.gtd.satyaki.dropboxintegrationapiv1.Main.setLoggedIn(Main.java:144)
at com.trucker.gtd.satyaki.dropboxintegrationapiv1.Main.onResume(Main.java:168)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1269)
at android.app.Activity.performResume(Activity.java:6766)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3377)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3440)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1510)
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)
Mainly in this particular line-
getShareURL(shareLink.url)
Please suggest me why this error occur, but yesterday using this code it worked.
UPDATE CODE ASKED BY Greg
String getShareURL(String strURL) {
URLConnection conn = null;
String redirectedUrl = null;
try {
URL inputURL = new URL(strURL);
conn = inputURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
System.out.println("Redirected URL: " + conn.getURL());
Log.e("Get Redirected URL",""+conn.getURL());
redirectedUrl = conn.getURL().toString();
is.close();
} catch (MalformedURLException e) {
Log.e("TAG", "Please input a valid URL");
} catch (IOException ioe) {
Log.e("TAG", "Can not connect to the URL");
}
return redirectedUrl;
}
This code taken from Share file in Dropbox
Im new to android developement and I am not sure what I missing to allow the code to work. Trying to create log in application. Could there be a problem with the way I am receiving the data or sending the data using dataoutputstream? of is there a better way that is not deprecated and complicated. Looking for the most minimalistic understandable solution.
Do in background code
#Override
protected Boolean doInBackground(String... params) {
DataOutputStream printout;
HttpURLConnection urlConn;
BufferedReader reader;
URL url;
String json;
JSONObject jObj;
//send POST login details to server
try {
url = new URL(SERVER_ADDRESS + "login.php");
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setRequestMethod("POST");
urlConn.setDoOutput(true);
urlConn.setRequestProperty("Accept-Charset", "UTF-8");
urlConn.setReadTimeout(10000);
urlConn.setConnectTimeout(15000);
HashMap<String, String> map = new HashMap<String, String>();
map.put("username", params[0]);
map.put("password", params[1]);
StringBuilder sb = new StringBuilder();
for(HashMap.Entry<String, String> e : map.entrySet()){
if(sb.length() > 0){
sb.append("&");
}
sb.append(URLEncoder.encode(e.getKey(), "UTF-8")).append("=").append(URLEncoder.encode(e.getValue(), "UTF-8"));
}
String loginDetails = sb.toString();
printout = new DataOutputStream(urlConn.getOutputStream());
printout.writeBytes(loginDetails);
printout.flush();
printout.close();
reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
StringBuilder sb2 = new StringBuilder();
String result = null;
while((result=reader.readLine())!=null) {
sb2.append(result + '\n');
Log.d("Results", sb2.toString());
};
json = result.toString();
jObj = new JSONObject(json);
JSONLogin = jObj.getBoolean(TAG_LOGINSTATUS);
Log.d("LoginStatus!!!!", JSONLogin.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
Log.d("JsonConvertion", "FAILED TO CONVERT JSON");
}
return JSONLogin;
}
Stack error
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime: Process: com.httpkhronolog.khronolog, PID: 2459
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime: java.lang.RuntimeException: An error occurred while executing doInBackground()
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime: at android.os.AsyncTask$3.done(AsyncTask.java:309)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime: at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime: at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:242)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime: at java.lang.Thread.run(Thread.java:818)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime: at com.httpkhronolog.khronolog.Login_Activity$checkUserDetails.doInBackground(Login_Activity.java:137)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime: at com.httpkhronolog.khronolog.Login_Activity$checkUserDetails.doInBackground(Login_Activity.java:79)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime: at android.os.AsyncTask$2.call(AsyncTask.java:295)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime: at java.lang.Thread.run(Thread.java:818)
login.php
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "someusername", "Password");
// Selecting Database
$db = mysql_select_db("khronolo_systemdb", $connection);
$username = $_POST["username"];
$password = $_POST["password"];
$query = "SELECT * FROM user_table WHERE password='$password' AND email='$username';";
$result = mysql_query($query, $connection) or die (mysql_error($connection));
$rows = mysql_num_rows($result);
if ($rows == 1) {
$returnValue[] = array("loginStatus"=> "true");
echo json_encode($returnValue);
}
else {
$returnValue[] = array("loginStatus"=> "false");
echo json_encode($returnValue);
}
mysql_close($connection);
}
?>
Use Volley a Network Library from Google. Follow this tutorial for the same. To know more about Volley refer this link
There are also other Networking libraries like okHttp.
And as of now your code is considered :
replace json = result.toString(); with json = sb2.toString(); at line 137
Instead of
json = result.toString();
You should do
json = sb2.toString();
Explanation
Your while loop when exits, the result will be null, so doing result.toString() would lead to nullpointerexception.
Any other library
You can use GSON library to help you get/set the response values without any hurdle.
GSON error