I'm using broadcast receiver to show a dialog.So the flow of code is something like:
Step1 Getting the requestCode value
Step2 Based on this requestCode the broadCast receiver goes to if or else if or else part
Step3 If the value that i entered using some scanner into the EditText(i.e Scan) doesn't matches it shows a Toast "Item Not Available".
Step 4 Once "Item Not Available" toast comes the focus changes to the Listview which is my problem.
Step5 Again if i pass value to the Scan EditText the Listview get click automatically.
So my question is "How to remove focus from the Listview" and set it to the EditText(i.e Scan).
For Reference I'm attaching the snap with code snippet and the layout.xml.Please have a look and drop your suggestions why the focus is going to the listview.
.java snippet
final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
loc = mspinner.getItemAtPosition(mspinner.getSelectedItemPosition())
.toString();
final String ItemNo;
final String Desc;
final String StockUnit;
final String PickSeq;
final String qtyCount;
final String qtyonHand;
final Button mok;
final Button mcancel;
final Button mplus;
final Button mminus;
final EditText medtQtyCount;
final EditText medtItem;
final EditText medtdesc;
final EditText medtuom;
final DatabaseHandler dbHandler;
final String[] UOM = null;
int requestCode;
LayoutInflater li = LayoutInflater.from(InventoryCount.this);
View promptsView = li.inflate(R.layout.quantityupdate, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
InventoryCount.this);
alertDialogBuilder.setView(promptsView);
//requestCode=Integer.parseInt(intent.getStringExtra("idx"));
requestCode=intent.getIntExtra("idx", -1);
// create alert dialog
final AlertDialog alertDialog = alertDialogBuilder.create();
dbHandler = new DatabaseHandler(InventoryCount.this);
medtuom = (EditText) promptsView.findViewById(R.id.edt_mseshipuom_mic);
mok = (Button) promptsView.findViewById(R.id.btn_mseshipOk_mic);
mcancel = (Button) promptsView.findViewById(R.id.btn_mseshipCancel_mic);
mplus = (Button) promptsView.findViewById(R.id.btn_mseshipIncr_mic);
mminus = (Button) promptsView.findViewById(R.id.btn_mseshipDecr_mic);
medtQtyCount = (EditText) promptsView
.findViewById(R.id.edt_shipShiped_mic);
medtdesc = (EditText) promptsView
.findViewById(R.id.edt_mseshipQtyOrd_mic);
medtItem = (EditText) promptsView
.findViewById(R.id.edt_mseshipItemNo_mic);
if (requestCode == 1) {
}
else if (requestCode == 0) {
// ItemNo
/*if (resultCode == RESULT_OK) {
Log.i("Scan resul format: ",
intent.getStringExtra("SCAN_RESULT_FORMAT"));
*/
String itNo = intent.getStringExtra("SCAN_RESULT");
dbhelper.getReadableDatabase();
MIC_Inventory mic_inventory = dbhelper.getMicInventoryDetails(
loc, itNo);
dbhelper.closeDatabase();
if (mic_inventory != null) {
loc = mspinner.getItemAtPosition(
mspinner.getSelectedItemPosition()).toString();
ItemNo = mic_inventory.getItemno();
Desc = mic_inventory.getItemdescription();
PickSeq = mic_inventory.getPickingseq();
StockUnit = mic_inventory.getStockunit();
qtyonHand = mic_inventory.getQoh();// This value gives
// QOHand
qtyCount = mic_inventory.getQc();
medtItem.setText(ItemNo);
medtdesc.setText(Desc);
medtQtyCount.setText(qtyCount);
medtuom.setText(StockUnit);
mplus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String a = medtQtyCount.getText().toString();
int b = Integer.parseInt(a);
b = b + 1;
a = a.valueOf(b);
medtQtyCount.setText(a);
}
});
mminus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int c = Integer.parseInt(medtQtyCount.getText()
.toString());
c = c - 1;
medtQtyCount.setText(new Integer(c).toString());
}
});
mok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
/*
* UOM[mspinnerUom.getSelectedItemPosition()] =
* medtQtyCount .getText().toString();
*/
MIC_UOMInternal mic_uom = new MIC_UOMInternal();
mic_uom.setLocation(loc);
mic_uom.setItemno(ItemNo);
String updatedqtyCount = medtQtyCount.getText()
.toString();
if (!qtyCount.equals(updatedqtyCount)) {
mic_uom.setQc(Double
.parseDouble(updatedqtyCount));
mic_uom.setUom(StockUnit);
MIC_Inventory mic_Inventory = new MIC_Inventory();
mic_Inventory.setItemdescription(Desc);
mic_Inventory.setItemno(ItemNo);
mic_Inventory.setLocation(loc);
mic_Inventory.setPickingseq(PickSeq);
mic_Inventory.setQc(updatedqtyCount);
mic_Inventory.setQoh(qtyonHand);
mic_Inventory.setStockunit(StockUnit);
dbHandler.getWritableDatabase();
String result = dbHandler
.insertIntoInternal(mic_uom);
if (result.equals("success")) {
result = dbHandler.updateMIC(mic_Inventory);
}
dbHandler.closeDatabase();
}
Intent i = new Intent(InventoryCount.this,
InventoryCount.class);
i.putExtra("et", 1);
i.putExtra("LOCATION", loc);
// i.putExtra("ID", ID);
startActivity(i);
// InventoryCount.this.finish();
}
});
mcancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
alertDialog.cancel();
}
});
// show it
alertDialog.show();
} else {
/*
* Toast.makeText(this, "Item not available",
* Toast.LENGTH_LONG).show();
*/
toastText.setText("Item not available");
Toast toast = new Toast(getBaseContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 410);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(toastLayout);
toast.show();
msearchtext.setText("");
/*msearchtext.setFocusableInTouchMode(true);
msearchtext.requestFocus();*/
/*msearchtext.setSelection(0);
lstView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
*/msearchtext.requestFocus();
}
else if (requestCode == 2) {
}
else
{
toastText.setText("Problem in Scanning");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 410);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(toastLayout);
toast.show();
}
}
Layout.xml
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/border_green"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<TextView
android:id="#+id/txt_InvTitle"
style="#style/pageTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:text="#string/invTitle" />
<View
android:id="#+id/txt_InvView"
android:layout_width="match_parent"
android:layout_height="2dip"
android:layout_below="#+id/txt_InvTitle"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#2E9AFE" />
<LinearLayout
android:id="#+id/invLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#+id/txt_InvView"
android:layout_marginTop="16dp" >
<TextView
android:id="#+id/txtLoc"
style="#style/textRegular"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="left|center"
android:text="#string/location" />
<Spinner
android:id="#+id/sploc"
style="#style/SpinnerItemAppTheme"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:editable="false" />
</LinearLayout>
<LinearLayout
android:id="#+id/invScanType"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/invLocation"
android:layout_gravity="center"
android:layout_marginBottom="3dp"
android:layout_marginLeft="3dp"
android:layout_marginTop="18dp"
android:orientation="horizontal" >
<EditText
android:id="#+id/edt_Search_mic"
style="#style/EditTextAppTheme_Scan"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:layout_weight=".15"
android:gravity="center"
android:hint="#string/scan" />
<RadioGroup
android:id="#+id/radioScanBasedOn_mic"
style="#style/RadioButtonAppTheme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:id="#+id/radioInum_mic"
style="#style/textRegular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:button="#drawable/radiobutton_selector"
android:checked="true"
android:drawablePadding="50dp"
android:paddingLeft="10dip"
android:text="#string/itemno" />
<RadioButton
android:id="#+id/radioNum_mic"
style="#style/textRegular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:button="#drawable/radiobutton_selector"
android:checked="false"
android:layout_marginRight="5dp"
android:layout_weight=".25"
android:drawablePadding="50dp"
android:paddingLeft="10dip"
android:text="#string/manfno" />
<RadioButton
android:id="#+id/radioUpc_mic"
style="#style/textRegular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:button="#drawable/radiobutton_selector"
android:checked="false"
android:layout_marginRight="5dp"
android:layout_weight=".25"
android:drawablePadding="50dp"
android:paddingLeft="10dip"
android:text="#string/upc" />
</RadioGroup>
</LinearLayout>
<HorizontalScrollView
android:id="#+id/scroll_full_mic"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/invScanType" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginTop="25dp"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/lay_fullTitle_mic"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#000000"
android:orientation="horizontal"
android:padding="5dp" >
<TextView
style="#style/textRegular_list"
android:layout_width="105dp"
android:layout_height="wrap_content"
android:text="#string/itemno"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textStyle="bold" />
<TextView
style="#style/textRegular_list"
android:layout_width="130dp"
android:layout_height="wrap_content"
android:gravity="center|left"
android:text="#string/description"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textStyle="bold" />
<TextView
style="#style/textRegular_list"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:gravity="center|left"
android:text="#string/pick_seq"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textStyle="bold" />
<TextView
style="#style/textRegular_list"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:gravity="center|left"
android:text="#string/qoh"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textStyle="bold" />
<TextView
style="#style/textRegular_list"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:gravity="center|left"
android:text="#string/qc"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textStyle="bold" />
<TextView
style="#style/textRegular_list"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:gravity="center|left"
android:text="#string/uom"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textStyle="bold" />
</LinearLayout>
<ListView
android:id="#+id/lst_msefull_mic"
android:layout_width="match_parent"
android:layout_height="match_parent"
style="#style/ListViewAppTheme.White" >
</ListView>
</LinearLayout>
</HorizontalScrollView>
<LinearLayout
android:id="#+id/lay_PO_mic"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="41dp"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:visibility="gone" >
<Button
android:id="#+id/btn_OrderLstImport_mic"
android:layout_width="100dp"
android:layout_height="100dp"
android:textSize="18dp"
android:textStyle="bold" />
<Button
android:id="#+id/btn_OrderLstExport_mic"
android:layout_width="100dp"
android:layout_height="100dp"
android:textSize="18dp"
android:textStyle="bold" />
<Button
android:id="#+id/btn_OrderLstExit_mic"
android:layout_width="100dp"
android:layout_height="100dp"
android:textSize="18dp"
android:textStyle="bold" />
</LinearLayout>
</RelativeLayout>
Add a textwatcher to edit text and check when text is not blank and it is not equal to expected text then only switch the focus.
/* Set Text Watcher listener */
yourEditText.addTextChangedListener(passwordWatcher);
and check for text once user enter text
private final TextWatcher passwordWatcher = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void afterTextChanged(Editable s) {
if (s.length() != 0 && passwordEditText.getText().equals("Your expected text")) {
// show your toast and change focus
}
}
}
You should make your listview not focusable by using setFocusable(false) when not required and when you get response correctly from barcode scanner then you can again make your listview focusable.
Related
I am using rest API and facing some issue when embedding an API. How do I save spinner and radio button data by value and using retrofit2.This API is for calculating BMR and BMR Please help!
Here is BMIquestions.java
public class BMIquestions extends AppCompatActivity implements View.OnClickListener{
Button nextbtn;
ImageButton date;
DatePickerDialog datePickerDialog;
EditText age, height, weight;
// Let's assume 1 = male and 0 = female
// Declare a RadioGroup object reference
RadioGroup rgGender;
// Declare RadioButton object references for Male and Female
RadioButton rbMale, rbFemale;
private String gender=null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bmiquestions);
getSupportActionBar().hide();
nextbtn = findViewById(R.id.Next);
date = findViewById(R.id.calender);
age = findViewById(R.id.age);
height = findViewById(R.id.currentHeight);
weight = findViewById(R.id.currentHeight);
rgGender = findViewById(R.id.gender_group);
rbMale = findViewById(R.id.male);
rbFemale = findViewById(R.id.female);
rgGender.clearCheck();
rgGender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
rbMale = group.findViewById(R.id.male);
rbFemale = group.findViewById(R.id.female);
if(rbMale.isSelected()){
rbMale.setTag("1");
rbMale.getTag().toString();
if(rbFemale.isSelected()){
rbFemale.setTag("0");
rbFemale.getTag().toString();
}
}
}
});
findViewById(R.id.female).setOnClickListener(this);
findViewById(R.id.male).setOnClickListener(this);
findViewById(R.id.Next).setOnClickListener(this);
String[] level = new String[]{"Not Very Activ", "Lightly Active", "Active", "Very Active"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(
this,
R.layout.drop_down_items,
level
);
AutoCompleteTextView autoCompleteTextView = findViewById(R.id.type);
autoCompleteTextView.setAdapter(adapter);
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(BMIquestions.this, autoCompleteTextView.getText().toString(), Toast.LENGTH_SHORT).show();
if(autoCompleteTextView.getText().toString().equals("Lightly Active")){
autoCompleteTextView.setTag("1.55");
}
}
});
date.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onClick(View view) {
// Calender class 's instance and get current,date ,month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);//current year
int mMonth = c.get(Calendar.MONTH);//current month
int mDay = c.get(Calendar.DAY_OF_MONTH);//current date
final int noofyears = (int) (mYear - c.get(Calendar.YEAR)); //calculate age
//date picker dialog
datePickerDialog = new DatePickerDialog(BMIquestions.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
age.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
}
}, mYear, mMonth, mDay);
DatePicker dp = datePickerDialog.getDatePicker();
WindowManager.LayoutParams params = datePickerDialog.getWindow().getAttributes();
//params.gravity = Gravity.CENTER_HORIZONTAL;
params.width = 50; // dialogWidth;
params.height = 100; // dialogHeight;
datePickerDialog.show();
}
});
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.Next:
openHomePage();
break;
case R.id.male:
gender="0";
break;
case R.id.female:
rbFemale.setTag("0");
gender=rbFemale.getTag().toString();
break;
}
}
public void openHomePage() {
String userHeight = height.getText().toString();
String userWeight = weight.getText().toString();
String userAge = age.getText().toString();
HashMap<String, String> meMap = new HashMap<String, String>();
meMap.put("height", userHeight);
meMap.put("age", userAge);
meMap.put("gender", gender);
//meMap.put("activity_level",act);
meMap.put("current_weight",userWeight);
Call<QuestionResponse> call = RetrofitClient
.getInstance()
.getApi()
.calculation(meMap);
call.enqueue(new Callback<QuestionResponse>() {
#Override
public void onResponse(Call<QuestionResponse> call, Response<QuestionResponse> response) {
QuestionResponse questionResponse = response.body();
if (response.isSuccessful()) {
if (questionResponse.getStatus().equals("SUCCESS")) {
Toast.makeText(BMIquestions.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(BMIquestions.this, HomePage.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
} else {
Toast.makeText(BMIquestions.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(BMIquestions.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<QuestionResponse> call, Throwable t) {
Toast.makeText(BMIquestions.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Intent i=new Intent(BMIquestions.this,HomePage.class);
startActivity(i);
}
}
Here is activity_bmiquestions.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.questions.BMIquestions">
<TextView
android:id="#+id/targetWeight"
android:layout_width="386dp"
android:layout_height="wrap_content"
android:fontFamily="#font/roboto_regular"
android:gravity="center"
android:paddingStart="12dp"
android:paddingTop="60dp"
android:text="Tell us About Youself"
android:textColor="#color/black"
android:textSize="22sp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="122dp"
android:fontFamily="#font/roboto_regular"
android:text="Gender:"
android:textColor="#color/black"
android:textSize="14dp" />
<RadioGroup
android:id="#+id/gender_group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="142dp"
android:paddingStart="24dp"
android:orientation="horizontal"
>
<RadioButton
android:id="#+id/female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
/>
<RadioButton
android:id="#+id/male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male" />
</RadioGroup>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="18dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal">
<EditText
android:id="#+id/age"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:hint="DD/MM/YYYY" />
<ImageButton
android:id="#+id/calender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:background="#drawable/ic_baseline_calendar_today_24" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="120dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="202dp"
android:fontFamily="#font/roboto_regular"
android:text="Height in centimeter"
android:textColor="#color/black"
android:textSize="14dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal">
<EditText
android:id="#+id/currentHeight"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:hint="Enter your height"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:text="cm"/>
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="17dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="202dp"
android:fontFamily="#font/roboto_regular"
android:text="When were you born ?"
android:textColor="#color/black"
android:textSize="14dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="120dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="202dp"
android:fontFamily="#font/roboto_regular"
android:text="Weight in kilogram"
android:textColor="#color/black"
android:textSize="14dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:orientation="horizontal">
<EditText
android:id="#+id/currentWeight"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:hint="Enter your weight" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="kg"
android:textColor="#color/black" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="440dp"
android:layout_marginStart="10dp">
<com.google.android.material.textfield.TextInputLayout
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"
android:layout_width="330dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="80dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="80dp"
android:hint="Activity Level" >
<AutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/type"
android:inputType="none">
</AutoCompleteTextView>
</com.google.android.material.textfield.TextInputLayout>
</RelativeLayout>
<android.widget.Button
android:id="#+id/Next"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="21dp"
android:background="#color/dark_grey"
android:text="Next"
android:textColor="#color/white"
android:textSize="15sp"
android:textStyle="bold"></android.widget.Button>
</RelativeLayout>
Here is Api Interface
public interface Api{
//GetCalculations
#POST("calculation")
Call<QuestionResponse> calculation(
#Body HashMap<String, String> body
);
}
Here is RetrofitClient.java
package com.example.signup.ui.api;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
//singeleton class defining retrofit client
//define base url
//initialize retrofit object
private static final String BASE_URL = "http://xxx.xxx.xxx.xxx:xxxx/api/";
private static RetrofitClient retrofitClient;
private static Retrofit retrofit;
// HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
// interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
private RetrofitClient() {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
//return instances when above method call
public static synchronized RetrofitClient getInstance() {
if (retrofitClient==null) {
retrofitClient = new RetrofitClient();
}
return retrofitClient;
}
public Api getApi() {
return retrofit.create(Api.class);
}
}
How can I fix this problem?
so I am trying to create an activity, and then add onclick listeners to it, but it wont let me refer. So the moment I open this activity in my app, my app crashes, saying 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference'
I have no idea why this is happening. I have correctly names them in accordance with the xml file as well.
Please help.
public class SubtaskActivity extends AppCompatActivity {
EditText etSubtaskName;
Button btnDone;
RadioGroup radgrpPri, radgrpTime;
RadioButton radbtnPriHigh, radbtnPriMed, radbtnPriLow, radbtnTimeMore, radbtnTimeMed, radbtnTimeLess;
boolean priHigh, priMed, priLow, timeMore, timeMed, timeLess;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
btnDone = findViewById(R.id.btnDone);
radgrpPri = findViewById(R.id.radgrpPri);
radgrpTime = findViewById(R.id.radgrpTime);
radbtnPriHigh = findViewById(R.id.radbtnPriHigh);
radbtnPriMed = findViewById(R.id.radbtnPriMed);
radbtnPriLow = findViewById(R.id.radbtnPriLow);
radbtnTimeMore = findViewById(R.id.radbtnTimeMore);
radbtnTimeMed = findViewById(R.id.radbtnTimeMed);
radbtnTimeLess = findViewById(R.id.radbtnTimeLess);
etSubtaskName = findViewById(R.id.etSubtaskName);
radgrpPri.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (radbtnPriHigh.isChecked())
{
priHigh = true;
priLow = false;
priMed = false;
}
else if (radbtnPriMed.isChecked())
{
priHigh = false;
priLow = false;
priMed = true;
}
else if (radbtnPriLow.isChecked())
{
priHigh = false;
priLow = true;
priMed = false;
}
}
});
radgrpTime.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (radbtnTimeMore.isChecked())
{
timeMore = true;
timeMed = false;
timeLess = false;
}
else if (radbtnTimeMed.isChecked())
{
timeMore = false;
timeMed = true;
timeLess = false;
}
else if (radbtnTimeLess.isChecked())
{
timeMore = false;
timeMed = false;
timeLess = true;
}
}
});
btnDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = etSubtaskName.getText().toString().trim();
Intent intent = new Intent(SubtaskActivity.this, TaskInfo.class);
intent.putExtra("subtaskName", name);
intent.putExtra("priHigh", priHigh);
intent.putExtra("priMed", priMed);
intent.putExtra("priLow", priLow);
intent.putExtra("timeMore", timeMore);
intent.putExtra("timeMed", timeMed);
intent.putExtra("timeLess", timeLess);
startActivity(intent);
}
});
}
}
XML File :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/it"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:background="#color/background"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/background"
android:orientation="vertical">
<TextView
android:id="#+id/tvSubtaskPriorityHeading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="16dp"
android:fontFamily="#font/roboto"
android:text="#string/priority_of_subtask"
android:textColor="#B8AEAE"
android:textSize="16sp" />
<RadioGroup
android:id="#+id/radgrpPri"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<RadioButton
android:id="#+id/radbtnPriHigh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:buttonTint="#color/red"
android:text="#string/high"
android:textColor="#color/white" />
<RadioButton
android:id="#+id/radbtnPriMed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:buttonTint="#color/yellow"
android:text="#string/medium"
android:textColor="#color/white" />
<RadioButton
android:id="#+id/radbtnPriLow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:buttonTint="#color/green"
android:text="#string/low"
android:textColor="#color/white" />
</RadioGroup>
<TextView
android:id="#+id/tvTimeWeightHeading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="32dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="16dp"
android:fontFamily="#font/roboto"
android:text="#string/time_this_subtask_may_consume"
android:textColor="#B8AEAE"
android:textSize="16sp" />
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/floating_hint_time_minutes"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:hintTextAppearance="#style/FlotatingHintStyle">
<EditText
android:id="#+id/etSubtaskName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:ems="10"
android:fontFamily="#font/roboto"
android:hint="#string/name_your_subtask"
android:inputType="textPersonName"
android:maxLength="20"
android:textColor="#color/white"
android:textColorHint="#B8AEAE"
android:textSize="14sp" />
</com.google.android.material.textfield.TextInputLayout>
<RadioGroup
android:id="#+id/radgrpTime"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<RadioButton
android:id="#+id/radbtnTimeMore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:buttonTint="#color/red"
android:text="#string/more"
android:textColor="#color/white" />
<RadioButton
android:id="#+id/radbtnTimeMed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:buttonTint="#color/yellow"
android:text="#string/medium"
android:textColor="#color/white" />
<RadioButton
android:id="#+id/radbtnTimeLess"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:buttonTint="#color/green"
android:text="#string/less"
android:textColor="#color/white" />
</RadioGroup>
</LinearLayout>
<Button
android:id="#+id/btnDone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="16dp"
android:layout_marginTop="32dp"
android:layout_marginRight="16dp"
android:gravity="center_horizontal"
android:text="#string/done"
app:backgroundTint="#color/orange_accent" />
</LinearLayout>
You didn't call in onCreate method setContentView(R.layout.youractivity). If you didn't, Android doesn't know what to render, so there are no views for you to provide.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.youractivity);
}
just set your (xml)layout file to setContentView in onCreate()
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
}
I'm having problems getting this view just to show up. When I go to the screen that should have the view nothing happens in the view Here are the relevant files:
CreateTimerActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_timer);
final Context context = this;
mVisible = true;
mControlsView = findViewById(R.id.create_timer_content_controls);
mContentView = findViewById(R.id.create_timer_content);
// Set up the user interaction to manually show or hide the system UI.
mContentView.setOnClickListener((View view) -> {
toggle();
});
/*XmlPullParser parser = getResources().getXml(R.id.view_tim);
AttributeSet attributes = Xml.asAttributeSet(parser);*/
final TableLayout tableLayout = (TableLayout) findViewById(R.id.create_timer_table);
TimerFormView timerFormView = new TimerFormView(context, tableLayout);
timerFormView.initializeComponents();
}
TimerFormView.java
public class TimerFormView extends TableLayout {
private Context context;
private final ContentValues timerValues;
private final ContentValues timerSegmentValues;
private final TableLayout tableLayout;
public TimerFormView(Context context, TableLayout tableLayout) {
this(context, null, tableLayout);
}
public TimerFormView(Context context, AttributeSet attrs, TableLayout tableLayout) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.TimerFormView, 0, 0);
String titleText = "Hello";
#SuppressWarnings("ResourceAsColor")
int valueColor = a.getColor(0,
android.R.color.holo_blue_light);
a.recycle();
this.context = context;
this.tableLayout = tableLayout;
TimerDatabase timerDatabase = new TimerDatabase(context);
SQLiteDatabase databaseHelper = timerDatabase.getWritableDatabase();
timerValues = new ContentValues();
timerValues.put(TimerDatabase.TimerEntry.COLUMN_NAME_TIMER_NAME, "");
timerSegmentValues = new ContentValues();
}
public TimerFormView(Context context, AttributeSet attrs)
{
this(context, attrs, null);
}
public void initializeComponents() {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.view_timer_form, this, true);
final TextView timerNameTextView = (TextView) findViewById(R.id.timerNameTxt);
timerNameTextView.setSingleLine(true);
InputFilter[] filterArrayTimerName = new InputFilter[1];
filterArrayTimerName[0] = new InputFilter.LengthFilter(32);
timerNameTextView.setFilters(filterArrayTimerName);
final Button saveTimerBtn = (Button) findViewById(R.id.saveTimerBtn);
saveTimerBtn.setEnabled(false);
saveTimerBtn.setOnClickListener((View v) -> {
timerValues.put(TimerDatabase.TimerEntry.COLUMN_NAME_TIMER_NAME, timerNameTextView.getText().toString());
});
// Enable the timer to be saved once text is entered
TextWatcher timerNameTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s){
if(s.length() > 0) {
saveTimerBtn.setEnabled(true);
} else {
saveTimerBtn.setEnabled(false);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){
// you can check for enter key here
}
public void onTextChanged (CharSequence s, int start, int before,int count) {
}
};
EditText timerNameEditText = (EditText) findViewById(R.id.timerNameTxt);
timerNameEditText.addTextChangedListener(timerNameTextWatcher);
// Segments
final TextView segmentNameTextView = (TextView) findViewById(R.id.segmentNameTxt);
segmentNameTextView.setSingleLine(true);
InputFilter[] filterArraySegmentName = new InputFilter[1];
filterArraySegmentName[0] = new InputFilter.LengthFilter(32);
segmentNameTextView.setFilters(filterArraySegmentName);
Button addSegmentBtn = (Button) findViewById(R.id.addSegmentBtn);
addSegmentBtn.setEnabled(false);
addSegmentBtn.setOnClickListener((View v) -> {
// Content for the new segment
TableRow segmentTableRow = new TableRow(context);
segmentNameTextView.setText(segmentNameTextView.getText());
segmentTableRow.addView(segmentNameTextView);
tableLayout.addView(segmentTableRow);
timerSegmentValues.put(TimerDatabase.TimerSegment.COLUMN_NAME_SEGMENT_NAME, segmentNameTextView.getText().toString());
});
TextWatcher segmentNameTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s){
if(s.length() > 0) {
saveTimerBtn.setEnabled(true);
} else {
saveTimerBtn.setEnabled(false);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){
// you can check for enter key here
}
public void onTextChanged (CharSequence s, int start, int before,int count) {
}
};
EditText segmentNameEditText = (EditText) findViewById(R.id.segmentNameTxt);
segmentNameEditText.addTextChangedListener(segmentNameTextWatcher);
EditText segmentDurationEditText = (EditText) findViewById(R.id.segmentDurationTxt);
//segmentDurationEditText.addTextChangedListener(segmentTextWatcher);
EditText segmentRepeatEditText = (EditText) findViewById(R.id.segmentRepeatTxt);
//segmentRepeatEditText.addTextChangedListener(segmentTextWatcher);
setVisibility(View.VISIBLE);
super.layout(50, 50, 50, 50);
setOrientation(LinearLayout.HORIZONTAL);
setGravity(Gravity.CENTER_VERTICAL);
}
}
view_timer_form.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="400dp" android:layout_height="400dp">
<TableRow android:layout_width="400dp" android:layout_height="400dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Create Timer"
android:id="#+id/createTimerLbl" />
</TableRow>
<TableRow android:layout_width="match_parent" android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Timer Name"
android:id="#+id/timerNameLbl"
android:gravity="top" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/timerNameTxt"
android:layout_column="1" />
</TableRow>
<TableRow android:layout_width="match_parent" android:layout_height="wrap_content" android:id="#+id/addSegmentNameRow">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Segment Name"
android:id="#+id/segmentNameLbl"
android:gravity="top" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/segmentNameTxt"
android:layout_column="1" />
</TableRow>
<TableRow android:layout_width="match_parent" android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Duration"
android:id="#+id/segmentDurationLbl"
android:gravity="top" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/segmentDurationTxt"
android:inputType="number"
android:layout_column="1" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Seconds"
android:id="#+id/durationSecondsLbl"
android:gravity="top" />
</TableRow>
<TableRow android:layout_width="match_parent" android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Repeat"
android:id="#+id/segmentRepeatLbl"
android:gravity="top" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/segmentRepeatTxt"
android:inputType="number"
android:layout_column="1" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Times"
android:id="#+id/segmentRepeatTimesLbl"
android:gravity="top" />
</TableRow>
<TableRow android:layout_width="match_parent" android:layout_height="wrap_content" android:id="#+id/addSegmentBtnRow">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Segment"
android:id="#+id/addSegmentBtn" />
</TableRow>
<TableRow android:layout_width="match_parent" android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save Timer"
android:id="#+id/saveTimerBtn" />
</TableRow>
</TableLayout>
activity_create_timer.xml
<FrameLayout 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="#0099cc"
tools:context="com.example.timer.CreateTimerActivity">
<TextView android:id="#+id/create_timer_content" android:layout_width="match_parent"
android:layout_height="match_parent" android:keepScreenOn="true" android:textColor="#33b5e5"
android:textStyle="bold" android:textSize="50sp" android:gravity="center"
android:text="" />
<!-- This FrameLayout insets its children based on system windows using
android:fitsSystemWindows. -->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:id="#+id/create_timer_content_controls"
style="?metaButtonBarStyle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
tools:ignore="UselessParent">
<com.example.timer.views.TimerFormView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/create_timer_table">
</com.example.timer.views.TimerFormView>
</LinearLayout>
</FrameLayout>
</FrameLayout>
I had such issue and I solved it in this ways...
Don't call any instance of customView or even static vars from activity.
only define constructor with (Context, Attributes)
and initialize everything you want inside customView class.
Good luck
If i'm click OK how to choose pick a value one service in radio button but different value.
void OpenDialogService() {
closeLyt.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
cancelTxt.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
okTxt.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
dialog.dismiss();
Bundle b = activity.getIntent().getExtras();
if(b == null)
b = new Bundle();
b.putString("service_id", "1");
startActivity(new Intent(activity, Step1.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP).putExtras(b));
overridePendingTransition(R.anim.push_left_in,R.anim.push_left_out);
}
});
dialog.show();
}
In this line for primary service :
b.putString("service_id", "1")
How i make conditional if service other give value :
b.putString("service_id", "2")
This is code snippet how you can achieve this with the help of RadioGroups
Your dialog layout should look like this :-
<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:orientation="vertical"
tools:context="com.example.test.MainActivity" >
<TextView
android:id="#+id/headerTxt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#ff669900"
android:gravity="center_horizontal"
android:padding="5dp"
android:text="Pick Service"
android:textColor="#FFF"
android:textSize="20sp" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_margin="10dp"
android:layout_marginTop="32dp" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/primaryTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:checked="true"
android:text="Primary Service"
android:textSize="18sp" />
<TextView
android:id="#+id/primaryContentTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/primaryTxt"
android:text=" -Dusting \n -Sweeping \n -Washing \n -Cleaning " />
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" >
<RadioButton
android:id="#+id/service_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<RadioButton
android:id="#+id/service_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp" />
</RadioGroup>
<TextView
android:id="#+id/otherTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/primaryContentTxt"
android:layout_marginTop="10dp"
android:checked="true"
android:gravity="left"
android:text="Other Service(Soon)"
android:textSize="18sp" />
</RelativeLayout>
</RelativeLayout>
<LinearLayout
android:id="#+id/closeLyt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/darker_gray"
android:weightSum="2" >
<TextView
android:id="#+id/cancelTxt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="1dp"
android:layout_weight="1"
android:background="#fff"
android:gravity="center"
android:padding="5dp"
android:text="CANCEL"
android:textColor="#000"
android:textSize="20sp" />
<TextView
android:id="#+id/okTxt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="1dp"
android:layout_weight="1"
android:background="#fff"
android:gravity="center"
android:padding="5dp"
android:text="OK"
android:textColor="#000"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
And you can inflate this layout in custom dialog box and with the help of radio buttons you can choose service type
int serviceNumber = 0;
void OpenDialogService() {
final Dialog dialog = new Dialog(this);
dialog.getWindow();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.pop_new_order2);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
TextView headerTxt = (TextView) dialog.findViewById(R.id.headerTxt);
TextView okTxt = (TextView) dialog.findViewById(R.id.okTxt);
TextView cancelTxt = (TextView) dialog.findViewById(R.id.cancelTxt);
TextView primaryTxt = (TextView) dialog.findViewById(R.id.primaryTxt);
TextView otherTxt = (TextView) dialog.findViewById(R.id.otherTxt);
TextView primaryContentTxt = (TextView) dialog.findViewById(R.id.primaryContentTxt);
LinearLayout closeLyt = (LinearLayout) dialog.findViewById(R.id.closeLyt);
// Radio Buttons
final RadioGroup radio = (RadioGroup) dialog.findViewById(R.id.radioGroup1);
radio.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
View radioButton = radio.findViewById(checkedId);
int index = radio.indexOfChild(radioButton);
Toast.makeText(getApplicationContext(), "service" +index, 500).show();
serviceNumber = index+1;
}
});
headerTxt.setText("Pick Services");
//TODO change color here
// headerTxt.setBackgroundResource(R.drawable.bg_dialog_header_success);
// closeLyt.setBackgroundResource(R.color.selector_close_alert_dialog_success);
closeLyt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
cancelTxt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
okTxt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
Bundle b = getIntent().getExtras();
if (b == null)
b = new Bundle();
b.putString("service_id", String.valueOf(serviceNumber));
Toast.makeText(getApplicationContext(), "service " + String.valueOf(serviceNumber), 500).show();
//TODO Handle Activity Transition Here
// startActivity(new Intent(MainActivity.this,
// Step1.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP).putExtras(b));
// overridePendingTransition(R.anim.push_left_in,
// R.anim.push_left_out);
}
});
dialog.show();
}
Result
You can get the selected item id of RadioGroup using, radioGroup.getCheckedRadioButtonId() and use if-else to choose different strings.
int id = radioGroup.getCheckedRadioButtonId();
if(id == radioButton1)
{
b.putString("service_id", "1");
}
else if(id == radioButton1)
{
b.putString("service_id", "2");
}
the question I going to ask, might be kind of complicated.
Pardon me, if I can't explain it clearly.
It's my first time having touch with android coding.
I would like to do a calculation doing android .
It's about Fuel Log.
What I want to do right now is
When I keep in the price(edittext) and pump(edittext),
the output will be shown straight away in the cost(textview), that I've placed.
I would want to do that,
but I don't think I have did the right coding for it.
I've tried out myself,
but I didn't run the application, cause I think that the codes I've done is not fully completed/right.
I would love to hear the advice from you guys.
Could someone please help me out with it?
Thank you,
your help will be much appreciate.
(:
MainActivity.java
public class MainActivity extends Activity {
Button saveButton = null;
EditText dateEdit;
EditText priceEdit;
EditText pumpEdit;
TextView costView;
EditText odometerEdit;
TextView fconView;
public boolean isNumeric(String str)
{
return str.matches("-?\\d+(\\.\\d+)?");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle bundle = getIntent().getExtras();
float price = Float.parseFloat(bundle.getString("priceEdit"));
float pump = Float.parseFloat(bundle.getString("pumpEdit"));
costView = (TextView)findViewById(R.id.tcost);
dateEdit = (EditText)findViewById(R.id.date);
priceEdit = (EditText)findViewById(R.id.fuelprice);
pumpEdit = (EditText)findViewById(R.id.fuelpump);
TextWatcher mCostChangeWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
if(!TextUtils.isEmpty(priceEdit.getText()) && !TextUtils.isEmpty(pumpEdit.getText())){
costView.setText(calculateCost(priceEdit.getText(), pumpEdit.getText()));
}
}
private float calculateCost(float price, float pump) {
final float costCal = (price * pump);
return costCal;
// TODO Auto-generated method stub
}
};
priceEdit.addTextChangedListener(mCostChangeWatcher);
pumpEdit.addTextChangedListener(mCostChangeWatcher);
saveButton = (Button) findViewById(R.id.saveBTN);
saveButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());
try
{
dbAdaptor.open();
String date = dateEdit.getText().toString();
String price = priceEdit.getText().toString();
String pump = pumpEdit.getText().toString();
String cost = Float.toString();
String odometer = odometerEdit.getText().toString();
String fcon = fconView.getText().toString();
dbAdaptor.insertLog(date, price, pump, cost, odometer, fcon);
}
catch(Exception e){
Log.d("Fuel Log", e.getMessage());
}
finally
{
if(dbAdaptor != null)
dbAdaptor.close();
}
}
});
}//oncreate
}//main
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_height="fill_parent"
tools:context=".MainActivity" >
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1">
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/datetxtview"
android:text="#string/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/date"
android:text=""
android:inputType="date"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fuelpricetxtview"
android:text="#string/fuelprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/fuelprice"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fuelpumptxtview"
android:text="#string/fuelpump"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/fuelpump"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow4"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/totalcosttxtview"
android:text="#string/totalcost"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<TextView
android:id="#+id/tcost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</TableRow>
<TableRow
android:id="#+id/tableRow5"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/odometertxtview"
android:text="#string/odometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/odometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow6"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fctxtview"
android:text="#string/fc"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<TextView
android:id="#+id/fcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</TableRow>
</TableLayout>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/saveBTN"
android:text="#string/save"
android:layout_width="wrap_content"
android:layout_height="60px" >
</Button>
<Button
android:id="#+id/cancelBTN"
android:text="#string/cancel"
android:layout_width="wrap_content"
android:layout_height="60px" >
</Button>
</LinearLayout>
</LinearLayout>
add change lister to both edit text
priceEdit.addTextChangedListener(mCostChangeWatcher);
pumpEdit.addTextChangedListener(mCostChangeWatcher);
TextWatcher mCostChangeWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
if(!TextUtils.isEmpty(priceEdit.getText()) && !TextUtils.isEmpty(pumpEdit.getText())){
costEdit.setText(calculateCost(priceEdit.getText(), pumpEdit.getText()));
}
}
};