Fragment Replace null pointer exception - android-fragments

I am trying to replace fragment with another inside a onItemClick of list view and i want to send a selected item name from list fragment to another fragment but its showing null pointer exception
#Override
public void onItemClick(AdapterView arg0, View view, int position,
long id)
{
try
{
Log.e("----- inside onItemClick -----", citySelected);
MapVisibleFragment newFragment = new MapVisibleFragment();
Bundle args = new Bundle();
args.putString("CITYNAME", citySelected);
newFragment.setArguments(args);
((BaseContainerFragment) getParentFragment()).replaceFragment(
newFragment, true);
} catch (Exception e)
{
e.printStackTrace();
}
}
but the same concept is working inside button click for the below one
try
{
ListFragmentFromDBRecords2 newFragment = new ListFragmentFromDBRecords2();
Bundle args = new Bundle();
args.putStringArrayList("names", allData);
newFragment.setArguments(args);
((BaseContainerFragment) getParentFragment()).replaceFragment(
newFragment, true);
Log.d("--->>>>", allData.toString());
}
catch (Exception e)
{
e.printStackTrace();
}

Based on your comment
((BaseContainerFragment) getParentFragment())
is null for you. Check why getParentFragment() method returns null.

Related

Read the database to MapProperty Javafx

I created MapProperty to read the information from the database as below.
The command runs fine with Map,ArrayList normal but error MapProperty.I want member to be ListProperty type so I can bind it to control
public MapProperty<String, ListProperty<String>> mapTaxonomy() {
MapProperty<String, ListProperty<String>> mapTaxonomy = new SimpleMapProperty<>();
try {
preparedStatement = connection.prepareStatement("");
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
String taxonomy = resultSet.getString("Taxonomy");
ListProperty<String> memberSelector = mapTaxonomy.get(taxonomy);
if (memberSelector == null) {
memberSelector = new SimpleListProperty<>();
mapTaxonomy.put(taxonomy, memberSelector);
}
memberSelector.add(resultSet.getString("Selector"));
}
} catch (SQLException ex) {
Logger.getLogger(ParserService.class.getName()).log(Level.SEVERE, null, ex);
}
return mapTaxonomy;
}
#Override
public void initialize(URL location, ResourceBundle resources) {
MapProperty<String, ListProperty<String>> mapTaxonomy = mapTaxonomy();
}
After I run the following error statement,please help me
Caused by: java.lang.UnsupportedOperationException
at java.util.AbstractMap.put(AbstractMap.java:209)
at javafx.beans.binding.MapExpression.put(MapExpression.java:262)
at touya.akira.storages.database.table.parser.ParserService.mapTaxonomy(ParserService.java:70)
at touya.akira.parser.styles.fixed.method.pagination.PaginationPresenter.initialize(PaginationPresenter.java:64)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
... 67 more
The default value of a SimpleMapProperty is a empty unmodifiable map. An exception is thrown when you try to modify it. Specify a modifiable ObservableMap as initial value to fix this issue.
MapProperty<String, ListProperty<String>> mapTaxonomy = new SimpleMapProperty<>(FXCollections.observableHashMap());

Get all registered listeners to an ObservableValue

How to get all listeners to an observable value? I could extend the class and override addListener and removeListener methods to store them in a set. But the set should already be stored somehow inside observable value. How could I get that set?
I find a way around it, you can't get direct access to the Listeners list but if you use a debugger(I use IntelliJ) you can see it if you look inside your ObservableProprty like this:(I hope this is clear enough)
another way:(You're a smart guy, you'll know how to fit into your case)
//SimpleFloatProperty we want to find its Listeners
FloatPropertyBase f=ampPS.currentProperty();
Object value;
ChangeListener[] list;
ChangeListener changeListener=null;
Field field = null;
try {
field = FloatPropertyBase.class.getDeclaredField("helper");
field.setAccessible(true);
value = field.get(f);
try {
field = value.getClass().getDeclaredField("listener");
field.setAccessible(true);
changeListener =(WeakChangeListener)field.get(value);
}catch (NoSuchFieldException e) {
e.printStackTrace();
}
try {
field = value.getClass().getDeclaredField("changeListeners");
field.setAccessible(true);
list =(ChangeListener[])field.get(value);
}catch (NoSuchFieldException e) {
e.printStackTrace();
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
the result:
(Notice the difference between 1 listener or more than 1)
I I'm adding Example for several types of values
public static ChangeListener[] getChangeListeners(ObservableValue observableValue){
Object value;
ChangeListener[] list=null;
ChangeListener changeListener=null;
Field field = null;
try {
if(observableValue instanceof SimpleFloatProperty ){
field = FloatPropertyBase.class.getDeclaredField("helper");
}
else if(observableValue instanceof SimpleBooleanProperty ){
field = BooleanPropertyBase.class.getDeclaredField("helper");
}
else if(observableValue instanceof SimpleIntegerProperty ){
field = IntegerPropertyBase.class.getDeclaredField("helper");
}
field.setAccessible(true);
value = field.get(observableValue);
try {
field = value.getClass().getDeclaredField("listener");
field.setAccessible(true);
changeListener =(ChangeListener)field.get(value);
}catch (NoSuchFieldException e) {
//e.printStackTrace();
}
try {
field = value.getClass().getDeclaredField("changeListeners");
field.setAccessible(true);
list =(ChangeListener[])field.get(value);
}catch (NoSuchFieldException e) {
//e.printStackTrace();
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if(list!=null){
return list;
}
else {
ChangeListener[] changeListeners = new ChangeListener[1];
changeListeners[0]=changeListener;
return changeListeners;
}
}
and I call it:
SimpleBooleanProperty booleanProperty = new SimpleBooleanProperty(true);
SimpleFloatProperty simpleFloatProperty = new SimpleFloatProperty(0);
SimpleIntegerProperty simpleIntegerProperty = new SimpleIntegerProperty(1);
booleanProperty.addListener(changeListener);
simpleFloatProperty.addListener(changeListener);
simpleIntegerProperty.addListener(changeListener);
simpleIntegerProperty.addListener(changeListener);
System.out.println(getChangeListeners(booleanProperty).length);
System.out.println(getChangeListeners(simpleFloatProperty).length);
System.out.println(getChangeListeners(simpleIntegerProperty).length);
the result:
so I do get warnings, but the job is done!
The documentation for ObservableValue.removeListener states:
If the given listener has not been previously registered (i.e. it was never added) then this method call is a no-op.
This leaves a few options if reflection is to be avoided.
First, call removeListener before adding the listener, such as:
final var property = someProperty();
final var listener = getListener();
property.removeListener( listener );
property.addListener( listener );
This technique is equivalent to using a Set, provided getListener() always returns the same object reference. (This may also work if different object references of the same class override equals to return true, but you'd have to double-check.)
The downside is having to keep a reference to the listener that was added, which could require a new class, but will at least require a new instance variable.
Second, keep a map of registered listeners, something to the effect of:
final HashMap<ObservableValue<?>, Object> map = new HashMap<>();
final var property = someProperty();
final var listener = getListener();
map.computeIfAbsent( property, p -> {
property.addListener( listener );
return property;
});
Although the question is looking for the list of listeners, I suspect the intent of the question is to avoid adding duplicate listeners, which is a common scenario.

Access fields of a TestNG test class from a TestListenerAdapter

Background
I have the following situation:
My test-classes implement org.testng.ITest
They all have a Helper containing info on the current test environment (e.g. device-under-test)
For example:
com.company.appundertest.Helper h;
public class TestClass implements org.testng.ITest {
private String testName;
//Helper is initialized externally in Factory + DataProvider
//and passed to Constructor.
public TestClass(com.company.appundertest.Helper hh) {
this.h = hh;
//constructor sets the test-name dynamically
//to distinguish multiple parallel test runs.
this.testName = "some dynamic test name";
}
#Override
public String getTestName() {
return this.testName;
}
#Test
public void failingTest() {
//test that fails...
}
}
These test-classes are executed in parallel using Factory and parallel data-provider.
Upon Test Failure, I need to access variables within the Helper instance of the failing test-class. These will be used to identify the environment at the point of failure (e.g. take screenshot on failing device).
This problem essentially boils down to:
How would I access fields within the TestNG test-class?
References
Access to private inherited fields via reflection in Java
Here's an example method. You can insert this in a Test Listener class (which extends TestListenerAdapter)
public class CustomTestNGListener extends TestListenerAdapter{
//accepts test class as parameter.
//use ITestResult#getInstance()
private void getCurrentTestHelper(Object testClass) {
Class<?> c = testClass.getClass();
try {
//get the field "h" declared in the test-class.
//getDeclaredField() works for protected members.
Field hField = c.getDeclaredField("h");
//get the name and class of the field h.
//(this is just for fun)
String name = hField.getName();
Object thisHelperInstance = hField.get(testClass);
System.out.print(name + ":" + thisHelperInstance.toString() + "\n");
//get fields inside this Helper as follows:
Field innerField = thisHelperInstance.getClass().getDeclaredField("someInnerField");
//get the value of the field corresponding to the above Helper instance.
System.out.println(innerField.get(thisHelperInstance).toString());
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Call this as follows:
#Override
public void onTestFailure(ITestResult tr) {
getCurrentTestHelper(tr.getInstance());
}
The #Vish 's solution is good, but you can avoid reflection with:
interface TestWithHelper {
Helper getHelper();
}
where your TestClass will implement it.
Then:
private void getCurrentTestHelper(Object testClass) {
if (testClass instanceof TestWithHelper) {
Helper helper = ((TestWithHelper) testClass).getHelper();
...
}
}

GLCanvas and GLJPanel produce different images

My SSCE is:
public static void main(final String[] args) throws IOException {
try {
SwingUtilities.invokeAndWait(new Runnable() {
#Override
public void run() {
int bitdepth = 10;
GLProfile.initSingleton();
GLProfile glProfile = GLProfile.getDefault();
GLCapabilities glCapabilities = new GLCapabilities( glProfile );
glCapabilities.setBlueBits(bitdepth);
glCapabilities.setGreenBits(bitdepth);
glCapabilities.setRedBits(bitdepth);
glCapabilities.setAlphaBits(2);
glCapabilities.setDoubleBuffered(true);
glCapabilities.setHardwareAccelerated(true);
glCapabilities.setNumSamples(4);
glCapabilities.setBackgroundOpaque(false);
glCapabilities.setSampleBuffers(true);
GraphicsConfiguration gc = getSomeGC();
JFrame jf = new JFrame(gc);
jf.setExtendedState(JFrame.MAXIMIZED_BOTH);
GLCanvas canvas = new GLCanvas(glCapabilities);
canvas.addGLEventListener(new GLEventListener() {
#Override
public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3,
int arg4) {
// TODO Auto-generated method stub
}
#Override
public void init(GLAutoDrawable arg0) {
// TODO Auto-generated method stub
}
#Override
public void dispose(GLAutoDrawable arg0) {
// TODO Auto-generated method stub
}
#Override
public void display(GLAutoDrawable drawable) {
System.out.println("Painting");
BufferedImage image = null;
try {
image = ImageIO.read(new File("img.tiff"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(image!=null){
GL2 gl2 = drawable.getGL().getGL2();
//gl2.glClear(GL.GL_COLOR_BUFFER_BIT);
int format = GL.GL_LUMINANCE;
int type = GL.GL_UNSIGNED_SHORT;
DataBufferUShort db = (DataBufferUShort) image.getRaster().getDataBuffer();
short[] shorts = db.getData(0);
Buffer buffer = ShortBuffer.wrap(shorts);
//gl2.glViewport(0, 0, image.getWidth(), image.getHeight());
gl2.glDrawPixels(image.getWidth(), image.getHeight(), format , type, buffer );
}
}
});
JPanel jp = new JPanel();
jp.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx=0;
gbc.gridy=0;
gbc.gridwidth=1;
gbc.gridheight=1;
gbc.weightx=1;
gbc.weighty=1;
gbc.anchor= GridBagConstraints.CENTER;
jp.add(canvas,gbc);
JScrollPane jsp = new JScrollPane();
jsp.getViewport().add(jp);
JLayeredPane jlp = new JLayeredPane();
jlp.setLayout(new GridBagLayout());
jlp.add(jsp, gbc);
//jsp.getViewport().add(dsc);
gbc = new GridBagConstraints();
gbc.gridx=0;
gbc.gridy=0;
gbc.gridwidth=1;
gbc.gridheight=1;
gbc.weightx=1;
gbc.weighty=1;
gbc.fill=GridBagConstraints.BOTH;
gbc.anchor= GridBagConstraints.CENTER;
jf.getContentPane().setLayout(new GridBagLayout());
jf.getContentPane().add(jlp,gbc);
jf.setVisible(true);
}
});
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I get two different displays for GLCanvas over GLJPanel. I trying to get 10 bit display on a monitor capable of 10bit grayscale.
The GLJPanel is in 8 bit while the GLCanvas throws an exception but is I believe displayed correctly at 10 bit.
Exception in thread "AWT-EventQueue-0" javax.media.opengl.GLException: Error making context 0x20000 current on Thread AWT-EventQueue-0, drawableWrite 0x42011b9a, drawableRead 0x42011b9a, werr: 0, WindowsWGLContext [Version 4.2 (Compat profile, arb, ES2 compat, ES3 compat, FBO, hardware) - 4.2.12327 Compatibility Profile Context FireGL 12.104.2.3000 [GL 4.2.0, vendor 12.104.2 (Compatibility Profile Context FireGL 12.104.2.3000)], options 0x1c03, this 0x263ce8f2, handle 0x20000, isShared false, jogamp.opengl.gl4.GL4bcImpl#633cca0,
quirks: [NoDoubleBufferedBitmap],
Drawable: WindowsOnscreenWGLDrawable[Realized true,
Factory jogamp.opengl.windows.wgl.WindowsWGLDrawableFactory#5dba26,
Handle 0x42011b9a,
Since this is a jogl bugreport please post the complete compilable SSCE with all includes into a bugreport at https://jogamp.org/bugzilla/
don't forget to attach the source code and the img.tiff
You are technically reporting two bugs thus you should file two bugs:
bug one:
We need to know more about your use-case and what kind of differences you see in the two images when using a GLCanvas and GLJPanel.
bug two:
We need a reproducer for the GLException: Error making context 0x20000 current on Thread
For more details read the JOGL Bugreports & Testing FAQ:
http://jogamp.org/wiki/index.php/Jogl_FAQ#Bugreports_.26_Testing

Riak Yokuzuna Schema upload , create index and search query always result in error 60,56,27

public class RiakSearch {
public static final String RIAK_SERVER = "10.11.172.17";
private static RiakCluster setUpCluster() throws UnknownHostException {
// This example will use only one node listening on localhost:10017
RiakNode node = new RiakNode.Builder()
.withRemoteAddress("10.11.172.17")
.withAuth("administrator", "password#123", null).build();
// This cluster object takes our one node as an argument
RiakCluster cluster = new RiakCluster.Builder(node).build();
// The cluster must be started to work, otherwise you will see errors
cluster.start();
return cluster;
}
public void uploadSchema() {
try {
RiakCluster cluster = setUpCluster();
RiakClient client = new RiakClient(cluster);
System.out.println("Client object successfully created");
File xml = new File("blog_post_schema.xml");
String xmlString = FileUtils.readFileToString(xml);
YokozunaSchema schema = new YokozunaSchema("blog_post_schema",
xmlString);
StoreSchema storeSchemaOp = new StoreSchema.Builder(schema).build();
client.execute(storeSchemaOp);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
RiakSearch obj = new RiakSearch();
obj.uploadSchema();
}
}
java.util.concurrent.ExecutionException: com.basho.riak.client.core.netty.RiakResponseException: Unknown message code: 56
at com.basho.riak.client.core.FutureOperation.get(FutureOperation.java:260)
at com.basho.riak.client.api.commands.CoreFutureAdapter.get(CoreFutureAdapter.java:52)
at com.basho.riak.client.api.RiakCommand.execute(RiakCommand.java:89)
at com.basho.riak.client.api.RiakClient.execute(RiakClient.java:293)
at com.search.RiakSearch.main(RiakSearch.java:64)
Caused by: com.basho.riak.client.core.netty.RiakResponseException: Unknown message code: 56
at com.basho.riak.client.core.netty.RiakResponseHandler.channelRead(RiakResponseHandler.java:52)
at io.netty.channel.ChannelHandlerInvokerUtil.invokeChannelReadNow(ChannelHandlerInvokerUtil.java:84)
at io.netty.channel.DefaultChannelHandlerInvoker.invokeChannelRead(DefaultChannelHandlerInvoker.java:153)
at io.netty.channel.PausableChannelEventExecutor.invokeChannelRead(PausableChannelEventExecutor.java:86)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:389)
at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:243)
at io.netty.handler.codec.ByteToMessageCodec.channelRead(ByteToMessageCodec.java:103)
at io.netty.channel.ChannelHandlerInvokerUtil.invokeChannelReadNow(ChannelHandlerInvokerUtil.java:84)
at io.netty.channel.DefaultChannelHandlerInvoker.invokeChannelRead(DefaultChannelHandlerInvoker.java:153)
at io.netty.channel.PausableChannelEventExecutor.invokeChannelRead(PausableChannelEventExecutor.java:86)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:389)
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:956)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:127)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:514)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:471)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:385)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:351)
at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116)
at io.netty.util.internal.chmv8.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1412)
at io.netty.util.internal.chmv8.ForkJoinTask.doExec(ForkJoinTask.java:280)
at io.netty.util.internal.chmv8.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:877)
at io.netty.util.internal.chmv8.ForkJoinPool.scan(ForkJoinPool.java:1706)
at io.netty.util.internal.chmv8.ForkJoinPool.runWorker(ForkJoinPool.java:1661)
at io.netty.util.internal.chmv8.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:126)
Make sure that Solr is actually started. By default, search is disabled in Riak 2.x. In order to enable it, change search property in /etc/riak/riak.conf to on. Then restart Riak.
I had the similar issue of
RiakError: 'Unknown message code: 56'
I solved it by changing the parameter of search in the 'riak.conf' file
Here is the file location, if you are using mac and installed via brew
/usr/local/Cellar/riak/2.2.2/libexec/etc/riak.conf
Here are the lines of code i changed from off to on
## To enable Search set this 'on'.
##
## Default: off
##
## Acceptable values:
## - on or off
search = on
I found the documentation explanation a little bit tricky to follow but more or less it is the reference to solve the issue.

Resources