logo
down
shadow

Android Listview - Load each row on thread


Android Listview - Load each row on thread

Content Index :

Android Listview - Load each row on thread
Tag : java , By : Jim Davis
Date : November 23 2020, 04:01 AM

I wish this helpful for you Is it possible in java to multi-thread each row in listview? My listitems is a description from files and when there are hundreds of files, the loading takes too long. I want it to be multi-threaded so I can see the items loaded one-by-one. , Assuming you have
ArrayAdapter<String> adapter;
public synchronized void addItemToList(String item){
    adapter.add(item);
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            adapter.notifyDataSetChanged();
        }
    });
}
public void runOnBackground(){
    new Thread(new Runnable() {
        @Override
        public void run() {
            while(true) {
                String item = getItemFromSomwhere();
                addItemToList(item);
            }
        }
    }).start();
}

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Safe, standard way to load images in ListView on a different thread?


Tag : android , By : jazzyfox
Date : March 29 2020, 07:55 AM
hop of those help?
I solve this by maintaining a WeakHashMap that remembers the last Bitmap I want to set for that view.

Android Loading ListView from another Thread


Tag : android , By : mlapida
Date : March 29 2020, 07:55 AM
this one helps. Please explain me why this code does not work?(I need to call the lv.setAdapter (adapterA) in the onClick(). It is necessary to change the adapters). It works if you run code on the main thread, but I need to load data in another Thread. I would be grateful for any ideas. Thank you. , SOLUTION:
package com.example.examplelist;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;

public class ActivityElemsExample extends Activity implements OnClickListener {
    ArrayList<Elem> myList;
    Button btn;
    ListView lv;
    AdapterA adapterA;
    AdapterB adapterB;
    boolean running = false;
    Thread thread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn = (Button)findViewById(R.id.button_loading);
        btn.setOnClickListener(this);
        lv = (ListView)findViewById(R.id.lv);

        myList = new ArrayList<Elem>();

        adapterA = new AdapterA(this, myList);
        adapterB = new AdapterB(this, myList);

    }

    public void onClick(View button){
        if(!running){
            running = true;
            Log.d("MyLogs", "LOADING");

            thread = new Thread(new Runnable(){
            public void run(){
                myList.clear();

                for(int i=0; i < 3000; i++){
                    myList.add(new Elem(i, System.currentTimeMillis(), "Elem "+i));
                }
                handler.sendEmptyMessage(1);
            }
            });
            thread.start();
        }
    }

    public void onDestroy(){
        super.onDestroy();
        if(thread != null){
            while(true){
                try{
                    thread.join();
                    break;
                }
                catch (InterruptedException e){}
            }
        }
    }

    public Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {

            lv.setAdapter(adapterA);

            running = false;
        }
    };
}

How to highlight android listview first item after load items to listview?


Tag : android , By : Michael T.
Date : March 29 2020, 07:55 AM
this one helps. 1.This is my listview
FromTableAdapter.setSelectedPosition(0); 
FromTableAdapter.notifyDataSetChanged();
<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item 
        android:state_selected="true"
        android:drawable="@color/pressed_color"/>
    <item
        android:drawable="@color/default_color" />
</selector> 
lv_FromTable.setItemChecked(0,true);
<ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:listSelector="@drawable/list_selector_background" />  

JavaFX listview load a wrong image in the custom cell with a thread


Tag : java , By : user143038
Date : March 29 2020, 07:55 AM
will be helpful for those in need I work on my first JavaFX project and have problem with listview custom cell factory. this is my code
private static Map<String, Image> images = new HashMap<>();

...

Image image;
if ((image = images.get(item.getOwnerId())) == null) {
    img.setImage(null);
    new Thread(() -> {
        Image image1 = new Image(item.getOwnerProfilePicUrl());
        images.put(item.getOwnerId(), image1);
        Platform.runLater(() -> img.setImage(image1));
    }).start();
} else {
    img.setImage(image);
}
...

import java.awt.Desktop; // importing more classes from awt than neccessary could result in problems
...

public class DischargeComment extends ListCell<Comment> {

    ...

    /**
     * Constructor to pass external cache
     * @param cache 
     */
    public DischargeComment(Map<String, SoftReference<Image>> cache) {
        if (cache == null) {
            throw new IllegalArgumentException();
        }
        this.cache = cache;
    }

    /**
     * constructor using the default cache
     */
    public DischargeComment() {
        this(getDefaultCache());
    }

    private final Map<String, SoftReference<Image>> cache;

    private static Map<String, SoftReference<Image>> defaultCache;

    private static final URL FXML_URL = DischargeComment.class.getResource("cell/discharge_comment.fxml");

    public static Map<String, SoftReference<Image>> getDefaultCache() {
        if (defaultCache == null) {
            defaultCache = new HashMap<>();
        }
        return defaultCache;
    }

    public static String search = "";
    private boolean loaded = false; // no need for a reference to fxmlloader here

    @Override
    protected void updateItem(Comment item, boolean empty) {
        super.updateItem(item, empty);

        if (empty || item == null) {
            setText(null);
            setGraphic(null);
        } else {
            if (!loaded) {
                FXMLLoader mLLoader = new FXMLLoader(FXML_URL);
                mLLoader.setController(this);

                try {
                    mLLoader.load();
                    img.setClip(new Circle(25, 25, 25));
                    loaded = true;
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            ...

            // use single access here
            // also use url as key
            cache.compute(item.getOwnerProfilePicUrl(), (key, value) -> {
                Image image = null;
                if (value != null) {
                    image = value.get();
                }
                if (image == null) {
                    image = new Image(key, true); // load image in background
                    value = new SoftReference<>(image);
                }
                img.setImage(image);
                return value;
            });

            lblUsername.setOnMouseClicked(e->{
                try {
                    Desktop.getDesktop().browse(new URI("https://www.instagram.com/" + item.getOwnerUsername()));
                } catch (IOException | URISyntaxException exception) {
                    exception.printStackTrace();
                }
            });

            setText(null);
            setGraphic(pane);
            setPrefHeight(Region.USE_COMPUTED_SIZE); // don't set height to -1
        }
    }
}

Android listview not load one by one item is load completely when complete data download?


Tag : android , By : user104292
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • How to identify the missing type id in Jackson error?
  • android data binding error: cannot find symbol
  • Spring Boot application with a jar dependency does not run after maven build
  • Spring Data JPA query , filter ? search engine ? JPQL?
  • Why LiveData returns null in ViewModel?
  • what this line of code mean....new URLClassLoader(new URL[0],getClass().getClassLoader());
  • Why do need to use new Random() instead of just Random Randomnum?
  • I want to access zk components from the java file
  • How do I cast FieldValue.serverTimestamp() to Kotlin/Java Date Class
  • Insertion Sort Double Array with User Input - JAVA
  • Creating 2 dimesional array with user input and find sum of specific columns
  • can not get Advertising ID Provider in android
  • Convert list of Objects to map of properties
  • How to represent an undirected weighted graph in java
  • Return values as array from collection
  • ByteBuddy generic method return cast to concrete type
  • ImageView hides the round corners of the parent
  • Is there a way to find setter method by its getter method or vice versa in a class?
  • Get aggregated list of properties from list of Objects(Java 8)
  • Unable to find a document in Mongodb where exact date match in java
  • UsernamePasswordAuthenticationFilter skips success handler
  • Use Java filter on stream with in a stream filter
  • Default Login not successful in spring boot 2.1.7
  • Adding key value pairs from a file to a Hashmap
  • Rub regex: matching a char except when after by another char
  • Convert Base64 String to String Array
  • Escape Unicode Character 'POPCORN' to HTML Entity
  • An empty JSON field which is a boolean/nullable field in Java model, is getting converted as null
  • Mongo java driver cannot find public constructor for interface
  • How to unit test writing a file to AWS Lambda output stream?
  • How to make a GitHub GraphQL API Call from Java
  • What's the difference between @ComponentScan and @Bean in a context configuration?
  • Expected class or package adding a view using a class
  • can be delete of a element in a static array be O(1)?
  • Instance variable heap or stack ? ( with specific example)
  • Assert progress of ProgressBar in Espresso test
  • How to detect if gson.fromjson() has excess elements
  • I cant generate the proper code to select the a specific filter on a BI dashboard I am working on
  • How to Inject Dependencies into a Servlet Filter with Spring Boot Filter Registration Bean?
  • Thrift types as a Generic
  • Effective algorithm to random 4 unique integers less than a big max such as 100_000
  • Combining or and negation in Java regex?
  • Unable to instantiate default tuplizer Exception
  • Multi-tenant migration to work with quarkus
  • Ignite persisting a Set: Cannot find metadata for object with compact footer
  • Maven cannot resolve Jacob dependency using eclipse
  • testcontainers oracle database container starts before database user is created
  • Launching two spring boot apps in integration test
  • Is there a way to add a HashMap's value that is a integer array into a ArrayList?
  • Is there any way that I can get a parameter in paintComponent?
  • Empty stack with one recursive method and one iterative method
  • What's the behavior of onBackpressureBuffer in RxJava2
  • Java regex can only use 1 quantifier in a lookback (need 2)
  • How to fix error in native query : it is showing syntax error near or at
  • How to retrieve nested object from a document and display it in FirestoreRecyclerOptions?
  • Why not use ListIterator for full LinkedList Operation?
  • Android Webview EvaluateJavascript sometimes does not return a response
  • Matcher java doesn't work but regex seems to be good
  • Finding dimensions of a .gif file
  • Java Number format how to change +/- sign to custom text
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com