Son Forum Aktiviteleri

1
Tümünü Gör

Json listview doldurma sorunu

Sorunumuz şu; listview'e json ile verileri parse edip alıyoruz yukarı bölümde olusturdugumuz search bar'ında arama yaptığımız zaman loga dogru sonucu vermesine rağmen listview'i yanlış şekilde dolduruyor. Örneğin; listview 5 veriyle başlangıcta doluyor arama yerine istediğimiz şeyi yazdıktan sonra mesela 1 sonuc buluyor. 1 sonuç bulduğunu loga doğru şekilde 1 olarak yazıyor fakat listview'de 1 tane sadece o veriyi getirmesi gerekirken daha önce olusturgu 5 verili listview'in tüm yerlerini buldugu 1 veriyle dolduruyor.

Bu sorunu nasıl çözebiliriz.

Kodumuz aşağıdaki şekilde. listview oluşturmakta sıkıntı olmadığı için xml'i yazmadım.

 

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.util.LangUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.app.Activity;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class restorantAltSayfa extends ListActivity {
    
    ListView listView;
     ArrayList<String> x = new ArrayList<String>();
     ArrayList<String> y = new ArrayList<String>();
     ArrayList<String> z = new ArrayList<String>();
     ArrayList<String> t = new ArrayList<String>();
     ArrayList<String> aramaVerileri = new ArrayList<String>();
     ArrayList<String> values = new ArrayList<String>();
     ArrayList<String> sonuclar = new ArrayList<String>();
     ArrayList<String> phoneArray = new ArrayList<String>();
     ArrayList<String> addressArray = new ArrayList<String>();
     public static String a="";
     public static String b="";
     public static String c="";
     public static String d=""; 
     public static String e="";
     public static boolean kontrol = false;
     public int sayac;
     public static HashMap<String, Object> searchHM = new HashMap<String, Object>();
     public static String strUrl = "http://www.bervamimarlik.com/restorant.php";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.restorant_altsayfa);    
                
        // URL to the JSON data         
        //String strUrl = "http://www.bervamimarlik.com/restorant.php";
        
        // Creating a new non-ui thread task to download json data 
        DownloadTask downloadTask = new DownloadTask();

        // Starting the download process
        downloadTask.execute(strUrl);
        
        // Getting a reference to ListView of activity_main
        listView = (ListView) findViewById(android.R.id.list);
        
        ListView lv = getListView();
        lv.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                    // getting values from selected ListItem
                    
                    String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
                    String phone = ((TextView) view.findViewById(R.id.phone)).getText().toString();
                    
                    döngü:for(int counter = 0; counter<sayac; counter++){
                        
                        if(name.equals(x.get(counter))){
                            a=y.get(counter); 
                            b=z.get(counter);
                            c=t.get(counter);
                            break döngü;
                        }
                    }
                    // Starting single contact activity
                    Intent in = new Intent(getApplicationContext(),
                            SingleContactActivity.class);
                    in.putExtra("Name", name);
                    in.putExtra("Phone", phone); 
                    in.putExtra("Description", a);
                    in.putExtra("Image", b);
                    in.putExtra("coordinate", c);
                    startActivity(in);

                }
            });
    Button buttonSearch =(Button)findViewById(R.id.button1);
    buttonSearch.setOnClickListener(new View.OnClickListener() {
        
        @Override
        public void onClick(View v) {
            EditText edt = (EditText)findViewById(R.id.editText1);
            String labelData = edt.getText().toString();//casita
            
            search: for(int i= 0; i<sayac; i++){
            d = aramaVerileri.get(i); //casita/taksim/restorant
            String[] sonuc = d.split("/"); //casita taksim restorant
            for(int say=0; say<sonuc.length; say++){
                String part = sonuc[say];  //casita
                if(part.equals(labelData)){ 
                    e=y.get(i);           //30001
                    sonuclar.add(e); //30001 i sonuclara ekle
                    continue search;
                    
                }//end if
                
            }//end inner for
            
        }//end out for
    
            String bulunanId = "";
            String eslenenId = "";
            String eslenenName = "";
            String eslenenImage = "";
            String eslenenPhone = "";
            String eslenenAddress = "";
             for(int sayBeni = 0; sayBeni<sonuclar.size(); sayBeni++){
                bulunanId = sonuclar.get(sayBeni);//30001
                loop:for(int sayBeniInner =0; sayBeniInner<sayac; sayBeniInner++){
                    eslenenId = y.get(sayBeniInner);
                    if(eslenenId.equals(bulunanId)){
                        eslenenName = x.get(sayBeniInner);
                        eslenenImage = z.get(sayBeniInner);
                        eslenenPhone = phoneArray.get(sayBeniInner);
                        eslenenAddress = addressArray.get(sayBeniInner);
                        
                        searchHM.put("Name", eslenenName);
                        searchHM.put("image", R.drawable.appicon);
                        searchHM.put("image_path", eslenenImage);
                        searchHM.put("Phone", eslenenPhone);
                        searchHM.put("Address", eslenenAddress);
                        Log.w("BULDUUUUU", eslenenName);
                        
                        break loop;
                    }//end if
                }//end inner for
            }// end out for
                 
            kontrol=true;
            listView.setAdapter(null);
            DownloadTask downloadTask = new DownloadTask();
            downloadTask.execute(strUrl);
    }//end onClick
});
    
    
    }
    

    
    /** A method to download json data from url */
    private String downloadUrl(String strUrl) throws IOException{
        String data = "";
        InputStream iStream = null;
        try{
                URL url = new URL(strUrl);
    
                // Creating an http connection to communicate with url 
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                // Connecting to url 
                urlConnection.connect();

                // Reading data from url 
                iStream = urlConnection.getInputStream();
                
                BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
                
                StringBuffer sb  = new StringBuffer();
                
                String line = "";
                while( ( line = br.readLine())  != null){
                    sb.append(line);
                }
                
                data = sb.toString();
                
                br.close();

        }catch(Exception e){
                Log.d("Exception while downloading url", e.toString());
        }finally{
                iStream.close();
        }

        return data;
    }

    
    
    /** AsyncTask to download json data */
    private class DownloadTask extends AsyncTask<String, Integer, String>{
        String data = null;
                @Override
                protected String doInBackground(String... url) {
                        try{
                            data = downloadUrl(url[0]);
                                
                        }catch(Exception e){
                            Log.d("Background Task",e.toString());
                        }
                        return data;
                }

                @Override
                protected void onPostExecute(String result) {
                    
                        // The parsing of the xml data is done in a non-ui thread 
                        ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
                        
                        // Start parsing xml data
                        listViewLoaderTask.execute(result);                        
                        
                }
    }
    
    /** AsyncTask to parse json data and load ListView */
    private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{

        JSONObject jObject;
        // Doing the parsing of xml data in a non-ui thread 
        @Override
        protected SimpleAdapter doInBackground(String... strJson) {
            try{
                jObject = new JSONObject(strJson[0]);
                CountryJSONParser countryJsonParser = new CountryJSONParser();
                countryJsonParser.parse(jObject);
            }catch(Exception e){
                Log.d("JSON Exception1",e.toString());
            }
            
            // Instantiating json parser class
            CountryJSONParser countryJsonParser = new CountryJSONParser();
            
            // A list object to store the parsed countries list
           List<HashMap<String, Object>> datas = null;
            
            try{
                // Getting the parsed data as a List construct
                
                datas = countryJsonParser.parse(jObject);
            }catch(Exception e){
                Log.d("Exception",e.toString());
            }           

            String[] from = { "Name","image","Phone", "Address","StarImage1","StarImage2","StarImage3","StarImage4","StarImage5"};
            int[] to = { R.id.name,R.id.imageView1,R.id.phone,R.id.adress,R.id.cost1,R.id.cost2,R.id.cost3,R.id.cost4,R.id.cost5};
            

            // Instantiating an adapter to store each items
            // R.layout.listview_layout defines the layout of each item     
            SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), datas, R.layout.list, from, to);  
            kontrol=false;
            return adapter;
        }
        
        /** Invoked by the Android on "doInBackground" is executed */
        @Override
        protected void onPostExecute(SimpleAdapter adapter) {
            
            // Setting adapter for the listview
        
                listView.setAdapter(null);
                adapter.notifyDataSetChanged();
                listView.setAdapter(adapter);
                
             
            
            for(int i=0;i<adapter.getCount();i++){
                HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
                String imgUrl = (String) hm.get("image_path");
                ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
                
                HashMap<String, Object> hmDownload = new HashMap<String, Object>();
                hm.put("image_path",imgUrl);
                hm.put("position", i);
                
                // Starting ImageLoaderTask to download and populate image in the listview 
                imageLoaderTask.execute(hm);
            }
        }        
    }
    
    /** AsyncTask to download and load an image in ListView */
    private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{

        @Override
        protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {
            
            InputStream iStream=null;
            String imgUrl = (String) hm[0].get("image_path");
            int position = (Integer) hm[0].get("position");
            
            URL url;
            try {
                url = new URL(imgUrl);
                
                // Creating an http connection to communicate with url
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                // Connecting to url                
                urlConnection.connect();

                // Reading data from url 
                iStream = urlConnection.getInputStream();
                
                // Getting Caching directory 
                File cacheDirectory = getBaseContext().getCacheDir();
                
                // Temporary file to store the downloaded image 
                File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");                
                       
                tmpFile.getParentFile().mkdirs();
                // The FileOutputStream to the temporary file
                FileOutputStream fOutStream = new FileOutputStream(tmpFile);
                
                // Creating a bitmap from the downloaded inputstream
                Bitmap b = BitmapFactory.decodeStream(iStream);                
                
                // Writing the bitmap to the temporary file as png file
                b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);                
                
                // Flush the FileOutputStream
                fOutStream.flush();
                
                //Close the FileOutputStream
                fOutStream.close();                
                
                // Create a hashmap object to store image path and its position in the listview
                HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
                
                // Storing the path to the temporary image file
                hmBitmap.put("image",tmpFile.getPath());
                
                // Storing the position of the image in the listview
                hmBitmap.put("position",position);                
                
                // Returning the HashMap object containing the image path and position
                return hmBitmap;                
                

            }catch (Exception e) {                
                e.printStackTrace();
            }
            return null;
        }
        
        @Override
        protected void onPostExecute(HashMap<String, Object> result) {
            // Getting the path to the downloaded image
            String path = (String) result.get("image");            
            
            // Getting the position of the downloaded image
            int position = (Integer) result.get("position");
            
            // Getting adapter of the listview
            SimpleAdapter adapter = (SimpleAdapter ) listView.getAdapter();
            
            // Getting the hashmap object at the specified position of the listview
            HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);    
            
            // Overwriting the existing path in the adapter 
            hm.put("image",path);
            
            // Noticing listview about the dataset changes
            adapter.notifyDataSetChanged();    
        }
    }

    
    //////////////////////////////////////////////
    
    
    public class CountryJSONParser {
        
        // Receives a JSONObject and returns a list
        public List<HashMap<String,Object>> parse(JSONObject jObject){        
            
            JSONArray jCountries = null;
            try {        
                // Retrieves all the elements in the 'countries' array 
                jCountries = jObject.getJSONArray("restorantTable");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            
             // Invoking getCountries with the array of json object
             // where each json object represent a country
            return getCountries(jCountries);
        }
        
        
        private List<HashMap<String, Object>> getCountries(JSONArray jCountries){
            int countryCount = jCountries.length();
            sayac = countryCount;
            List<HashMap<String, Object>> countryList = new ArrayList<HashMap<String,Object>>();
            HashMap<String, Object> country = null;    

            // Taking each country, parses and adds to list object 
            for(int i=0; i<countryCount;i++){
                try {
                    // Call getCountry with country JSON object to parse the country 
                    country = getCountry((JSONObject)jCountries.get(i));
                    countryList.add(country);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            
            return countryList;
        }
        
        // Parsing the Country JSON object 
        private HashMap<String, Object> getCountry(JSONObject jCountry){

            HashMap<String, Object> country = new HashMap<String, Object>();
            String acilName = "";
            String image="";
            String phone = "";    
            String address="";
            String description = "";
            String stardata = "";
            String coordinate = "";
            String search = "";
            String id = "";
            
            try {
                acilName = jCountry.getString("restorantName");
                image = jCountry.getString("images");
                phone = jCountry.getString("restorantPhone");
                address = jCountry.getString("restorantSemt");
                stardata = jCountry.getString("restorantCost");
                coordinate = jCountry.getString("restorantCoordinates");
                search = jCountry.getString("restorantSearch");
                id = jCountry.getString("restorantId");
                
                String details = phone ;
                
                if(stardata.equals("1")){
                    country.put("StarImage1", R.drawable.dollar);
                    country.put("StarImage2", R.drawable.dollarempty);
                    country.put("StarImage3", R.drawable.dollarempty);
                    country.put("StarImage4", R.drawable.dollarempty);
                    country.put("StarImage5", R.drawable.dollarempty);
                }else if(stardata.equals("2")) {
                    country.put("StarImage1", R.drawable.dollar);
                    country.put("StarImage2", R.drawable.dollar);
                    country.put("StarImage3", R.drawable.dollarempty);
                    country.put("StarImage4", R.drawable.dollarempty);
                    country.put("StarImage5", R.drawable.dollarempty);
                }else if(stardata.equals("3")) {
                    country.put("StarImage1", R.drawable.dollar);
                    country.put("StarImage2", R.drawable.dollar);
                    country.put("StarImage3", R.drawable.dollar);
                    country.put("StarImage4", R.drawable.dollarempty);
                    country.put("StarImage5", R.drawable.dollarempty);
                }else if(stardata.equals("4")) {
                    country.put("StarImage1", R.drawable.dollar);
                    country.put("StarImage2", R.drawable.dollar);
                    country.put("StarImage3", R.drawable.dollar);
                    country.put("StarImage4", R.drawable.dollar);
                    country.put("StarImage5", R.drawable.dollarempty);
                }else {
                    country.put("StarImage1", R.drawable.dollar);
                    country.put("StarImage2", R.drawable.dollar);
                    country.put("StarImage3", R.drawable.dollar);
                    country.put("StarImage4", R.drawable.dollar);
                    country.put("StarImage5", R.drawable.dollar);
                }
                
                country.put("Name", acilName);
                country.put("image", R.drawable.appicon);
                country.put("image_path", image);
                country.put("Phone", phone);
                country.put("Address", address);
                
                x.add(acilName); 
                y.add(id);
                z.add(image);
                t.add(coordinate);
                aramaVerileri.add(search);
                phoneArray.add(phone); 
                addressArray.add(address);
            } catch (JSONException e) {            
                e.printStackTrace();
            }    if(kontrol==false){    
            return country;
            } else{
                return searchHM;
            }
        }
    }  
}

picture-19435-1400867139.jpg
9 yıl 5 ay önce yanıtladın