Reputation: 135
I create a simple Project to load all images in drawable
Here is my code
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list = (ImageView)findViewById(R.id.tung);
ct = getApplicationContext();
try
{
IDs = getAllResourceIDs(R.drawable.class);
n= IDs.length;
dem=0;
list.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
++dem;
list.setImageResource(IDs[dem]);
if(dem==n-1)
dem=0;
}
});
Thread x = new Thread(
new Runnable ()
{
public void run()
{
while(true)
{
try
{
++dem;
//Toast.makeText(ct, ""+dem, 20).show();
list.setImageResource(IDs[dem]);
if(dem==n-1)
dem=0;
}
catch(Exception e)
{
//Toast.makeText(ct,e.toString(), 200).show();
}
}
}
}
);
x.start();
}
catch(Exception e)
{
Toast.makeText(this,e.toString(), 200).show();
}
}
anh here is getAllResourceIDs function to get all ids
private int[] getAllResourceIDs(Class<?> aClass) throws IllegalArgumentException{
/* Get all Fields from the class passed. */
Field[] IDFields = aClass.getFields();
/* int-Array capable of storing all ids. */
int[] IDs = new int[IDFields.length];
try {
/* Loop through all Fields and store id to array. */
for(int i = 0; i < IDFields.length; i++){
/* All fields within the subclasses of R
* are Integers, so we need no type-check here. */
// pass 'null' because class is static
IDs[i] = IDFields[i].getInt(null);
}
} catch (Exception e) {
/* Exception will only occur on bad class submitted. */
throw new IllegalArgumentException();
}
return IDs;
the file main.xml has only a ImageView with id = "tung" I tried to load all images using a Thead named x by using code list.setImageResource(IDs[dem]); as you can see in my code but notthing is happen Can you explain it for me ! Thank a lot !
Upvotes: 0
Views: 67
Reputation: 135
JRaymond ! Thankyou a lot I create a Xthead class extends Thread like this
class XThread extends Thread
{
public int ids[];
public ImageView icon;
public int dem,n;
XThread(int[] ids ,ImageView icon)
{
this.ids = ids;
this.icon= icon;
dem=0;
n = ids.length;
}
public void run()
{
while(true)
{
try
{
Thread.sleep(500);
handle.post(new Runnable()
{
public void run()
{
++dem;
icon.setImageResource(ids[dem]);
if(dem==n-1)
dem=0;
}
});
}
catch(Exception e)
{
}
}
}
}
and in onCreate() function
XThread x = new XThread(IDs,list);
x.start();
Upvotes: 0
Reputation: 11782
Well for starters catch (Exception e)
is almost never a good idea, as it hides all of the meaningful information you can get when an error occurs.
Your error in particular is on this line in your background thread:
list.setImageResource(IDs[dem]);
Background threads are not allowed to manipulate UI objects. Instead you need to use either an AsyncTask (simpler) or a Handler (Advanced)
Upvotes: 1