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
Related
Actually I created a pdf viewer and i jus want to create a longclicklistener to open my new activity and as u can see here
Screenshot
And there is already a click listener assigned with this button and i also want to combine longclicklistener so when i long click that button then automatically launch my second activity
public void actionButtonClick(View view) {
if (pageCount == 0) {
Toast.makeText(getApplicationContext(), getString(R.string.no_selected_pdf), Toast.LENGTH_LONG).show();
return;
}
final BottomSheetDialog dialog = new BottomSheetDialog(MainActivity.this);
dialog.setContentView(R.layout.bottom_sheet);
dialog.setCanceledOnTouchOutside(true);
NumberPicker numberPicker = (NumberPicker) dialog.findViewById(R.id.number_picker);
if (numberPicker != null) {
numberPicker.setMaxValue(pageCount);
numberPicker.setValue(pdfView.getCurrentPage() + 1);
numberPicker.setOnValueChangedListener((picker, oldVal, newVal) -> {
pdfView.jumpTo(newVal - 1, true);
});
}
dialog.show();
}
public void openButtonClick(View view) {
launchPicker();
}
private void startAnimation(int state) {
actionLayout.animate()
.translationY(state == 0 ? actionLayout.getHeight() : 0)
.alpha(state == 0 ? 0 : 1.0f)
.setDuration(300).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
menu.findItem(R.id.hide_or_show_button).setChecked(state != 1);
super.onAnimationEnd(animation);
}
});
}
private void hideOrShowActionButton() {
if (actionLayout.getAlpha() == 1.0)
startAnimation(0);
else
startAnimation(1);
}
private void showSnackBar(#NonNull String msg, boolean isError) {
Snackbar snackbar = Snackbar
.make(findViewById(R.id.main_layout), msg, Snackbar.LENGTH_SHORT);
snackbar.setBackgroundTint(ContextCompat
.getColor(Objects.requireNonNull(getApplicationContext()),
isError ? R.color.err_color : R.color.main_color));
snackbar.setTextColor(ContextCompat
.getColor(Objects.requireNonNull(getApplicationContext()), R.color.white));
snackbar.show();
}
#Override
public void loadComplete(int nbPages) {
pageCount = nbPages;
warningLayout.setVisibility(View.GONE);
PdfDocument.Meta meta = pdfView.getDocumentMeta();
detailsMap.clear();
detailsMap.add(meta.getTitle());
detailsMap.add(meta.getAuthor());
detailsMap.add(meta.getSubject());
detailsMap.add(meta.getKeywords());
detailsMap.add(meta.getCreator());
detailsMap.add(meta.getProducer());
detailsMap.add(dateFormatter(meta.getCreationDate()));
detailsMap.add(dateFormatter(meta.getModDate()));
}
private String dateFormatter(String data) {
if (!data.isEmpty()) {
String date = data.substring(2);
String y = date.substring(0, 4);
String m = date.substring(4, 6);
String d = date.substring(6, 8);
return y + "/" + m + "/" + d;
} else {
return data;
}
}
#Override
public void onPageChanged(int page, int pageCount) {
pageNumber.setText(String.valueOf(page + 1));
}
#Override
public void onPageError(int page, Throwable t) {
showSnackBar(getString(R.string.page_not_loaded) + page, true);
}
}
Xml File
This Is Xml File if needed
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg_color"
tools:context=".MainActivity">
<com.github.barteksc.pdfviewer.PDFView
android:id="#+id/pdf_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg_color"
app:layout_anchor="#+id/warning"
app:layout_anchorGravity="center">
<Button
android:id="#+id/button"
android:layout_width="42dp"
android:layout_height="11dp"
android:layout_below="#id/textView"
android:layout_alignParentBottom="true"
android:layout_marginBottom="518dp"
android:text="open activity 2" />
</com.github.barteksc.pdfviewer.PDFView>
<LinearLayout
android:id="#+id/warning"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="#string/no_selected_pdf"
android:textColor="#color/secondary_text_color"
android:textSize="16sp" />
<TextView
android:id="#+id/tv_open_pdf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:clickable="true"
android:focusable="true"
android:onClick="openButtonClick"
android:padding="10dp"
android:text="#string/click_to_select_pdf"
android:textColor="#color/main_color"
android:textSize="18sp" />
</LinearLayout>
<FrameLayout
android:id="#+id/action_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/action_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="20dp"
android:contentDescription="#string/action_btn_description"
android:onClick="actionButtonClick"
app:backgroundTint="#color/main_color"
app:borderWidth="0dp"
app:tint="#color/white" />
<TextView
android:id="#+id/tv_page_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:elevation="16dp"
android:text="x"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#android:color/white"
android:textSize="16sp" />
</FrameLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
There is an onClick and onLongClick listener for each view :
#Override
protected void onCreate(Bundle savedInstanceState) {
//...
FloatingActionButton actionButton = findViewById(R.id.actionButton);
actionButton.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// start your activity from here
return true;
}
});
}
So I am developing one android application in which I have created one custom dialog box. but the problem arises that, this dialog box is showing correct in my phone and on emulator also. But it can't get display properly on redmi or other phones.
Here is screenshot on my mobile device
and [![On other device][2]][2]
On other device
[2]: https://i.stack.imgur.com/b3H4J.jpg
Here is my code:-
custom_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFF538"
android:padding="10dp">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Would you like to continue"
android:textColor="#color/black"
android:textSize="30dp"
android:textStyle="bold" />
<TextView
android:id="#+id/bld"
android:layout_width="269dp"
android:layout_height="wrap_content"
android:textColor="#color/black" />
<EditText
android:id="#+id/txt_input"
android:layout_width="382dp"
android:layout_height="69dp"
android:layout_marginTop="10dp"
android:background="#drawable/back"
android:hint="Why are you sending this request?"
android:maxLength="100"
android:textSize="20sp" />
<!-- In given textview we have used maxlength =100
because we have to display small information so we use limited characters.-->
<TextView
android:layout_width="wrap_content"
android:layout_height="117dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="11dp"
android:text="Your request will display publicly in blood request section.And if your any request is present in Blood Request will be deleted"
android:textColor="#FF0303"
android:textSize="20dp" />
<Button
android:id="#+id/btn_okay"
android:layout_width="134dp"
android:layout_height="60dp"
android:layout_weight="0"
android:layout_marginTop="10dp"
android:backgroundTint="#color/black"
android:text="yes"
android:textColor="#ffffff"
android:textSize="18sp" />
<Button
android:id="#+id/btn_cancel"
android:layout_width="136dp"
android:layout_height="60dp"
android:layout_gravity="right"
android:layout_marginTop="-58dp"
android:layout_weight="0"
android:backgroundTint="#color/black"
android:gravity="center"
android:text="no"
android:textColor="#ffffff"
android:textSize="18sp" />
</LinearLayout>
donor.java
private void alertDialog() {
final AlertDialog.Builder alert = new AlertDialog.Builder(Bloodbank.this);
View mView = getLayoutInflater().inflate(R.layout.custom_dialog2, null);
Button btn_cancel = (Button) mView.findViewById(R.id.btn_cancel);
Button btn_okay = (Button) mView.findViewById(R.id.btn_okay);
TextView bld = (TextView) mView.findViewById(R.id.bld);
bld.setText("selected blood group is "+item);
alert.setView(mView);
final AlertDialog alertDialog = alert.create();
alertDialog.setCanceledOnTouchOutside(false);
btn_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Request dismissed", Toast.LENGTH_SHORT).show();
alertDialog.dismiss();
}
});
btn_okay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
SQLiteDatabase db = dbHandler.getWritableDatabase();
String sql1 = "delete from request where time < date('now','-2 day') AND Username = '" + MainActivity.getValue() + "'";
db.execSQL(sql1);
String sql = "select Name,contactNo from request where Username = '" + MainActivity.getValue() + "'";
Cursor cursor = db.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
runOnUiThread(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void run() {
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
vibrator.vibrate(VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE));
Toast.makeText(getApplicationContext(), "your request is pending. Please delete that first.", Toast.LENGTH_SHORT).show();
}
});
}
});
}
while (cursor.moveToNext());
}
catch (Exception e) {
runOnUiThread(new Runnable() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void run() {
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
vibrator.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
Toast.makeText(getApplicationContext(), "Please select blood group first", Toast.LENGTH_SHORT).show();
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
}
alertDialog.dismiss();
}
});
alertDialog.show();
alertDialog.getWindow().setLayout(700, 833); //Controlling width and height.
}
Try to change these lines
alertDialog.show();
alertDialog.getWindow().setLayout(700, 833); //Controlling width and height.
With these line
int width = (int) (getResources().getDisplayMetrics().widthPixels * 0.90);
int height = (int) (getResources().getDisplayMetrics().heightPixels * 0.60);
if (alertDialog.getWindow() != null) {
alertDialog.getWindow().setLayout(width, height);
}
alertDialog.show();
To avoid unnecessary stuff, the validate function is called when the update, delete, insert button are clicked. The problem is with the EditText with inputType="number" i.e with etPrice and etSNumber.I think,there is something wrong with the validate_price() and validate_supplier_no().Please Correct Me.
public class QueryActivity extends AppCompatActivity {
private EditText etName, etPrice, etSupplier, etSNumber;
private Button insert_btn, increment, decrement, update_btn, delete_btn, call_btn;
private TextView quantity_tv;
private int quantity_value = 0;
private TextInputLayout inputLayout_name, inputLayout_price, inputLayout_supplier, inputLayout_supplier_no;
int _id, price, quantity, supplier_no = 0;
String name, supplier;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_query);
increment = findViewById(R.id.increment);
decrement = findViewById(R.id.decrement);
insert_btn = findViewById(R.id.insert_btn);
update_btn = findViewById(R.id.update_product);
delete_btn = findViewById(R.id.delete_product);
call_btn = findViewById(R.id.call_btn);
etName = findViewById(R.id.et_name);
etPrice = findViewById(R.id.et_price);
quantity_tv = findViewById(R.id.quantity);
etSupplier = findViewById(R.id.et_supplier);
etSNumber = findViewById(R.id.et_sNumber);
inputLayout_name = findViewById(R.id.textInput_name);
inputLayout_price = findViewById(R.id.textInput_price);
inputLayout_supplier = findViewById(R.id.textInput_supplier);
inputLayout_supplier_no = findViewById(R.id.textInput_supplier_no);
Intent intent = getIntent();
_id = intent.getIntExtra("_id", 0);
name = intent.getStringExtra("name");
price = intent.getIntExtra("price", 0);
quantity = intent.getIntExtra("quantity", 0);
quantity_value = quantity;
supplier = intent.getStringExtra("supplier");
supplier_no = intent.getIntExtra("supplier_no", 0);
String price_str = String.valueOf(price);
if (_id != 0) {
etName.setText(name.toString());
etPrice.setText(String.valueOf(price));
quantity_tv.setText(String.valueOf(quantity).toString());
etSupplier.setText(supplier.toString());
etSNumber.setText(String.valueOf(supplier_no));
insert_btn.setVisibility(View.GONE);
} else {
update_btn.setVisibility(View.GONE);
delete_btn.setVisibility(View.GONE);
}
//OnClickListeners
insert_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(v);
insertProduct();
}
});
update_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(v);
updateProduct();
}
});
delete_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(v);
deleteProduct();
}
});
//add quantity btn
increment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
quantity_value += 1;
display(quantity_value);
}
});
//subtract quantity btn
decrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
quantity_value -= 1;
if (quantity_value <= -1) {
quantity_value = 0;
}
display(quantity_value);
}
});
call_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(supplier_no==0){
Toast.makeText(getApplicationContext(),"Please Enter Supplier Number",Toast.LENGTH_SHORT).show();
}
else {
Intent intent_call = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", String.valueOf(supplier_no), null));
startActivity(intent_call);
}
}
});
}//onCreate Ends
public void validate(View view) {
try {
if (validate_name() && validate_price() && validate_supplier() && validate_supplier_no()) {
Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_SHORT).show();
}
}
catch (NumberFormatException e){
Toast.makeText(getApplicationContext(), "Not Success!", Toast.LENGTH_SHORT).show();
}
}
private boolean validate_supplier_no() {
if (TextUtils.isEmpty(etSNumber.getText().toString())) {
inputLayout_supplier_no.setError("Invalid input");
return false;
} else {
inputLayout_supplier_no.setErrorEnabled(false);
return true;
}
}
private boolean validate_supplier() {
if (etSupplier.getText().toString().isEmpty()) {
inputLayout_supplier.setError("Supplier cannot be blanked");
return false;
} else {
inputLayout_supplier.setErrorEnabled(false);
return true;
}
}
private boolean validate_price() {
if (TextUtils.isEmpty(etPrice.getText().toString())) {
inputLayout_price.setError("Invalid input");
return false;
} else {
inputLayout_price.setErrorEnabled(false);
return true;
}
}
private boolean validate_name() {
if (etName.getText().toString().isEmpty()) {
inputLayout_name.setError("Name cannot be blanked");
return false;
} else {
inputLayout_name.setErrorEnabled(false);
return true;
}
}
private void deleteProduct() {
String selection = _ID + " = ? ";
String[] selectionArgs = {String.valueOf(_id)};
Uri uri = ContentUris.withAppendedId(CONTENT_URI, _id);
int rowsDeleted = getContentResolver().delete(uri, selection, selectionArgs);
}
private void updateProduct() {
String selection = _ID + " = ? ";
String[] selectionArgs = {String.valueOf(_id)};
String et_productName = etName.getText().toString();
int et_productPrice = Integer.parseInt(etPrice.getText().toString());
int tv_productQuantity = Integer.parseInt(quantity_tv.getText().toString());
String et_productSupplier = etSupplier.getText().toString();
int et_productSNumber = Integer.parseInt(etSNumber.getText().toString());
ContentValues values = new ContentValues();
values.put(PRODUCT_NAME, et_productName);
values.put(PRICE, et_productPrice);
values.put(QUANTITY, tv_productQuantity);
values.put(SUPPLIER, et_productSupplier);
values.put(SUPPLIER_NO, et_productSNumber);
Uri uri = CONTENT_URI;
int rowsUpdated = getContentResolver().update(uri, values, selection, selectionArgs);
Toast.makeText(this, "Item inserted at: " + rowsUpdated, Toast.LENGTH_SHORT).show();
}
private void insertProduct() {
String et_productName = etName.getText().toString();
int et_productPrice = Integer.parseInt(etPrice.getText().toString());
int tv_productQuantity = Integer.parseInt(quantity_tv.getText().toString());
String et_productSupplier = etSupplier.getText().toString();
int et_productSNumber = Integer.parseInt(etSNumber.getText().toString());
ContentValues values = new ContentValues();
values.put(PRODUCT_NAME, et_productName);
values.put(PRICE, et_productPrice);
values.put(QUANTITY, tv_productQuantity);
values.put(SUPPLIER, et_productSupplier);
values.put(SUPPLIER_NO, et_productSNumber);
Uri uri = CONTENT_URI;
Uri uriRowsInserted = getContentResolver().insert(uri, values);
Toast.makeText(this, "Item inserted at: " + uriRowsInserted, Toast.LENGTH_SHORT).show();
}
//for updating the quantity_tv
public void display(int number) {
quantity_tv.setText(String.valueOf(number));
}
}
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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#e0e0e0"
android:orientation="vertical"
tools:context=".QueryActivity"
>
<android.support.design.widget.TextInputLayout
android:id="#+id/textInput_name"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/et_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Product Name..."
android:inputType="text" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/textInput_price"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/et_price"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Product Price..."
android:inputType="number" />
</android.support.design.widget.TextInputLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal">
<Button
android:id="#+id/increment"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="+" />
<TextView
android:id="#+id/quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="0"
android:textSize="24sp" />
<Button
android:id="#+id/decrement"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="-" />
</LinearLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/textInput_supplier"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/et_supplier"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Supplier Name..."
android:inputType="text" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/textInput_supplier_no"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/et_sNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter SupplierNumber..."
android:inputType="number" />
</android.support.design.widget.TextInputLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:gravity="center_horizontal"
android:orientation="vertical">
<Button
android:id="#+id/insert_btn"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#drawable/button_layout"
android:text="ADD IT" />
<Button
android:id="#+id/delete_product"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#drawable/button_layout"
android:text="DELETE IT" />
<Button
android:id="#+id/update_product"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#drawable/button_layout"
android:text="Save Changes" />
<Button
android:id="#+id/call_btn"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:background="#drawable/button_layout"
android:drawableLeft="#drawable/call"
android:drawablePadding="-40dp"
android:text="CALL" />
</LinearLayout>
</LinearLayout>
Note: With Empty etPrice or etSNumber,this code throws java.lang.NumberFormatException: Invalid int: ""
You should call insertProduct, deleteProduct and updateProduct only if inputs are valid. Change your method validate like below
public boolean validate(View view) {
try {
if (validate_name() && validate_price() && validate_supplier() && validate_supplier_no()) {
Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_SHORT).show();
return true;
}
}
catch (NumberFormatException e){
Toast.makeText(getApplicationContext(), "Not Success!", Toast.LENGTH_SHORT).show();
}
return false;
}
and start using as
delete_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(validate(v)) {
deleteProduct();
}
}
});
you can Set Error for your EditText not for your Layout.So you car rewrite your code by this way:
etPrice.setError ("Price cannot be blanked");
return false;
} else {
etPrice.setErrorEnabled(false);
return true;
I am confused what might be the reason behind this error.While making my edittext field null after entering a digit into it my application is getting crashed.can you find a solution for this situation ??
here is my code
java file
public class CSLActivity extends AppCompatActivity {
private Common mApp;
private AutoCompleteTextView clgName, conCent, loc;
private MultiAutoCompleteTextView skill;
private String[] qulify = new String[]{"Select Highest Qualification", "PG", "UG", "DIPLOMA"};
public String abc, abcd;
public ScrollView scrollView;
public ProgressBar progressBar;
private String q;
private Spinner level;
private int ab = 1990;
public EditText fullName, frm_yr, to_yr;
private boolean ins = false;
private boolean cIns = false;
private Button next;
private TextfieldValidator textfieldValidator;
private AlphabetValidator alphabetValidator;
private int i = 0, j = 0;
private boolean exit = false;
private String get;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_csl);
scrollView = (ScrollView) findViewById(R.id.scroll_view);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
fullName = (EditText) findViewById(R.id.fullName);
level = (Spinner) findViewById(R.id.level);
clgName = (AutoCompleteTextView) findViewById(R.id.clg_name);
conCent = (AutoCompleteTextView) findViewById(R.id.concent);
frm_yr = (EditText) findViewById(R.id.frm_yr);
to_yr = (EditText) findViewById(R.id.to_yr);
skill = (MultiAutoCompleteTextView) findViewById(R.id.skill);
loc = (AutoCompleteTextView) findViewById(R.id.location);
textfieldValidator = new TextfieldValidator();
alphabetValidator = new AlphabetValidator();
next = (Button) findViewById(R.id.next);
frm_yr.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//abc = frm_yr.getText().toString();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
//i = Integer.parseInt(frm_yr.getText().toString());
//i = Integer.parseInt(abc.toString());
i = Integer.parseInt(frm_yr.getText().toString());
}
});
to_yr.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
//j = Integer.parseInt(to_yr.getText().toString());
//j = Integer.parseInt(abcd.toString());
j = Integer.parseInt(to_yr.getText().toString());
}
});
new GetCollege(CSLActivity.this, progressBar, scrollView, clgName).execute();
new GetCourse(CSLActivity.this, conCent).execute();
new GetSkillSet(CSLActivity.this, scrollView, progressBar, skill).execute();
new GetLocation(CSLActivity.this, scrollView, loc, progressBar).execute();
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_item, qulify);
level.setAdapter(adapter1);
level.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
get = level.getSelectedItem().toString();
if (get.equalsIgnoreCase("PG")) {
q = "1";
} else if (get.equalsIgnoreCase("UG")) {
q = "2";
} else {
q = "3";
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
clgName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt = (TextView) view.findViewById(R.id.ins_name);
clgName.setText(txt.getText().toString());
conCent.requestFocus();
ins = true;
}
});
conCent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt = (TextView) view.findViewById(R.id.display);
conCent.setText(txt.getText().toString());
cIns = true;
frm_yr.requestFocus();
}
});
loc.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt1 = (TextView) view.findViewById(R.id.ins_name);
loc.setText(txt1.getText().toString());
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromInputMethod(view.getWindowToken(), 0);
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.next:
if (fullName.getText().toString().length() == 0) {
fullName.setError("Field Mandatory");
fullName.requestFocus();
} else if (!alphabetValidator.validate(fullName.getText().toString())) {
fullName.setError("Enter a Valid Name");
fullName.requestFocus();
} else if (get.equalsIgnoreCase("Select Highest Qualification")) {
level.requestFocus();
Toast.makeText(getApplicationContext(), "select Qualification", Toast.LENGTH_SHORT).show();
} else if (clgName.getText().toString().length() == 0) {
clgName.setError("Field Mandatory");
clgName.requestFocus();
} else if (conCent.getText().toString().length() == 0) {
conCent.setError("Field Mandatory");
conCent.requestFocus();
} else if (frm_yr.getText().toString().length() == 0) {
frm_yr.setError("Field Mandatory");
frm_yr.requestFocus();
} else if (to_yr.getText().toString().length() == 0) {
to_yr.setError("Field Mandatory");
to_yr.requestFocus();
} else if (i > j) {
to_yr.setError("Passed out year less than join year");
to_yr.requestFocus();
} else if (i == j) {
to_yr.setError("Check the year entered");
to_yr.requestFocus();
} else if (i <= ab) {
frm_yr.setError("Enter a valid Year");
frm_yr.requestFocus();
} else if (j <= ab) {
to_yr.setError("Enter a valid Year");
to_yr.requestFocus();
} else if (skill.getText().toString().length() == 0) {
skill.setError("Field Mandatory");
skill.requestFocus();
} else if (!textfieldValidator.validate(skill.getText().toString())) {
skill.setError("Enter a Valid Skill");
skill.requestFocus();
} else if (loc.getText().toString().length() == 0) {
loc.setError("Field Mandatory");
loc.requestFocus();
} else if (!textfieldValidator.validate(loc.getText().toString())) {
loc.setError("Enter a Valid Location");
} else {
next.setEnabled(false);
new CslIns(CSLActivity.this, mApp.getPreference().getString(Common.u_id, ""), fullName.getText().toString(), q,
clgName.getText().toString(), conCent.getText().toString(), frm_yr.getText().toString(), to_yr.getText().toString(),
skill.getText().toString(), loc.getText().toString(), ins, cIns).execute();
/*startActivity(new Intent(getApplicationContext(), MailVerify.class));
finish();*/
}
break;
}
}
});
}
#Override
public void onBackPressed() {
if (exit) {
mApp.getPreference().edit().putBoolean(Common.PAGE1, false).commit();
super.onBackPressed();
return;
} else {
Toast.makeText(this, "Press Back again to Cancel Signup Process.", Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 2000);
}
}
}
my xml file
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="com.shuan.Project.signup.employee.CSLActivity">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<ScrollView
android:id="#+id/scroll_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/activity_horizontal_margin"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/fullName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_margin"
android:hint="Full Name"
android:imeOptions="actionNext"
android:inputType="textPersonName" />
</android.support.design.widget.TextInputLayout>
<Spinner
android:id="#+id/level"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_margin" />
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_margin">
<AutoCompleteTextView
android:id="#+id/clg_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/clg_name"
android:imeOptions="actionNext" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_margin">
<AutoCompleteTextView
android:id="#+id/concent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/concent"
android:imeOptions="actionNext"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<LinearLayout
android:id="#+id/yr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_margin"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Joined"
android:textColor="#000"
android:textStyle="bold" />
<EditText
android:id="#+id/frm_yr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/small_margin"
android:hint="Year"
android:imeOptions="actionNext"
android:inputType="numberDecimal"
android:maxLength="4"
android:singleLine="true" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Passed :"
android:textColor="#000"
android:textStyle="bold" />
<EditText
android:id="#+id/to_yr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/small_margin"
android:hint="Year"
android:imeOptions="actionNext"
android:inputType="numberDecimal"
android:maxLength="4"
android:singleLine="true" />
</LinearLayout>
</LinearLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/layout_skill"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_margin">
<MultiAutoCompleteTextView
android:id="#+id/skill"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Your Skills"
android:imeOptions="actionNext"
android:inputType="text" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/layout_location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_margin">
<AutoCompleteTextView
android:id="#+id/location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/location"
android:imeOptions="actionDone"
android:inputType="textAutoComplete" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/next"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="#dimen/activity_horizontal_margin"
android:background="#drawable/signin_border"
android:text="START"
android:textAppearance="?android:textAppearanceMedium"
android:textColor="#fff"
android:textStyle="bold" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
log cat
FATAL EXCEPTION: main
Process: com.shuan.Project, PID: 1432
java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at com.shuan.Project.signup.employee.CSLActivity$1.afterTextChanged(CSLActivity.java:95)
at android.widget.TextView.sendAfterTextChanged(TextView.java:7998)
at android.widget.TextView$ChangeWatcher.afterTextChanged(TextView.java:9814)
at android.text.SpannableStringBuilder.sendAfterTextChanged(SpannableStringBuilder.java:990)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:529)
at android.text.SpannableStringBuilder.delete(SpannableStringBuilder.java:224)
at android.text.SpannableStringBuilder.delete(SpannableStringBuilder.java:38)
at android.view.inputmethod.BaseInputConnection.deleteSurroundingText(BaseInputConnection.java:252)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:389)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:78)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5649)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
Try this code
public void afterTextChanged(Editable s) {
if(to_yr.getText().toString().length != 0){
j =Integer.parseInt(to_yr.getText().toString());
}
}
it works fine for me
At a first look, to me it seems to block on onAfterTextChanged, because is trying to parse an int from a String which is empty, so it just throws the error.
Try to verify if the EditText is "" before of parsing the integer, if it is not "" or null do as your code, if it's "" or null give it a default value, like 0 or what you want.
This crash is because of your code in afterTextChanged callback.
You should check if to_yr.getText is having some valid value before parsing it to the integer. Do not parse empty string.
Use below code:
public void afterTextChanged(Editable s) {
if(!TextUtils.isEmpty(to_yr.getText()){
j = Integer.parseInt(to_yr.getText().toString());
}
}
This is happening because you parse the empty string and the Integer class throws exception named:
Invalid int
java.lang.NumberFormatException
Do the check before parsing integer. For example
String s;
if(s != null && (!s.isEmpty())){
Integer i = s.ParseInt();
}
I have ten questions from my succession. I want to do,
1- an answer to a problem (only one button should be clicked)
2- When I go to the next question, see the answer I clicked radiobutton the previous
JAVA Class
public class Sinavsorulari extends Activity {
TextView tv_soruNum, tv_soru;
RadioButton rb_a, rb_b, rb_c, rb_d;
Button btn_sonrakiSoru,btn_oncekiSoru , btn_kaydet;
String url = "http://192.168.56.2/soru_cekme.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sinav_sorulari);
tv_soruNum=(TextView)findViewById(R.id.tv_soruNum);
tv_soru=(TextView)findViewById(R.id.tv_soru);
btn_oncekiSoru=(Button)findViewById(R.id.btn_oncekiSoru);
btn_sonrakiSoru=(Button)findViewById(R.id.btn_sonrakiSoru);
btn_kaydet = (Button) findViewById(R.id.btn_kaydet);
rb_a = (RadioButton) findViewById(R.id.rb_cevapa);
rb_b = (RadioButton) findViewById(R.id.rb_cevapb);
rb_c = (RadioButton) findViewById(R.id.rb_cevapc);
rb_d = (RadioButton) findViewById(R.id.rb_cevapd);
btn_oncekiSoru.setEnabled(false);
btn_kaydet.setEnabled(false);
btn_kaydet.setVisibility(View.INVISIBLE);
new HttpAsyncTask().execute(url);
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(final String result) {
final String[] cevaplar = new String[20];
final JSONArray[] jsonarray = {null};
final String[] soru1 = {null};
final String[] id_soru1 = {null};
final int[] y = {0};
final String[] cvp = new String[24];
try {
final int[] t = { 0 };
jsonarray[0] = new JSONArray(result);
final JSONObject obj1 = jsonarray[0].getJSONObject(t[0]);
id_soru1[0] = obj1.getString("id_soru");
soru1[0] = obj1.getString("baslik_soru");
tv_soruNum.setText(id_soru1[0]);
tv_soru.setText(soru1[0]);
for (int k = 0; k < 4; k++) {
cvp[k] = obj1.getString("icerik_cevap");
if(k == 0){
rb_a.setText(cvp[k]);
}else if(k == 1) {
rb_b.setText(cvp[k]);
}else if(k == 2){
rb_c.setText(cvp[k]);
}else if(k == 3){
rb_d.setText(cvp[k]);
}
}
if ( rb_a.isSelected()){
cvp[y[0]]="A";
}
else if( rb_b.isSelected()){
cvp[y[0]] ="B";
}
else if( rb_c.isSelected()){
cvp[y[0]]="C";
}
else if( rb_d.isSelected()){
cvp[y[0]]="D";
}
else {
rb_a.setChecked(false);
rb_b.setChecked(false);
rb_c.setChecked(false);
rb_d.setChecked(false);
}
final JSONArray finalJsonarray = jsonarray[0];
btn_sonrakiSoru.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
t[0]+=4;
y[0] +=1;
btn_oncekiSoru.setEnabled(true);
JSONObject obj2 = finalJsonarray.getJSONObject(t[0]);
id_soru1[0] = obj2.getString("id_soru");
soru1[0] = obj2.getString("baslik_soru");
tv_soruNum.setText(id_soru1[0]);
tv_soru.setText(soru1[0]);
for (int k = 0; k < 4; k++) {
cvp[k] = obj2.getString("icerik_cevap");
if (k == 0) {
rb_a.setText(cvp[k]);
} else if (k == 1) {
rb_b.setText(cvp[k]);
} else if (k == 2) {
rb_c.setText(cvp[k]);
} else if (k == 3) {
rb_d.setText(cvp[k]);
}
}
if ( rb_a.isSelected()){
cvp[y[0]]="A";
}
else if( rb_b.isSelected()){
cvp[y[0]] ="B";
}
else if( rb_c.isSelected()){
cvp[y[0]]="C";
}
else if( rb_d.isSelected()){
cvp[y[0]]="D";
}
else {
rb_a.setChecked(false);
rb_b.setChecked(false);
rb_c.setChecked(false);
rb_d.setChecked(false);
}
int j=t[0] + 4;
if(j == finalJsonarray.length()){
btn_sonrakiSoru.setEnabled(false);
btn_sonrakiSoru.setVisibility(View.INVISIBLE);
btn_kaydet.setVisibility(View.VISIBLE);
btn_kaydet.setEnabled(true);
btn_kaydet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btn_oncekiSoru.setEnabled(false);
}
});
}
}catch (JSONException e) {
e.printStackTrace();
}
}
});
btn_oncekiSoru.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
t[0]-=4;
JSONObject obj2 = null;
try {
obj2 = finalJsonarray.getJSONObject(t[0]);
id_soru1[0] = obj2.getString("id_soru");
soru1[0] = obj2.getString("baslik_soru");
tv_soruNum.setText(id_soru1[0]);
tv_soru.setText(soru1[0]);
for (int k = 0; k <4; k++) {
cvp[k] = obj2.getString("icerik_cevap");
if (k == 0) {
rb_a.setText(cvp[k]);
} else if (k == 1) {
rb_b.setText(cvp[k]);
} else if (k == 2) {
rb_c.setText(cvp[k]);
} else if (k == 3) {
rb_d.setText(cvp[k]);
}
}
if ( rb_a.isSelected()){
cvp[y[0]]="A";
}
else if( rb_b.isSelected()){
cvp[y[0]] ="B";
}
else if( rb_c.isSelected()){
cvp[y[0]]="C";
}
else if( rb_d.isSelected()){
cvp[y[0]]="D";
}
else {
rb_a.setChecked(false);
rb_b.setChecked(false);
rb_c.setChecked(false);
rb_d.setChecked(false);
}
if( t[0] == 0 ){
btn_oncekiSoru.setEnabled(false);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
and my .xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/tv_soruNum"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/tv_soru"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/tv_soruNum"
android:layout_toEndOf="#+id/tv_soruNum"
android:layout_marginLeft="48dp"
android:layout_marginStart="48dp" />
<View
android:layout_width="match_parent"
android:layout_height="3dp"
android:layout_below="#+id/tv_soru"
android:id="#+id/view"
android:layout_marginBottom="25dp"
android:layout_marginTop="35dp"
android:background="#000000" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/rb_cevapa"
android:layout_below="#+id/view"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:checked="false" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/rb_cevapb"
android:layout_below="#+id/rb_cevapa"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="52dp"
android:checked="false" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/rb_cevapc"
android:layout_below="#+id/rb_cevapb"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="68dp"
android:checked="false" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/rb_cevapd"
android:layout_below="#+id/rb_cevapc"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="68dp"
android:checked="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Oncekı"
android:id="#+id/btn_oncekiSoru"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_sonrakiSoru"
android:layout_alignTop="#+id/btn_oncekiSoru"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:text="Sonraki" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Kaydet"
android:id="#+id/btn_kaydet"
android:layout_alignTop="#+id/btn_sonrakiSoru"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
Thanks for help me..
For the RadioButton problem you need to add a RadioGroup like the example below.
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="#+id/radio_pirates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pirates"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_ninjas"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/ninjas"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
For displaying the selected RadioButton you could use a Toast.
Use RadioGroup refer here
Example
activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="How do you like the quality of our tutorials?"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RadioGroup
android:id="#+id/radioGroup"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="#+id/radioButton1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Excellent " />
<RadioButton
android:id="#+id/radioButton2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Satisfactory" />
<RadioButton
android:id="#+id/radioButton3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Below Average" />
</RadioGroup>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/clearBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="onClear"
android:text="Clear " />
<Button
android:id="#+id/submitBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="onSubmit"
android:text="Submit" />
</LinearLayout>
</LinearLayout>
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends Activity {
private RadioGroup radioGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Initialize Radio Group and attach click handler */
radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
radioGroup.clearCheck();
/* Attach CheckedChangeListener to radio group */
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton rb = (RadioButton) group.findViewById(checkedId);
if(null!=rb && checkedId > -1){
Toast.makeText(MainActivity.this, rb.getText(), Toast.LENGTH_SHORT).show();
}
}
});
}
public void onClear(View v) {
/* Clears all selected radio buttons to default */
radioGroup.clearCheck();
}
public void onSubmit(View v) {
RadioButton rb = (RadioButton) radioGroup.findViewById(radioGroup.getCheckedRadioButtonId());
Toast.makeText(MainActivity.this, rb.getText(), Toast.LENGTH_SHORT).show();
}
}
This may helps you.
For your problem, you should use a RadioGroup.
A RadioGroup is basically a group of RadioButtons such that only one can be selected at time. Although you can customise it to allow multiple selections, but by default it allows you to select one RadioButton at a time.
So form a RadioGroup that contains 4 RadioButtons for 4 options.
radioGroup = (RadioGroup) findViewById(R.id.myRadioGroup);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// find which radio button is selected
switch(checkedId){
case R.id.rb_option1: //1st option selected
break;
case R.id.rb_option2: //2nd option selected
break;
case R.id.rb_option3: //3rd option selected
break;
case R.id.rb_option4: //4th option selected
break;
}
}
});
Hope this helps :)