So I have an object with some fields (Two edit text and a radiogroup with two radiobuttons) and I need them all to be completed to create the object, I have all done except the gender (masculino-femenino down boolean down there coming from a from radiobutton). Everything works but the radioButton, How can I know they're empty, I'm running out of logic ideas and I know it have to ve something easy for this, probably obious This is what I have:
```
public boolean camposCompletos() {
if (nombre.isEmpty()) {
return false;
} else if (desc.isEmpty()) {
return false;
}else if (masculino.isChecked() || femenino.isChecked()) {
sexo_comprobacion = false;
return false;
}
return true;
}
```
Try with following code it will help you.
//activity xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male" />
<RadioButton
android:id="#+id/female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female" />
</RadioGroup>
<Button
android:id="#+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Click" /> </LinearLayout>
//activity code
public class MainActivity extends AppCompatActivity {
private RadioButton maleRB, femaleRB;
private Button button;
private String selectedOption = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
maleRB = findViewById(R.id.male);
femaleRB = findViewById(R.id.female);
button = findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (maleRB.isChecked()) selectedOption = maleRB.getText().toString();
if (femaleRB.isChecked()) selectedOption = femaleRB.getText().toString();
Toast.makeText(MainActivity.this,selectedOption,Toast.LENGTH_LONG).show();
}
});
}
}
How to run timer one after another?
for eg: I am using two edittext and one button,
after giving input to 2 edittext as 1 and 2(in minutes), the timer should first complete the first given input and then to start the 2nd input.
Then when i click stop timer, it should stop and display the edittext input and the stopped timer value.
but it's working only for 1st input..but fails in second input.
Here is the code which I tried.
public class MainActivity extends Activity implements OnClickListener {
private Button buttonStartTime, buttonStopTime;
private EditText edtTimerValue;
private EditText edtTimerValue1;
private TextView textViewShowTime; // will show the time
private TextView textViewShowTime1; // will show the time
private CountDownTimer countDownTimer; // built in android class
private CountDownTimer countDownTimer1; // built in android class
// CountDownTimer
private long totalTimeCountInMilliseconds; // total count down time in
private long totalTimeCountInMilliseconds1;
// milliseconds
private long timeBlinkInMilliseconds; // start time of start blinking
private long timeBlinkInMilliseconds1;
private boolean blink; // controls the blinking .. on and off
private boolean blink1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStartTime = (Button) findViewById(R.id.btnStartTime);
buttonStopTime = (Button) findViewById(R.id.btnStopTime);
textViewShowTime = (TextView) findViewById(R.id.tvTimeCount);
edtTimerValue = (EditText) findViewById(R.id.edtTimerValue);
buttonStartTime.setOnClickListener(this);
buttonStopTime.setOnClickListener(this);
textViewShowTime1 = (TextView) findViewById(R.id.tvTimeCount1);
edtTimerValue1 = (EditText) findViewById(R.id.edtTimerValue2);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnStartTime) {
textViewShowTime.setTextSize(15);
setTimer();
buttonStopTime.setVisibility(View.VISIBLE);
buttonStartTime.setVisibility(View.GONE);
edtTimerValue.setVisibility(View.GONE);
edtTimerValue.setText("");
startTimer();
} else if (v.getId() == R.id.btnStopTime) {
countDownTimer.cancel();
if(countDownTimer1!=null) {
countDownTimer1.cancel();
}
buttonStartTime.setVisibility(View.VISIBLE);
buttonStopTime.setVisibility(View.GONE);
edtTimerValue.setVisibility(View.VISIBLE);
}
}
private void setTimer() {
int time = 0;
if (!edtTimerValue.getText().toString().equals("")) {
time = Integer.parseInt(edtTimerValue.getText().toString());
} else
Toast.makeText(MainActivity.this, "Please Enter Minutes...",
Toast.LENGTH_LONG).show();
totalTimeCountInMilliseconds = 60 * time * 1000;
timeBlinkInMilliseconds = 30 * 1000;
}
private void startTimer() {
countDownTimer = new CountDownTimer(totalTimeCountInMilliseconds, 500) {
#Override
public void onTick(long leftTimeInMilliseconds) {
long seconds = leftTimeInMilliseconds / 1000;
if (leftTimeInMilliseconds < timeBlinkInMilliseconds) {
if (blink) {
textViewShowTime.setVisibility(View.VISIBLE);
} else {
textViewShowTime.setVisibility(View.INVISIBLE);
}
blink = !blink; // toggle the value of blink
}
textViewShowTime.setText(String.format("%02d", seconds / 60)
+ ":" + String.format("%02d", seconds % 60));
}
#Override
public void onFinish() {
// this function will be called when the timecount is finished
textViewShowTime.setText("Time up!");
textViewShowTime.setVisibility(View.VISIBLE);
buttonStartTime.setVisibility(View.VISIBLE);
buttonStopTime.setVisibility(View.GONE);
edtTimerValue.setVisibility(View.VISIBLE);
setTimer1(); //here i am using two call the second input
startTimer1(); //here i am using to start the second input automatically.
}
}.start();
}
//this is not working..
private void setTimer1() {
Log.e("text","tesxt");
int time = 0;
if (!edtTimerValue1.getText().toString().equals("")) {
time = Integer.parseInt(edtTimerValue1.getText().toString());
} else
Toast.makeText(MainActivity.this, "Please Enter Minutes...",
Toast.LENGTH_LONG).show();
totalTimeCountInMilliseconds1 = 60 * time * 1000;
timeBlinkInMilliseconds1 = 30 * 1000;
}
//this function is also not working to start the second input..
private void startTimer1() {
Log.e("time","time");
countDownTimer1 = new CountDownTimer(timeBlinkInMilliseconds1, 500) {
#Override
public void onTick(long millisUntilFinished) {
long seconds = millisUntilFinished / 1000;
if (millisUntilFinished < timeBlinkInMilliseconds) {
if (blink1) {
textViewShowTime1.setVisibility(View.VISIBLE);
} else {
textViewShowTime1.setVisibility(View.INVISIBLE);
}
blink1 = !blink1;
}
textViewShowTime1.setText(String.format("%02d", seconds / 60)
+ ":" + String.format("%02d", seconds % 60));
}
#Override
public void onFinish() {
textViewShowTime1.setText("Time up!");
textViewShowTime1.setVisibility(View.VISIBLE);
edtTimerValue1.setVisibility(View.VISIBLE);
}
}.start();
}
}
The layout is this.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal"
android:padding="10dp" >
<EditText
android:id="#+id/edtTimerValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:hint="minutes"
android:inputType="phone" />
<Button
android:id="#+id/btnStartTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="2"
android:gravity="center"
android:text="Start Timer" />
<Button
android:id="#+id/btnStopTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="2"
android:gravity="center"
android:text="Stop Timer"
android:visibility="gone" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/tvTimeCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:00"
android:textStyle="bold"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal"
android:padding="10dp" >
<EditText
android:id="#+id/edtTimerValue2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:hint="minutes"
android:inputType="phone" />
<Button
android:id="#+id/btnStartTime2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="2"
android:gravity="center"
android:text="Start Timer"
android:visibility="gone"/>
<Button
android:id="#+id/btnStopTime2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="2"
android:gravity="center"
android:text="Stop Timer"
android:visibility="gone" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/tvTimeCount1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:00"
android:textStyle="bold"/>
</LinearLayout>
</LinearLayout>
I have made a progress bar in Android but it is not at all working. What am I doing wrong? I have just started to learn android. Below is my code.
MainActivity.java-
public class MainActivity extends AppCompatActivity {
ProgressBar progressBar;
int mporgress=0;
EditText time;
private Handler mHandler = new Handler();
private static final int PROGRESS = 0x1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void Startbuttononclick(View view){
Button startbutton=(Button) findViewById(R.id.button);
startbutton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
mporgress = Integer.parseInt(time.getText().toString());
progressBar.setProgress(mporgress);
new Thread(new Runnable() {
public void run() {
while (mporgress < 100) {
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(mporgress);
mporgress = doWork();
try{
Thread.sleep(1000);
}catch (InterruptedException e){}
}
});
}
}
}).start();
}
});
}
public void doprogress(View view) {
}
public int doWork(){
mporgress++;
return mporgress;
}
}
Activity_main.xml-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.android.progressbar.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the time:"
android:inputType="number"
android:id="#+id/editText" />
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="500dp"
android:layout_height="200dp"
android:id="#+id/progressBar4"
android:layout_gravity="center"
android:scrollbarSize="500dp" />
<Button
android:text="START"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:layout_gravity="center"
android:onClick="Startbuttononclick" />
</LinearLayout>
Check out this image below-
- https://i.stack.imgur.com/2TBIb.png
Note- Enter the time in this image is an EditText with a hint and not a TextView.
It is appearing but not working.
I have done these changes so far.-
https://i.stack.imgur.com/UujpB.png
But still the progress bar is still continuously rotating.
Seems you forgot to initialize EditText -time and ProgressBar. Init it inside onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar =(ProgressBar) findViewById(R.id.progressBar4);
time = (EditText) findViewById(R.id.editText); //here
}
Also inside button click the bar:
progressBar = new ProgressBar(this);
mporgress = Integer.parseInt(time.getText().toString());
................
.............
As a beginner I have some questions about optimizing my application speed. I'm building a simple quiz app there I have an sqlite database inside with some information. With that information I'm generating my questions in quiz page.
It was working pretty fine and fast until I fixed some buttons/background in sketch and use them. Now it's working much more slower and I'm getting error messages at logcat like "Skipped xxx frames! The application may be doing too much work on its main thread." I have searched on google for a while and found out that the bitmaps are slowing down my application. Have read about async and using a new thread to make it run faster.
As a solution I have resized some of my bitmaps, but then I'm getting less quality in my design, so I decided to fix it. I have googled some more about loading my layout with async or a new thread but didn't really find out how/where to do it. What makes me confused is that I don't know if it's to load layout with a new thread is the best solution or to load other processes with new thread. Need some recommendation about how to optimize my app. Here is my code, at least the quiz page that is slowest. I'm not really sure what to optimize there with a new thread. Under a question it's just countdowntimer that is running, and when next clicked countdowntimer starts over and the gui updates with the new question.
My quizpage code:
public class QuizPage extends ActionBarActivity
{
DatabaseHelper dbHelper = new DatabaseHelper(this);
Cursor kommunCrs, lanCrs, riktCrs;
ArrayList<Kommuner> kommunLista = new ArrayList<Kommuner>();
ArrayList<Lan> lanLista = new ArrayList<Lan>();
ArrayList<Riktnummer> riktLista = new ArrayList<Riktnummer>();
ArrayList<Fragar> fragaLista = new ArrayList<Fragar>();
Fragar svList = new Fragar();
Fragar frageObj = new Fragar();
int buttonRaknare = 0;
CountDownTimer cd;
long millisLeft;
long totalMillis = 10100;
int pBarProgress;
TextView pageNr, fraga, cdText;
RadioButton valA, valB, valC, valD;
RadioGroup rg;
Button avsluta, nasta;
ProgressBar pBar;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_page);
checkDB(); // Checking the DB
getCursorData(); // Getting data to cursors
setCrsdataList(); // Setting cursor data to lists
setViewElements(); // Set textview, buttons etc.
setButtonListeners();
getNastaFragaData(); // Refresing the gui with the next question
startCountdownTimer(totalMillis, false); // Countdowntimer starts
}
private void getCursorData()
{
kommunCrs = dbHelper.getDatabase().query("Kommuner ORDER BY RANDOM() LIMIT 50", new String[]{"kommun_id", "kommun_namn", "kommun_lan", "kommun_befolkning"}, null, null, null, null, null);
lanCrs = dbHelper.getDatabase().query("Lan ORDER BY RANDOM()", new String[]{"lan_namn", "lan_befolkning", "lan_antal_kommun", "lan_yta", "lan_id"}, null, null, null, null, null);
riktCrs = dbHelper.getDatabase().query("Riktnummer ORDER BY RANDOM() LIMIT 50", new String[]{"riktnr", "riktnr_omrade", "riktnr_id"}, null, null, null, null, null);
}
private void setCrsdataList()
{
if (kommunCrs.getCount() != 0 && lanCrs.getCount() != 0 && riktCrs.getCount() != 0) {
kommunCrs.moveToFirst();
lanCrs.moveToFirst();
riktCrs.moveToFirst();
for (int i = 0; i < kommunCrs.getCount(); i++) {
Kommuner tempKommun = new Kommuner();
tempKommun.setKommun_namn(kommunCrs.getString(kommunCrs.getColumnIndex("kommun_namn")));
tempKommun.setKommun_lan(kommunCrs.getString(kommunCrs.getColumnIndex("kommun_lan")));
tempKommun.setKommun_befolkning(kommunCrs.getString(kommunCrs.getColumnIndex("kommun_befolkning")));
tempKommun.setKommun_id(kommunCrs.getInt(kommunCrs.getColumnIndex("kommun_id")));
kommunLista.add(tempKommun);
kommunCrs.moveToNext();
}
for (int i = 0; i < lanCrs.getCount(); i++) {
Lan tempLan = new Lan();
tempLan.setLan_namn(lanCrs.getString(lanCrs.getColumnIndex("lan_namn")));
tempLan.setLan_befolkning(lanCrs.getString(lanCrs.getColumnIndex("lan_befolkning")));
tempLan.setLan_antal_kommun(lanCrs.getString(lanCrs.getColumnIndex("lan_antal_kommun")));
tempLan.setLan_yta(lanCrs.getString(lanCrs.getColumnIndex("lan_yta")));
tempLan.setLan_id(lanCrs.getInt(lanCrs.getColumnIndex("lan_id")));
lanLista.add(tempLan);
lanCrs.moveToNext();
}
for (int i = 0; i < riktCrs.getCount(); i++) {
Riktnummer tempRiktnr = new Riktnummer();
tempRiktnr.setRiktnr(riktCrs.getString(riktCrs.getColumnIndex("riktnr")));
tempRiktnr.setRiktnr_omrade(riktCrs.getString(riktCrs.getColumnIndex("riktnr_omrade")));
tempRiktnr.setRiktnr_id(riktCrs.getInt(riktCrs.getColumnIndex("riktnr_id")));
riktLista.add(tempRiktnr);
riktCrs.moveToNext();
}
//Generating my questions here and taking in to a list
fragaLista = frageObj.slumpaFragor(kommunLista, lanLista, riktLista);
Collections.shuffle(fragaLista);
}
else
{
Toast.makeText(getApplicationContext(), "Finns ingen data i databasen!", Toast.LENGTH_SHORT).show();
}
}
private void getNastaFragaData()
{
fraga.setText(fragaLista.get(buttonRaknare).getFraga());
valA.setText(fragaLista.get(buttonRaknare).getSvarArr().get(0).toString());
valB.setText(fragaLista.get(buttonRaknare).getSvarArr().get(1).toString());
valC.setText(fragaLista.get(buttonRaknare).getSvarArr().get(2).toString());
valD.setText(fragaLista.get(buttonRaknare).getSvarArr().get(3).toString());
pageNr.setText(Integer.toString(buttonRaknare+1) + "/20");
}
private void rattSvarCheck()
{
if (valA.isChecked())
{
fragaLista.get(buttonRaknare).userInput = valA.getText().toString();
if (valA.getText().hashCode() == fragaLista.get(buttonRaknare).getRattSvar().hashCode())
{
svList.antalRattSvar++;
}
else
{
svList.antalFelSvar++;
}
}
else if (valB.isChecked())
{
fragaLista.get(buttonRaknare).userInput = valB.getText().toString();
if (valB.getText().hashCode() == fragaLista.get(buttonRaknare).getRattSvar().hashCode())
{
svList.antalRattSvar++;
}
else
{
svList.antalFelSvar++;
}
}
else if (valC.isChecked())
{
fragaLista.get(buttonRaknare).userInput = valC.getText().toString();
if (valC.getText().hashCode() == fragaLista.get(buttonRaknare).getRattSvar().hashCode())
{
svList.antalRattSvar++;
}
else
{
svList.antalFelSvar++;
}
}
else if (valD.isChecked())
{
fragaLista.get(buttonRaknare).userInput = valD.getText().toString();
if (valD.getText().hashCode() == fragaLista.get(buttonRaknare).getRattSvar().hashCode())
{
svList.antalRattSvar++;
}
else
{
svList.antalFelSvar++;
}
}
else
{
fragaLista.get(buttonRaknare).userInput = "";
svList.antalTomtSvar++;
}
}
private void resultatToDatabas()
{
dbHelper.resultatToDatabas(svList.antalRattSvar, svList.antalFelSvar, svList.antalTomtSvar);
Intent i = new Intent(getBaseContext(),QuizResultat.class);
i.putExtra("rslist", fragaLista);
i.putExtra("sl", svList);
finish();
startActivity(i);
}
private void startCountdownTimer(long millis, final boolean isResume)
{
if (!isResume)
{
pBar.setProgress(100);
pBar.setProgressDrawable(pBar.getResources().getDrawable(R.drawable.nypbar));
}
else
{
pBar.setProgress(pBarProgress);
pBar.setProgressDrawable(pBar.getResources().getDrawable(R.drawable.nypbar));
if (pBar.getProgress() < 55 && pBar.getProgress() > 23 )
{
pBar.getProgressDrawable().setColorFilter(Color.parseColor("#FFFFB800"), PorterDuff.Mode.SRC_IN);
}
else if (pBar.getProgress() < 23)
{
pBar.getProgressDrawable().setColorFilter(Color.parseColor("#FFE71000"), PorterDuff.Mode.SRC_IN);
}
}
int callInterval = 100;
cd = new CountDownTimer(millis, callInterval)
{
public void onTick(long millisUntilFinished)
{
millisLeft = millisUntilFinished;
pBarProgress = pBar.getProgress();
int secondsRemaining = (int) millisUntilFinished / 100;
float fraction = millisUntilFinished / (float) totalMillis;
// progress bar is based on scale of 1 to 100;
pBar.setProgress((int) (fraction * 100));
cdText.setText(String.format("%2.1f", secondsRemaining / 10.0, Integer.toString(secondsRemaining)));
if (pBar.getProgress() < 55 && pBar.getProgress() > 23 )
{
pBar.getProgressDrawable().setColorFilter(Color.parseColor("#FFFFB800"), PorterDuff.Mode.SRC_IN);
}
else if (pBar.getProgress() < 23)
{
pBar.getProgressDrawable().setColorFilter(Color.parseColor("#FFE71000"), PorterDuff.Mode.SRC_IN);
}
}
public void onFinish() {
nasta.performClick();
}
}.start();
}
// Deklarera knappar, textview osv.
private void setViewElements()
{
pageNr = (TextView) findViewById(R.id.pageNumberTxt);
fraga = (TextView) findViewById(R.id.fragaTxt);
valA = (RadioButton) findViewById(R.id.valAbtn);
valB = (RadioButton) findViewById(R.id.valBbtn);
valC = (RadioButton) findViewById(R.id.valCbtn);
valD = (RadioButton) findViewById(R.id.valDbtn);
rg = (RadioGroup) findViewById(R.id.valRadioGrupp);
avsluta = (Button) findViewById(R.id.avslutaBtn);
nasta = (Button) findViewById(R.id.nastaBtn);
pBar = (ProgressBar) findViewById(R.id.progressBar);
cdText = (TextView) findViewById(R.id.counterTxt);
}
private void setButtonListeners()
{
// Nästaknapp onClick
nasta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
cd.cancel(); // Avslutar countdowntimer
rattSvarCheck(); // Kontrollerar om svaret är rätt
if (buttonRaknare > 17)
{
nasta.setBackground(getResources().getDrawable(R.drawable.avsluta_selector));
}
if (buttonRaknare != 19) // Så länge det inte är sista frågan
{
buttonRaknare++;
rg.clearCheck(); // Tar bort check från valknapparna
startCountdownTimer(totalMillis, false); // Startar om den avslutade countdowntimer
getNastaFragaData(); // Tar nästa frågans innehåll till view
}
else if (buttonRaknare == 19)
{
resultatToDatabas(); // Sparar resultaten till databasen
}
}
});
// Avslutaknapp onClick
avsluta.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
cd.cancel(); // Pausar cooldowntimer först
visaAlertDialog(); // Visar alert dialog
}
});
}
// Visa alertDialog
private void visaAlertDialog()
{
AlertDialog.Builder adBuild = new AlertDialog.Builder(this)
.setTitle("Avsluta")
.setMessage("Vill du avsluta quizet?")
.setIcon(android.R.drawable.ic_delete)
.setPositiveButton(new String(Character.toChars(0x1F616)) + " Japp! ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton(new String(Character.toChars(0x1F60A)) + " Nej", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
cd.cancel();
//RESUME COUNTDOWNTIMER
startCountdownTimer(millisLeft, true);
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
dialog.cancel();
cd.cancel();
//RESUME COUNTDOWNTIMER
startCountdownTimer(millisLeft, true);
}
});
AlertDialog alertDialog = adBuild.create();
alertDialog.show();
}
private void checkDB()
{
try
{
dbHelper.createDataBase();
dbHelper.openDataBase();
} catch (IOException a) {
a.printStackTrace();
} catch (SQLException b) {
b.printStackTrace();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
{
setContentView(R.layout.activity_quiz_page);
setViewElements();
setButtonListeners();
getNastaFragaData();
}
else
{
setContentView(R.layout.activity_quiz_page);
setViewElements();
setButtonListeners();
getNastaFragaData();
}
}
// onBackPressed metod som visar alertDialog
#Override
public void onBackPressed()
{
cd.cancel();
visaAlertDialog();
}
// onStop METHOD
#Override
protected void onStop()
{
super.onStop();
dbHelper.close();
}
}
My quizpage layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:background="#drawable/quizpage_bg"
tools:context="com.example.onur.quiz.QuizPage">
<TextView
android:layout_width="60dp"
android:layout_height="wrap_content"
android:text="1/20"
android:id="#+id/pageNumberTxt"
android:textSize="18dp"
android:textColor="#ffab6200"
android:background="#drawable/pagenumberbg"
android:textStyle="italic|bold"
android:gravity="center"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:paddingTop="2dp"
android:paddingBottom="5dp"
android:paddingRight="3dp"
android:paddingLeft="3dp" />
<Button
android:layout_width="135dp"
android:layout_height="50dp"
android:id="#+id/nastaBtn"
android:focusable="false"
android:nestedScrollingEnabled="false"
android:background="#drawable/nasta_selector"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="15dp" />
<Button
android:layout_width="30dp"
android:layout_height="30dp"
android:id="#+id/avslutaBtn"
android:background="#drawable/exit_selector"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true" />
<RadioGroup
android:id="#+id/valRadioGrupp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="false"
android:gravity="center_vertical"
android:layout_marginTop="20dp"
android:layout_alignParentStart="false"
android:layout_below="#+id/progressBar"
android:divider="#00FFFFFF"
android:layout_above="#+id/nastaBtn"
android:layout_marginBottom="10dp"
android:background="#drawable/svarbg" >
<RadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="valAtxt"
android:id="#+id/valAbtn"
android:checked="false"
android:textSize="22dp"
android:layout_alignParentLeft="true"
android:paddingBottom="12dp"
android:paddingTop="12dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/custom_rg_drawer"
android:paddingLeft="15dp" />
<RadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="valBbtn"
android:id="#+id/valBbtn"
android:checked="false"
android:textSize="22dp"
android:layout_alignLeft="#+id/nastaBtn"
android:paddingBottom="12dp"
android:paddingTop="12dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/custom_rg_drawer"
android:paddingLeft="15dp" />
<RadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="valCbtn"
android:id="#+id/valCbtn"
android:checked="false"
android:textSize="22dp"
android:paddingBottom="12dp"
android:paddingTop="12dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/custom_rg_drawer"
android:paddingLeft="15dp" />
<RadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="valDbtn"
android:id="#+id/valDbtn"
android:checked="false"
android:textSize="22dp"
android:layout_alignParentLeft="true"
android:paddingBottom="12dp"
android:paddingTop="12dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:background="#drawable/custom_rg_drawer"
android:paddingLeft="15dp" />
</RadioGroup>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Hur många personer bor i Trollhättan?"
android:id="#+id/fragaTxt"
android:textColor="#ffc37800"
android:textSize="24dp"
android:layout_marginTop="20dp"
android:layout_below="#+id/avslutaBtn"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="false"
android:gravity="center"
android:background="#drawable/fragabg"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<ProgressBar
style="#android:style/Widget.ProgressBar.Horizontal"
android:progressDrawable = "#drawable/nypbar"
android:layout_width="290dp"
android:layout_height="10dp"
android:id="#+id/progressBar"
android:layout_marginTop="15dp"
android:layout_below="#+id/fragaTxt" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="10.00"
android:id="#+id/counterTxt"
android:layout_alignParentRight="true"
android:layout_below="#+id/fragaTxt"
android:layout_marginTop="11dp" />
</RelativeLayout>
I don't think it has much to do with bitmaps, especially if you are pulling them from Drawable resources. The source of your lag is likely your database queries, which are happening in onCreate, which are blocking the main thread to do disk access. Instead, use a CursorLoader as described in https://developer.android.com/training/load-data-background/setup-loader.html
I am working on creating activity that has too many animations, and when starting this activity the logcat shows me this message again and again during the life time of this activity:
I/Choreographer﹕ Skipped 36 frames! The application may be doing too much work on its main thread.
so I did many stuff in another threads, but still there is heavy access on the main UI thread. as well as, the animation is becoming really slow on some high resolution devices
what can be possible solution for handling this problem ?
UPDATED: added code
so here is the code of showing the views(which are 6 imageButtons),
private void setupAnimationForAllViews(ArrayList<View> listOfViews,
int animationId,
final boolean isAppearing) {
int startDelay = mDelay; // milliseconds
int numberOfViews = listOfViews.size();
for (int i = 0; i < numberOfViews; i++) {
final Animation animator = AnimationUtils.loadAnimation(mContext, animationId);
animator.setStartOffset(startDelay);
startDelay += mOffSet; // every view will start after 100 milliseconds from the other
final View currentView = listOfViews.get(i);
final int indexOfCurrentCheckedItem = i;
mMainUIThreadHandler.post(new Runnable() {
#Override
public void run() {
currentView.startAnimation(animator);
}
});
}
}
I trigger it in seperated thread like this:
new Thread(new Runnable() {
#Override
public void run() {
setupAnimationForAllViews(tempListOfViews,
animationId, isAppearing);
}
}).start();
In the same activity i have Ken Burns View, which implement ken burns effect on 2 images, The code of this kenBurnsView is in this link: KenBurnsView
so this is the main activity xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#111"
android:orientation="vertical"
android:weightSum="7">
<FrameLayout
android:id="#+id/header"
android:layout_weight="6"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<yasinseyhan.com.yukselirgroup.Activities.GeneralActivities.KenBurnsView
android:id="#+id/header_picture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/uphill2" />
<ImageView
android:id="#+id/header_logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="#drawable/header_white" />
</FrameLayout>
<LinearLayout
android:id="#+id/dsd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_weight="1"
android:weightSum="3"
android:orientation="vertical"
>
<View
android:layout_width="fill_parent"
android:layout_height="2dp"
android:background="#android:color/white"
android:layout_weight="0.5"/>
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<ImageView
android:id="#+id/btnKur"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#drawable/btn_kurumsal_selector"/>
<ImageView
android:id="#+id/btnGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#drawable/btn_groups"/>
<ImageView
android:id="#+id/btnSektorelFaa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#drawable/btn_sektorel_selector"/>
</LinearLayout>
<LinearLayout
android:id="#+id/secondLineLinearLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<ImageView
android:id="#+id/btnInsanKayna"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#drawable/btn_ik_selector"/>
<ImageView
android:id="#+id/btnGale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#drawable/btn_galeri_selector"/>
<ImageView
android:id="#+id/btnIlet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#drawable/btn_iletisim_selector"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_weight="0.5"
android:background="#android:color/white"/>
</LinearLayout>
</LinearLayout>
This is the main activity java part:
public class MainActivity extends Activity {
//Buttons in the MainActivity
AnimationHelper animationHelper;
ArrayList<View> listOfButtons;
Handler mUIThreadHandler = new Handler();
private final int hideOnClickAnimation = R.anim.fade_out;
private final int displayAnimation = R.anim.test_anim;
//For Kenburns View with multible images
private KenBurnsView mKenBurnsView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
initAnimation();
init();
// for testing, we may put those in initAnimation()
animationHelper.setDelay(100);
animationHelper.setOffSet(50);
mKenBurnsView.setResourceIds(R.drawable.test16, R.drawable.uphill2);
}
private void initAnimation() {
//Adding OnClickListeners to the Buttons in the MainActivity - End
// The order is important here
listOfButtons = new ArrayList<>();
listOfButtons.add(btnGroupSirketleri);
listOfButtons.add(btnGale);
listOfButtons.add(btnSektorelFaa);
listOfButtons.add(btnKur);
listOfButtons.add(btnInsanKayna);
listOfButtons.add(btnIlet);
// Adding Animation
animationHelper = new AnimationHelper(listOfButtons, this, mUIThreadHandler);
}
private void initUI() {
//initializing the buttons in the mainactivity
btnKur = (ImageView) findViewById(R.id.btnKur);
btnGroup = (ImageView) findViewById(R.id.btnGroup);
btnSektorelFaa = (ImageView) findViewById(R.id.btnSektorelFaa);
btnInsanKayna = (ImageView) findViewById(R.id.btnInsanKayna);
btnGale = (ImageView) findViewById(R.id.btnGale);
btnIlet = (ImageView) findViewById(R.id.btnIlet);
// KenBurns View
mKenBurnsView = (KenBurnsView) findViewById(R.id.header_picture);
}
private void init() {
//Adding OnClickListeners to the Buttons in the MainActivity - Start
btnKur.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
animationHelper.hideViewsWithClickedView(hideOnClickAnimation, v);
}
});
btnGroup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
animationHelper.hideViewsWithClickedView(hideOnClickAnimation, v);
}
});
btnSektorelFaa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
animationHelper.hideViewsWithClickedView(hideOnClickAnimation, v);
}
});
btnInsanKayna.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
animationHelper.hideViewsWithClickedView(hideOnClickAnimation, v);
}
});
btnGale.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
animationHelper.hideViewsWithClickedView(hideOnClickAnimation, v);
}
});
btnIlet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
animationHelper.hideViewsWithClickedView(hideOnClickAnimation, v);
}
});
}
#Override
protected void onResume() {
super.onResume();
animationHelper.displayViews(displayAnimation, new IDoOnEndOfWholeAnimation() {
#Override
public void doIt() {
if (!mKenBurnsView.isAnimating)
mKenBurnsView.startKenBurnsAnimation();
}
});
}
#Override
protected void onPause() {
super.onPause();
if (mKenBurnsView.isAnimating)
mKenBurnsView.stopKenBurnsAnimation();
}
}
I reduced the sizes and a little bit the resolution of images for Kenburns and the buttons backgrounds in order to get it working smoothly. Playing with threads did not solve the issue of lagging for me.