How am I able to insert the i from the for loop in the imageview below, not the i to replace 12 in the file name so that it can become;
ImageView Moon_img12 = new ImageView(new Image(getClass().getResourceAsStream("/Images/tiles/i.png")));
Code:
for(int i=0; i<=total_donnation; i++)
{
ImageView Moon_img12 = new ImageView(new Image(getClass().getResourceAsStream("/Images/tiles/12.png")));
}
Try
ImageView[] moon_images = //init array
//loop
ImageView Moon_img = new ImageView(new Image(getClass().getResourceAsStream("/Images/tiles/"+i+".png
moon_images[i]= Moon_img;
Thanks you all, i have solved it now using your help.
GridPane grid = new GridPane();
int max_columns = 5;
int current_row = 0;
int current_column = 0;
int total_donnation = 7;
for(int i=1; i<=total_donnation; i++)
{
ImageView Moon_img = new ImageView(new Image(getClass().getResourceAsStream("/Images/tiles/"+i+".png")));
grid.add(Moon_img, current_column,current_row);
current_column = current_column+1;
if (current_column == max_columns )
{
current_row = current_row+1;
current_column = 0;
}
}
return grid;
Related
This question already has answers here:
The application may be doing too much work on its main thread
(21 answers)
Closed 1 year ago.
I have a block of code to load a table view. But for large data, my app is crashing. I want to fix that and also want to show a progress bar while loading the table view data. I tried with the AsyncTask but it is showing Skipped 98 frames! The application may be doing too much work on its main thread.
My onCreate code (Updated): -
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sheet);
myDb = new DBHelper(this);
loadIntentInputs();
setToolbar();
new MyWorker(this).execute();
}
My AsyncTask code (Updated): -
public class MyWorker extends AsyncTask < String , Context , Void > {
private Context context ;
private ProgressDialog progressDialog;
public MyWorker (Context context) {
this.context = context ;
progressDialog = new ProgressDialog ( context ) ;
progressDialog.setCancelable ( false ) ;
progressDialog.setMessage ( "Retrieving data..." ) ;
progressDialog.setTitle ( "Please wait" ) ;
progressDialog.setIndeterminate ( true ) ;
}
# Override
protected void onPreExecute ( ) {
progressDialog.show () ;
}
# Override
protected Void doInBackground ( String ... params ) {
runOnUiThread(new Runnable() {
#Override
public void run() {
showAttendanceTable();
}
});
return null ;
}
# Override
protected void onPostExecute ( Void result ) {
if(progressDialog != null && progressDialog.isShowing()){
progressDialog.dismiss ( ) ;
}
}
}
showAttendanceTable method code (Updated): -
private void showAttendanceTable() {
TableLayout tableLayout = findViewById(R.id.table_layout);
int day_in_month = getDayInMonth(month_year);
int row_size = sid_array.length+1;
TableRow[] rows = new TableRow[row_size];
TextView[] rolls_tv = new TextView[row_size];
TextView[] names_tv = new TextView[row_size];
TextView[][] status_tv = new TextView[row_size][day_in_month+1];
for (int i = 0; i < row_size; i++) {
rolls_tv[i] = new TextView(this);
names_tv[i] = new TextView(this);
for (int j = 1; j <= day_in_month; j++) {
status_tv[i][j] = new TextView(this);
}
}
// for excel file
HSSFSheet hssfSheet = null;
try {
hssfSheet = hssfWorkbook.createSheet(month_year);
} catch (IllegalArgumentException e){
e.printStackTrace();
}
HSSFRow hssfRow;
// setting 1st row
rolls_tv[0].setText("Roll");
names_tv[0].setText("Name");
// setting excel file
hssfRow = hssfSheet.createRow(0);
hssfRow.createCell(0).setCellValue("Roll");
hssfRow.createCell(1).setCellValue("Name");
rolls_tv[0].setTextSize(1,22);
names_tv[0].setTextSize(1,22);
rolls_tv[0].setTypeface(rolls_tv[0].getTypeface(), Typeface.BOLD);
names_tv[0].setTypeface(names_tv[0].getTypeface(), Typeface.BOLD);
rolls_tv[0].setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
names_tv[0].setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
rolls_tv[0].setTextColor(Color.parseColor("#FF000000"));
names_tv[0].setTextColor(Color.parseColor("#FF000000"));
for (int i = 1; i <=day_in_month ; i++) {
String date = String.valueOf(i);
if(i<10) date = "0"+date;
status_tv[0][i].setText(date);
// setting excel file
hssfRow.createCell(i+1).setCellValue(date);
status_tv[0][i].setTextSize(1,22);
status_tv[0][i].setTypeface(status_tv[0][i].getTypeface(), Typeface.BOLD);
status_tv[0][i].setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
status_tv[0][i].setTextColor(Color.parseColor("#FF000000"));
}
// setting rows after 1st row
for (int i = 1; i < row_size ; i++) {
rolls_tv[i].setText(roll_array[i-1]);
names_tv[i].setText(name_array[i-1]);
// setting excel file
hssfRow = hssfSheet.createRow(i);
hssfRow.createCell(0).setCellValue(roll_array[i-1]);
hssfRow.createCell(1).setCellValue(name_array[i-1]);
rolls_tv[i].setTextSize(1,20);
names_tv[i].setTextSize(1,20);
rolls_tv[i].setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
names_tv[i].setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
rolls_tv[i].setTextColor(Color.parseColor("#FF000000"));
names_tv[i].setTextColor(Color.parseColor("#FF000000"));
int count=0;
for (int j = 1; j <=day_in_month ; j++) {
String day = String.valueOf(j);
String month = month_year.substring(0,3);
String year = month_year.substring(4,8);
String status = myDb.getStatus(sid_array[i-1],day+" "+month+" "+year);
if (status!=null && status.equals("A")) {
status_tv[i][j].setText(status);
status_tv[i][j].setBackgroundColor(Color.parseColor("#EF9A9A"));
// setting excel file
hssfRow.createCell(j+1).setCellValue(status);
} else if (status!=null && status.equals("P")) {
status_tv[i][j].setText(String.valueOf(++count));
status_tv[i][j].setBackgroundColor(Color.parseColor("#A5D6A7"));
// setting excel file
hssfRow.createCell(j+1).setCellValue(String.valueOf(count));
}
status_tv[i][j].setTextSize(1,20);
status_tv[i][j].setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
status_tv[i][j].setTextColor(Color.parseColor("#FF000000"));
}
}
for (int i = 0; i < row_size; i++) {
rows[i] = new TableRow(this);
rolls_tv[i].setPadding(20,12,20,12);
names_tv[i].setPadding(20,12,20,12);
if (i==0) {
rows[i].setBackgroundColor(Color.parseColor("#FFD400"));
} else if(i%2==0) {
rows[i].setBackgroundColor(Color.parseColor("#EEEEEE"));
} else {
rows[i].setBackgroundColor(Color.parseColor("#E4E4E4"));
}
rows[i].addView(rolls_tv[i]);
rows[i].addView(names_tv[i]);
for (int j = 1; j <=day_in_month ; j++) {
status_tv[i][j].setPadding(20,12,20,12);
rows[i].addView(status_tv[i][j]);
}
tableLayout.addView(rows[i]);
}
tableLayout.setShowDividers(TableLayout.SHOW_DIVIDER_MIDDLE);
}
The problem is you are running new thread on your doInBackground method and you have placed your showAttendanceTable() code inside runOnUiThread() which is causing too many work to consume main thread.Just copy paste the below code, replace it with your doInBackground() method and everything will work fine.
protected Void doInBackground ( String ... params ) {
showAttendanceTable();
}
return null ;
}
Copy this much part of your code from showAttendanceTable() to onPreExecute() method:
TableLayout tableLayout = findViewById(R.id.table_layout);
int day_in_month = getDayInMonth(month_year);
int row_size = sid_array.length+1;
TableRow[] rows = new TableRow[row_size];
TextView[] rolls_tv = new TextView[row_size];
TextView[] names_tv = new TextView[row_size];
TextView[][] status_tv = new TextView[row_size][day_in_month+1];
for (int i = 0; i < row_size; i++) {
rolls_tv[i] = new TextView(this);
names_tv[i] = new TextView(this);
for (int j = 1; j <= day_in_month; j++) {
status_tv[i][j] = new TextView(this);
}
}
I want to add layout dynamically in my android app using java code only, not using XML code. Kindly help me with this. Advance thank you.
with using this code I had done this :
public void makeSeat()
{
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(3,3,3,3);
GridLayout gl = (GridLayout) findViewById(R.id.grid_main);
int column = 4;
int row = 5;
int i_total = 4*5;
int i_busSeatNo = 1;
gl.setAlignmentMode(GridLayout.ALIGN_BOUNDS);
gl.setColumnCount(column);
gl.setRowCount(row + 1);
CheckBox btn;
for(int i =0, c = 0, r = 1; i < i_total; i++, c++)
{
if(c == column)
{
c = 0;
r++;
i_busSeatNo++;
}
if (r == c+1 ){
i_busSeatNo = r;
}
btn = new CheckBox(this);
btn.setGravity(Gravity.CENTER);
btn.setBackgroundResource(R.drawable.chbox);
btn.setButtonDrawable(R.drawable.chbox);
btn.setHeight(val_seat);
btn.setWidth(val_seat);
btn.setText(""+i_busSeatNo); //(r+" "+c); //r+" "+c
int cnt = Integer.parseInt(r+""+c);
btn.setId(cnt);
final CheckBox finalBtn = btn;
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(DynamicBus.this,
"id: " + finalBtn.getId() + "\nNo: " + finalBtn.getText(),
Toast.LENGTH_SHORT).show();
}
});
if(c != column-1) {
i_busSeatNo = i_busSeatNo+5;
}
gl.addView(btn, i);
GridLayout.LayoutParams param =new GridLayout.LayoutParams();
param.height = val_seat;
param.width = val_seat;
param.rightMargin = 7;
param.topMargin = 7;
param.setGravity(Gravity.CENTER);
param.columnSpec = GridLayout.spec(c);
if (r==1)
param.rowSpec = GridLayout.spec(r,1);
btn.setLayoutParams (param);
}
}
Output :
what I get :
https://i.stack.imgur.com/FqynC.png
what I want :
https://i.stack.imgur.com/QZCTI.png
I'm loading in Assets from the main game class which extends the libgdx class game. In the create() method of that class i'm calling Assets.loadAtlas(); and this calls:
public static void loadAtlas() {
String textureFile = "data/rubenSprite.txt";
myTextures = new TextureAtlas(Gdx.files.internal(textureFile));
TextureRegion[] walkRightFrames = new TextureRegion[4];
for (int i = 0; i < 5; i++)
{
walkRightFrames[i] = myTextures.findRegion("wframe" + (i + 1));
}
rubenWalkRight = new Animation(0.2f, walkRightFrames[0], walkRightFrames[1],
walkRightFrames[2], walkRightFrames[3], walkRightFrames[4]);
TextureRegion[] walkLeftFrames = new TextureRegion[4];
for (int i = 0; i < 5; i++)
{
walkLeftFrames[i] = new TextureRegion(walkRightFrames[i]);
walkLeftFrames[i].flip(true,false);
}
rubenWalkLeft = new Animation(0.2f, walkLeftFrames[0], walkLeftFrames[1],
walkLeftFrames[2], walkLeftFrames[3], walkLeftFrames[4]);
TextureRegion[] idleRightFrames = new TextureRegion[3];
for (int i = 0; i < 4; i ++)
{
idleRightFrames[i] = myTextures.findRegion("iframe" + (i + 1));
}
rubenIdleRight = new Animation(0.2f, idleRightFrames[0], idleRightFrames[1],
idleRightFrames[2], idleRightFrames[3]);
TextureRegion[] idleLeftFrames = new TextureRegion[3];
for (int i = 0; i < 4; i++)
{
idleLeftFrames[i] = new TextureRegion(idleRightFrames[i]);
idleLeftFrames[i].flip(true,false);
}
rubenIdleLeft = new Animation(0.2f, idleLeftFrames[0], idleLeftFrames[1],
idleLeftFrames[2], idleLeftFrames[3]);
TextureRegion[] jumpRightFrames = new TextureRegion[4];
for (int i = 0; i < 5; i++)
{
jumpRightFrames[i] = myTextures.findRegion("jframe" + (i + 1));
}
rubenJumpRight = new Animation(0.2f, jumpRightFrames[0], jumpRightFrames[1],
jumpRightFrames[2], jumpRightFrames[3], jumpRightFrames[4]);
TextureRegion[] jumpLeftFrames = new TextureRegion[4];
for (int i = 0; i < 5; i++)
{
jumpLeftFrames[i] = new TextureRegion(jumpRightFrames[i]);
jumpLeftFrames[i].flip(true,false);
}
rubenJumpLeft = new Animation(0.2f, jumpLeftFrames[0], jumpLeftFrames[1],
jumpLeftFrames[2], jumpLeftFrames[3], jumpLeftFrames[4]);
TextureRegion fallRight = new TextureRegion();
fallRight = myTextures.findRegion("fall");
rubenFallRight = new Animation(0f, fallRight);
TextureRegion fallLeft = new TextureRegion(fallRight); ;
fallLeft.flip(true,false);
rubenFallLeft = new Animation(0f, fallLeft);
}
From the tutorials I've looked at, it seems correct to me. I've given the player states and drawn the animations within them inside the mainRenderer depending on the state the player is in. This code seems fine also:
private void renderRuben () {
TextureRegion keyFrame;
switch (world.ruben.getState()) {
case Ruben.RUBEN_STATE_HIT:
keyFrame = Assets.bobHit;
break;
case Ruben.RUBEN_STATE_WALKING:
if (Ruben.facingRight == true)
{
keyFrame = Assets.rubenWalkRight.getKeyFrame(world.ruben.getStateTime(), Animation.ANIMATION_NONLOOPING);
break;
}
else
{
keyFrame = Assets.rubenWalkLeft.getKeyFrame(world.ruben.getStateTime(), Animation.ANIMATION_NONLOOPING);
break;
}
case Ruben.RUBEN_STATE_FALL:
if (Ruben.facingRight == true) {
keyFrame = Assets.rubenFallRight.getKeyFrame(world.ruben.getStateTime(), Animation.ANIMATION_NONLOOPING);
break;
}
else {
keyFrame = Assets.rubenFallLeft.getKeyFrame(world.ruben.getStateTime(), Animation.ANIMATION_NONLOOPING);
break;
}
case Ruben.RUBEN_STATE_JUMP:
if (Ruben.facingRight == true) {
keyFrame = Assets.rubenJumpRight.getKeyFrame(world.ruben.getStateTime(), Animation.ANIMATION_NONLOOPING);
break;
}
else {
keyFrame = Assets.rubenJumpRight.getKeyFrame(world.ruben.getStateTime(), Animation.ANIMATION_NONLOOPING);
break;
}
case Ruben.RUBEN_STATE_IDLE:
default:
if (Ruben.facingRight == true) {
keyFrame = Assets.rubenIdleRight.getKeyFrame(world.ruben.getStateTime(), Animation.ANIMATION_LOOPING);
}
else {
keyFrame = Assets.rubenIdleRight.getKeyFrame(world.ruben.getStateTime(), Animation.ANIMATION_LOOPING);
}
}
float side = world.ruben.getVelocity().x < 0 ? -1 : 1;
if (side < 0)
batch.draw(keyFrame, world.ruben.position.x + 0.5f, world.ruben.position.y - 0.5f, side * Ruben.RUBEN_WIDTH, Ruben.RUBEN_HEIGHT);
else
batch.draw(keyFrame, world.ruben.position.x - 0.5f, world.ruben.position.y - 0.5f, side * Ruben.RUBEN_WIDTH, Ruben.RUBEN_HEIGHT);
}
I packed the Atlases using TexturePacker GUI and saved the png and txt file into /assets/data folder.
The overall project has no errors, it just says 'application not responding' when it opens up in the emulator. What am i doing wrong?
Create Method for game class:
public class GameView extends Game {
// used by all screens
public SpriteBatch batcher;
#Override
public void create () {
batcher = new SpriteBatch();
Settings.load();
Assets.loadAtlas();
setScreen(new MainMenuScreen(this));
}
}
Overall it was something to do with the Emulator not the application, The emulator wasn't compatible with Open GL ES 2.0, So I downloaded GenyMotion and now it works fine.
http://www.genymobile.com/en/
I'm trying to add row to JTable like this
DefaultTableModel model = new DefaultTableModel();
try {
Builder builder = new Builder();
Document doc = builder.build(Config.PATH +"incasation.xml");
Element root = doc.getRootElement();
Elements childs = root.getChildElements("locations");
model.addColumn("Name");
model.addColumn("Total");
model.addColumn("Location fee");
model.addColumn("Bank");
model.addColumn("Tax");
float baseSum = 0;
float locationSum = 0;
float bankSum = 0;
float taxSum = 0;
for(int i=0; i< childs.size(); i++)
{
Element child = childs.get(i);
model.addRow(new Object[] {
child.getFirstChildElement("name").getValue(),
child.getFirstChildElement("base").getValue(),
child.getFirstChildElement("locationfee").getValue(),
child.getFirstChildElement("bank").getValue(),
child.getFirstChildElement("tax").getValue()
});
baseSum += Float.parseFloat(child.getFirstChildElement("base").getValue());
locationSum += Float.parseFloat(child.getFirstChildElement("locationfee").getValue());
bankSum += Float.parseFloat(child.getFirstChildElement("bank").getValue());
taxSum += Float.parseFloat(child.getFirstChildElement("tax").getValue());
}
model.addRow(new Object[] {
"SUM",
Float.toString(baseSum),
Float.toString(locationSum),
Float.toString(bankSum),
Float.toString(taxSum)
});
}
catch(Exception e){}
and in that case it JTable gets only first row, so I tryied like this
DefaultTableModel model = new DefaultTableModel();
try {
Builder builder = new Builder();
Document doc = builder.build(Config.PATH +"incasation.xml");
Element root = doc.getRootElement();
Elements childs = root.getChildElements("locations");
model.addColumn("Name");
model.addColumn("Total");
model.addColumn("Location fee");
model.addColumn("Bank");
model.addColumn("Tax");
float baseSum = 0;
float locationSum = 0;
float bankSum = 0;
float taxSum = 0;
for(int i=0; i< childs.size(); i++)
{
Element child = childs.get(i);
model.addRow(new Object[] {
child.getFirstChildElement("name").getValue(),
child.getFirstChildElement("base").getValue(),
child.getFirstChildElement("locationfee").getValue(),
child.getFirstChildElement("bank").getValue(),
child.getFirstChildElement("tax").getValue()
});
}
for(int j=0; j< childs.size(); j++)
{
Element child = childs.get(j);
baseSum += Float.parseFloat(child.getFirstChildElement("base").getValue());
locationSum += Float.parseFloat(child.getFirstChildElement("locationfee").getValue());
bankSum += Float.parseFloat(child.getFirstChildElement("bank").getValue());
taxSum += Float.parseFloat(child.getFirstChildElement("tax").getValue());
}
model.addRow(new Object[] {
"SUM",
Float.toString(baseSum),
Float.toString(locationSum),
Float.toString(bankSum),
Float.toString(taxSum)
});
}
catch(Exception e){}
I this case the last row is not added.
How to solve this problem?
EDIT
I found the solution one of the value was empty string thats why there was no sum.
It should be like
String base = child.getFirstChildElement("base").getValue();
baseSum += Float.parseFloat(base.equals("") ? "0" : base);
You have edited the question with a solution. However, the solution was not obvious because an exception was thrown that was caught and disregarded.
This is a great example of why this line of code can be problematic:
catch(Exception e){}
I would suggest to at least do a e.printStackTrace(), so that worse case debugging would be easier.
i have this piece of code
ImageIcon[] Image = {
new ImageIcon("../KingGame/src/game/img/1.gif"),
new ImageIcon("../KingGame/src/game/img/2.gif"),
new ImageIcon("../KingGame/src/game/img/3.gif"),
new ImageIcon("../KingGame/src/game/img/4.gif"),
new ImageIcon("../KingGame/src/game/img/5.gif"),
new ImageIcon("../KingGame/src/game/img/6.gif"),
new ImageIcon("../KingGame/src/game/img/7.gif"),
new ImageIcon("../KingGame/src/game/img/8.gif"),
new ImageIcon("../KingGame/src/game/img/9.gif"),
};
an d i tried with the code below replace the script above
ImageIcon image[] = new ImageIcon[9];
for (int i = 1; i < image.length; i++) {
new ImageIcon("../KingGame/src/game/img/"+i+".gif");
}
but the result is...any image is loaded. what is the error?
thanks
You forgot to put new images into array:
image[i] = new ImageIcon("../KingGame/src/game/img/"+i+".gif");
Now it does the same thing as your old code.
It should be
for (int i = 0; i < image.length; i++) {
image[i] =new ImageIcon("../KingGame/src/game/img/"+(i+1)+".gif");
}