mardi 4 août 2015

Cache Images with Volley

I'm trying to implement Image Caching into my app. The code i currently have regarding the images is below:

Network call to get images:

public void getImage(String url, final ImageView imageView) {

    System.out.println("Image Url is: " + url);
    ImageRequest requestImage = new ImageRequest(url, new Response.Listener<Bitmap>() {
        @Override
        public void onResponse(Bitmap response) {
            imageView.setImageBitmap(response);
        }
    }, 0, 0, null, null);

    queue.add(requestImage);
}

How could I implement the caching? I have read a few articles on SO, but am not sure on how to implement it into my app?

Thanks for your help



via Chebli Mohamed

Append the result of a left join to an entity field

I would like to append the result of a left join to an entity field. In SQL it would be this query:

SELECT * FROM thethreads t
LEFT JOIN thread_votes tv
ON t.idthread=tv.thread
AND tv.from_user like "test2";

Then I'd have a column in my Thethread entity I can populate with the left join information. I don't know how to do that.

The rest of the information is to illustrate what I want to do :

At the moment I've those two entities called "Thethread" and "ThreadVote". Each "TheThread" has a bunch of "ThreadVote" (which correspond to up votes or down votes from users, an user can have only one thread vote by thread (-1 or +1, like on StackOverflow). Anyway, I want to know if an user has already voted so I can paint the up vote or down vote arrow (like stackoverflow again). What I'm doing at the moment is inefficient: I'm getting a TheThread List and then I'm checking within that list if a vote by the current user exists. I would like to have everything done within the EJB where I make the JPA queries. I would like something like this :

private static final String SELECT_NEWEST_THREADS = "Select t From Thethread t LEFT JOIN ThreadVote tv ON t.idthread=tv.thread AND tv.user1 like :currentUser ORDER BY t.datePosted";
@Override
public List<Thethread> giveNewestThread(int amount, int page,
        String currentUser) {
    Query query = em.createQuery(SELECT_NEWEST_THREADS);
    query.setParameter("currentUser", currentUser);
    query.setMaxResults(amount);
    List<Object[]> temp = query.getResultList();
    List<Thethread> threadList = new ArrayList<Thethread>();
    for (Object[] o : temp) {
        Thethread thread = (Thethread) o[0];
        thread.setThreadcurrentUserVote((ThreadVote) o[1]);
        threadList.add(thread);
    }
    return threadList;
}

This gives me an Exception :

Exception Description: Object comparisons can only be used with OneToOneMappings.  Other mapping comparisons must be done through query keys or direct attribute level comparisons. 
Mapping: [org.eclipse.persistence.mappings.DirectToFieldMapping[idthread-->thethreads.IDTHREAD]] 

with the entities :

@Entity
@Table(name = "thethreads")
@NamedQuery(name = "Thethread.findAll", query = "SELECT t FROM Thethread t")
public class Thethread implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    private int idthread;
    private String content;
    private int downvotes;    
    private int upvotes; 
    // bi-directional many-to-one association to User
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "posted_by")
    private User user;
    // bi-directional many-to-one association to ThreadVote
    @OneToMany(mappedBy = "thethread")
    private List<ThreadVote> threadVotes;
    @Transient 
    privateThreadVote currentUserVote;
    //...
}

ThreadVote entity:

@Entity
@Table(name = "thread_votes")
@NamedQuery(name = "ThreadVote.findAll", query = "SELECT t FROM ThreadVote t")
public class ThreadVote implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "id_votes_thread")
    private int idVotesThread;
    private int vote;
    // bi-directional many-to-one association to Thethread
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "thread")
    private Thethread thethread;
    // bi-directional many-to-one association to User
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "from_user")
    private User user1;
    // bi-directional many-to-one association to User
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "to_user")
    private User user2;
    //...
}

I other words I would like to remove this ForumThread class and have everything queried and get the result in the entity Thethread.



via Chebli Mohamed

netbeans plugin run method but not when action event fire

i started netbeans plugin development with this basic tutorial . and i modyfied it to get the text of current edited file.

so i created a action class which extends ActionListener .so when i click the icon of my plugin from toolbar it open dialog and show content.but it repeats .when i close another one open then another dialog so on..

i think this is because i add property each time listener when i click the button .so how can i fix this ..

this is the code i used

public final class SomeAction implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        PropertyChangeListener l = new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                JTextComponent jtc = EditorRegistry.lastFocusedComponent();
                if (jtc != null) {
                    Document d = jtc.getDocument();
                    int msgType = NotifyDescriptor.INFORMATION_MESSAGE;
                    NotifyDescriptor df;
                    try {
                        df = new NotifyDescriptor.Message(d.getText(0, d.getLength() - 1), msgType);
                        DialogDisplayer.getDefault().notify(df);
                    } catch (BadLocationException ex) {
                        Exceptions.printStackTrace(ex);
                    }

                }
            }
        };

        EditorRegistry.addPropertyChangeListener(l);  // i guess here is the problem but i couldn't able to find where should i put this line 

    }



via Chebli Mohamed

When I do not use from a condition I can get the data from php, But when I use from a condition, I Can not get data from php

My php code is correct. But I have a strange problem when I use a condition in my code. My php code sends the "A" string from server to android. In the following code when I do not use a condition in my code in the GetText() method, I can get the A string and display it in the TextView well. But when I use a condition as follows, I can not get and display the A string in the TextView . Please help me. I do not know that where is this problem.

Pass = pass.getText().toString();

// Create data variable for sent values to server

String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(Name, "UTF-8");
    data += "&" + URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(Email, "UTF-8");
    data += "&" + URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(Login, "UTF-8");
    data += "&" + URLEncoder.encode("pass", "UTF-8") + "=" + URLEncoder.encode(Pass, "UTF-8");

String text = "";
BufferedReader reader = null;

// Send data
try{
   // Defined URL  where to send data
   URL url = new URL("http://ift.tt/1VTwxEV");

   // Send POST data request
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   conn.setDoOutput(true);
   conn.setRequestMethod("POST");
   OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
   wr.write(data);
   wr.flush();

   // Get the server response

   reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
   StringBuilder sb = new StringBuilder();
   String line = null;

   // Read Server Response
   while((line = reader.readLine()) != null){
       // Append server response in string
       sb.append(line);
    }

    text = sb.toString();
} catch(Exception ex){

} finally{
    try{
        reader.close();
    } catch(Exception ex){}
}

// Show response on activity
String A = "A";

if(text.equals(A)){
    content.setText(text); //it can not display the text in the TextView
}

}



via Chebli Mohamed

Displaying key-values in HashMap

I have 2 questions regarding the code bellow,

1.I have the key "two" twice in my hashmap, while printing, "two" is displayed only once.Why its not displaying "two" twice?

2.How to selectively display the key "two"?

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class main {
public static void main(String[] args){
HashMap<String,String> myMap = new HashMap<String,String>();

    myMap.put("one", "1");
    myMap.put("two", "2");
    myMap.put("three", "3");
    myMap.put("two", "4");

    Set <String> mySet =myMap.keySet();
    Iterator itr = mySet.iterator();

    while(itr.hasNext()){
        String key = (String) itr.next();
        System.out.println(key);
    }

}
}



via Chebli Mohamed

Calling many methods of many objects many times per second

I have a structure like that

  abstract Class Entity {
    //some variables... 
    //some methods ...
    public abstract void render(Graphics g);
    }

Thats the parent ..Now I have 3 children..

Class A extends Entity{}
Class B extends Entity{}
Class C extends Entity{} 

Every class has some different stuff do render .One is for example drawing yellow circle , second green text and the third is displaying image.

But ... there is a thing.

Class A have List<B>... 
Class B have List<C>... 

One Entity has for example 10 Bs ... and each B has 20 Cs ... So now .. I have a render method that renders 60x per second.. And I have to call every render method from every object.

So I have something like this

for(A a : listOfAs){
   for(B b : listOfBs){
      for(C c : listOfCs){
         c.render(g);
      }b.render(g);
   }a.render(g);
}

Now if you imagine I have much more objects like that and I call this method 60x per second ... I find this really ...really bad practice.. I don't know how to solve this better or so... I don't think that this for each loop is actually the best solution or not. Anyone any ideas ?

I was thinking about implementing the child like that :

Entity x = new A(); ... 
Entity y = new B(); ... 

and so but some of the classes have other methods that have to be looped like that and I cannot call them from parent.

For the render method ... Just stick to the fact that you have to loop something many times in a short period of time for a long time.

I cannot progress through this ... I got stuck here for a long time and I am not sure how to solve this.



via Chebli Mohamed

jar not launching - UnsatisfiedLinkError

I have exported my java project into a jar in my desktop (chose the option that creates a project.jar and a project_lib).

When I run java -jar project.jar on cmd, I get this exception:

    Exception in thread "main" java.lang.RuntimeException: Application launch error
    at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:122)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.UnsatisfiedLinkError: com.sun.glass.ui.win.WinApplication._invokeLater(Ljava/lang/Runnable;)V
    at com.sun.glass.ui.win.WinApplication._invokeLater(Native Method)
    at com.sun.glass.ui.Application.invokeLater(Application.java:338)
    at com.sun.javafx.tk.quantum.QuantumToolkit.defer(QuantumToolkit.java:620)
    at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:173)
    at com.sun.javafx.application.PlatformImpl.runAndWait(PlatformImpl.java:212)
    at com.sun.javafx.application.PlatformImpl.tkExit(PlatformImpl.java:320)
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:421)
    at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:47)
    at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:115)
    ... 1 more

I guess it is probably caused by my project's paths but I don't know how to fix this.



via Chebli Mohamed