ANDROID JSON OKUMA VE LISTVIEW GÖSTERİMİ


Sizlerle örnek bir proje paylaşmak istiyorum. Github a commitlenmiş projeyi indirebilirsiniz.


Okuma yapılacak olan JSON aşağıdaki gibidir.

{"fixtures":[{"id":-1,"date":"2015-10-05Tdk 90+:00Z","homeTeam":"Duisburg","awayTeam":"Paderborn","goalsHomeTeam":2,"goalsAwayTeam":0,"description":" GOAL! Duisburg GOAL! Duisburg","lat":51.4344079,"lng":6.762329299999999}]}

ilk iş olarak AndroidManifest.xml ine


   <uses-permission android:name="android.permission.INTERNET" />
   <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

 Internet ve network accesine açıyoruz.  

activity_main.xml

 <RelativeLayout 

xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidlistviewwithjson.MainActivity">

       <ListView
             android:id="@+id/list"
             android:layout_width="fill_parent"
             android:layout_height="fill_parent" />
      
</RelativeLayout>



bu kısımda ListView eklememizi yaptık.
Mylist.xml

<xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

       <LinearLayout
    android:layout_weight="50"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >
   
    <ImageView
        android:id="@+id/icon"
        android:layout_width="60dp"
        android:layout_height="60dp"
       android:padding="5dp" />
 
     <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >
       
     <TextView
        android:id="@+id/item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="3dp"
        android:padding="2dp"
        android:textColor="#33CC33" />
    
       <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:layout_marginLeft="5dp"/>
   
      </LinearLayout>
   </LinearLayout>
  
 <LinearLayout
    android:layout_weight="50"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >
       
    <ImageView
        android:id="@+id/icon2"
        android:layout_width="30dp"
        android:layout_height="30dp"
       android:padding="3dp" />
      
      <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
   
    <TextView
        android:id="@+id/item2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="5dp"
        android:padding="1dp"
        android:textColor="#33CC33" />
    
     <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:layout_marginLeft="5dp"/>
   
    </LinearLayout>

      </LinearLayout>
   
</LinearLayout>



LinearLayout kullanarak Amblem koyabileceğimiz  ImageView ile Ev Sahibi ve Deplasman takım isimleri ve skorların yerleştirileceği kısımlar ekleniyor. 

package com.example.androidlistviewwithjson;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;




import com.example.androidlistviewwithjson.model.Match;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {

CustomListAdapter adapter;


ListView list;


List matches = new ArrayList();
  ListView listView;

HttpAsyncTask task;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

task = new HttpAsyncTask(this);
task.execute("fixtures.json");


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

final Handler handler = new Handler();
        TimerTask doAsynchronousTask = new TimerTask() {
            @Override
            public void run() {
            handler.post(new Runnable() {
                    public void run() {
                   
                    task = new HttpAsyncTask();
                    task.execute("fixtures.json");
                   
                    }
                });
            }
        };
        Timer timer = new Timer();
        timer.schedule(doAsynchronousTask, 40000, 40000);

}




  private class HttpAsyncTask extends AsyncTask {
   
  List matches = new ArrayList();
  Activity act;

   public HttpAsyncTask(Activity act) {
// TODO Auto-generated constructor stub
    this.act = act;

   }
 
   public HttpAsyncTask() {
}


  @Override
       protected String doInBackground(String... urls) {

           return GET(urls[0]);
       }
       // onPostExecute displays the results of the AsyncTask.
       @Override
       protected void onPostExecute(String result) {
           Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
       
           getJSON(result);
         
         
         
          if (adapter == null) {
          adapter=new CustomListAdapter(act, matches);
    list=(ListView)findViewById(R.id.list);
    list.setAdapter(adapter);
   
    list.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView parent, View view,
    int position, long id) {
   
                   
                     // ListView Clicked item value
                     Match  match    = (Match) listView.getItemAtPosition(position);
                     
   
   
    Toast.makeText(getApplicationContext(), match.getDescription(), Toast.LENGTH_SHORT).show();
   
    }
    });
          }
          else {
       
          adapter.clear();
          adapter.addAll(matches);
       
                   //notify that the model changed
                   adapter.notifyDataSetChanged();
       
          }
       
     
           //  etResponse.setText(result);
      }
     
     
       private void getJSON(String result) {
       
         try {
           
            JSONObject jsonObj = new JSONObject(result);
               
                 // Getting JSON Array node
                 JSONArray contacts = jsonObj.getJSONArray("fixtures");

                 List values = new ArrayList();
                 // looping through All Contacts
                 for (int i = 0; i < contacts.length(); i++) {
                     JSONObject c = contacts.getJSONObject(i);
                   
                     String homeTeam = c.getString("homeTeam");
                     String awayTeam = c.getString("awayTeam");
                     String goalsHomeTeam = c.getString("goalsHomeTeam");
                     String goalsAwayTeam = c.getString("goalsAwayTeam");
                     String matchDescription = c.getString("description");
                   
                     Match m = new Match();
                     m.setHomeTeam(homeTeam);
                     m.setAwayTeam(awayTeam);
                     m.setHomeGoalTeam(goalsHomeTeam);
                     m.setAwayGoalTeam(goalsAwayTeam);
                     m.setDescription(matchDescription);
                   
                     matches.add(m);
                   
                 
                   
                   
                      }
               
       
               
         
               
               
         } catch (JSONException e) {
       
        Log.e("Exception", e.getMessage());
         }
       
          }
     
     
      public String GET(String url){
             InputStream inputStream = null;
             String result = "";
             try {
     
                 // create HttpClient
                 HttpClient httpclient = new DefaultHttpClient();
     
                 // make GET request to the given URL
                 HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
     
                 // receive response as inputStream
                 inputStream = httpResponse.getEntity().getContent();
     
                 // convert inputstream to string
                 if(inputStream != null)
                     result = convertInputStreamToString(inputStream);
                 else
                     result = "Did not work!";
     
             } catch (Exception e) {
                 Log.d("InputStream", e.getLocalizedMessage());
             }
     
             return result;
         }
     
      private  String convertInputStreamToString(InputStream inputStream) throws IOException{
             BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
             String line = "";
             String result = "";
             while((line = bufferedReader.readLine()) != null)
                 result += line;
     
             inputStream.close();
             return result;
     
         }
   }

}

40 sn de bir çalışan AsyncTask hazırlıyoruz. Bu task JSON u okuyup işleyecek. Akabinde matches değişkeninde saklayacak. Bu değişkeni gösterim yapmak üzere CustomListAdapter sınıfına gönderiyoruz.

package com.example.androidlistviewwithjson;

import java.util.List;

import com.example.androidlistviewwithjson.model.Match;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;



public class CustomListAdapter extends ArrayAdapter {

private final Activity context;
private List matches;

public CustomListAdapter(Activity context, List matches) {
super(context, R.layout.mylist, matches);
// TODO Auto-generated constructor stub
this.context=context;
this.matches = matches;


}



public View getView(int position,View view,ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.mylist, null,true);

TextView txtTitle = (TextView) rowView.findViewById(R.id.item);
TextView txtTitle2 = (TextView) rowView.findViewById(R.id.item2);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
ImageView imageView2 = (ImageView) rowView.findViewById(R.id.icon2);
TextView extratxt = (TextView) rowView.findViewById(R.id.textView1);
TextView extratxt2 = (TextView) rowView.findViewById(R.id.textView2);

Match m=matches.get(position);

txtTitle.setText(m.getHomeTeam());
txtTitle2.setText(m.getAwayTeam());
extratxt.setText(m.getHomeGoalTeam());
extratxt2.setText(m.getAwayGoalTeam());
return rowView;

};
}

İyi Çalışmalar.







Yorumlar

Bu blogdaki popüler yayınlar

IONIC BAŞLANGIÇ

Cannot resolve the collation conflict between “Turkish_CI_AS” and “SQL_Latin1_General_CP1_CI_AS” in the equal to operation

Golang working with interfaces and functions -3