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

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.

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)

Distributed Engine DBException

I have created a table in my local system :
CREATE TABLE default.test_distributed ( a Int8) ENGINE = Distributed(logs, default, test_remote)
and created a table in remote system with IP 10.121.21.33 :
create table test_remote (a Int8) Engine=Log
and then I inserted data in my local system :
insert into test_distributed values (1011)
And then I fired Select query :
select * from test_distributed
And got following exception :
2017.05.02 18:49:36.155606 [ 14 ] ConnectionPoolWithFailover: Connection failed at try №1, reason: Code: 210, e.displayText() = DB::NetException: Connection refused: (10.121.21.33:9000), e.what() = DB::NetException
2017.05.02 18:49:36.155982 [ 14 ] ConnectionPoolWithFailover: Connection failed at try №2, reason: Code: 210, e.displayText() = DB::NetException: Connection refused: (10.121.21.33:9000), e.what() = DB::NetException
2017.05.02 18:49:36.156316 [ 14 ] ConnectionPoolWithFailover: Connection failed at try №3, reason: Code: 210, e.displayText() = DB::NetException: Connection refused: (10.121.21.33:9000), e.what() = DB::NetException
2017.05.02 18:49:36.162780 [ 4 ] executeQuery: Code: 279, e.displayText() = DB::NetException: All connection tries failed. Log:
Code: 210, e.displayText() = DB::NetException: Connection refused: (10.121.21.33:9000), e.what() = DB::NetException
Code: 210, e.displayText() = DB::NetException: Connection refused: (10.121.21.33:9000), e.what() = DB::NetException
Code: 210, e.displayText() = DB::NetException: Connection refused: (10.121.21.33:9000), e.what() = DB::NetException
, e.what() = DB::NetException (from 127.0.0.1:33590) (in query: select * from test_distributed), Stack trace:
clickhouse-server(StackTrace::StackTrace()+0x16) [0x17c6e76]
clickhouse-server(DB::Exception::Exception(std::string const&, int)+0x1f) [0xfdd9ff]
clickhouse-server(PoolWithFailoverBase::getMany(DB::Settings const*, PoolMode)+0x773) [0x17615f3]
clickhouse-server(DB::ConnectionPoolWithFailover::doGetMany(DB::Settings const*, PoolMode)+0x33) [0x17617f3]
clickhouse-server(DB::MultiplexedConnections::initFromShard(DB::IConnectionPool*)+0x26d) [0x19afcad]
clickhouse-server(DB::MultiplexedConnections::MultiplexedConnections(DB::IConnectionPool*, DB::Settings const*, std::shared_ptr, bool, PoolMode)+0x138) [0x19b0a38]
clickhouse-server(DB::RemoteBlockInputStream::createMultiplexedConnections()+0x3fb) [0x1665e8b]
clickhouse-server(DB::RemoteBlockInputStream::readPrefix()+0x23) [0x166b043]
clickhouse-server(DB::AsynchronousBlockInputStream::calculate(MemoryTracker*)+0x60) [0xfe8ea0]
clickhouse-server(ThreadPool::worker()+0x141) [0x17d2d91]
clickhouse-server() [0x33d4faf]
/lib/x86_64-linux-gnu/libpthread.so.0(+0x8182) [0x7f8fe38aa182]
/lib/x86_64-linux-gnu/libc.so.6(clone+0x6d) [0x7f8fe2ec530d]
check settings on local system
SELECT * FROM system.clusters
and check following files /etc/clickhouse-server/config.xml for remote_servers section
see https://clickhouse.yandex/reference_en.html#Distributed for remote_servers example config

request.GetResponse() Timeout

Waker.cs
class Waker
{
Timer timer;
public Waker()
{
timer = null;
}
public void WakeUpApplicationPool(object obj)
{
string url = "http://www.example.com";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Program.LogToFile("WakeUpApplicationPool: " + response.StatusDescription);
response.Close();
}
catch (Exception ex)
{
Program.LogToFile("WakeUpApplicationPool_Error: " + ex.ToString());
}
}
public void Start()
{
TimerCallback callback = new TimerCallback(WakeUpApplicationPool);
int DUE_TIME = 0; //The amount of time to delay before the callback parameter invokes its methods.
int PERIOD = int.Parse(ConfigurationManager.AppSettings["WakerIntervalPeriod"]); //The time interval (miliseconds) between invocations of the methods referenced by callback
timer = new Timer(callback, null, DUE_TIME, PERIOD);
}
public void Stop()
{
timer.Dispose();
}
}
Program.cs:
static void Main(string[] args)
{
try
{
Waker waker = new Waker();
waker.Start();
}
catch(Exception ex)
{
LogToFile(ex.ToString());
}
}
Log file:
15 Apr 2015 18:29:39 - WakeUpApplicationPool: OK
15 Apr 2015 18:31:39 - WakeUpApplicationPool: OK
15 Apr 2015 18:33:59 - WakeUpApplicationPool_Error: System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 205.144.171.35:80
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetResponse()
at ConsoleReporting.Waker.WakeUpApplicationPool(Object obj)
15 Apr 2015 18:35:39 - WakeUpApplicationPool: OK
15 Apr 2015 18:37:39 - WakeUpApplicationPool: OK
15 Apr 2015 18:41:18 - WakeUpApplicationPool_Error: System.Net.WebException: The operation has timed out
at System.Net.HttpWebRequest.GetResponse()
at ConsoleReporting.Waker.WakeUpApplicationPool(Object obj)
15 Apr 2015 18:43:18 - WakeUpApplicationPool_Error: System.Net.WebException: The operation has timed out
at System.Net.HttpWebRequest.GetResponse()
at ConsoleReporting.Waker.WakeUpApplicationPool(Object obj)
15 Apr 2015 18:45:18 - WakeUpApplicationPool_Error: System.Net.WebException: The operation has timed out
at System.Net.HttpWebRequest.GetResponse()
at ConsoleReporting.Waker.WakeUpApplicationPool(Object obj)
15 Apr 2015 18:47:18 - WakeUpApplicationPool_Error: System.Net.WebException: The operation has timed out
at System.Net.HttpWebRequest.GetResponse()
at ConsoleReporting.Waker.WakeUpApplicationPool(Object obj)
The problem is:
My code is not working after it hit the Timed Out error. But after I restart the Program.exe, it is working again but it hit the Timed Out error after 10 minutes.
I want to use this Program.exe to wake up my application pool which hosted at hosting provider.
So could anyone tell the reason and solution is? I referred this,but it is not working for my code either
The problem is solved after I set the WakerIntervalPeriod to 10 minutes instead of 5 minuets.

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

Plotting Image Histogram Using Androidplot

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()

Resources