Plotting Image Histogram Using Androidplot - image

I m a beginner programmer, I am developing an android application which process an image and generate its histogram. I am using AndroidPlot to draw different color channels of an image in the histogram, but I'm having some errors and exceptions.
This is my code :
public class ImgHistogram extends Activity {
ImageView ImageView;
LinearLayout ll;
ImageView imgView;
private Bitmap source ;
private XYPlot xyPlot;
public XYSeries rSerie;
int[] intensities={
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,
101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,
201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255
} ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.histo);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
imgView = (ImageView) findViewById(R.id.img);
Bundle bundle = this.getIntent().getExtras();
source=(Bitmap) bundle.getParcelable("img");
imgView.setImageBitmap(source);
// initialize our XYPlot reference:
xyPlot = (XYPlot) findViewById(R.id.xyplot);
Bitmap image = Bitmap.createBitmap(source.getWidth(),source.getHeight(), Bitmap.Config.ARGB_8888);
ArrayList<Integer> rVals = new ArrayList<Integer>();
for (int x = 0; x < image.getWidth(); x++) {
for (int y = 0; y < image.getHeight(); y++) {
int color = image.getPixel(x, y);
rVals.add((color >> 16) & 0xff); //red channel
}}
rSerie = new SimpleXYSeries(
rVals, SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "red channel");
// Create a formatter to format Line and Point of income series
LineAndPointFormatter format = new LineAndPointFormatter(
Color.rgb(0, 0, 255), // line color
Color.rgb(200, 200, 200), // point color
Color.rgb(10, 20, 20), // fill color (none)
null );
// add series to the xyplot:
xyPlot.addSeries(rSerie, format);
// Formatting the Domain Values ( X-Axis )
xyPlot.setDomainValueFormat(new Format() {
private static final long serialVersionUID = 1L;
#Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
return new StringBuffer( intensities[ ( (Number)obj).intValue() ] );
}
#Override
public Object parseObject(String source, ParsePosition pos) {
return null;
}
});
xyPlot.setDomainLabel("");
xyPlot.setRangeLabel("");
// Increment X-Axis by 1 value
xyPlot.setDomainStep(XYStepMode.INCREMENT_BY_VAL, 1);
xyPlot.getGraphWidget().setRangeLabelWidth(50);
// Reduce the number of range labels
xyPlot.setTicksPerRangeLabel(2);
// Reduce the number of domain labels
xyPlot.setTicksPerDomainLabel(2);
// Remove all the developer guides from the chart
// xyPlot.disableAllMarkup();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
and this is the stack trace:
05-23 23:52:21.731: E/AndroidRuntime(30404): FATAL EXCEPTION: main
05-23 23:52:21.731: E/AndroidRuntime(30404): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dreamaker.magipixel/com.dreamaker.magipixel.processing.ImgHistogram}: java.lang.NullPointerException
05-23 23:52:21.731: E/AndroidRuntime(30404): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
05-23 23:52:21.731: E/AndroidRuntime(30404): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
05-23 23:52:21.731: E/AndroidRuntime(30404): at android.app.ActivityThread.access$700(ActivityThread.java:159)
05-23 23:52:21.731: E/AndroidRuntime(30404): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
05-23 23:52:21.731: E/AndroidRuntime(30404): at android.os.Handler.dispatchMessage(Handler.java:99)
05-23 23:52:21.731: E/AndroidRuntime(30404): at android.os.Looper.loop(Looper.java:137)
05-23 23:52:21.731: E/AndroidRuntime(30404): at android.app.ActivityThread.main(ActivityThread.java:5419)
05-23 23:52:21.731: E/AndroidRuntime(30404): at java.lang.reflect.Method.invokeNative(Native Method)
05-23 23:52:21.731: E/AndroidRuntime(30404): at java.lang.reflect.Method.invoke(Method.java:525)
05-23 23:52:21.731: E/AndroidRuntime(30404): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
05-23 23:52:21.731: E/AndroidRuntime(30404): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
05-23 23:52:21.731: E/AndroidRuntime(30404): at dalvik.system.NativeStart.main(Native Method)
05-23 23:52:21.731: E/AndroidRuntime(30404): Caused by: java.lang.NullPointerException
05-23 23:52:21.731: E/AndroidRuntime(30404): at com.dreamaker.magipixel.processing.ImgHistogram.onCreate(ImgHistogram.java:110)
05-23 23:52:21.731: E/AndroidRuntime(30404): at android.app.Activity.performCreate(Activity.java:5372)
05-23 23:52:21.731: E/AndroidRuntime(30404): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
05-23 23:52:21.731: E/AndroidRuntime(30404): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
05-23 23:52:21.731: E/AndroidRuntime(30404): ... 11 more
I hope that someone could help me!

Given the fact that in the line in question (ImgHistogram.java:110) you have only 1 object which could possibly cause the exception - xyPlot:
xyPlot.addSeries(rSerie, format);
This suggests that findViewByID returns null =< xyPlot is null. There is a question about this: findViewByID returns null the accepted answer should solve your problem:
Wait until onFinishInflate()

Related

Why is mstor throwing a NotSerializableException on inbox.close()

I'm using the basic mstor logic with version 1.0.0 of of the maven mstor library, but it's throwing an Exception on the inbox.close() method. Note: I am not doing any writing to the disk so this Exception is odd. I made, as an attempt, my class which calls this code to "implement Serializable", but that did not help.
This code is running from a SpringBoot REST Service.
If I don't do an inbox.close(), then on Windows the mbox file is still open (not released by this library) after the method below completes.
Here's the basic code:
Properties properties = new Properties();
properties.setProperty("mail.store.protocol", "mstor");
properties.setProperty("mstor.mbox.metadataStrategy", "none");
properties.setProperty("mstor.mbox.cacheBuffers", "disabled");
properties.setProperty("mstor.mbox.bufferStrategy", "mapped");
properties.setProperty("mstor.metadata", "disabled");
properties.setProperty("mstor.mozillaCompatibility", "enabled");
Session session = Session.getInstance(properties);
try {
store = session.getStore(new URLName("mstor:" + pathToMboxFile));
store.connect();
inbox = (MStorFolder) store.getDefaultFolder();
inbox.open(Folder.READ_ONLY);
Message[] messages = inbox.getMessages();
int bodyPartCount = 0;
// ***********************
// process all mbox data.
// *************************
for (int pos = 0; pos < messages.length; pos++)
{
// processing.
}
catch (NoSuchProviderException e)
{
log.debug("MboxController NoSuchProviderException Exception: " + e.getMessage());
}
catch (javax.mail.MessagingException e)
{
errors.append(e);
log.debug("MboxController MessagingException Exception: " + e.getMessage());
}
finally
{
// close the mbox store
try
{
inbox.close(false);
store.close();
}
catch (MessagingException e)
{
log.debug("MboxController Closing Store Exception: " + e.getMessage());
}
}
Now, although the code does work and returns the mbox text and closes the file, when the inbox.close(false) runs, I get this error stack (or something close to it) each time in the Tomcat log:
2019-03-31 08:06:09 - Disk Write of 191 failed:
"java.io.NotSerializableException: net.fortuna.mstor.data.MessageInputStream
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:441)
at net.sf.ehcache.Element.writeObject(Element.java:791)
at sun.reflect.GeneratedMethodAccessor88.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1140)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at net.sf.ehcache.util.MemoryEfficientByteArrayOutputStream.serialize(MemoryEfficientByteArrayOutputStream.java:97)
at net.sf.ehcache.store.disk.DiskStorageFactory.serializeElement(DiskStorageFactory.java:413)
at net.sf.ehcache.store.disk.DiskStorageFactory.write(DiskStorageFactory.java:392)
at net.sf.ehcache.store.disk.DiskStorageFactory$DiskWriteTask.call(DiskStorageFactory.java:493)
at net.sf.ehcache.store.disk.DiskStorageFactory$PersistentDiskWriteTask.call(DiskStorageFactory.java:1151)
at net.sf.ehcache.store.disk.DiskStorageFactory$PersistentDiskWriteTask.call(DiskStorageFactory.java:1135)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)

JavaFX Exception in Application start method file upload

High I've been trying for two days to create a link to a card folder, I'm currently trying to gain add a random card to the interface but I keep on getting an exception I don't understand how my class path is wrong I tried everything any help would be hugely appreciated. I'm at a bit of dead end and I can't find anything that will help with the issue online
my code is as follows
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
//Imports for components in this application.
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
//Imports for images.
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class HighLowJavafx extends Application {
// Declare labels
Label lblFirst, lblSecond, lblNext;
// Declare Radio Buttons
// radio button 1 with an empty string for its label
RadioButton rb1 = new RadioButton();
// radio button 2 with an empty string for its label
RadioButton rb2 = new RadioButton();
Button btnFirst, btnSecond;
// Declare controls at class scope.
Label lblStatus;
MenuBar mBar;
Image imgRight2;
ImageView imgViewRight;
public HighLowJavafx() {
// TODO Auto-generated constructor stub
}
#Override
public void init() {
// Instantiate components.
lblFirst = new Label("First Card Dealt:");
lblSecond = new Label("Second Card dealt:");
lblNext = new Label("Next Card Will Be:");
mBar = new MenuBar();
// ------------------------------------------------------------------
// File menu
Menu mnuFile = new Menu("File");
// add new game to file menu
MenuItem newGame = new MenuItem("New Game");
mnuFile.getItems().add(newGame);
// add shuffle to file menu
MenuItem shuffle = new MenuItem("Shuffle");
mnuFile.getItems().add(shuffle);
// add exit to file menu
MenuItem exit = new MenuItem("Exit");
mnuFile.getItems().add(exit);
// Add the menu to the menu bar.
mBar.getMenus().add(mnuFile);
// -------------------------------------------------------------------
// Create a help menu.
Menu mnuHelp = new Menu("Help");
// Add menu items to the help menu.
MenuItem aboutItem = new MenuItem("About");
mnuHelp.getItems().add(aboutItem);
aboutItem.setOnAction(ae -> showAboutDialog());
// Add the help menu to the menu bar.
mBar.getMenus().add(mnuHelp);
// ------------------------------------------------------------------
// Add image view
imgViewRight = new ImageView();
// Handle menu events.
newGame.setOnAction(ae -> {
});
}// init()
private void showAboutDialog() {
// Create a new stage and set sizes and title.
Stage dialog = new Stage();
dialog.setWidth(250);
dialog.setHeight(180);
dialog.setTitle("About");
// A label for the dialog.
Label lblAbout = new Label(" Luke Gallagher 2933229 ");
// An OK button for the dialog.
Button btnOK = new Button("OK");
// Handle events (clicks) on the dialog button.
btnOK.setOnAction(ae -> dialog.close());
btnOK.setMinWidth(120);
// Layout for the about dialog.
VBox vbAbout = new VBox();
BorderPane dlgBP = new BorderPane();
dlgBP.setCenter(btnOK);
// The button.
BorderPane bpLbl = new BorderPane();
bpLbl.setCenter(lblAbout);
// Set the padding.
vbAbout.setPadding(new Insets(40));
vbAbout.setSpacing(20);
// Add components.
vbAbout.getChildren().add(bpLbl);
vbAbout.getChildren().add(dlgBP);
// Create a scene.
Scene dlgScene = new Scene(vbAbout);
// Set the scene.
dialog.setScene(dlgScene);
// Show the stage.
dialog.show();
}// showAboutDialog()
public int cardNum() {
int Num = (int) Math.ceil(Math.random() * 52);
return Num;
}
#Override
public void start(Stage pStage) throws Exception {
// Set the title.
pStage.setTitle("Hi-Lo Card Game");
// Set the width and height.
// Width and height.
pStage.setWidth(600);
pStage.setHeight(400);
// images
// fileR = new File("cards/" + cardRight.toString(cardRight)+/".png")
// imgRight2= new Image("cards/2_of_clubs.png");
// imgViewRight.setImage(imgRight2);
// imgRight2= new Image(fileR.toURI().toString());
// imgViewRight.setImage(imgRight2);
// Instantiate components.
lblFirst = new Label("First Card Dealt:");
lblSecond = new Label("Second Card Dealt:");
lblNext = new Label("Next Card Will Be:");
// Start and stop buttons.
btnFirst = new Button("<- Deal First Card");
btnSecond = new Button("Deal Second Card ->");
// Manage button sizes.
btnFirst.setMaxWidth(130);
btnSecond.setMaxWidth(130);
// rb button functionality only one can be selected at once
ToggleGroup group = new ToggleGroup();
RadioButton rb1 = new RadioButton("Higher");
rb1.setToggleGroup(group);
rb1.setSelected(true);
RadioButton rb2 = new RadioButton("Lower");
rb2.setToggleGroup(group);
// Create a layout.
BorderPane bpMain = new BorderPane();
// Add components to the layout.
bpMain.setTop(mBar);
BorderPane.setAlignment(lblSecond, Pos.TOP_RIGHT);
BorderPane.setMargin(lblSecond, new Insets(12, 80, 12, 12));
bpMain.setRight(lblSecond);
VBox pane1 = new VBox();
pane1.getChildren().add(lblNext);
pane1.getChildren().add(rb1);
pane1.getChildren().add(rb2);
pane1.getChildren().add(btnFirst);
pane1.getChildren().add(btnSecond);
pane1.setSpacing(10);
BorderPane.setAlignment(pane1, Pos.CENTER);
BorderPane.setMargin(pane1, new Insets(40, 12, 12, 120));
bpMain.setCenter(pane1);
// images
// final Image img = new Image("cards/"+cardNum()+".png");
final ImageView imgView = new ImageView(".cards");
// vbox2
VBox pane2 = new VBox();
pane2.getChildren().add(lblFirst);
BorderPane.setAlignment(pane2, Pos.TOP_LEFT);
BorderPane.setMargin(pane2, new Insets(12, 12, 12, 12));
bpMain.setLeft(pane2);
// disables max button to keep everything in-line
pStage.resizableProperty().setValue(Boolean.FALSE);
// Create a scene.
Scene s = new Scene(bpMain);
// Set the scene.
pStage.setScene(s);
btnFirst.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
imgView.setImage(new Image("cards/2_of_clubs.png"));
pane2.getChildren().add(imgView);
pane2.getChildren().add(lblFirst);
BorderPane.setAlignment(pane2, Pos.TOP_LEFT);
BorderPane.setMargin(pane2, new Insets(12, 12, 12, 12));
bpMain.setLeft(pane2);
}
});
// Show the stage.
pStage.show();
}// start()
public static void main(String[] args) {
// Launch the application.
launch();
}// main()
}// class
the exceptions and errors I'm getting is as follows
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found
at javafx.scene.image.Image.validateUrl(Image.java:1118)
at javafx.scene.image.Image.<init>(Image.java:620)
at javafx.scene.image.ImageView.<init>(ImageView.java:166)
at HighLowJavafx.start(HighLowJavafx.java:267)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
... 1 more
Caused by: java.lang.IllegalArgumentException: Invalid URL or resource not found
at javafx.scene.image.Image.validateUrl(Image.java:1110)
... 12 more
Exception running application HighLowJavafx
Picked up _JAVA_OPTIONS: -Xmx512M

Why am I getting an "exception while running" error? [duplicate]

This question already has an answer here:
Java - NullPointerException in Array [duplicate]
(1 answer)
Closed 7 years ago.
I made an array of Images to be set with a lesser number of image views. I want 10 images to randomly assign themselves to 4 Image views and then be displayed through the gridpane. Every time I run the code I get an error, "exception while running application". Is it the path of the images? I don't see any obvious errors.
package Flag;
import java.util.Random;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class Flag extends Application {
#Override public void start(Stage primaryStage) {
// Initialize Variables
GridPane pane = new GridPane();
pane.setAlignment(Pos.CENTER);
ImageView [] imv = new ImageView [4];
Image [] images = new Image[10];
//Fill Images array
images[0] = new Image(Flag.class.getResourceAsStream("images/flag0.gif"));
images[1] = new Image(Flag.class.getResourceAsStream("images/flag1.gif"));
images[2] = new Image(Flag.class.getResourceAsStream("images/flag2.gif"));
images[3] = new Image(Flag.class.getResourceAsStream("images/flag3.gif"));
images[4] = new Image(Flag.class.getResourceAsStream("images/flag4.gif"));
images[5] = new Image(Flags.class.getResourceAsStream("images/flag5.gif"));
images[6] = new Image(Flag.class.getResourceAsStream("images/flag6.gif"));
images[7] = new Image(Flag.class.getResourceAsStream("images/flag7.gif"));
images[8] = new Image(Flags.class.getResourceAsStream("images/flag8.gif"));
images[9] = new Image(Flags.class.getResourceAsStream("images/flag9.gif"));
//Random number
Random rand = new Random();
//Give Each Image an Image View
for (ImageView imv1 : imv) {
/*This is line 38*/ imv1.setImage(images[rand.nextInt(9)]);
}
// Add nodes to pane
pane.add(imv[0], 0, 0);
pane.add(imv[1], 0, 1);
pane.add(imv[2], 1, 0);
pane.add(imv[3], 1, 1);
//Create a scene and place it in the stage
Scene scene = new Scene(pane);
primaryStage.setTitle("ShowGridPane");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
Here's the log
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.javafx.main.Main.launchApp(Main.java:642)
at com.javafx.main.Main.main(Main.java:805)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:403)
at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:47)
at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:115)
at java.lang.Thread.run(Thread.java:724)
Caused by: java.lang.NullPointerException
at Flag.Flag.start(FlagsHwB.java:38)
at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:319)
at com.sun.javafx.application.PlatformImpl$5.run(PlatformImpl.java:215)
at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:179)
at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:176)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:176)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:29)
at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:73)
... 1 more
Java Result: 1
images[9] - this does not exist. The array only has nine elements. The error message says this: Caused by: java.lang.ArrayIndexOutOfBoundsException: 9
The problem is because of
Image [] images = new Image[9];
You are initializing an array of 9 elements and trying to insert 10 elements into it.
images[9] = new Image(Flags.class.getResourceAsStream("images/flag9.gif"));
represents the 9th index and the 10th element. Just increase the array size to 10 i.e.
Image [] images = new Image[10];
A better option is to use an ArrayList if you are not sure of the size of the array. ArrayList resizes itself on element adding.
Edit - as per user comments
The NullPointerException is because you haven't initialized any of you ImageView's. Initialize the ImageView's before using them.
for (ImageView imv1 : imv) {
imv1 = new ImageView(); // Initialization
imv1.setImage(images[rand.nextInt(9)]);
}
or you can directly use
for (ImageView imv1 : imv) {
imv1 = new ImageView(images[rand.nextInt(9)]));
}

Can I put the renderscript memory allocation inside a loop to process a series of variable size arrays?

I am trying to modify the parallel reduction algorithm. I am using a logic to divide an given array length into powers of 2. For example if i put in the number 26, I make array 1 of 16 elements, the next array of 8 elements and the last array of 2 elements. Although 26 in itself is not a power of 2 but by this method i have more number of sub arrays created from the main array where each of them can be subjected to parallel reduction. but to be able to do this in rendercript i use a loop to each time rewrite the renderscript memory allocation while it has only one context but it is throwing me errors. can you help me in this part? point me to my blind spot? the following is my code!
private void createScript() {
log ("i'm in createscript");
int pp=0;
int qq=1;
int ii=0;
**mRS = RenderScript.create(this);**
for (int gstride=0; gstride < address.length/2; gstride++){
log("im in stride noof gstride:"+gstride);
// this is the address array location
int strtadd=address[ii];
int sze = 0;
sze=address[qq]-address[pp]+1;
tempin =new int [sze];
System.arraycopy(input, strtadd, tempin, 0, tempin.length);
strtadd=address[ii+2];
log("Generated size of array: " + tempin.length);
//renderscript declarations
`enter code here`**mInAllocation=Allocation.createSized(mRS,Element.I32(mRS),tempin.length);
`enter code here`mOutAllocation=Allocation.createSized(mRS,Element.I32(mRS),address.length/2); `
mInAllocation.copyFrom(tempin);
mScript = new ScriptC_reduce2(mRS, getResources(), R.raw.reduce2);
//int row_width = input.length;
mScript.bind_gInarray(mInAllocation);
mScript.set_gIn(mInAllocation);
mScript.set_gOut(mOutAllocation);
mScript.set_gScript(mScript);
//time measurement
long lStartTime = new Date().getTime();
for (int stride = tempin.length / 2; stride > 0; stride /= 2) {
mScript.set_stride(stride);
mScript.invoke_filter();
}**
long lEndTime = new Date().getTime();
long difference = lEndTime - lStartTime;
nettime[gstride]=difference;
pp=pp+1;
qq=qq+1;
mInAllocation.copyTo(tempin);
output[gstride] = tempin[0];
}
int sum=0;
int sum2=0;
int i = 0; .
while(i < output.length) {
sum += output[i];
sum2 +=nettime[i];
i++;
}
t1.setText(String.format("output:%s\n\nExecution time:%s",
+sum, +sum2 +"ms")); //input:%s\n\n ArrayToString(input),
}
I get the following error as copied from the error log: I don't think its out of memory ` `error.
V/RenderScript( 2890): rsContextCreate dev=0x2a14ea68
V/ScriptC ( 2890): Create script for resource = reduce2
D/StopWatch( 2890): StopWatch bcc: RSCompilerDriver::loadScriptCache time (us): 1988
D/StopWatch( 2890): StopWatch bcc: RSCompilerDriver::build time (us): 2485
D/AndroidRuntime( 2890): Shutting down VM
W/dalvikvm( 2890): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
E/AndroidRuntime( 2890): FATAL EXCEPTION: main
E/AndroidRuntime( 2890): java.lang.RuntimeException: Unable to start activity `enter code `enter code here`ComponentInfo{com.example.paralleladd2/com.example.paralleladd2.Paralleladd2}:java.lang .NullPointerException
E/AndroidRuntime( 2890): at `enter code here`android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
E/AndroidRuntime( 2890): at `enter code here`android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
E/AndroidRuntime( 2890): at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/AndroidRuntime( 2890): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
E/AndroidRuntime( 2890): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime( 2890): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime( 2890): at android.app.ActivityThread.main(ActivityThread.java:5041)
E/AndroidRuntime( 2890): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 2890): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime( 2890): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime( 2890): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime( 2890): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime( 2890): Caused by: java.lang.NullPointerException
E/AndroidRuntime( 2890): at com.example.paralleladd2.Paralleladd2.createScript(Paralleladd2.java:157)
E/AndroidRuntime( 2890): at com.example.paralleladd2.Paralleladd2.onCreate(Paralleladd2.java:48)
E/AndroidRuntime( 2890): at android.app.Activity.performCreate(Activity.java:5104)
E/AndroidRuntime( 2890): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
E/AndroidRuntime( 2890): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
Allocation creation should be fine inside the loop. I think your problem is coming from having the script creation inside the loop. I would create one reduce script outside your allocation creation loop and re-use it in the loop.
Script creation is very resource intensive and could be running the system out of resources.

Fatal error when camera is initializing and back button is pressed or page navigating

I'm working on WP7/8 application with barcode scanning. And have a problem with disposing camera. Camera initialize too long, and when camera is still initializing and I press back button, I've got a fatal error:
A first chance exception of type 'System.ObjectDisposedException'
occurred in Microsoft.Devices.Camera.ni.dll WinRT information: Fatal
error. Disposing capture device.
Could anybody helps me how to avoid this error?
my code:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
InitializeAndGo();
base.OnNavigatedTo(e);
}
protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
{
disposeCamera();
}
private void PhotoCameraOnInitialized(object sender, CameraOperationCompletedEventArgs cameraOperationCompletedEventArgs)
{
_width = Convert.ToInt32(_photoCamera.PreviewResolution.Width);
_height = Convert.ToInt32(_photoCamera.PreviewResolution.Height);
_luminance = new PhotoCameraLuminanceSource(_width, _height);
if (_photoCamera.IsFlashModeSupported(FlashMode.Auto))
{
_photoCamera.FlashMode = FlashMode.Off;
}
cameraInitialized = true;
Dispatcher.BeginInvoke(() =>
{
FlashCheckbox.IsEnabled = true;
if (_photoCamera.IsFlashModeSupported(FlashMode.Auto))
{
_photoCamera.FlashMode = FlashMode.Off;
}
});
_photoCamera.Focus();
}
private void InitializeAndGo()
{
stopScan = false;
_photoCamera = new PhotoCamera();
_photoCamera.Initialized += PhotoCameraOnInitialized;
_photoCamera.AutoFocusCompleted += PhotoCameraOnAutoFocusCompleted;
viewfinderBrush.SetSource(_photoCamera);
_previewTransform.Rotation = _photoCamera.Orientation;
_results = new ObservableCollection<Result>();
_barcodeReader = new BarcodeReader();
_barcodeReader.TryHarder = true;
_barcodeReader.AutoRotate = true;
_service = new MyMoviesDataService(ErrorDataService);
}
private void disposeCamera()
{
try
{
cameraInitialized = false;
StopScan();
_photoCamera.Initialized -= PhotoCameraOnInitialized;
_photoCamera.AutoFocusCompleted -= PhotoCameraOnAutoFocusCompleted;
_photoCamera.Dispose();
_photoCamera = null;
}
catch (Exception ex)
{
App.ShowErrorToast(ex.Message);
}
}
Don't use the camera until it's been successfully initialized (You can check this in the camera's Initialized event).
Also, wrap any usages of the camera in a
try
{
// camera code here
}
catch (ObjectDisposedException)
{
// re-initialize the camera?
}
to handle situations like suspension, which will dispose of the camera automatically.
As for the
An exception of type 'System.ObjectDisposedException' occurred in
Microsoft.Devices.Camera.ni.dll and wasn't handled before a
managed/native boundary WinRT information: Fatal error. Disposing
capture device.
This is something Microsoft needs to fix; I mean, how are you supposed to handle a native code exception if it isn't allowed to propagate to managed code?
Where is the exception coming from (which code line / block)?
I would for starter put a try...catch around InitializeAndGo() in the OnNavigatedTo event handler. And on the whole PhotoCameraOnInitialized event handler also.
Cheers,

Resources