mardi 4 août 2015

Java passing className + object to generic method

So I'm complete lost in the part of generic method's. In Android java I want a MyDownloadHelper for downloading my JSON data which will be returned next. Got this working in 2 seperate files with different class/object-names. However, I can't get this thing to work dynamicly. This is my current source.

The current situation will let me call the MySQLiteHelper.getRecipients(); in another activity and will me return the correct data. I am also using 2 classes (Pakbon, Recipient) for setting the correct data.

I think I'm pretty close to the solution but i really need a blow in the right direction. Thanks in advantage.

public class MyDownloadHelper {

private static final int timeout = 10000;
private  Class<? extends Object[]> cls;
private static final String API_SERVER = "http://www.***.nl/json/";
private Object[] obj;

public MyDownloadHelper(){
}

protected Recipient[] getRecipients() {
    try {
        //Recipient[] recipients = getInstance(Recipient[].class);
        Recipient[] recipients   = this.download(Recipient[].class, API_SERVER + "getRecipients");
        return recipients;
    } finally {
        return null;
    }
}

protected Pakbon[] getPackingSlips() {
    try {
        Pakbon[] pakbon = this.download(Pakbon[].class, API_SERVER + "getPackingSlips");
        return pakbon;
    } finally {
        return null;
    }
}

private <T> Object[] download(Class<T> a, String url){
    HttpURLConnection c = null;

    try {
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setRequestProperty("Content-length", "0");
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        c.setConnectTimeout(timeout);
        c.setReadTimeout(timeout);
        c.connect();
        int status = c.getResponseCode();

        switch (status) {
            case 200:
            case 201:
                Gson gson = new Gson();
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));

                Object[] objectData = gson.fromJson(br, a);
                return gson.fromJson(br, cls);

        }
    } catch (IOException ex) {

    } finally{
        if (c != null) {
            try {
                c.disconnect();
            } catch (Exception ex) {
                Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
            }
        }
    }



    return null;

}

}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire