Soru & Cevap

JSON Parse ile Farklı URL leri Çağırmak

01.02.2014 - 07:03

Merhaba;

Bir yayın akışı sayfası hazırlıyorum. Bunun için her güne bir button atadım. Yapmak istedigim her button da farklı bir güne ait url yi çağırmak. bunu nasıl gerçekleştirebilirim.

Yayın Akışı Sınıfı:

[code]package com.denemeservis;


import java.util.ArrayList;
import java.util.HashMap;

 

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;

import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class YayinAkisi extends Activity {

    private ListView list;
    private TextView ver;
    private TextView name;
    private TextView api;

    private Button btnYayinakisidiger;
    private Button btnYayinakisimesaj;
    private Button btnYayinakisikamera;

    private Button pzt;
    private Button sal;
    private Button crs;
    private Button prs;
    private Button cum;
    private Button cmt;
    private Button pzr;

    ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();

    // url yi çagıralım
    private static String url[] = { "http://api.learn2crack.com/android/jsonos/" };

    // json tag isimleri
    private static final String TAG_OS = "android";
    private static final String TAG_VER = "ver";
    private static final String TAG_NAME = "name";
    private static final String TAG_API = "api";

    JSONArray android = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yayin_akisi);
        oslist = new ArrayList<HashMap<String, String>>();

        btnYayinakisidiger = (Button) findViewById(R.id.button1);
        btnYayinakisidiger.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent radyo = new Intent(getApplicationContext(),
                        DigerRadyo.class);
                startActivity(radyo);
            }
        });

        btnYayinakisimesaj = (Button) findViewById(R.id.button2);
        btnYayinakisimesaj.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent mesaj = new Intent(getApplicationContext(),
                        MesajGonder.class);
                startActivity(mesaj);
            }
        });

        btnYayinakisikamera = (Button) findViewById(R.id.button3);
        btnYayinakisikamera.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent kamera = new Intent(getApplicationContext(),
                        Kamera.class);
                startActivity(kamera);
            }
        });

        pzt = (Button) findViewById(R.id.button4);
        pzt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                new JSONParse().execute(url[0]);

            }
        });

        sal = (Button) findViewById(R.id.button5);
        sal.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                new JSONParse().execute(url[0]);

            }
        });

        crs = (Button) findViewById(R.id.button6);
        crs.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                new JSONParse().execute(url[0]);

            }
        });

        prs = (Button) findViewById(R.id.button7);
        prs.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                new JSONParse().execute(url[0]);

            }
        });

        cum = (Button) findViewById(R.id.button8);
        cum.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                new JSONParse().execute(url[0]);

            }
        });

        cmt = (Button) findViewById(R.id.button9);
        cmt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                new JSONParse().execute(url[0]);

            }
        });

        pzr = (Button) findViewById(R.id.button10);
        pzr.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                new JSONParse().execute(url[0]);

            }
        });

    }

    private class JSONParse extends AsyncTask<String, String, JSONObject> {
        private ProgressDialog pDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            ver = (TextView) findViewById(R.id.vers);
            name = (TextView) findViewById(R.id.name);
            api = (TextView) findViewById(R.id.api);
            pDialog = new ProgressDialog(YayinAkisi.this);
            pDialog.setMessage("Yayın Akışı Alınıyor ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();

        }

        @Override
        protected JSONObject doInBackground(String... args) {

            JSONParser jParser = new JSONParser();

            // Getting JSON from URL
            JSONObject json = jParser.getJSONFromUrl(url[0]);
            return json;
        }

        @Override
        protected void onPostExecute(JSONObject json) {
            pDialog.dismiss();
            try {
                android = json.getJSONArray(TAG_OS);
                oslist.clear();
                for (int i = 0; i < android.length(); i++) {

                    JSONObject c = android.getJSONObject(i);

                    // Storing JSON item in a Variable
                    String ver = c.getString(TAG_VER);
                    String name = c.getString(TAG_NAME);
                    String api = c.getString(TAG_API);

                    // Adding value HashMap key => value
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put(TAG_VER, ver);
                    map.put(TAG_NAME, name);
                    map.put(TAG_API, api);

                    oslist.add(map);
                }

                list = (ListView) findViewById(R.id.listViewYayin);

                ListAdapter adapter = new SimpleAdapter(YayinAkisi.this,
                        oslist,

                        R.layout.list_v,

                        new String[] { TAG_VER, TAG_NAME, TAG_API }, new int[] {
                                R.id.vers, R.id.name, R.id.api });

                list.setAdapter(adapter);
                list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {
                    }
                });

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }[/code]

JSON Parser Sınıfı :

[code]package com.denemeservis;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();            

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}[/code]

 

Teşekkürler

102 Görüntülenme

1 Cevap

Sitedeki sorulara cevap verebilmek için giriş yapın ya da üye olun.

picture-3606-1408610132.jpg
cgural
02.02.2014 - 04:35

Sizdeki sınıf tasarımı üzerinden gidecek olsam 

-url isimli String diziye sözünü ettiğiniz diğer URL'leri eklerdim

-Her Button'a özel oluşturduğum anonim OnClickListener içinde, url[]'deki uygun öğeyi uygun indisi kullanarak  parametre şeklinde JsonParse isimli AsyncTask'a geçirirdim.

-JsonParse AsyncTask'inin doInBackground metodunun içinde kesinlikle parametre olarak gelen args değişkeninden faydalanırdım, url[0]'dan değil.

Şurada kodun sadece değişen kısımlarını bir araya koymaya çalıştım: https://gist.github.com/caner/8769250