искам решетъчен изглед със зареждане чрез превъртане Имам извличане на изображение от сървъра, но искам само 10 изгледа на изображения, други могат да се зареждат при превъртане на решетъчен изглед

public class NewMovie extends Activity {
GridView lv;
Vibrator vibrator;
SimpleAdapter adapter;
Button b;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    Log.i("Category", MainActivity.movie_Category);
    setContentView(R.layout.new_movie);

    vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    lv = (GridView) findViewById(R.id.grid_view);

    // URL to the JSON data
    String strUrl = "http://vaibhavtech.com/work/android/movie_list.php?category="
            + MainActivity.movie_Category + "&sub_category=new";
    // Creating a new non-ui thread task to download json data
    DownloadTask downloadTask = new DownloadTask();
    // Starting the download processt
    downloadTask.execute(strUrl);

    // Getting a reference to ListView of activity_main
    lv.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // // TODO Auto-generated method stub
            vibrator.vibrate(40);
            LayoutInflater inflater = getLayoutInflater();
            View view = inflater.inflate(R.layout.customtoast,
                    (ViewGroup) findViewById(R.id.custom_toast_layout));
            Toast toast = new Toast(getApplicationContext());
            toast.setDuration(Toast.LENGTH_LONG);
            toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
            toast.setView(view);
            toast.show();
            MainActivity.movie_Id = ((TextView) arg1
                    .findViewById(R.id.tv_girdview_content_id)).getText()
                    .toString();
            Log.i("Name is", MainActivity.movie_Id);

            startActivity(new Intent(NewMovie.this, MovieDescription.class));
        }

    });

}

/** 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]);
            MovieParser countryJsonParser = new MovieParser();
            countryJsonParser.parse(jObject);
        } catch (Exception e) {
            Log.d("JSON Exception1", e.toString());
        }

        // Instantiating json parser class
        MovieParser countryJsonParser = new MovieParser();

        // A list object to store the parsed countries list
        List<HashMap<String, Object>> countries = null;

        try {
            // Getting the parsed data as a List construct
            countries = countryJsonParser.parse(jObject);
        } catch (Exception e) {
            Log.d("Exception", e.toString());
        }

        // Keys used in Hashmap
        String[] from = { "image", "id", "year", "duration", "name" };

        // Ids of views in listview_layout
        // int[] to = {
        // R.id.iv_radio_data_image,R.id.tv_radio_data_id,R.id.tv_radio_data_like,R.id.tv_radio_data_rating,R.id.tv_radio_data_listner,R.id.tv_radio_data_radio_url,R.id.tv_radio_data_name};
        int[] to = { R.id.iv_girdview_content_image,
                R.id.tv_girdview_content_id, R.id.tv_girdview_content_like,
                R.id.tv_girdview_content_listner,
                R.id.tv_girdview_content_name };
        // Instantiating an adapter to store each items
        // R.layout.listview_layout defines the layout of each item
        adapter = new SimpleAdapter(getBaseContext(), countries,
                R.layout.grid_view_content, from, to);

        return adapter;
        // lv.setAdapter(new ListAdapter(getApplicationContext()));
    }

    /** Invoked by the Android on "doInBackground" is executed */
    @Override
    protected void onPostExecute(SimpleAdapter adapter) {

        // Setting adapter for the listview
        lv.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("flag_path");
            ImageLoaderTask imageLoaderTask = new ImageLoaderTask();

            HashMap<String, Object> hmDownload = new HashMap<String, Object>();
            hm.put("flag_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("flag_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");

                // 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
            adapter = (SimpleAdapter) lv.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);

            // lv.invalidateViews();
            adapter.notifyDataSetChanged();

        }
    }

}

---------********** ***********------------- ----------------------------

Моля, помогнете, намерих това и от време на зареждане, искам да заредя още изображение от сървъра, когато превъртам като стил на приложение във Facebook. над моя код, моля, помогнете ми.


person Abhishek Maheshwari    schedule 28.10.2013    source източник
comment
не съм работил по това, това може да ви помогне stackoverflow.com/questions/12583419/   -  person SathishKumar    schedule 28.10.2013
comment
@SathishKumar всичко е наред, но знаете защо приложението ми за съжаление спира, когато се зареди изображение.   -  person Abhishek Maheshwari    schedule 28.10.2013
comment
публикувайте вашия logcat, тогава само аз мога да идентифицирам какво се обърка   -  person SathishKumar    schedule 28.10.2013
comment
@SathishKumar, моля, помогнете и ми дайте идея за това stackoverflow.com/questions/19676978/   -  person Abhishek Maheshwari    schedule 30.10.2013


Отговори (1)


Бенджи ми помогна тук.

public class EndlessScrollListener implements OnScrollListener {

    private int visibleThreshold = 5;
    private int currentPage = 0;
    private int previousTotal = 0;
    private boolean loading = true;

    public EndlessScrollListener() {
    }
    public EndlessScrollListener(int visibleThreshold) {
        this.visibleThreshold = visibleThreshold;
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
        if (loading) {
            if (totalItemCount > previousTotal) {
                loading = false;
                previousTotal = totalItemCount;
                currentPage++;
            }
        }
        if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
            // I load the next page of gigs using a background task,
            // but you can call any function here.
            new LoadGigsTask().execute(currentPage + 1);
            loading = true;
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
    }
}

Вижте това вън

person Rethinavel    schedule 28.10.2013
comment
Заменете този ред mImageLoader.displayImage( "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS2IhCj9av5PIv4ZThNnLCirOSPktnXqIE8yvg9j41hLBH31keM" holder.imgMovie); с mImageLoader.displayImage( "http://vaibhavtech.com/work/android/admin/upload/" + mDemoDataAl.get(position).getmDemoPoster(), holder.imgMovie); Това е ред # 200. И не мога да ви помогна със зареждането на данни, докато превъртате без подходяща информация. - person Rethinavel; 29.10.2013
comment
хей, моля, помогнете отново в приложението за филми, yow ми даде безкраен списък в NewMovie.java файл, но има един проблем, след като превъртането на мрежата предишното изображение се замени с изображения по-долу и отново се превърта нагоре, зарежда се отново, искам да се зареди веднъж и никога да не се променя превъртане. - person Abhishek Maheshwari; 09.11.2013
comment
Добре, моят JSON има 10 000 изображения, така че как мога да спра изображенията първоначално, че само 10 изображения трябва да се показват? И когато превъртя, трябва да се покажат следващите 10 изображения. - person Amit Jayaswal; 18.12.2014
comment
@AmitJayaswal Не е добра практика да зареждате 10 000 изображения в json. Ще отнеме повече време за анализ/отговор и изоставане в потребителския интерфейс. Горният отговор не отговаря на вашите изисквания. Можете да внедрите onScrollListener и да персонализирате вашите нужди. - person Rethinavel; 18.12.2014
comment
Добре, @RethinavelPillai, тогава ще получа първите 10 изображения от JSON и в onScroll() ще извикам същия JSON с увеличаване на брояча, така че следващия път ще получа текущите 10 + следващите 10 изображения. Правилният начин ли е? Тъй като с помощта на този начин моето приложение няма да получи твърде много натоварване. - person Amit Jayaswal; 18.12.2014
comment
@AmitJayaswal : Да, можете да направите същото. - person Rethinavel; 18.12.2014
comment
@RethinavelPillai можеш ли да ми кажеш как успяваш да изтеглиш от сървър? - person Erum; 20.08.2015