save audio file using MediaStore API - java

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

Related

Load activity from a string variable

I am doing an app where I have questions displayed and I have stored the next question number in a database so the user can resume whenever they wanted.
My problem here is I fetch the next question number from the DB and append the number to a String variable so then goNextQuestion is equal to Question# (# being the number from the DB).
I then want to pass that variable, for example it is equal to Question2, to the new Intent function to load the activity associated with that question.
Here is the code from Home.class:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
final String goQuestion = "Question" + lastQuestion";
startActivity(new Intent(Home.this, Class.forName(goQuestion)));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
The full Home.class can be viewed here: https://pastebin.com/6mbrBpQm
My expected result would be it wil load the same way as it would if I just passed Question2.class into the Intent. However, there is an error and the catch statement is always executed with the following error:
W/System.err: java.lang.ClassNotFoundException: Question2.class
at java.lang.Class.classForName(Native Method)
at java.lang.Class.forName(Class.java:400)
at java.lang.Class.forName(Class.java:326)
at uk.co.jrtevents.k_quiz.Home$1.onClick(Home.java:45)
W/System.err: at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
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:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.ClassNotFoundException: Didn't find class "Question2.class" on path: DexPathList[[zip file "/data/app/uk.co.jrtevents.k_quiz-1/base.apk"],nativeLibraryDirectories=[/data/app/uk.co.jrtevents.k_quiz-1/lib/x86, /system/lib, /vendor/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
... 13 more
What would be the best way to resolve this?
Link to Question2.class: https://pastebin.com/5sdsc1Ec
you can try something like below.
if you use the Simple class name like Step8CompletedActivity then it will give the error.
var clazz =
Class.forName(Step8CompletedActivity::class.java.simpleName!!).kotlin as KClass<Activity>
below error will come
java.lang.ExceptionInInitializerError
at com.google.samples.motionlayoutcodelab.MainActivityKt.access$getData$p(MainActivity.kt:1)
at com.google.samples.motionlayoutcodelab.MainActivity.onCreate(MainActivity.kt:114)
at android.app.Activity.performCreate(Activity.java:6662)
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:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.ClassNotFoundException: Step8CompletedActivity
at java.lang.Class.classForName(Native Method)
at java.lang.Class.forName(Class.java:400)
at java.lang.Class.forName(Class.java:326)
at com.google.samples.motionlayoutcodelab.MainActivityKt.<clinit>(MainActivity.kt:39)
at com.google.samples.motionlayoutcodelab.MainActivityKt.access$getData$p(MainActivity.kt:1) 
instead of using the simple name only use Canonical name or Full name with path
var clazz =
Class.forName(Step8CompletedActivity::class.java.canonicalName!!).kotlin as KClass<Activity>
or using below will produce the same results.
var clazz =
Class.forName("com.google.samples.motionlayoutcodelab.Step8CompletedActivity").kotlin as KClass<Activity>
You don't have put .class
final String goQuestion = "Question" + lastQuestion;
Try this
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
final String goQuestion = "Question" + lastQuestion;
startActivity(new Intent(Home.this, Class.forName(goQuestion)));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});

Getting list of device ringtones, weird error on 1 emulator?

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)

java.lang.IllegalArgumentException: Parameter specified as non-null is null

getting java.lang.IllegalArgumentException: Parameter specified as non-null is null, with Camera Intent in Kotlin, but in JAVA this code is working.
I am very confusing why It is happening.
after Capture Image I am getting this error and crashng app.
try {
val imageFile = createImageFile()
val callCameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if(callCameraIntent.resolveActivity(packageManager) != null) {
val authorities = packageName + ".provider"
val imageUri = FileProvider.getUriForFile(this, authorities, imageFile)
callCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
startActivityForResult(callCameraIntent, CAMERA_REQUEST_CODE)
}
} catch (e: IOException) {
Toast.makeText(this, "Could not create file!", Toast.LENGTH_SHORT).show()
}
fun createImageFile(): File {
val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
val imageFileName: String = "JPEG_" + timeStamp + "_"
val storageDir: File = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
if(!storageDir.exists()) storageDir.mkdirs()
val imageFile = File.createTempFile(imageFileName, ".jpg", storageDir)
imageFilePath = imageFile.absolutePath
return imageFile
}
09-30 13:32:19.145 6918-6918/app.smallbites.com.smallbites E/AndroidRuntime: FATAL EXCEPTION: main
Process: app.smallbites.com.smallbites, PID: 6918
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1001, result=-1, data=null} to activity {app.smallbites.com.smallbites/app.smallbites.com.smallbites.ui.onboarding.AddKidActivity}: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter data
at android.app.ActivityThread.deliverResults(ActivityThread.java:4268)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4312)
at android.app.ActivityThread.-wrap19(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1644)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6501)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter data
at app.smallbites.com.smallbites.ui.onboarding.AddKidActivity.onActivityResult(Unknown Source:37)
The problem is in your data you wanna transmit to. You put Null object when it should be NonNull
Check the next things:
Permission for camera
Permission for storage (read/write)
Check the place where do you want to store your file, usually, people are fighting with issues internal/external storage.
Also, please, check if your question exists. I guess I found a similar problem.
android camera : Failure delivering result ResultInfo{who=null, request=0, result=-1, data=null} to activity

I can't get resources using java class .error: Attempt to invoke virtual method

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;

java.lang.NullPointerException: Attempt to get length of null array [duplicate]

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);
}
}

Categories

Resources