picasso error. image URL COMES from database but not set in picasso image - picasso

Picasso.with(context).load(Image.get(position)).into(new Target() {#Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from{Log.d("abhinav1", "onBitmapLoaded: "+bitmap); r.setBackground(new BitmapDrawable(bitmap));}#Override public void onBitmapFailed(Drawable errorDrawable{}#Override public void onPrepareLoad(Drawable placeHolderDrawable) {
}});

after search i found that the data comes from the server in the string from then first you have to decrypt the string into bitmap and then set in imageview

In your onBitmapLoaded method, you can use
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom >from) {
Log.d("abhinav1", "onBitmapLoaded: "+bitmap);
r.setBackground(new BitmapDrawable(context.getResources(), bitmap));
}
please pass the Resources in the BitmapDrawable constructor.

Related

How to get Shared preferences in doInBackground method of AsyncTask

I am building a data transfer app using direct Wifi. I am getting the string value of extension from Uri in the onActivityResult method and storing it in Shared preferences.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
String extension;
Uri uri = data.getData();
Context context = getActivity().getApplicationContext();
extension = "."+getMimeType(context, uri);
SharedPreferences sharedPreferences = myContext.getSharedPreferences(myName, MODE_PRIVATE);
SharedPreferences.Editor myEdit = sharedPreferences.edit();
myEdit.putString("hello", extension);
myEdit.apply();
}
It is working fine till now as the value of extension is storing in shared preferences successfully. Now, in the onConnectionInfoAvailable method (related to the broadcast receiver), I am calling an AsyncTask.
#Override
public void onConnectionInfoAvailable(final WifiP2pInfo info) {
new FileServerAsyncTask().execute();
}
Now, I want to get the shared preference value in doInBackground method of AsyncTask. But I am not getting the value of extension from shared preferences, although my code is working fine. Please help.
public static class FileServerAsyncTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
try {
SharedPreferences sh = myContext.getSharedPreferences(myName, MODE_PRIVATE);
String extension = sh.getString("hello", "no");
}....
Note: myContext and myName are defined as public static variables.

Verify Backing Bean values using Arquillian Warp

My goal is to test using Arquillian Warp
1. Already navigated to a JSF page on a previous test
2. On a another test set a text field to a value, using warp i need to inject the ViewScope Bean , and verify the value in the backing bean
Sample Code
#RunWith(Arquillian.class)
#WarpTest
#RunAsClient
public class TestIT {
private static final String WEBAPP_SRC = "src/main/webapp";
private static final String WEB_INF_SRC = "src/main/webapp/WEB-INF";
private static final String WEB_RESOURCES = "src/main/webapp/resources";
#Deployment(testable = true)
public static WebArchive createDeployment() {
File[] files = Maven.resolver().loadPomFromFile("pom.xml")
.importRuntimeDependencies().resolve().withTransitivity().asFile();
WebArchive war = ShrinkWrap.create(WebArchive.class, "test.war")
.addPackages(true, "com.mobitill")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsWebInfResource(new File(WEB_INF_SRC, "template.xhtml"))
.addAsWebInfResource(new File(WEB_INF_SRC, "jboss-web.xml"))
.addAsWebInfResource(new File(WEB_INF_SRC, "web.xml"))
.addAsWebResource(new File(WEBAPP_SRC, "index.xhtml"))
.addAsWebResource(new File("src/main/webapp/demo", "home.xhtml"), "demo/home.xhtml")
.addAsResource("test-persistence.xml", "META-INF/persistence.xml")
.merge(ShrinkWrap.create(GenericArchive.class).as(ExplodedImporter.class)
.importDirectory(WEB_RESOURCES).as(GenericArchive.class), "resources")
.addAsLibraries(files);
System.out.println(war.toString(true));
return war;
}
#Drone
private WebDriver browser;
#ArquillianResource
private URL deploymentUrl;
#Test
#InSequence(1)
public final void browserTest() throws Exception {
browser.get(deploymentUrl.toExternalForm() + "index");
guardHttp(loginImage).click();
Assert.assertEquals("navigate to home page ", "https://127.0.0.1:8080/citi/demo/home", browser.getCurrentUrl());
}
#Test
#InSequence(2)
public final void homeManagedBean() throws Exception {
Warp
.initiate(new Activity() {
#Override
public void perform() {
WebElement txtMerchantEmailAddress = browser.findElement(By.id("txtMerchantEmailAddress"));
txtMerchantEmailAddress.sendKeys("demouser#yahoo.com");
guardAjax(btnMerchantSave).click();
}
})
.observe(request().header().containsHeader("faces-request"))
.inspect(new Inspection() {
private static final long serialVersionUID = 1L;
#Inject
HomeManagedBean hmb;
#ArquillianResource
FacesContext facesContext;
#BeforePhase(UPDATE_MODEL_VALUES)
public void initial_state_havent_changed_yet() {
Assert.assertEquals("email value ", "demouser#yahoo.com", hmb.getMerchantEmail());
}
#AfterPhase(UPDATE_MODEL_VALUES)
public void changed_input_value_has_been_applied() {
Assert.assertEquals(" email value ", "demouser#yahoo.com", hmb.getMerchantEmail());
}
});
}
}
the error i keep gettting is
org.jboss.arquillian.warp.impl.client.execution.WarpSynchronizationException: The Warp failed to observe requests or match them with response.
There were no requests matched by observer [containsHeader('faces-request')]
If Warp enriched a wrong request, use observe(...) method to select appropriate request which should be enriched instead.
Otherwise check the server-side log and enable Arquillian debugging mode on both, test and server VM by passing -Darquillian.debug=true.
at org.jboss.arquillian.warp.impl.client.execution.SynchronizationPoint.awaitResponses(SynchronizationPoint.java:155)
at org.jboss.arquillian.warp.impl.client.execution.DefaultExecutionSynchronizer.waitForResponse(DefaultExecutionSynchronizer.java:60)
at org.jboss.arquillian.warp.impl.client.execution.WarpExecutionObserver.awaitResponse(WarpExecutionObserver.java:64)
any help will be welcomed or an alternative way of validating a jsf viewscope bean during integration testing
I was able to sort out it was not working and able to create a sample project for future reference if anyone comes by the same problem
Testing using arquillian warp example

how to pause and resume a download in javafx

I am building a download manager in javafx
I have added function to download button which initialises new task.More than one download is also being executed properly.
But I need to add pause and resume function. Please tell how to implement it using executor. Through execute function of Executors, task is being started but how do i pause & then resume it??
Below I am showing relevant portions of my code. Please tell if you need more details. thanks.
Main class
public class Controller implements Initializable {
public Button addDownloadButton;
public Button pauseResumeButton;
public TextField urlTextBox;
public TableView<DownloadEntry> downloadsTable;
ExecutorService executor;
#Override
public void initialize(URL location, ResourceBundle resources) {
// here tableview and table columns are initialised and cellValueFactory is set
executor = Executors.newFixedThreadPool(4);
}
public void addDownloadButtonClicked() {
DownloadEntry task = new DownloadEntry(new URL(urlTextBox.getText()));
downloadsTable.getItems().add(task);
executor.execute(task);
}
public void pauseResumeButtonClicked() {
//CODE FOR PAUSE AND RESUME
}
}
DownloadEntry.java
public class DownloadEntry extends Task<Void> {
public URL url;
public int downloaded;
final int MAX_BUFFER_SIZE=50*1024;
private String status;
//Constructor
public DownloadEntry(URL ur) throws Exception{
url = ur;
//other variables are initialised here
this.updateMessage("Downloading");
}
#Override
protected Void call() {
file = new RandomAccessFile(filename, "rw");
file.seek(downloaded);
stream = con.getInputStream();
while (status.equals("Downloading")) {
byte buffer=new byte[MAX_BUFFER_SIZE];
int c=stream.read(buffer);
if (c==-1){
break;
}
file.write(buffer,0,c);
downloaded += c;
status = "Downloading";
}
if (status.equals("Downloading")) {
status = "Complete";
updateMessage("Complete");
}
return null;
}
}
You may be interested in Concurrency in JavaFX.
I guess you should also have a look at pattern Observer.
By the way I think you should not use constant string as a status ("Downloading", etc), creating an enum would be a better approach.
In your loop, around the read/write part, there should be a synchronization mechanism, controlled by your pause/resume buttons (see the two links).

How can i call dynamic object like a function?

I am studying orchard architecture.i have faced with a strange concept in display management section.
in Partial view page there is a 'function call like' syntax like so Display(Model.Head). that is not a function thought, it is a dynamic object defined in orchard WebViewPage.
I am wondering how to define a dynamic object so that you can call it (and pass it an argument as well) like a function as i mentioned.
thanks in advance.
A lighter weight way to do it without clay would be to subclass the built-in DynamicObject class.
public static dynamic Display;
void Main()
{
Display = new MyCallableObject();
//this is what i was after
Console.Write(Display("bla bla bla"));
}
public class MyCallableObject:DynamicObject
{
public override bool TryInvoke(InvokeBinder binder, object[] args, out Object result)
{
result = string.Format("This is response for {0}",args.FirstOrDefault());
return true;
}
}
I finally found it my self!
all the operations have done with Clay Library behind the scene.i have wrote a sample console app for demonstrating the process.
class Program
{
static void Main(string[] args)
{
Display = ClayActivator.CreateInstance<MyResponser>(new List<IClayBehavior> {new MyFunctionCallBehavior()});
//this is what i was after
Console.Write(Display("bla bla bla"));
}
public static dynamic Display;
}
public class MyFunctionCallBehavior : IClayBehavior
{
public object InvokeMember(Func<object> proceed, object self, string name, INamedEnumerable<object> args)
{
return ((MyResponser)self).ResponseForRequest(args.FirstOrDefault().ToString());
}
}
public class MyResponser
{
public string ResponseForRequest(string param)
{
return string.Format("This is response for {0}",param);
}
}

I want to display an PNG image using J2ME MIDlet classes on blackberry device

I am trying to display a PNG image on blackberry device for OS 5.0 using J2ME MIDlet class instead of a blackberry RIMlet class. Can I use J2ME MIDlet instead of RIMlets? Would it be compatible with blackberry as blackberry do support J2ME? Can I get the image from it?
To display an image on the screen of a BlackBerry® device, create an Image object and populate it by calling the static Image.createImage() method. Provide the location of the image as a parameter.
refer display an PNG image using J2ME MIDlet classes on blackberry device
Can i use J2ME MIDlet instead of RIMlets...
YES, but there are certain advantages like mentioned here.
and if you want to go with MIDlet, here is an example using ImageItem,
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class ImageItemMIDlet extends MIDlet implements CommandListener{
private Command exit;
private ImageItem imageItem;
private Image image;
private Display display;
private Form form;
public ImageItemMIDlet(){
try{
image = Image.createImage("/yourImage.png");
} catch (Exception e){ }
imageItem = new ImageItem("This is the IMAGE_ITEM Application",
image, ImageItem.LAYOUT_DEFAULT, "image");
}
public void startApp(){
form = new Form("ImageItem Example");
display = Display.getDisplay(this);
exit = new Command("Exit", Command.EXIT, 1);
form.append(imageItem);
form.addCommand(exit);
form.setCommandListener(this);
display.setCurrent(form);
}
public void pauseApp(){}
public void destroyApp(boolean unconditional){
notifyDestroyed();
}
public void commandAction(Command c, Displayable d){
String label = c.getLabel();
if(label.equals("Exit")){
destroyApp(true);
}
}
}
public class Midlet extends MIDlet {
public Display display;
public void startApp() {
Canvas obj = new DrawImage();
display = Display.getDisplay(this);
display.setCurrent(obj);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public class DrawImage extends Canvas{
int width = getWidth();
int height = getHeight();
protected void paint(Graphics g) {
try {
System.out.println("111111");
Image image = Image.createImage("/Waterfall.png");
if(image != null)
g.drawImage(image, 0, 0, Graphics.TOP | Graphics.LEFT);
else
System.out.println("2222");
} catch (IOException ex) {
System.out.println(ex);
}
}
}
}
Its good to use Midlet with canvas to show on canvas because if you use Midlet with Form then its show image but its also showing the theme of mobile in background of form. If you use canvas you can use also background image for your front image.
Thanks

Resources