Hüseyin Çelik Blog Sayfasi

.Net, Java, Android, Progress 4gl Paylasimlarim

Android json kullanim örnegi

Merhaba uzun zamandir android üzerine yazi yazmak istiyordum. Zaman sikintisindan bir türlü firsat olmadi. Son projemde kullandigim bir java class'ini paylasmak istiyorum.

public class servisClient<T extends jsonSerilizeble> {

    public servisClient() {

    }

    servisParam param;
    servisListener listener;
    String strError;
    String strLoading = "Sunucuya baglaniliyor ...";

    private static HttpClient httpClient = new DefaultHttpClient();
    private static Gson gson = new Gson();

    public JSONObject callMetod() {
        try {

            HttpResponse response = null;
            HttpPost httpRequest = new HttpPost(sporcuConfig.getServisUrl() + param.getUrl());

            if (statics.getLogin() != null) {
                StringEntity se;

                loginParam prm = statics.getLogin().clone();
                prm.setResim("");

                baseParam metodParam = new baseParam();
                metodParam
                        .setUser(prm);
                metodParam.setList(param.getEntity());


                se = new StringEntity(gson.toJson(metodParam));

                httpRequest.setEntity(se);
            }

            httpRequest.setHeader("Accept", "application/json");
            httpRequest.setHeader("Content-type", "application/json");
            httpRequest.setHeader("Accept-Encoding", "gzip"); //for gzip compression

            response = (HttpResponse) httpClient.execute(httpRequest);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream in = entity.getContent();
                Header contentEncoding = response.getFirstHeader("Content-Encoding");
                //if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                if (contentEncoding != null && contentEncoding.getValue().indexOf("gzip") != -1) {
                    in = new GZIPInputStream(in);
                }
                //in.close();
                String resultString = streamToString(in);
                return new JSONObject(resultString);
            }

        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), e.getMessage());
            try {
                JSONObject object = new JSONObject();
                object.put("status", false);
                object.put("mesaj", e.getMessage());
                object.put("resim", e.getMessage());
                return object;
            } catch (Exception x) {
                x.printStackTrace();
            }

        }
        return null;
    }

    public void doRequest(final Class<T> cls) {

        final ProgressDialog dialog = ProgressDialog.show(statics.getCurrentActivity(), "Bekleyin", strLoading, true);

        new Thread(new Runnable() {

            T result = null;

            Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    if (dialog != null)
                        dialog.dismiss();

                    int status = 0;
                    String string = "";
                    if (msg != null) {
                        status = msg.getData().getInt("status");
                        string = msg.getData().getString("mesaj");
                    }

                    if (status == 0) {
                        if (listener != null)
                            listener.onError(this, string);
                    } else {
                        if (listener != null)
                            listener.onEnd(this, result);
                    }
                }
            };

            public void run() {
                try {

                    JSONObject resultObj = callMetod();
                    if (resultObj != null) {

                        //Class fooClass = Class.forName(cls.getName());
                        //fooClass.newInstance();

                        //Constructor[] constructors = cls.getConstructors();

                        //Constructor constructor = cls.getConstructor(JSONObject.class);
                        //result = (T) constructor.newInstance(resultObj);

                        result = cls.newInstance();
                        result.setJSONObject(resultObj);
                    }

                    handler.sendMessage(getMessage(1, ""));

                } catch (Exception e) {
                    Log.e(getClass().getSimpleName(), e.getMessage());
                    handler.sendMessage(getMessage(0, e.getMessage()));
                }
            }
        }).start();
    }

    private Message getMessage(int status, String mesaj) {
        Message m = new Message();
        Bundle b = new Bundle();
        b.putInt("status", status);
        b.putString("mesaj", mesaj);
        m.setData(b);
        return m;
    }

    private static String streamToString(InputStream is) {
        //create a new BufferedReader for the input stream
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        //create a new StringBuilder to append the lines
        StringBuilder sb = new StringBuilder();

        //initialize an empty string
        String line = null;

        try {
            //iterate as long as there is still lines to be read
            while ((line = reader.readLine()) != null) {
                //append the line and a newline character to our StringBuilder
                sb.append(line + "\n");
            }
        }
        //catch an IOException and print it
        catch (IOException e) {
            e.printStackTrace();
        }
        //close the stream when we're done
        finally {
            try {
                is.close();
            }
            //catch and print an exception if it's thrown
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        //return the stream converted to a string
        return sb.toString();
    }

    public void setParam(servisParam p) {
        param = p;
    }

    public void setListener(servisListener l) {
        listener = l;
    }

    public void setLoadingString(String str) {
        strLoading = str;
    }
}

 

Loading