Monday, April 16, 2012

Javascript static method in class defined inside global object

I know Javascript doesn't have classes in the same way that traditional OOP languages do and that a "class" definition such as the following, is merely a function object that can be used with the new keyword:



function MyClass(){
this.a = function(){ /* Do something */ }; // Public function
function b(){ /* Do something */ }; // Private function
}


What I'm wondering is, if I define a global object (to avoid polluting the namespace) and define my classes inside this object, can I define a static method for my class in a nicer way than this:



var MyObject = {
MyClass: function(){
this.a = function(){ /* Do something */ }; // Public function
function b(){ /* Do something */ }; // Private function
},
}
MyObject.MyClass.MyStaticMethod = function(){ /* Do something */ };


I was thinking something along the lines of defining MyStaticMethod inside the MyClass function scope - is this possible?





Calling RESTful from apache camel

i am currently using Http method for invoking some url which will create a JIRA issue.



Now i want to use apache camel, how can i use that.



I've to invoke the following link through camel.
http://localhost:8080/rest/api/2/project/" + key + /components



As i'm new to camel,Please suggest some solutions and examples too.



Thanks





Google Chrome Javascript debugging issue

It used to be that when I stopped at a breakpoint in Google Chrome, and hovered over a variable, there would be a popup showing me the value of that variable. For some reason, that has simply stopped happening. Can anyone think what might have stopped this behaviour and how I might be able to restore it?





PHP how to join to records from array

Hi it is any way to connect to records where value is the same?



like



[12]=> Array (
[ID] => 127078
[row1] =>
[post] => N16 7UJ
)

[13]=> Array (
[ID] => 127078
[row1] => something
[post] =>
)


and make like that



[12]=> Array (
[ID] => 127078
[row1] => something
[post] => N16 7UJ
)




2D Engines for Javascript

I'm attempting to build a tile-based game in javascript, using HTML5 canvas. There are -many- engines to choose from, such as;





... and the list goes on and on.



However, there does not seem to be one de facto standard among all these different implementations. Essentially I am looking for the 'jQuery' of javascript game engines. One that is backed by a (larger) community, has excellent documentation and is actively maintained. Most of these just seem like one-man projects to me.



To phrase this into a real question; what is the de facto standard for 2d game engines in javascript?



Additionally I would be very interested in experiences with actual implementations (other than demo pong / pacman games).





How we can write in a file through a j2me code?

How we can write in a file through a j2me code ?





jQuer UI autocomplete jsonp mapping response

I am trying to use the autocomplete from jqueryUI. When i alert the response i get the following : ([ { "id": "test", "label": "test", "value": "test" } ]);



but when i try to map the result the dropdown result is empty. here is my code:



<script>
$(function() {
function log( message ) {
$( "<div/>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}

$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
alert(data);
response( $.map( data, function( item ) {
return {
label: item.label,
value: item.value
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
</script>


my server side script uses the following code:



echo $_GET['jsonp_callback'] . '(' . $data . ');';


Thanks anyway





IE9 Error 80020102, using vbscript Preserve keyword with doctype strict

I'm using IE9 beta with the test code below and i encounter an 80020102 error when vbscript tries to append to the array. If I run this in quirks mode it seems to work.



Not knowing if this is an MS issue or something improper I'm doing, I've submitted it to IE9s bug depot. Does anyone have a suggestion on a work around?



I'd post the full html, but it always looks malformed in the preview.



-- VBscript part ---    
Function getBlankArray()
getBlankArray = Array()
End Function

Function appendArray(arr, val)
redim preserve arr(ubound(arr) + 1)
arr(ubound(arr)) = val
appendArray = arr
End Function

-- javascript part ---
function test()
{
var contextKeysArray = getBlankArray();
var jscontextKeysArray = new Array();
for(var x=0; x < 10; x++)
{

jscontextKeysArray[x] = x;

}

for(i = 0; i < jscontextKeysArray.length; i++)
{
contextKeysArray = (appendArray(contextKeysArray, jscontextKeysArray[i]));
}

}




Evaluating more than 255 cells using Apache POI 3.8

I've recently migrated to Apache POI 3.8 in order to handle .xlsx files as well as .xls. There appears to be a bug when evaluating more than 255 cells. To test, I'm just summing a range of cells:



SUM(B2:IW2)



Each cell contains "10".



Here's the code to evaluate the formula:



FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
evaluator.clearAllCachedResultValues();
String result = DataFormatter().formatCellValue(cell, evaluator);


The result of my integration test is 2550; it should be 2560.



DataFormatter().formatCellValue(cell, evaluator)


Calls this code in org.apache.poi.ss.formula.LazyAreaEval:



public ValueEval getRelativeValue(int relativeRowIndex, int relativeColumnIndex) {

int rowIx = (relativeRowIndex + getFirstRow() ) & 0xFFFF;
int colIx = (relativeColumnIndex + getFirstColumn() ) & 0x00FF;

return _evaluator.getEvalForCell(rowIx, colIx);
}


which doesn't evaluate beyond 255.



Is there a workaround for this? The reason for this implementation is to allow client users to enter their own excel formulas for whatever requirements might need and for the system I'm working on to calculate the result using these formulas only. IE, the values of the cells (in my example, "10") are read dynamically form a separate source. I can't change the orientation of the cells being evaluated to use rows instead of columns as the existing structure is in production.



Any help much appreciated!





Improving performance of Racket Code and error when trying to byte compile

I hacked together several code snippets from various sources and created a crude implementation of a Wolfram Blog article at http://bit.ly/HWdUqK - for those that are mathematically inclined, it is very interesting!



Not surprisingly, given that I'm still a novice at Racket, the code takes too much time to calculate the results (>90 min versus 49 seconds for the author) and eats up a lot of memory. I suspect it is all about the definition (expListY) which needs to be reworked.



Although I have it working in DrRacket, I am also having problems byte-compiling the source, and still working on it
(Error message: +: expects type <number> as 1st argument, given: #f; other arguments were: 1 -1)



Anybody want to take a stab at improving the performance and efficiency? I apologize for the unintelligible code and lack of better code comments.



PS: Should I be cutting and pasting the code directly here?





Annotation accepting n parameters

I'd like to be able to call an annotation with as many parameter as I want, something like this :



@Authorize("Admin", "Moderator", "User")
public static void read() {
// ...
}


So far, here's my annotation :



@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Authorize {
String[] value() default {};
}


But as you may know, this only works with :



@Authorize
@Authorize("Admin")
@Authorize({"Admin", "Moderator", "User"})


In fact, the first two are fine to me, it's the last one that bothers me.



The reason is simple.



For rights, I want a method to be available for many profile, and {} means "WITH", I'm looking for a "OR" ;)



Thanks!





How to make good use of kernel's stack trace?

If you are lucky when your kernel module crashes, you would get an oops with a log with a lot of information, such as values in the registers etc. One such information is the stack trace. Take this example:



[<f97ade02>] ? skink_free_devices+0x32/0xb0 [skin_kernel]
[<f97aba45>] ? cleanup_module+0x1e5/0x550 [skin_kernel]
[<c017d0e7>] ? __stop_machine+0x57/0x70
[<c016dec0>] ? __try_stop_module+0x0/0x30
[<c016f069>] ? sys_delete_module+0x149/0x210
[<c0102f24>] ? sysenter_do_call+0x12/0x16


My guess is that the +<number1>/<number2> has something to do with the offset from function in which the error has occurred. That is, by inspecting this number, perhaps looking at the assembly output I should be able to find out the line (better yet, instruction) in which this error has occurred. Is that correct?



My question is, what are these two numbers exactly? How do you make use of them?





How to make a movie clip along with photos and audio .?

How to make a movie clip that shows images along with an audio clip . want to save it as a movie clip formats .?





Paypal SetExpressCheckout Soap

when i try to setExpressCheckout, i get ack = success but not token return.



the version of paypal api is 87.0
Here the wsdl link : https://www.sandbox.paypal.com/wsdl/PayPalSvc.wsdl



here to command i use in axis2-1.6.1 to generate java code



-uri PayPalSvc.wsdl -p com.paypal.soap.PayPalAPIAA - pn PayPalAPIAA -s


here the code for SetExpressCheckout



String setExpressCheckout(PayPalBuyer buyer, PayPalSeller seller) throws AxisFault, RemoteException {

PaymentDetailsType paymentDetails = new PaymentDetailsType();
BasicAmountType orderTotal = new BasicAmountType();
orderTotal.setCurrencyID(CurrencyCodeType.USD);
orderTotal.setString("10.00");
paymentDetails.setOrderTotal(orderTotal);
paymentDetails.setPaymentAction(PaymentActionCodeType.Sale);


SetExpressCheckoutRequestDetailsType details = new SetExpressCheckoutRequestDetailsType();
details.setPaymentDetails(new PaymentDetailsType[]{paymentDetails});
details.setReturnURL(buyer.getReturnUrl());
details.setCancelURL(buyer.getCancelUrl());

SetExpressCheckoutRequestType pprequest = new SetExpressCheckoutRequestType();
pprequest.setVersion("87.0");
pprequest.setSetExpressCheckoutRequestDetails(details);

RequesterCredentials requesterCredentials = new RequesterCredentials();
CustomSecurityHeaderType customSecurityHeaderType = new CustomSecurityHeaderType();

UserIdPasswordType userIdPasswordType = new UserIdPasswordType();
userIdPasswordType.setUsername(seller.getUser());
userIdPasswordType.setPassword(seller.getPass());
userIdPasswordType.setSignature(seller.getSignature());
customSecurityHeaderType.setCredentials(userIdPasswordType);

requesterCredentials.setRequesterCredentials(customSecurityHeaderType);
String endPoint = null;
endPoint = "https://api-3t.sandbox.paypal.com/2.0/"; //sandbox API Signature

PayPalAPIInterfaceServiceStub stub = new PayPalAPIInterfaceServiceStub(endPoint);
stub._getServiceClient().getOptions().setProperty(HTTPConstants.CHUNKED, false);
SetExpressCheckoutReq checkoutReq = new SetExpressCheckoutReq();
checkoutReq.setSetExpressCheckoutRequest(pprequest);

SetExpressCheckoutResponse expressCheckout = stub.setExpressCheckout(checkoutReq, requesterCredentials);
SetExpressCheckoutResponseType setExpressCheckoutResponse = expressCheckout.getSetExpressCheckoutResponse();

System.out.println(setExpressCheckoutResponse.getAck());
System.out.println(setExpressCheckoutResponse.isTokenSpecified());
System.out.println(setExpressCheckoutResponse.getToken());


here the result that i get



Success
false
null


how i get ack success but token is null?



thanks in advance.





Sencha Touch 2 list background change

I have a list within my application, but was wondering if it is possible to have each list displayed show a different background colour, rather than the same one through out each item?



I have created a template but would be nice to have the background of each change colour.



Thanks



EDIT: I have also created the same list via a 'Ext.dataview.component.DataItem' / 'DataView' so if this is easier to control separately then great, as I am looking at interfering in te process of creating each and setting its background, if that is at all possible.





Paramiko hangs while loading a module (continuation). Usage with Aspects Oriented Programming?

So my problem is exactly the same as the question I referenced in the title:
Why does Paramiko hang if you use it while loading a module?



I also created a similar unit test and couldn't find any solution.



I'm currently trying to create some non-regression tests for a big python script.
This script executes unix commands through SSH (paramiko) on many hosts. To achieve that, I want to use aspect oriented programming in two steps:




  1. To create scenarios:
    Capture calls and return values of external functions called by the script and serialize them in some scenario files (to create scenarios easily from real usage).


  2. When running non-regression tests:
    Replace external functions to compare calls with the scenario file, and return the value stored in the scenario (deserialized).




Just for info, I'm doing that with "aspects" module which works very well (http://www.cs.tut.fi/~ask/aspects/index.shtml)



My only problem is I wanted to control that from a kind of caller script, which would define wrapper functions, replace function calls... and call the main script. This way looks very clean to me cause I don't do any modification in the code of the script to test.



However the only way I know to call code in a python module is with import... But if I call the main scrit this way, it gets stuck as soon as Paramiko connects to the first host... All the rest seems to work fine.



So do you have any idea to call the main script without being frozen by paramiko, and without adding a lot of code inside of it?



Many thanks,
Romain





What happens to memory after '' in a C string?

Surprisingly simple/stupid/basic question, but I have no idea: Suppose I want to return the user of my function a C-string, whose length I do not know at the beginning of the function. I can place only an upper bound on the length at the outset, and, depending on processing, the size may shrink.



The question is, is there anything wrong with allocating enough heap space (the upper bound) and then terminating the string well short of that during processing? i.e. If I stick a '' into the middle of the allocated memory, does (a.) free() still work properly, and (b.) does the space after the '' become inconsequential? Once '' is added, does the memory just get returned, or is it sitting there hogging space until free() is called? Is it generally bad programming style to leave this hanging space there, in order to save some upfront programming time computing the necessary space before calling malloc?



To give this some context, let's say I want to remove consecutive duplicates, like this:



input "Hello oOOOo !!" --> output "Helo oOo !"



... and some code below showing how I'm pre-computing the size resulting from my operation, effectively performing processing twice to get the heap size right.



char* RemoveChains(const char* str)
{
if (str == NULL) {
return NULL;
}
if (strlen(str) == 0) {
char* outstr = (char*)malloc(1);
*outstr = '';
return outstr;
}
const char* original = str; // for reuse
char prev = *str++; // [prev][str][str+1]...
unsigned int outlen = 1; // first char auto-counted

// Determine length necessary by mimicking processing
while (*str) {
if (*str != prev) { // new char encountered
++outlen;
prev = *str; // restart chain
}
++str; // step pointer along input
}

// Declare new string to be perfect size
char* outstr = (char*)malloc(outlen + 1);
outstr[outlen] = '';
outstr[0] = original[0];
outlen = 1;

// Construct output
prev = *original++;
while (*original) {
if (*original != prev) {
outstr[outlen++] = *original;
prev = *original;
}
++original;
}
return outstr;
}




Breadth First Traversal for a Tree, Python

I figured out Depth First Traversal for a Tree.



def _dfs(tree, res):
if tree:
res += [tree.key]
_dfs(tree.left, res)
_dfs(tree.right, res)
return res


I can't seem to find a solution for Breadth First Search. Will one have to use queues or stacks?



Thanks!!





APN settings from within app xcode

My app, makes use of APN services. At first launch, it sends a



[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];  


request. This triggers a system alert with permission request. No matter what the user chooses, it will be possible to change it from Settings, notification pane. The app gets the notifications and everything seems to work fine. Now I have been asked to place a switch inside the app to activate/deactivate push notifications from inside the app. I don't think this is possible, but before answering I'd like to get a confirmation. Is there a way to access (read and/or write) notification permissions related to a specific app from within the app itself (just like app defaults preferences)? Is there a way to delete the app from the list of the apps which need push notifications once it has been added due to the initial request? Thank you.





Undefined symbols for architecture i386 when adding FaceBook Connect

I have the following failed code when i run my application on iPhone 5.1 simulator. My app runs smoothly before i add in the Facebook Connect into my application.



Undefined symbols for architecture i386:
"_FBCreateNonRetainingArray", referenced from:
-[FBSession initWithKey:secret:getSessionProxy:] in FBSession.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)



May I know what can i do to get rid of those?



Thanks





Find all topics related to a post id using CakePHP

I'm trying to write a model method that will pull topics attached to a post. The DB setup is as follows:



Post
id
title

Topic
id
title

Post_Topic
id
post_id
topic_id


and the example method...



public function getPostTopics($postId)
{
$topics = $this->find('all', ...
return $topics;
}


What I need to do is find the relationships in the DB and then store them in the following format for the return e.g. tag1, tag2, tag3.



Can anyone help me out?



Here are the associations:



Post.php
class Post extends AppModel
{
public $name = 'Post';

public $belongsTo = 'User';

public $hasMany = array('Answer');

// Has many topics that belong to topic post join table... jazz
public $hasAndBelongsToMany = array(
'Topic' => array('with' => 'TopicPost')
);
}

Topic.php
class Topic extends AppModel
{
public $hasMany = array(
'TopicPost'
);
}

TopicPost.php
class TopicPost extends AppModel {
public $belongsTo = array(
'Topic', 'Post'
);
}


and for an example of how it's saved into the Database (to give an idea of how a function in the model works) in the first place (courtesy of another helpful person on SO)



public function savePostTopics($postId, $topics)
{
// Explode the topics by comma, so we have an array to run through
$topics = explode(',', $topics);
// Array for collecting all the data
$collection = array();



foreach($topics as $topic)
{
// Trim it so remove unwanted white spaces in the beginning and the end.
$topic = trim($topic);

// Make it all lowercase for consistency of tag names
$topic = strtolower($topic);

// Check if we already have a topic like this
$controlFind = $this->find(
'first',
array(
'conditions' => array(
'title' => $topic
),
'recursive' => -1
)
);

// No record found
if(!$controlFind)
{
$this->create();
if(
!$this->save(
array(
'title' => $topic
)
)
)
{
// If only one saving fails we stop the whole loop and method.
return false;
}
else
{
$temp = array(
'TopicPost' => array(
'topic_id' => $this->id,
'post_id' => $postId
)
);
}
}
else
{
$temp = array(
'TopicPost' => array(
'topic_id' => $controlFind['Topic']['id'],
'post_id' => $postId
)
);
}

$collection[] = $temp;
}

return $this->TopicPost->saveMany($collection, array('validate' => false));




How to get object from many-to-many related tables using Cursor

Could anybody writes me how to use Cursor on two tables in many-to-many relation?
For example we have tables:



BOOKS(id, title)

AUTHORS(id, name)

BOOKSAUTHORS(bookId, authorId)


and we have a classes



class Book{
int id;
String title;
List<Author> authors;
}

class Author{
int id;
String name;
}


How using Cursor get object of Book class with filled list of authors?





best path finding algorithm?

What is the best path finding algorithm, when agent is blind and cannot choose the maximum or minimum path, it can store the information once it will visit the node but can't compare two node, i tried varies path finding algorithms such as A*, DFS,BFS and Qlearning ect but more are less all are based on comparison, or on sorting method. Even I tried to simulate the path by using random search method but it always follow the same path never randomize the path? Please help me I really need help. If you ask then I will post my code.. Thanks in advance.





Cast base instance to derived class (downcast) in C#

Suppose I have two classes:



class Employee 


and



class AdvancedEmployee:Employee


I know something like this won't work, as I can't downcast on C#:



var employee = new Employee();
var advanced = employee as AdvancedEmployee;


My question is: How to accomplish downcast in a efficient way?
Actually I have a constructor on AdvancedEmployee that takes a Employee as parameter and use it to inject its values, basically making a clone.





how to change the marker on OnItemSelected Listener of gallery in android

I am trying to change the marker on OnItemSelected Listener if gallery.Actually i have a gallery showing list of items and a map showing marker of the respected items in gallery .i want to change the marker ( from blue to orange ) when i select an item from the gallery .how can i do it.i have done changing marker on tapping it by the code in this link



http://www.google.com/url?q=http%3A%2F%2Fstackoverflow.com%2Fquestions%2F7038636%2Fhow-to-change-the-marker-for-the-overlay-on-tap-for-android&sa=D&sntz=1&usg=AFQjCNFOnFJHf-f0nTea-a3Rs5hpx4U1IQ ,but not getting how can i do the same with onItemSelected Listener.please suggest some ways.





Ef code first with existing database

Suppose I have two database tables, say tb1 and tb2, with



[tb1]
id primary key
name
lastname

[tb2]
id primary key
tb1_ID foreign key
phone_no
degree
grade



Relationship tb1 may hold multiple record of table two. i.e: one to many relationship.

For this relationship I need an entity that hold all column of tb1 one and only one column on tb2 (say only ph no.).

Suggest me the easiest possible way.





Post Message on Friends Facebook Wall post

Hi I am working on Application in which i have to post Gretting to my friends Wall post through My Account so How can i Perform it if anyone have idea Please help me.
Thanks in Advance..





Status access overflow while accessing array of chars

    FILE *input;
FILE *output;

input=fopen("in.txt", "r");
output=fopen("out.txt", "w");


char buffer[1000];
char bytebuffer=0;
char tempchr=0;
char huffmancode[100]={0};
int bufferindex=7;

fgets(&buffer[0],255,input);

int length=0;
while (buffer[length]!=0) length++;



fputc(length,output);

int j;
int k;



for (j=0;j<length;j++){
tempchr=buffer[j];
strcpy(&huffmancode[0],code[tempchr-97]);
k=0;

while(huffmancode[k]!=0){
if (huffmancode[k]!='0'){
setBit(&bytebuffer,bufferindex);
}
bufferindex-=1;
if (bufferindex==-1){
fputc(bytebuffer,output);
bytebuffer=0;
bufferindex=7;
}
k++;
}

}


this code is failing due



tempchr=buffer[j];


It works perfectly fine for j<10 but for j>=10 the program throws a status access overflow exception. buffer variable is allocated for 1000 bytes so I don't have a clue why the program is failing to access an index in bounds. Why is this failing?



There are some array definitions which I didn't include. I don't think they are the problem but here are they anyways.



    int agac[1000]={21,12,9,7,5,
5,4,0,0,0,
0,3,2,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0
};
char sembol[1000]={0,0,0,'a','b',
0,'f',0,0,0,
0,'u','k',0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0
};

char *code[27]={ "00","01",0,0,0,
"11",0,0,0,0,
"101",0,0,0,0,
0,0,0,0,"100",
0,0,0,0,0,
0,0
};




application not working on android 4.0.4

i was working on a media player app on 2.2 that worked fine on my phone nexus S on 2.3.6 i upgraded my phone to ice cream sandwich 4.0.4 it's not working anymore when i commented this portion of code it worked what's the problem with this code :



public void loadfiles()
{
File file = new File("/sdcard");
String [] liste;
liste=file.list();
String txt=new String("");
db.begin_transaction();
for(int i=0;i<liste.length;i++){
File file1 =new File("/sdcard/"+liste[i]);
if (file1.isDirectory()&&(i!=liste.length-2)){search("/sdcard/"+liste[i]);}}
db.end_transaction();
}
public void search(String url)
{
File file = new File(url);
String [] liste;
liste=file.list();
String txt = new String("");
for(int i=0;i<liste.length;i++)
{
File file1 =new File(url+"/"+liste[i]);
if (file1.isDirectory()){search(url+"/"+liste[i]);}
else if(liste[i].endsWith(".mp3"))
{
//HashMap<String, String> info = MP3HeaderInfo.getInfo(file.getAbsolutePath()+"/"+liste[i]);

//db.insererUneChanson((liste[i]).substring(0,liste[i].length()-4),file.getAbsolutePath()+"/"+liste[i],info.get("Artist"),info.get("Album"),info.get("Year"));

}
}




NullpointerException when trying to save the current Android app view as image

Hi stackoverflow community,



in my application I'd like to have a button which allows the user to capture the current view. For that reason, I've written the following method (oriented towards: Android save view to jpg or png ):



private LinearLayout container; 

public void createImageOfCurrentView(View v) {
if(isExternalStoragePresent()) {
container = findViewById(R.id.container);
container.setDrawingCacheEnabled(true);
Bitmap b = container.getDrawingCache();
File dir = new File(Environment.getExternalStorageDirectory().getPath()+"/"+getPackageName()+"/");
dir.mkdirs();
File file = new File(dir, "image.jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
b.compress(CompressFormat.JPEG, 95, fos); // NullPointerException!
Toast.makeText(this, "The current view has been succesfully saved as image.", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
Toast.makeText(this, "Unfortunatly an error occured and this action failed.", Toast.LENGTH_SHORT).show();
}
}else {
Toast.makeText(this, "Bacause of lacking access to the storage of this device, the current view couldn't be saved as an image.", Toast.LENGTH_LONG).show();
}
}


The problem is according to LogCat that there occured a NullPointerException when trying to create the jpeg. So probably the method container.getDrawingCache() is not working. On the phone the file is generated. However with the size of 0 bytes and no visible image. I would appreciate any suggestions what I have to do in order to make it work as I want.