How to adjust relative layout when zooming an item? - android

I have created a screen in which have created RelativeLayout dynamically. After that I have added some ImageView under RelativeLayout.
The requirement is that when I click on any Image View then that ImageView should be zoom by 20% and other images show be adjusted automatically.
So I have two problems:
How to zoom a particular ImageView (other ImagesView should be zoom out if already zoomed in)
How to adjust other Image View when perform zoom in and zoom out
Please suggest, I have not worked on Animation before.
Here is code to create layout dynamically:
// Method for adding layout and images
private void addRow(List<HashMap<String, String>> list) {
int breaker = 4, j, row = 0, tempSize = 0;
// Getting number of rows to create
row = (drinkList.size() % 5) == 0 ? drinkList.size() / 5 : (drinkList.size() / 5) + 1;
// Looping for rows
for (j = 0; j < row; j++) {
// Specifying breaker value to break the images row
if (j % 2 != 0) {
breaker = 4;
} else {
breaker = 5;
}
// Creating layout for rows
RelativeLayout layout = new RelativeLayout(Drinks.this);
layout.setId(111 + j);
// Setting layout parameters to row layout
// layout.setLayoutParams(new
// LayoutParams(LayoutParams.WRAP_CONTENT,
// LayoutParams.WRAP_CONTENT, Gravity.CENTER));
RelativeLayout.LayoutParams newParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
if (j > 0) {
newParams.addRule(RelativeLayout.BELOW, (111 + j) - 1);
}
layout.setLayoutParams(newParams);
int c = 0;
tempSize = list.size();
// Looping for placing Images
while (tempSize != 0 && c < breaker) {
// getting hash map from list
HashMap<String, String> h = new HashMap<String, String>();
h = list.get(0);
// Creating Image
final ImageView imageView = new ImageView(Drinks.this);
// Layout Parameters for Image
LayoutParams lpImage = new LayoutParams(150, 150);
imageView.setId(111 + c);
if (c > 0) {
lpImage.addRule(RelativeLayout.RIGHT_OF, (111 + c) - 1);
}
imageView.setTag(c);
lpImage.setMargins(10, 10, 10, 10);
imageView.setLayoutParams(lpImage);
URI uri = null;
URL imageUrl;
String brandID, categoryID, flavourID;
try {
imageUrl = new URL(h.get(Utility.KEY_ICON).toString().replace(" ", "%20"));
brandID = h.get(Utility.KEY_BRAND_ID);
categoryID = h.get(Utility.KEY_CATEGORY_ID);
flavourID = h.get(Utility.KEY_FLAVOUR_ID);
// HashMap<String, String> hash = new HashMap<String,
// String>();
// hash.put(Utility.KEY_BRAND_ID, brandID);
// hash.put(Utility.KEY_CATEGORY_ID, categoryID);
// Setting tag
imageView.setTag(brandID);
uri = new URI(imageUrl.toString());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Loading image from URLs
ImageLoader imageLoader = new ImageLoader(Drinks.this);
imageLoader.DisplayImage(uri.toString(), R.drawable.ic_launcher, imageView);
/**
* Click Listener of Image
* **/
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(Drinks.this, "TAG " + imageView.getTag(), 2000).show();
if (!pressed) {
imageView.startAnimation(zoomIn);
pressed = !pressed;
} else {
imageView.startAnimation(zoomOut);
pressed = !pressed;
}
}
});
layout.addView(imageView);
// removing items from list
list.remove(0);
c++;
tempSize--;
}
containerLayout.addView(layout);
}

Related

How to check imageview is empty or not where imageview created programmatically in android

I created image view programatically, and need check image view is empty or not.
getdrawable(),getHeigt() and getwidth() methodes but it is not working for me.
Imageview created like this:
ImageView iv = new ImageView(this);
code:
public void dynamicTable(String alist[]) throws NullPointerException {
try {
TableLayout tl = (TableLayout) findViewById(R.id.main_table1);
tl.setBackgroundColor(Color.GRAY);
sizelen = alist.length;
cam = new Button[sizelen];
iv = new ImageView[sizelen];
int k;
for (k = 0; k < sizelen; k++) {
try {
final int j = k;
TableRow tr_head = new TableRow(this);
TableLayout.LayoutParams rowparams = new TableLayout.LayoutParams(
TableLayout.LayoutParams.FILL_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT);
int leftMargin = 2;
int topMargin = 1;
int rightMargin = 2;
int bottomMargin = 1;
rowparams.setMargins(leftMargin, topMargin, rightMargin,
bottomMargin);
rowparams.weight = (float) 0.5;
tr_head.setLayoutParams(rowparams);
// tr_head.setId(10);
tr_head.setBackgroundColor(Color.WHITE);
/*
* tr_head.setLayoutParams(new LayoutParams(
* LayoutParams.FILL_PARENT LayoutParams.WRAP_CONTENT));
*/
cam[k] = new Button(this);
cam[k].setText(alist[k]);
cam[k].setTextColor(Color.WHITE);
cam[k].setBackgroundColor(Color.parseColor("#ffab00"));
cam[k].setClickable(true);
cam[k].setFocusable(true);
cam[k].setGravity(Gravity.LEFT);
cam[k].setMaxLines(2);
cam[k].setPadding(10, 10, -10, 10);
cam[k].setAllCaps(false);
cam[k].setTextSize(13);
cam[k].setLayoutParams(new TableRow.LayoutParams(85,
TableLayout.LayoutParams.WRAP_CONTENT));
// cam[i].setWidth(150);
// cam[i].setEms(0);
// cam[i].setGravity(25);
// cam[i](Gravity.LEFT);
// cam[i].setLayoutParams(params);
cam[k].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cam[j].setBackgroundColor(Color.GRAY);
camera(j);
}
});
tr_head.addView(cam[k]); // add the column to the table row
// here
iv[k] = new ImageView(this);
iv[k].setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
iv[k].setPadding(0, 7, 10, 0);
iv[k].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
imageviewOnclick(iv[j]);
}
});
tr_head.addView(iv[k]); // dd the column to the table row
// here
tl.addView(tr_head, rowparams);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
These methods will take the photo from the phone and display it in an ImageView, i guess you can use this in your code to see if the photo shows up or not.
public void DisplayPhotoPreview(){
DisplayPhotoPreview = (Button)findViewById(R.id.UploadPhotoPreviewBtn);//Finds the button in design and put it into a button variable.
DisplayPhotoPreview.setOnClickListener(//Listens for a button click.
new View.OnClickListener() {//Creates a new click listener.
#Override
public void onClick(View v) {//does what ever code is in here when the button is clicked
switch (v.getId()) {//switches to the case if that .id. is clicked.
case R.id.UploadPhotoPreviewBtn://Does what ever the code is in the case if the upload button is clicked.
//I open up an intent variable and through different commands and I open up my gallery on my phone and i cant get
//out of the gallery until i choose a photo. Then I save the photo in the intent and call the onActivityResult() method which displays the image.
//Also a intent is how two activities can send data.
Intent ChoosePhotoFromGallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(ChoosePhotoFromGallery, RESULT_LOAD_IMAGE);//Stores the image into the variable.
break;
}
}
}
);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//so the if statement checks if the image came through, double checks if the result is okay and triple checks to see if the data is not null.
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null){
//gets the address of the image/data !!!!!!ALSO CAN HOLD THE ADDRESS FOR THE SERVER!!!!!!.
Uri Image = data.getData();
ItemPhotoPreview = (ImageView)findViewById(R.id.ItemPhotoPreviewImageView);
//Sets the image into the variable and displays it
ItemPhotoPreview.setImageURI(Image);
}
}

two array dimensional ArrayIndexOutOfBoundException and NullPointerException

i wrote a code for calculating some weights. they are integer weights.
and i need to save them in every time the button is clicked.
please help me. i cant see why the compiler gives me an error when i try to push the button for the second time. here is my complete code:
public class TrainingActivity extends Activity {
private EditText etIn1, etIn2, etDesired;
private TextView prevInput;
int W[][] = new int[2][];
int X[][] = new int[30][];
int w0=0, w1=0, w2=0, p=1, sum=0, clicks=0;
private Button nxtData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.training_activity);
View backgroundImage = findViewById(R.id.background);
Drawable background = backgroundImage.getBackground();
background.setAlpha(40);
etIn1= (EditText) findViewById(R.id.etInput1);
etIn2 = (EditText) findViewById(R.id.etInput2);
etDesired = (EditText) findViewById(R.id.etDesired);
prevInput = (TextView) findViewById(R.id.prevInput);
nxtData = (Button) findViewById(R.id.nextData);
nxtData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int sum = 0;
++clicks;
int intetIn1 = Integer.parseInt(etIn1.getText().toString());
int intetIn2 = Integer.parseInt(etIn2.getText().toString());
int intetDesired = Integer.parseInt(etDesired.getText().toString());
X[clicks-1] = new int[] {intetIn1, intetIn2, 1};
prevInput.setText("Last Inputs: (" + intetIn1 + ", " + intetIn2 +
", " + intetDesired + ")");
if(clicks == 1) {
if(intetDesired == 1) {
W[0] = new int[] {intetIn1, intetIn2, 1};
W[1] = W[0];
} else if(intetDesired == (-1)){
W[0] = new int[] {-intetIn1, -intetIn2, -1};
W[1] = W[0];
}
} else if(clicks > 1) {
for(int i=0; i<3; i++){
sum = sum + W[clicks-1][i] * X[clicks-1][i];
} if(sum>0 && intetDesired==1) {
W[clicks] = W[clicks-1];
} else if(sum<0 && intetDesired==(-1)) {
W[clicks] = W[clicks-1];
} else if(sum<=0 && intetDesired==1) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] + X[clicks-1][i];
}
} else if(sum>=0 && intetDesired==(-1)) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] - X[clicks-1][i];
}
}
}
etIn1.setText("");
etIn2.setText("");
etDesired.setText("");
}
});
}}
and here is the exception it throws:
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
UPDATEEEEEEEE
i fixed the problem with arrayindexoutofboundexception by changing W[2][] to W[20][]. but in some clicks it gives me this error:
java.lang.NullPointerException
and it's not clear in which clicks. sometimes it's in the second click. or some times it's in fourth click. please help.
W[clicks] = W[clicks - 1];
in above line, you have get error because you have only define size of the array
int W[][] = new int[2][];
so it assigned W[0][] and W[1][] only
When click on second time variable clicks value is 2 then compiler gives ArrayIndexOutOfBoundException
EDITED.............................................................
you have got null value because of your bad logic and not proper way to build two dimensional array. Pls use debug tool to find the actual problem to implement logic and use two dimensional array like below example in java or android:
List<List<Integer>> triangle = new ArrayList<List<Integer>>();
List<Integer> row1 = new ArrayList<Integer>(1);
row1.add(2);
triangle.add(row1);
List<Integer> row2 = new ArrayList<Integer>(2);
row2.add(3);row2.add(4);
triangle.add(row2);
triangle.add(Arrays.asList(6,5,7));
triangle.add(Arrays.asList(4,1,8,3));
System.out.println("Size = "+ triangle.size());
for (int i=0; i<triangle.size();i++)
System.out.println(triangle.get(i));

working with canvas : The specified child already has a parent. You must call removeView() on the child's parent first

I visit so many solutions regarding this issue but can't catch it clearly .When ever I run the project first time it works perfectly but when I run it second time then it fire this error in logCat
The specified child already has a parent. You must call removeView() on the child's parent first
where is the error in that code segment ?where should I change in code. any suggestion is acceptable .Thanks in advance ..
Main.java
public class MainActivity extends Activity {
List<PieDetailsItem> piedata = new ArrayList<PieDetailsItem>(0);
EditText edt3;
Button btnChart;
public String s15;
public String[] strArray;
public ImageView mImageView ;
public LinearLayout finalLayout ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
finalLayout = (LinearLayout) findViewById(R.id.pie_container);
mImageView = new ImageView(this);
edt3 = (EditText) this.findViewById(R.id.editText1);
btnChart = (Button) findViewById(R.id.button1);
btnChart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*if(mImageView != null) {
finalLayout.removeView(mImageView);
}
else {*/
s15 = edt3.getText().toString();
/*System.out.println("value 1 is --->"+s10);
System.out.println("value 2 is --->"+s12);*/
System.out.println("value 3 is --->"+s15);
String domain = s15;
strArray = domain.split("\\,");
for (String str : strArray) {
System.out.println(str);
}
// }
openChart();
}
});
}
private void openChart(){
Integer[] items = new Integer[strArray.length];
//double[] distribution = new double[strArray.length];
for (int i = 0; i < items.length; i++) {
items[i] = Integer.parseInt(strArray[i]);
System.out.println("xxxxxx"+items[i]);
}
PieDetailsItem item;
int maxCount = 0;
int itemCount = 0;
// int items[] = { 20, 40, 10, 15, 5 };
int colors[] = { -6777216, -16776961, -16711681, -12303292, -7829368 };
// String itemslabel[] = { " vauesr ur 100", " vauesr ur 200",
// " vauesr ur 300", " vauesr ur 400", " vauesr ur 500" };
for (int i = 0; i < items.length; i++) {
itemCount = items[i];
item = new PieDetailsItem();
item.count = itemCount;
// item.label = itemslabel[i];
item.color = colors[i];
piedata.add(item);
maxCount = maxCount + itemCount;
}
int size = 200;
int BgColor = 0xffa11b1;
Bitmap mBaggroundImage = Bitmap.createBitmap(size, size,
Bitmap.Config.ARGB_8888);
View_PieChart piechart = new View_PieChart(this);
piechart.setLayoutParams(new LayoutParams(size, size));
piechart.setGeometry(size, size, 2, 2, 2, 2, 2130837504);
piechart.setSkinparams(BgColor);
piechart.setData(piedata, maxCount);
piechart.invalidate();
piechart.draw(new Canvas(mBaggroundImage));
piechart = null;
//ImageView mImageView = new ImageView(this);
mImageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
mImageView.setBackgroundColor(BgColor);
mImageView.setImageBitmap(mBaggroundImage);
//LinearLayout finalLayout = (LinearLayout) findViewById(R.id.pie_container);
finalLayout.addView(mImageView);
}
}
You're adding mImageView to the layout multiple times. A view can only be part of 1 ViewGroup. You need to either add it only once, or create a second ImageView if you really want 2 of them in the layout.

Application closed after some time in android

I create a image slide show type application, I my application used thread.
My application run successfully but after some time application suddenly close.
I am used following line of code to release memory
System.gc();
Runtime.getRuntime().gc();
without above code same issue occur.
Logcat:
03-13 12:45:09.250 / dalvikvm:
### ABORTING: DALVIK: HEAP MEMORY CORRUPTION IN internal_bulk_free addr=0x0
20713 20715 F03-13 12:45:09.250 / libc
Fatal signal 11 (SIGSEGV) at 0xdeadbaad (code=1), thread 20715 (GC)
How to solve my problem?
Please help me.
MY code is:
public class MyRunnable implements Runnable {
private int delayTime = 0;
private Vector<Integer> my_PlaylistRecord_ContentIds =new Vector<Integer>();
private Vector<Integer> delayArray =new Vector<Integer>();
private Vector<Long> video_Duration_List = new Vector<Long>();
private Vector<Integer> relative_Ids = new Vector<Integer>();
private Vector<RelativeLayout> layouts = new Vector<RelativeLayout>();
private RelativeLayout customRelativeLayout ;
private ArrayList<String> _idArray;
private ArrayList<String> _delayArray;
private int countPlus = 0;
private int totalSize = 0;
private ArrayList<Playlist_record> playlist_records;
private FinalPlaylist finalPlaylist;
private int fullscreenId =0;
private int screenId =0;
private int screenIndex =0;
private long videoDuration = 0;
public MyRunnable(ArrayList<Integer> _playlistRrecord_ContentIds, FinalPlaylist _finalPlaylist, List<Integer> delayLists, List<Long> videoDurationList) {
finalPlaylist = _finalPlaylist;
for (Integer id : _playlistRrecord_ContentIds) {
//System.out.println("content id:"+id);
my_PlaylistRecord_ContentIds.add(id);
}
for (Integer string : delayLists) {
//System.out.println("delay time :"+string);
delayArray.add(string);
}
for (Long videoDuration : videoDurationList) {
video_Duration_List.add(videoDuration);
}
totalSize = delayArray.size();
Iterator<Integer> myVeryOwnIterator = layoutMap.keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
int key=(Integer) myVeryOwnIterator.next();
System.out.println("key:"+key);
customRelativeLayout = layoutMap.get(key);
//System.out.println(" test customRelativeLayout.getChildCount():"+customRelativeLayout.getChildCount());
layouts.add(customRelativeLayout);
relative_Ids.add(key);
}
// Find screen s
List<Container> containers = appDataBase.getAllCotainer();
for (Container container : containers) {
if(container.getName().equals("S")){
System.out.println("screen INVISIBLE index:");
screenId = container.getContainer_id();
System.out.println(" index :"+screenId);
}
if(container.getName().equals("FS")){
fullscreenId = container.getContainer_id();
}
}
// find index number of screen s container
for (int i = 0 ; i < relative_Ids.size() ; i++) {
if(screenId == relative_Ids.get(i)){
screenIndex = i;
}
}
/* for (int i = 0 ; i < relative_Ids.size() ; i++) {
List<Container> containers = appDataBase.getAllCotainer();
for (Container container : containers) {
if(container.getName().equals("FS")){
System.out.println("Full screen INVISIBLE index:"+i);
RelativeLayout relativeLayout = layouts.get(i);
//relativeLayout.setVisibility(View.INVISIBLE);
layouts.set(i, relativeLayout);
} else if(container.getName().equals("S")){
System.out.println("screen INVISIBLE index:"+i);
RelativeLayout relativeLayout = layouts.get(i);
relativeLayout.setVisibility(View.INVISIBLE);
layouts.set(i, relativeLayout);
}
}
}*/
}
public void run() {
System.out.println("screen container id:"+screenId);
while(IS_THREAD_RUN){
if(countPlus < totalSize){
Runnable iRunnable= new Runnable() {
public void run() {
// System.out.println(" ** countPlus:"+ countPlus);
// System.out.println(" ** totalSize:"+ totalSize);
// System.out.println("my_playlist_ids size:"+my_PlaylistRecord_ContentIds.size());
// System.out.println("my_playlist_ids content:"+my_PlaylistRecord_ContentIds.get(countPlus));
// Get all playlist record
List<Playlist_record> playlist_records = finalPlaylist.getPlayerArray();
Playlist_record playlist_record = playlist_records.get(countPlus);
//System.out.println("test run container id:"+playlist_record.getContainer_id());
// ***********************************
// Check playlist_record validation
// ***********************************
//System.out.println("playlist_recordId:"+my_playlist_ids.get(countPlus));
boolean isvalidContent = false;
isvalidContent = appDataBase.isPlayContent(playlist_record.getPlaylist_record_id());
System.out.println("Valid Content:"+isvalidContent);
if(isvalidContent){
// Hide layout, Fetch all container data and get name equals to FS and S then relative layout
/*
for (int i = 0 ; i < relative_Ids.size() ; i++) {
List<Container> containers = appDataBase.getAllCotainer();
for (Container container : containers) {
if(container.getName().equals("FS")){
System.out.println("Full screen INVISIBLE index:"+i);
RelativeLayout relativeLayout = layouts.get(i);
//relativeLayout.setVisibility(View.INVISIBLE);
layouts.set(i, relativeLayout);
} else if(container.getName().equals("S")){
System.out.println("screen INVISIBLE index:"+i);
RelativeLayout relativeLayout = layouts.get(i);
relativeLayout.setVisibility(View.INVISIBLE);
layouts.set(i, relativeLayout);
}
}
}*/
//System.out.println(" layouts:"+layouts.toString());
for (int i = 0 ; i < relative_Ids.size() ; i++) {
if(relative_Ids.get(i) == playlist_record.getContainer_id()){
//System.out.println("countainer id:"+relative_Ids.get(i));
// System.out.println("playlist_record.getContainer_id():"+playlist_record.getContainer_id());
customRelativeLayout = layouts.get(i);
// System.out.println("customRelativeLayout.getChildCount():"+customRelativeLayout.getChildCount());
// Fetch all container data and get name equals to FS and S then relative layout visible
if(screenId == playlist_record.getContainer_id()){
customRelativeLayout.setVisibility(View.VISIBLE);
//customRelativeLayout.bringToFront();
}else {
RelativeLayout relativeLayout = layouts.get(screenIndex);
relativeLayout.setVisibility(View.INVISIBLE);
layouts.set(screenIndex, relativeLayout);
}
//Weather id match
try {
Feature_Defination feature_Defination = appDataBase.getFeatureDefinition(relative_Ids.get(i));
if(relative_Ids.get(i)==feature_Defination.getContainerID()){
System.out.println("match");
displayWeatherData(customRelativeLayout,feature_Defination.getContainerID(),feature_Defination);
}
} catch (Exception e) {
e.printStackTrace();
}
//System.out.println("transition effect:"+playlist_record.getTransition());
//customRelativeLayout.setVisibility(View.VISIBLE);
setContent(my_PlaylistRecord_ContentIds.get(countPlus),customRelativeLayout,getAnimation(playlist_record.getTransition()),delayArray.get(countPlus));
}
} // End for loop
System.out.println("my_playlist_ids:"+my_PlaylistRecord_ContentIds.get(countPlus));
// setContent(my_playlist_ids.get(countPlus),customRelativeLayout);
countPlus =countPlus+1;
if(countPlus >= totalSize){
countPlus = 0;
}
}else{
countPlus =countPlus+2;
if(countPlus >= totalSize){
countPlus = 0;
}
}
} //run method end
};
handler.post(iRunnable);
}else{
countPlus = 0;
}
//System.out.println("countplus before thread sleep:"+delayArray.get(countPlus)+" countPlus:"+countPlus);
//System.out.println("countplus sleep video duration:"+videoDuration);
try {
long sleepTime = delayArray.get(countPlus);
// System.out.println("sleep delay :"+sleepTime);
if(sleepTime==0){
long videoTime = video_Duration_List.get(countPlus);
if(videoTime == 0 ){
sleepTime = 1000;
}else{
sleepTime = videoTime;
}
}else{
sleepTime = (sleepTime * 1000)+1000;
}
/*
if(videoDuration!=0){
System.out.println("sleep count plus"+countPlus);
countPlus = countPlus - 1;
if(countPlus<=0){
countPlus = 0;
}
System.out.println("sleep countPlus:"+countPlus);
sleepTime = videoDuration;
}*/
// new DisplayContentAsync().execute(""+my_PlaylistRecord_ContentIds.get(countPlus));
System.out.println("sleep time:"+sleepTime);
Thread.sleep(sleepTime);
//Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // run method end
}
}
/* class DisplayContentAsync extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
// get video file length
// check video
// *********************************************************
String play_FileName = "";
//Get all record from content table
File conFile = new File( Util.ROOT_PATH + "Contents/"+play_FileName);
//Check image file
ImageFileFilter imageFileFilter = new ImageFileFilter(conFile);
VideoFileFilter videoFileFilter = new VideoFileFilter(conFile);
Content content = appDataBase.getContentTemp(""+params[0]);
System.out.println("content id:"+content.getContent_id());
System.out.println("content path:"+content.getContent());
try {
String[] contentArray = null;
contentArray = content.getContent().split("/");
play_FileName = contentArray[contentArray.length-1];
} catch (Exception e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String filePath = Util.ROOT_PATH + "Contents/"+conFile.getName();
if(videoFileFilter.accept(conFile)){
System.out.println("Video file name:"+play_FileName);
// Get video file play duration
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(filePath);
String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
long time1 = Long.parseLong( time );;
System.out.println("video time: "+time1);
}
// setContent(my_playlist_ids.get(countPlus),customRelativeLayout);
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
*/
#SuppressLint("NewApi")
public void setContent(int content_id,RelativeLayout _customRelativeLayout,List<Animation> _animations, int _videoTimeDuration){
//System.gc();
//Runtime.getRuntime().gc();
List<Animation> animations = _animations;
RelativeLayout customRelativeLayout = _customRelativeLayout;
ImageView imageView = null;
VideoView videoView = null;
WebView webView = null;
int height = customRelativeLayout.getHeight();
int width = customRelativeLayout.getWidth();
final int videoTimeDuration = _videoTimeDuration;
Animation anim1 = null ;
Animation anim2 = null;
Animation anim3 = null;
for(int p=0; p<animations.size();p++){
if(p==0){
anim1 = animations.get(p);
System.out.println("animation 1");
}else if(p==1){
anim2 = animations.get(p);
System.out.println("animation 2");
}else if(p==2){
anim3 = animations.get(p);
System.out.println("animation 3");
}
}
//System.out.println("layout height :"+height);
//System.out.println("layout height :"+height);
// Find all child from relative layout
int childcount = customRelativeLayout.getChildCount();
//System.out.println("get all child:"+childcount);
for (int i=0; i < childcount; i++){
View view = customRelativeLayout.getChildAt(i);
if (view instanceof ImageView) {
imageView = (ImageView) view;
// do what you want with imageView
}else if (view instanceof VideoView) {
videoView = (VideoView) view;
// do what you want with imageView
}else if (view instanceof WebView) {
webView = (WebView) view;
// do what you want with imageView
}
}
String play_FileName = "";
//Get all record from content table
//System.out.println("content id match with:"+content_id);
Content content = appDataBase.getContent(""+content_id);
//System.out.println("content id:"+content.getContent_id());
//System.out.println("content path:"+content.getContent());
try {
String[] contentArray = null;
contentArray = content.getContent().split("/");
play_FileName = contentArray[contentArray.length-1];
} catch (Exception e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
System.out.println("Play file name:"+play_FileName);
//Toast.makeText(Display.this, play_FileName, 1000).show();
//System.out.println("Play file duration:"+duration);
/*
// Set animation
if(animations!=null && animations.size()>=2){
System.out.println("animation 2 available ");
final Animation endanim = anim2;
final RelativeLayout relativeLayout = customRelativeLayout;
customRelativeLayout.startAnimation(anim1);
anim1.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation arg0) {
}
#Override
public void onAnimationRepeat(Animation arg0) {
}
#Override
public void onAnimationEnd(Animation arg0) {
relativeLayout.startAnimation(endanim);
}
});
}else if(animations!=null && animations.size()==1){
System.out.println("animation 1 available");
imageView.setAnimation(anim1);
}else {
System.out.println("animation not available");
}
*/
File conFile = new File( Util.ROOT_PATH + "Contents/"+play_FileName);
//Check image file
ImageFileFilter imageFileFilter = new ImageFileFilter(conFile);
VideoFileFilter videoFileFilter = new VideoFileFilter(conFile);
WebFileFilter webFileFilter = new WebFileFilter(conFile);
String filePath = Util.ROOT_PATH + "Contents/"+conFile.getName();
//check file size is zero or not
File chkFile = new File(filePath);
if(chkFile.length()>0){
if(imageFileFilter.accept(conFile)){
//System.out.println("filter image file name:"+conFile.getName());
videoView.setVisibility(View.GONE);
imageView.setVisibility(View.VISIBLE);
webView.setVisibility(View.GONE);
// Check android os
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH){
//System.out.println("jelly bean");
Drawable drawable = Drawable.createFromPath(filePath);
imageView.setBackground(drawable);
//imageView.setImageBitmap(decodeFile(chkFile, 1000, 1000));
// Set animation
if(animations!=null && animations.size()>=2){
System.out.println("animation 2 available ");
final Animation endanim = anim2;
final ImageView finalImage = imageView;
imageView.startAnimation(anim1);
anim1.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation arg0) {
}
#Override
public void onAnimationRepeat(Animation arg0) {
}
You can try this.Add below line in android manifest file :
android:largeHeap="true"
Thanks.

Getting id of imageview

I am making a number of imageViews programmatically in a loop and assigning them ids. But when in onClick method I need to get the id of images, it is returning the id of the last image only. How do I get the id of the image that is clicked?
The code I am using:
for (int j = 0; j < 5; j++) {
TableRow tr = new TableRow(this);
imageUrl = "http://ondamove.it/English/images/users/";
imageUrl = imageUrl + listObject.get(j).getImage();
image = new ImageView(this);
image.setPadding(20, 10, 0, 0);
image.setId(j+1);
tr.addView(image);
try {
new DownloadFileAsync(image, new URL(imageUrl))
.execute(imageUrl);
images.add(image);
//images = new ImageView[5];
}
catch (Exception e) {
e.printStackTrace();
}
tr.addView(image);
table.addView(tr, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
image.setOnClickListener(clickImageListener);
Following is the onclicklistener.
private OnClickListener clickImageListener = new OnClickListener() {
public void onClick(View v) {
imageId = image.getId();
Intent fullScreenIntent = new Intent(v.getContext(),FullImageActivity.class);
fullScreenIntent.putExtra(ProfilePageNormalUser.class.getName(),imageId);
ProfilePageNormalUser.this.startActivity(fullScreenIntent);
}
};
Inside the onClick(View v) method you can call v.getId() - this will return you the ID of the View being clicked. Hope this helps.
Try this out:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int index = 0;
for (int i = 0; i < image.length; i++)
{
if (image[i].getId() == v.getId())
{
index = i;
break;
}
}
Toast.makeText(this, "Image clicked index => "+index, Toast.LENGTH_SHORT).show();
}

Categories

Resources