NullPointerException getDefaultSharedPreferences() - java

I keep getting NullPointerException on this line:
SharedPreferences myPreference = PreferenceManager.getDefaultSharedPreferences(this);
I ran some things through and I believe that I have the wrong context as it is in a subpackage of the main package so I don't think it can reference the XML preference files. I have used this in class's that are in the main package with no trouble but for some reason this causes an exception.
Full code:
package schoolBook.Icestone.Expandable;
import schoolBook.Icestone.Days;
import schoolBook.Icestone.Main;
import schoolBook.Icestone.SetPreference;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class Lesson1 extends Lessons {
public Lesson1(String name) {
super(name);
// setGroup(" " + Days.getLessonarray(0) + " ");
String key = "W" + Main.getWeek() + "_" + SetPreference.xmlday + "_L"
+ SetPreference.xmllesson + "_Lesson";
System.out.println(key);
try {
SharedPreferences myPreference = PreferenceManager
.getDefaultSharedPreferences(this);
String group = myPreference.getString(key, "def");
setGroup(" " + group + " ");
} catch (NullPointerException ex) {
ex.printStackTrace();
setGroup(" " + Days.getLessonarray(0) + " ");
}
}
}
Lessons class extends Activity so think that may be the source of my problem but im not sure.
File structure:
Icestone
Main.class and some other classes that use shared preference and it works fine
Lessons package (Lesson1 & Lesson are in this package)
XML folder with the preferences in it
if anyone could help shed some light on this problem it would be much appreciated

You can't do this inside the constructor.
If it extends Activity Class it should't has a constructor, you need to handle that inside the oncreate method.

Related

How to manipulate files by ffmpeg in Android 31: permission denied

I am trying to use FFmpeg in my android app. So I want to test it if it works before moving on. I use an external library : github link
The code looks like this :
package net.omidn.aslanmediaconverter;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.arthenica.ffmpegkit.ExecuteCallback;
import com.arthenica.ffmpegkit.FFmpegKit;
import com.arthenica.ffmpegkit.FFmpegSession;
import com.arthenica.ffmpegkit.Session;
import net.bramp.ffmpeg.job.FFmpegJob;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
FFmpegJob myjob;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.text_view);
FFmpegJob job = null;
File inFile = new File("/storage/emulated/0/video_2021-05-29_17-50-20.mp4");
String inputName = Uri.fromFile(inFile).toString();
Log.d(TAG, inputName);
Log.d(TAG,"file exists : " + String.valueOf(inFile.exists()));
Log.d(TAG,"file canRead : " + String.valueOf(inFile.canRead()));
FFmpegSession fFmpegSession = FFmpegKit.executeAsync("-i file:///storage/emulated/0/video_2021-05-29_17-50-20.mp4 -c:v mpeg4 file:///storage/emulated/0/out.mp4",
new ExecuteCallback() {
#Override
public void apply(Session session) {
}
});
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
textView.setText("" + fFmpegSession.getState().name() + " " + fFmpegSession.getOutput());
}
}
As you can see I give the files with file:/// protocol. If I don't use that the resault is the same. The three lines of Log.d(...) will print :
2021-06-03 00:58:08.869 8376-8376/net.omidn.aslanmediaconverter D/MainActivity: file:///storage/emulated/0/video_2021-05-29_17-50-20.mp4
2021-06-03 00:58:08.869 8376-8376/net.omidn.aslanmediaconverter D/MainActivity: file exists : true
2021-06-03 00:58:08.869 8376-8376/net.omidn.aslanmediaconverter D/MainActivity: file canRead : false
The video file has read access on the storage :
I found a way to do this from the libraries wiki page.
I will quote it here:
If you want to use a file selected using Storage Access Framework (SAF) with FFmpegKit, you can use the following methods to convert a Uri to a file path defined with FFmpegKit's saf: protocol. That path can be safely used as input or output in FFmpegKit and FFprobeKit commands.
Input
Uri uri = intent.getData();
String inputPath = FFmpegKitConfig.getSafParameterForRead(requireContext(), uri);
FFmpegKit.execute("-i " + inputPath + " ... output.mp4");
Output
Uri uri = intent.getData();
String outputPath = FFmpegKitConfig.getSafParameterForWrite(requireContext(), uri);
FFmpegKit.execute("-i input.mp4 ... " + outputPath);
The wiki page on GitHub

Java "method does not override or implement a method from a supertype" error

When i try to compile the following code using javac or gradlew
I got the error method does not override or implement a method from a supertype #Override
The error happened to the two #Override functions
How to solve that ?
code.java:
package com.android.commands.locksettings;
import android.os.ResultReceiver;
import android.os.ServiceManager;
import android.os.ShellCallback;
import com.android.internal.os.BaseCommand;
import com.android.internal.widget.ILockSettings;
import java.io.FileDescriptor;
import java.io.PrintStream;
public final class LockSettingsCmd extends BaseCommand {
private static final String USAGE =
"usage: locksettings set-pattern [--old OLD_CREDENTIAL] NEW_PATTERN\n" +
" locksettings set-pin [--old OLD_CREDENTIAL] NEW_PIN\n" +
" locksettings set-password [--old OLD_CREDENTIAL] NEW_PASSWORD\n" +
" locksettings clear [--old OLD_CREDENTIAL]\n" +
"\n" +
"locksettings set-pattern: sets a pattern\n" +
" A pattern is specified by a non-separated list of numbers that index the cell\n" +
" on the pattern in a 1-based manner in left to right and top to bottom order,\n" +
" i.e. the top-left cell is indexed with 1, whereas the bottom-right cell\n" +
" is indexed with 9. Example: 1234\n" +
"\n" +
"locksettings set-pin: sets a PIN\n" +
"\n" +
"locksettings set-password: sets a password\n" +
"\n" +
"locksettings clear: clears the unlock credential\n";
public static void main(String[] args) {
(new LockSettingsCmd()).run(args);
}
#Override
public void onShowUsage(PrintStream out) {
out.println(USAGE);
}
#Override
public void onRun() throws Exception {
ILockSettings lockSettings = ILockSettings.Stub.asInterface(ServiceManager.getService("lock_settings"));
lockSettings.asBinder().shellCommand(FileDescriptor.in, FileDescriptor.out,
FileDescriptor.err, getRawArgs(), new ShellCallback(), new ResultReceiver(null) {});
}
}
Solved by restoring original BaseCommand file, Thanks to #deHaar

Why Android class is equal but values in class is not equal?

package com.custom.wangzhi.myapp;
import android.util.Log;
public class TestUtil {
public void print(Class clazz, int t) {
try {
Log.i("print 1 ", "result " + R.layout.class.equals(clazz)
+ " " + R.layout.class.getClassLoader().equals(clazz.getClassLoader())
);
Log.i("print 2 ", R.layout.act1 + " " + clazz.getDeclaredField("act1").get(null)+" "+t);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.custom.wangzhi.myapp;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainActivity1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.latzc1);
Log.i("MainActivity1", "wangzhi app " + R.layout.act1);
new TestUtil().print(R.layout.class, R.layout.act1);
}
Log:
11-26 10:07:23.097 7999-7999/com.custom.dynamic.layoutcastdemo I/MainActivity1: wangzhi app 2130968577
11-26 10:07:23.097 7999-7999/com.custom.dynamic.layoutcastdemo I/print1 : result true true
11-26 10:07:23.097 7999-7999/com.custom.dynamic.layoutcastdemo I/print2 : 2130968576 2130968577 2130968577
MainActivity1 is a library module
if i run by the default in android studio is ok ,but when i use layoutcast (i do some change in this ) run,then print log in above
what layoutcast do:
1.it will find the code which is changed(compare the "projectdir/build/outputs/**.apk" 's time )
2.use aapt package all resource to generate a res.zip and R.java 3.use javac,dex all changed java file to generate a dex 4.then translate the res.zip and dex to android phone, 5. use DexClassloader load the dex and generate a new Resource which add res.zip to replace the system Resource .6.finally ,reboot the application.
my english is poor ,and first ask in stackoverflow,so if anyone don't know my mean ,please contact me . thanks very much

call the desired methods from the jar file

below is my java file, and i'm exporting the same an separate jar file ,name of the jar is "Softassert"
package com.annuity_payer;
import java.util.Arrays;
import java.util.Map;
import org.testng.Assert;
import org.testng.Reporter;
import com.thoughtworks.selenium.SeleneseTestBase;
public class Softassert extends SeleneseTestBase {
private StringBuffer verificationErrors;
private StringBuffer verificationSuccess;
public Softassert() {
verificationErrors = new StringBuffer();
verificationSuccess = new StringBuffer();
}
public void verifyEquals(String actual, String expected, String msg) {
try {
Assert.assertEquals(actual, expected, msg);
verificationSuccess.append(msg + ":" + " " + "Actual Result:" + " "
+ actual + " " + "Expected Result:" + " " + expected
+ " - Condition PASSED" + "\n");
} catch (AssertionError e) {
verificationErrors.append(e + "-Condition FAILED" + "\n");
}
}
}
so then i'm creating an new project and the jar file is mapped with build path to retrieve an method from the jar file
below are the code
import com.annuity_payer.Softassert.*;
public class testJar {
Softassert prabu = new Softassert();
prabu.verifyEquals("test","test","verification");
from that above i'm creating an object name of "prabu", then try to call desire method (i.e verifyEquals method)
when i try the same its shown an error "syntax error on tokens" Please clarify / help how to call the method from my jar file
You don't need the star in the import if you only want to import "Softassert", use...
import com.annuity_payer.Softassert;
If you want all classes in the annuity_payer package, you can use
import com.annuity_payer.*;
You might be getting confused with "import static" statements

Using external libraries when developing Android application

I want to implement an application that uses image recognition system IQEngines. I'm using eclipse for that. I'm trying test codes IQEngines provide but the result I'm getting is that "File apple.jpg does't exist"
I'm not sure where the problem lies. It seems like I imported all relevant jar files so the code should work. In eclipse I changed Main method into onCreate so that the activity can run
Does anyone have a clue?? Has anyone ever used IQEngines?
There's javaiqe.java that javaiqe_test.java is using but it's very long so I don't want to attach
package com.Camera;
import java.io.File;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import com.iqengines.javaiqe.javaiqe;
import com.iqengines.javaiqe.javaiqe.IQEQuery;
/**
* IQEngines Java API
*
* test file
*
* #author
*/
public class javaiqe_test extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.resultImg);
final String KEY = "64bc6a7fd77643899d3af8b305924165";
final String SECRET = "c27e162ea7c24c619f850014124598";
/*
* An API object is initialized using the API key and secret
*/
iqe = new javaiqe(KEY, SECRET);
uploadObject();
/*
* You can quickly query an image and retrieve results by doing:
*/
File test_file = new File("apple.jpg");
// Query
IQEQuery query = iqe.query(test_file);
System.out.println("query.result : " + query.getResult());
System.out.println("query.qid : " + query.getQID());
tv.setText(query.getResult());
// Update
/* String update = iqe.update();
System.out.println("Update : " + update);*/
// Result
String result = iqe.result(query.getQID(), true);
System.out.println("Result : " + result);
// Upload
//uploadObject();
}
/**
* Sample code for uploading an object
*/
public static void uploadObject() {
// Your object images
ArrayList<File> images = new ArrayList();
images.add(new File("res/drawable/apple.jpg"));
// Object infos
String name = "Computational Geometry, Algorithms and Applications, Third Edition";
// Optional infos
String custom_id = "book0001";
String meta = "{\n\"isbn\": \"9783540779735\"\n}";
boolean json = false;
String collection = "books";
// Upload
//System.out.println("Upload : " + iqe.upload(images, name, custom_id, meta, json, collection));
System.out.println("Upload : " + iqe.upload(images, name));
}
private static javaiqe iqe = null;
}
If you're sure you've imported everything you need, then it could be useful, if you clean your eclipse project, and rebuild it again. Other reason might be - that you've forgotten to 'redeploy' your application.
This might be helpful too.
Good luck! Probably you've missed some minor detail - I've been using external jars without any problems in Android projects.

Categories

Resources