I am having a little problem with Relative Layouts. I'm doing a project in which I have to read some values from a .CSV file and display them dynamically in a Relative Layout. I'll put a couple of code snippets and images and then explain my problem.
First Code snippet:
package ekalavya.pratnala.quiz;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.StringTokenizer;
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
public class QuizActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Beginning of variable declarations
File quizSpecs = new File("mnt/sdcard/teacher.csv"); // Read the file
BufferedReader csvReader = null;
String line = ""; // Storing each line in a string
StringTokenizer currentLine = null;
int noOfQuestions = 0; // Number of questions in the quiz
int time = 0; // Duration of the quiz
int[][] quizData; // Storing the quiz specifications in an integer array
int i = 0, j = 0; // Loop variables
int[][] questionImages = {
{ R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d,
R.drawable.e, R.drawable.f, R.drawable.g, R.drawable.h,
R.drawable.i, R.drawable.j },
{ R.drawable.a_checked, R.drawable.b_checked,
R.drawable.c_checked, R.drawable.d_checked,
R.drawable.e_checked, R.drawable.f_checked,
R.drawable.g_checked, R.drawable.h_checked,
R.drawable.i_checked, R.drawable.j_checked },
{ R.drawable.zero, R.drawable.one, R.drawable.two,
R.drawable.three, R.drawable.four, R.drawable.five,
R.drawable.six, R.drawable.seven, R.drawable.eight,
R.drawable.nine },
{ R.drawable.zero_checked, R.drawable.one_checked,
R.drawable.two_checked, R.drawable.three_checked,
R.drawable.four_checked, R.drawable.five_checked,
R.drawable.six_checked, R.drawable.seven_checked,
R.drawable.eight_checked, R.drawable.nine_checked } };
// End of variable declarations
try {
csvReader = new BufferedReader(new FileReader(quizSpecs));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
line = csvReader.readLine();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
currentLine = new StringTokenizer(line, ",");
noOfQuestions = Integer.parseInt(currentLine.nextToken());
time = Integer.parseInt(currentLine.nextToken());
while (currentLine.hasMoreTokens())
;
quizData = new int[noOfQuestions][6];
for (i = 0; i < noOfQuestions; i++) {
try {
line = csvReader.readLine();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
currentLine = new StringTokenizer(line, ",");
for (j = 0; j < 6; j++) {
quizData[i][j] = Integer.parseInt(currentLine.nextToken());
}
}
try {
csvReader.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ScrollView s1 = new ScrollView(this);
RelativeLayout r1 = new RelativeLayout(this);
for (i = 0; i < 2; i++) {
switch (quizData[i][1]) {
case 1:
case 2:
for (j = 0; j < quizData[i][2]; j++) {
ImageView option = new ImageView(this);
option.setImageResource(questionImages[0][j]);
option.setId(j + (10 * (i + 1)));
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF, j - 1
+ (10 * (i + 1)));
option.setLayoutParams(params);
r1.addView(option, params);
}
break;
}
}
s1.addView(r1, new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
this.setContentView(s1);
}
}
Image 1: https://www.dropbox.com/s/vzpilyotvgtipbb/pic2.png
Second Code snippet:
package ekalavya.pratnala.quiz;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.StringTokenizer;
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
public class QuizActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Beginning of variable declarations
File quizSpecs = new File("mnt/sdcard/teacher.csv"); // Read the file
BufferedReader csvReader = null;
String line = ""; // Storing each line in a string
StringTokenizer currentLine = null;
int noOfQuestions = 0; // Number of questions in the quiz
int time = 0; // Duration of the quiz
int[][] quizData; // Storing the quiz specifications in an integer array
int i = 0, j = 0; // Loop variables
int[][] questionImages = {
{ R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d,
R.drawable.e, R.drawable.f, R.drawable.g, R.drawable.h,
R.drawable.i, R.drawable.j },
{ R.drawable.a_checked, R.drawable.b_checked,
R.drawable.c_checked, R.drawable.d_checked,
R.drawable.e_checked, R.drawable.f_checked,
R.drawable.g_checked, R.drawable.h_checked,
R.drawable.i_checked, R.drawable.j_checked },
{ R.drawable.zero, R.drawable.one, R.drawable.two,
R.drawable.three, R.drawable.four, R.drawable.five,
R.drawable.six, R.drawable.seven, R.drawable.eight,
R.drawable.nine },
{ R.drawable.zero_checked, R.drawable.one_checked,
R.drawable.two_checked, R.drawable.three_checked,
R.drawable.four_checked, R.drawable.five_checked,
R.drawable.six_checked, R.drawable.seven_checked,
R.drawable.eight_checked, R.drawable.nine_checked } };
// End of variable declarations
try {
csvReader = new BufferedReader(new FileReader(quizSpecs));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
line = csvReader.readLine();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
currentLine = new StringTokenizer(line, ",");
noOfQuestions = Integer.parseInt(currentLine.nextToken());
time = Integer.parseInt(currentLine.nextToken());
while (currentLine.hasMoreTokens())
;
quizData = new int[noOfQuestions][6];
for (i = 0; i < noOfQuestions; i++) {
try {
line = csvReader.readLine();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
currentLine = new StringTokenizer(line, ",");
for (j = 0; j < 6; j++) {
quizData[i][j] = Integer.parseInt(currentLine.nextToken());
}
}
try {
csvReader.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ScrollView s1 = new ScrollView(this);
RelativeLayout r1 = new RelativeLayout(this);
for (i = 0; i < 1; i++) {
switch (quizData[i][3]) {
case 1:
case 2:
for (j = 0; j < quizData[i][2]; j++) {
ImageView option = new ImageView(this);
option.setImageResource(questionImages[0][j]);
option.setId(j + (10 * (i + 1)));
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF, j - 1
+ (10 * (i + 1)));
option.setLayoutParams(params);
r1.addView(option, params);
}
break;
}
}
s1.addView(r1, new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
this.setContentView(s1);
}
}
Image 2: https://www.dropbox.com/s/itazcpshjzbza4t/pic1.png
When the loop in the switch case with variable 'i' is run only once, the second output comes. And if I run it twice, the first output comes. But that's not what I want. I want the first output row to show below the second output row. I know something is wrong in the code but I don't know how to rectify it. Please help me! Also, I want to know how to place those elements anywhere on the screen.
P.S. I haven't been allowed to upload images because my reputation is less than 10 (I'm a newbie here). So, I put them on Dropbox and have put the links here. Sorry for the inconvenience.
I have solved this: I specified only the RIGHT_OF property before and hence it didn't know where to place it vertically and so put it at the top. Specifying the BELOW property as well fixed the issue.
Related
hi dear here I am posting my whole class where I am getting problem. First I explain my problem. I am generating an arrayList "Items" using spinners and the elements in spinners and arrays are exactly same then After comparing array length and ArayList size I want to jump on next activity but problem is occoured in comparing arrays now please help me for this problem
Thanks here is my activity
package com.example.mine4.pantryrecipes;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import java.util.List;
import java.util.ArrayList;
import android.view.View;
import android.widget.Toast;
import android.widget.Button;
import android.widget.TextView;
public class AddItem extends Activity {
MultiSelectionSpinner spinner1,spinner2,spinner3,spinner4;
Button button1;
TextView tv;
private int count = 0;
List<String> Items=new ArrayList<>();
List<String> veg=new ArrayList<>();
List<String> spice=new ArrayList<>();
List<String> dairy=new ArrayList<>();
ArrayList<Boolean> subset = new ArrayList<>();
String[] arrayRecipe = { "chicken","vegetable oil","ginger",
"onion", "garlic","potatoes","tomatoes","roasted peanuts", "peanut butter"};
String[] arrayRecipe2 = { "chicken","garlic","vegetable oil", "tomatoes",
"Dijon mustard","breadcrumbs","Parmesan cheese","unsalted butter"};
String[] arrayRecipe3 = { "chicken", "vegetable oil","unsalted butter",
"sugar", "garlic", "sauce"};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item);
button1=(Button)findViewById(R.id.button1);
tv=(TextView)findViewById(R.id.tv);
String[] arrayItems = {"chicken"};
String[] arrayVeg = { "vegetable oil", "ginger",
"garlic","potatoes" ,"tomatoes","onion"};
String[] arraySpice = { "roasted peanuts", "sauce","Dijon mustard" };
String[] arrayDairy = { "breadcrumbs", "Parmesan cheese", "unsalted butter","sugar", "peanut butter" };
spinner1 = (MultiSelectionSpinner) findViewById(R.id.mySpinner1);
spinner2 = (MultiSelectionSpinner) findViewById(R.id.mySpinner2);
spinner3 = (MultiSelectionSpinner) findViewById(R.id.mySpinner3);
spinner4= (MultiSelectionSpinner) findViewById(R.id.mySpinner4);
spinner1.setItems(arrayItems);
spinner2.setItems(arrayVeg);
spinner3.setItems(arraySpice);
spinner4.setItems(arrayDairy);
}
public void onClick(View v)
{
Items=spinner1.getSelectedStrings();
veg=spinner2.getSelectedStrings();
spice=spinner3.getSelectedStrings();
dairy=spinner4.getSelectedStrings();
Items.addAll(veg);
Items.addAll(spice);
Items.addAll(dairy);
// for(int i=0;i<Items.size();i++)
// tv.append(Items.get(i));
compareArray();
//count++;
}
public void compareArray()
{
for(int j = 0 ; j < arrayRecipe.length ; j++)
{
for(int i = 0 ; i <Items.size() ; i++)
{
if((arrayRecipe[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
if ((arrayRecipe2[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
if ((arrayRecipe3[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
}
}
if(subset != null) {
if ((arrayRecipe.length == subset.size())) {
Intent nextClass = new Intent();
nextClass.setClass(AddItem.this, TenIngreRec.class);
startActivity(nextClass);
finish();
Toast.makeText(getApplicationContext(), "arrayRecipe", Toast.LENGTH_LONG).show();
}
if ((arrayRecipe2.length == subset.size())) {
Intent nextClass = new Intent();
nextClass.setClass(AddItem.this, EightIngreRec.class);
startActivity(nextClass);
finish();
Toast.makeText(getApplicationContext(), "arrayRecipe2", Toast.LENGTH_LONG).show();
}
if ((arrayRecipe3.length == subset.size())) {
Intent nextClass = new Intent();
nextClass.setClass(AddItem.this, EightIngreRec.class);
startActivity(nextClass);
finish();
Toast.makeText(getApplicationContext(), "arrayRecipe3", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "Un-Matched", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onBackPressed()
{
// code here to show dialog
super.onBackPressed(); // optional depending on your needs
Intent intn = new Intent(AddItem.this,Exmain.class);
startActivity(intn);
}
}
and the major problem occured in this code which is array indexOutOfBound
for(int j = 0 ; j < arrayRecipe.length ; j++)
{
for(int i = 0 ; i <Items.size() ; i++)
{
if((arrayRecipe[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
if ((arrayRecipe2[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
if ((arrayRecipe3[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
}
}
thanks again for helping me
array.Length() always count from 1 not form zero use
arrayRecipe.length -1 in your for loop
Use This
for(int j = 0 ; j < (arrayRecipe.length)-1 ; j++)
{
for(int i = 0 ; i <Items.size() ; i++)
{
if((arrayRecipe[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
if ((arrayRecipe2[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
if ((arrayRecipe3[i].equals(Items.get(j))))
{
subset.add(true);
break;
}
}
}
Two problems:
You're using the size of arrayRecipe to bound the index of arrayRecipe, arrayRecipe2 and arrayRecipe3 All three arrays are different in size, hence leading to your error. You need 3 different for loops, one for each arrayRecipe.
Your i and j are in the wrong places.
Items.get(j) should be Items.get(i) as you are using Items.size to limit the size of i. Likewise, arrayRecipe.get(i) should be arrayRecipe.get(j).
Also, it is true that getLength() and getSize() start counting from 1 rather than 0 so the index of the final slot is (getLenght() - 1), but by using < as the clause in your for loop handles that.
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.
We are building an app that is supposed to do several things based on an input text file. First it parses the data in the text file and extracts the useful information and builds a linkedList. The Linked List is a group of BinaryBlock objects. From there we want to dynamically graph the getwfs() function of the BinaryBlocks. At this point, we have got the graph somewhat working but instead of graphing over time it graphs in one big clump and scrolls all the way to the end.
BinaryBlock is listed here:
This is fully tested and functional and really only important in the larger context of the program:
// BinaryBlock.java
public class BinaryBlockLite {
private int pwda[], wfs[];
String lineData;
public BinaryBlockLite( String data ){ // class constructor
lineData = data;
pwda = new int[5];
wfs = new int[4];
setWfs();
}//end constructor
public String WfsToString(){
if (wfs.length == 0)
return "";
String data = "Channel 2: ";
for(int i = 0; i < wfs.length; ++i ){
data = data + "wfs[" + i + "]=" + wfs[i] + " ";
}
return data + "\n";
}
//===========================================================
// Setters
//=============================================================
//read the 5 individual bytes of the Pwda from LineData and into the pwda[] array
private void setPwda(){
int location = 13;
for(int i = 0; i < 5; ++i){
String temp = "" + lineData.charAt(++location) + lineData.charAt(++location);
pwda[i] = Integer.parseInt(temp, 16);
}
}
//logically manipulate the 5 bytes of the PWDA into 4 10-bit WFSs
private void setWfs(){
setPwda();
int j = 0;
for (int i = 0; i < 4; ++i){
wfs[i] = ((pwda[j] << 2) | (( pwda[j + 1] >> 6) & 0x03)) & 0x03ff;
wfs[++i] = ((pwda[j + 1] << 4) | (( pwda[j + 2] >>> 4) & 0x0f)) & 0x03ff;
wfs[++i] = ((pwda[j + 2] << 6) | (( pwda[j + 3] >>> 2) & 0x3f)) & 0x03ff;
wfs[++i] = ((pwda[j + 3] << 8) | (( pwda[j + 4] >>> 0) & 0xff)) & 0x03ff;
}
}
//===========================================================
// Getters
//=============================================================
public int[] getPwda(){
return pwda;
}
public int[] getWfs(){
return wfs;
}
}//end BinaryBlock Class
The main harness is listed here:
The problem is simply that instead of repainting each time and graphing it across the screen, it graphs all of the point at one time.
//MainActivity.java
import android.os.Bundle;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import com.smith.fsu.wave.BinaryBlockLite;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.ListIterator;
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
public class MainActivity extends Activity {
public static LinkedList<BinaryBlockLite> list;
Button btnMain;
Boolean fileLoaded = false;
int xTick = 0,
lastMinX = 0;
Context context = this;
//
////////////////////////////////////////////////////////////////
//import test
private XYMultipleSeriesDataset WFDataset = new XYMultipleSeriesDataset();
private XYMultipleSeriesRenderer WaveFormRenderer = new XYMultipleSeriesRenderer();
private XYSeries WFCurrentSeries;
private GraphicalView WFChartView;
//////////////////////////////////////////////////////////////////////////
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = new LinkedList<BinaryBlockLite>();
btnMain=(Button)findViewById(R.id.btnMain);
WaveFormRenderer.setAxisTitleTextSize(16);
WaveFormRenderer.setChartTitleTextSize(20);
WaveFormRenderer.setLabelsTextSize(15);
WaveFormRenderer.setLegendTextSize(15);
WaveFormRenderer.setMargins(new int[] {20, 30, 15, 0});
WaveFormRenderer.setAxesColor(Color.YELLOW);
String seriesTitle = "Input Data";
XYSeries series = new XYSeries(seriesTitle);
WFDataset.addSeries(series);
WFCurrentSeries = series;
XYSeriesRenderer renderer = new XYSeriesRenderer();
renderer.setColor(Color.GREEN);
WaveFormRenderer.addSeriesRenderer(renderer);
WaveFormRenderer.setXAxisMin(0.0);
WaveFormRenderer.setXAxisMax(500);
// renderer.setFillBelowLine(true) ;
// renderer.setFillBelowLineColor(Color.BLUE);
}
public void chartClick(View view) throws IOException{
String strData = "";
AssetManager amInput = context.getAssets();
BufferedReader reader;
InputStream is = null;
try {
is = amInput.open("Dinamap-Data.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
reader = new BufferedReader(new InputStreamReader(is));
try {
while( (strData = reader.readLine()) != null ) {
addBlock( strData ); //call to paint line
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//while loop
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//end mainClick() method for btnMain
public void writeClick(View view){
//write decimal data for wfs out to file from LinkedList<BinaryBlock>
//using WfsToString() method of BinaryBlock class in separate thread
(new Thread(new Runnable() {
#Override
public void run() {
FileOutputStream fos = null;
try {
fos = openFileOutput("wfs.txt", Context.MODE_WORLD_READABLE);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
ListIterator<BinaryBlockLite> itr = list.listIterator();
while (itr.hasNext()){
String temp = itr.next().WfsToString();
try {
fos.write(temp.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
})).start();
btnMain.setEnabled(false);
}
private void addBlock(final String strData) {
new Thread(new Runnable() {
public void run() {
int wfs[];
//read line into binaryBlockLite object and store object in Linked List
BinaryBlockLite bb = new BinaryBlockLite(strData);
list.add(bb);
//get the wfs data from the BinaryBlockLite object
wfs = new int[bb.getWfs().length];
wfs = bb.getWfs();
//grab each wfs individually and paint to the chart, and increment xTick
for (int k = 0; k < wfs.length; ++k){
/* check if we need to shift the x axis */
if (xTick > WaveFormRenderer.getXAxisMax()) {
WaveFormRenderer.setXAxisMax(xTick);
WaveFormRenderer.setXAxisMin(++lastMinX);
}
if (wfs[k] > 1000){
WFCurrentSeries.add(xTick, WFCurrentSeries.getY(xTick - 1));
}
else{
WFCurrentSeries.add(xTick, wfs[k]);
}
++xTick;
}
WFChartView.repaint();
}
}).start();
}
#Override
protected void onResume() {
super.onResume();
if (WFChartView == null) {
LinearLayout layout = (LinearLayout) findViewById(R.id.WFchart);
WFChartView = ChartFactory.getLineChartView(this, WFDataset, WaveFormRenderer);
layout.addView(WFChartView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
// boolean enabled = WFDataset.getSeriesCount() > 0;
// setSeriesEnabled(enabled);
} else {
WFChartView.repaint();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
I think it's either super simple or a threading issue which is something that I haven't played with enough. Any help would be appreciated.
Looking at the code, I see that you add all the data to the series and then call repaint.
If you want the data to be gradually added, then move the repaint inside the for loop and put a Thread.sleep() inside, to give a chance to the UI thread to actually do the repaint.
This code work perfectly but i can't make work with ANDROID, i need to comapre two image ?
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.util.Vector;
import javax.imageio.ImageIO;
public class Untitled1 {
public static void main(String[] args) {
Vector original = testImg("b.jpg");
Vector clonde = testImg("a.jpg");
System.out.println(original.equals(clonde));
}
public static Vector testImg(String file) {
Vector all = new Vector();
try {
BufferedImage im = ImageIO.read(new FileInputStream(file));
int w = im.getWidth(null);
int h = im.getHeight(null);
int[] rgbs = new int[w * h];
int x = 0;
im.getRGB(0, 0, w, h, rgbs, 0, w);
for (int i = 0; i < w; i+=100) {
Vector line = new Vector();
for (int j = 0; j < h; j+=100) {
line.add(new Integer(rgbs[x]));
// System.out.println("Pixel " + i + "," + j + "has " + "RGB values of " + rgbs[x]);
x++;
}
all.add(line);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return all;
}
}
a couple of things:
you should be returning true from onOptionsItemSelected() if your code handles the selected menu option, and false if it doesn't.
you should break your loop as soon as you determine the images are different. Why do more work than you need to?
there is no need to use a case/switch here. You only handle a single menu item.
so:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() != 1000)
return (super.onOptionsItemSelected(item);
for(int i=0;i<tabA.length;i++)
{
if(tabA[i] != tabB[i])
{
Toast.makeText(this, "Image are not equal", Toast.LENGTH_LONG).show();
return (true);
}
}
Toast.makeText(this, "Image are equal", Toast.LENGTH_LONG).show();
return (true);
}
I've been trying to make a Javanese language translation along with the sound. the translation result is displayed successfully, but the sound won't come out. it throws exception.
Java.io.IOException: Prepare failed: status=0x1
at android.media.MediaPlayer.prepare(Native Method)
at com.cinta.jawa.JawaSearchActivity.playAudio(JawaSearchActivity.java:51)
at com.cinta.jawa.JawaSearchActivity$1.onClick(JawaSearchActivity.java:178)
at android.view.View.performClick(View.java:2408)
at android.view.View$PerformClick.run(View.java:8816)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
it says that i got wrong at line 52 and 179, but i have no idea what makes it wrong. Can anybody help me?
here is the code:
package com.cinta.jawa;
import java.io.IOException;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Activity;
import android.content.res.XmlResourceParser;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class JawaSearchActivity extends Activity {
private EditText etSearch;
private TextView tvResult;
Jawa jawa = new Jawa(this);
boolean booSearch = false;
public static MediaPlayer myplayer = new MediaPlayer();
public static ArrayList<Uri> pathlist = new ArrayList<Uri>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
etSearch = (EditText) findViewById(R.id.editTextSearch);
tvResult = (TextView) findViewById(R.id.textViewResult);
Button btnSearch = (Button) findViewById(R.id.button_search);
btnSearch.setOnClickListener(onClickListener);
}
public void playAudio() {
try {
if (myplayer.isPlaying()) {
myplayer.stop();
myplayer.release();
}
if (pathlist.size() >= 1) {
for (int i = 0; i< pathlist.size();i++){
Uri path = pathlist.get(i);
myplayer.setDataSource(this, path);
myplayer.prepare(); /*this is the error line*/
myplayer.start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
myplayer.setLooping(true);
}
private String[] getWord(XmlResourceParser words, String strWord)
throws XmlPullParserException, IOException {
int eventType = -1;
String[] strReturn = new String[2];
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG) {
String strName = words.getName();
if (strName.equals("word")) {
String wordValue = words.getAttributeValue(null, "key");
if (wordValue.equalsIgnoreCase(strWord)) {
strReturn[0] = words.getAttributeValue(null, "file");
strReturn[1] = words.getAttributeValue(null,
"translate");
return strReturn;
}
}
}
eventType = words.next();
}
return strReturn;
}
OnClickListener onClickListener = new OnClickListener() {
public void onClick(View v) {
XmlResourceParser jawaDictionary = getResources()
.getXml(R.xml.jawa);
String strWord[] = new String[2];
String[] strNumb = null;
int intstrNumb = 0;
String angkaBo = null;
System.out.println("AWAL NIHH??" + angkaBo);
Long angka = null;
boolean booFind = false;
StringBuilder strbTranslate = new StringBuilder();
myplayer.reset();
myplayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer arg0) {
for (int i = 0; i< pathlist.size();i++){
pathlist.remove(i);
if (pathlist.size() >= 1) {
myplayer.reset();
playAudio();
}
}
}
});
String strWords = etSearch.getText().toString().trim();
String[] astrWord = strWords.split(" ");
int intCountWords = astrWord.length;
for (int i = 0; i < intCountWords; i++) {
try {
String perWord = astrWord[i].trim();
int perWordL = perWord.length();
for (int x = 0; x < perWordL; x++) {
if (Character.isDigit(perWord.charAt(x))) {
angka = Long.parseLong(perWord);
}
}
strWord = getWord(jawaDictionary, astrWord[i].trim());
System.out.println("STRWORD NYE APAAN??" + strWord[0]);
jawaDictionary.close();
jawaDictionary = getResources().getXml(R.xml.jawa);
if (strWord[0] != null) {
System.out.println("MASUK SINI GA SIHHHHHH??");
strbTranslate.append(strWord[1]);
strbTranslate.append(" ");
System.out.println("COBA DILIAT " + strbTranslate);
System.out.println("KALOYANG INI?? " + pathlist);
tvResult.setText(strbTranslate);
booSearch = true;
} else {
System.out.println("MASUK MANA DONK??");
if (angka != null) {
angkaBo = NumberScanActivity.convert(angka);
System.out.println("COBA LIAT INI MUNCUL GAKK??"
+ angkaBo);
String angkaNih = angkaBo.trim();
strNumb = angkaNih.split(" ");
System.out.println("HOHOHEHEHEHK??" + angkaNih);
System.out.println("BLUKUTUKKK??" + strNumb);
intstrNumb = strNumb.length;
for (int y = 0; y < intstrNumb; y++) {
System.out
.println("MASUK SINI KAGA?? HAYOOOOOO "
+ strNumb[y]);
strbTranslate.append(strNumb[y]);
strbTranslate.append(" ");
}
tvResult.setText(strbTranslate);
booSearch = true;
}
}
} catch (Exception e) {
}
}
String fullText = strbTranslate.toString();
pathlist = SyllableScanActivity.convertSentenceToSyl(fullText);
System.out.println("COBA LIAT ISI PATHLIS APAAN>>>>>> "+pathlist);
if (!myplayer.isPlaying()) {
playAudio(); /*this is the error line*/
}
if (booFind == false) {
if (booSearch == false)
tvResult.setText("Sorry, No Result");
}
}
};
}
See this link this will help you to solve your problem.
I am using this code in my project for playing audio files. I am not using mediaPlayer.prepair();
see if this help's you...
bGSound = MediaPlayer.create(MusicPlay.this,R.drawable.music_ground);
float bGLeftVol = (float) (bGSoundVolume.getProgress()/100.0);
float bGRightVol = (float) (bGSoundVolume.getProgress()/100.0);
bGSound.setLooping(true);
bGSound.setVolume(bGLeftVol, bGRightVol);
bGSound.start();