Query about a DatePicker program in android - android

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textview1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click here for change"/>
</LinearLayout>
//////////////////////////////////////////////////
package date_program.day_program;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
public class SampleActivity extends Activity {
/** Called when the activity is first created. */
private int year,month,day;
private TextView tvdisplay;
private Button btpress;
static final int DATE_DIALOG_ID=999;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvdisplay=(TextView)findViewById(R.id.textview1);
btpress=(Button)findViewById(R.id.button1);
tpress.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
showDialog(DATE_DIALOG_ID);
}
});
final Calendar c=Calendar.getInstance();
year=c.get(Calendar.YEAR);
month=c.get(Calendar.MONTH);
day=c.get(Calendar.DAY_OF_MONTH);
Updatedisplay();
}
protected Dialog OnCreateDialog(int Id) {
switch(Id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,datepicking,year,month,day);
}
return null;
}
private DatePickerDialog.OnDateSetListener datepicking =new
DatePickerDialog.OnDateSetListener(){
public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
year=arg1;
month=arg2;
day=arg3;
Updatedisplay();}
};
private void Updatedisplay() {
tvdisplay.setText(new StringBuilder().append("Date-").
append(month+1).append("/").append(day).append("/").append(year));
}
}
In android why I can't change the current date using this program i.e after clicking on the button no dialog box is appeared,is there any wrong in this program please explain in details.Thank you for your time and consideration.

This is the wrong method signature:
protected Dialog OnCreateDialog(int Id) {
switch(Id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,datepicking,year,month,day);
}
The correct method to override is protected Dialog onCreateDialog(int id) (note the lowercase 'o' at the beginning...case matters!). You can protect yourself against such errors in the future by following two simple rules:
Method names, by convention, should always start with a lowercase letter. This is how the entire framework operates
Use the #Override annotation over all methods you override from the framework. In this case, the compiler would have told you that OnCreateDialog is an invalid override of onCreateDialog

Related

Trying to get callbacks from DialogFragment to a fragment but the app is crashing

My app's MainActivity has a ViewPager which has three children(swipe views). When swiped to last child, the ActionBar gets two menu items. On clicking one item, a Dialog pops up to add a name of an item into a Database. On clicking second menu item, another Dialog pops up that prompts user to enter the name of the item that is to be removed from the Database. These Dialogs are getting constructed by separate Dialog Fragments. Basically what I want is to get the callback event from the Dialog that the positive or negative button has been clicked and wanna perform some action in the fragment which is as I mentioned is the last child of my ViewPager. I've seen the Android documentation as well as a Youtube video to learn how to implement the interface, yet my app's crashing.
Here's the code for my DialogFragment which shows a Dialog that prompts the user to enter input and save it to the Database.
package com.example.android.mybusiness;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class AddCigaretteNameDialog extends DialogFragment {
EditText userInput;
String cigaretteName;
DbHelper dbHelper;
public AddCigaretteNameDialogListener listener;
public interface AddCigaretteNameDialogListener {
void onDialogPositiveClick(String name);
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
dbHelper = new DbHelper(getContext());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// SET THE TITLE FOR THE DIALOG.
builder.setTitle(R.string.add_title);
// GET THE LAYOUT INFLATOR
LayoutInflater inflater = getActivity().getLayoutInflater();
// INFLATE THE LAYOUT AND PUT IT INTO A VARIABLE.
// PASS NULL AS PARENT VIEW, BECAUSE IT'S GOING IN THE DIALOG
View view = inflater.inflate(R.layout.edit_text_for_dialogs, null);
// GET THE EDIT_TEXT FROM THE 'VIEW' VARIABLE.
userInput = view.findViewById(R.id.cigarette_name_user_input);
// SET THE LAYOUT FOR THE DIALOG
builder.setView(view);
// SET ACTION BUTTONS
builder.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// GET THE USER INPUT FROM THE EDIT_TEXT ABOVE AND PUT IT INTO A VARIABLE.
cigaretteName = userInput.getText().toString();
// PUT THE USER INPUT IN THE DATABASE.
Boolean result = dbHelper.insertCigaretteName(cigaretteName);
if (result) {
// SHOW SUCCESS MESSAGE THAT CIGARETTE NAME HAS BEEN INSERTED.
Toast.makeText(getContext(), cigaretteName + " has been added successfully!", Toast.LENGTH_SHORT).show();
listener.onDialogPositiveClick(cigaretteName);
} else {Toast.makeText(getContext(), "Something is wrong", Toast.LENGTH_SHORT).show();}
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dismiss();
}
});
// RETURN THE DIALOG.
return builder.create();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
// VERIFY THAT THE HOST ACTIVITY IMPLEMENTS THE CALLBACK INTERFACE
try {
listener = (AddCigaretteNameDialogListener) getTargetFragment();
} catch (ClassCastException e){
// THE ACTIVITY DOESN'T IMPLEMENT INTERFACE, THROW AN EXCEPTION.
throw new ClassCastException(getActivity().toString() + " must implement listener");
}
}
}
And here's the fragment which is the last child of the view pager.
package com.example.android.mybusiness;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
*/
public class Purchase extends Fragment implements AddCigaretteNameDialog.AddCigaretteNameDialogListener {
Spinner spinner;
DbHelper dbHelper;
ArrayAdapter<String> arrayAdapter;
// FRAGMENT'S CONSTRUCTOR.
public Purchase() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// KIND OF REQUIREMENT FOR OPTION MENUS.
setHasOptionsMenu(true);
// INSTANTIATING THE OBJECT TO RUN A FUNCTION, WHICH GETS THE CIGARETTES NAME.
dbHelper = new DbHelper(getContext());
// Inflate the layout for this fragment
// AND PUT IT INTO A VARIABLE SO WIDGETS CAN BE ACCESSED.
View view = inflater.inflate(R.layout.fragment_purchase, container, false);
// FIND THE spinner.
spinner = view.findViewById(R.id.spinner);
// CREATING THIS ADAPTER TO POPULATE THE SPINNER WIDGET.
arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, dbHelper.getAllCigaretteNames());
// SETTING THE ADAPTER TO THE SPINNER, WHICH WILL PROVIDE THE CONTENT TO BE SELECTED BY ME.
spinner.setAdapter(arrayAdapter);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_cigarette:
AddCigaretteNameDialog addCigaretteNameDialog = new AddCigaretteNameDialog();
addCigaretteNameDialog.show(getFragmentManager(), "add_cigarette_name");
return true;
case R.id.remove_cigarette:
RemoveCigaretteNameDailog RemoveCigaretteNameDailog = new RemoveCigaretteNameDailog();
RemoveCigaretteNameDailog.show(getFragmentManager(), "add_cigarette_name");
; return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onDialogPositiveClick(String name) {
arrayAdapter.add(name);
}
}
Here's the crash log:
12-07 13:13:59.278 25327-25327/com.example.android.mybusiness
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.mybusiness, PID: 25327
java.lang.NullPointerException: Attempt to invoke interface method 'void
com.example.android.mybusiness.AddCigaretteNameDialog$AddCigaretteNameDialogListener.onDialogPositiveClick(java.lang.String)'
on a null object reference
at com.example.android.mybusiness.AddCigaretteNameDialog$2.onClick(AddCigaretteNameDialog.java:58)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5296)
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:912)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707)
Line 58 is
listener.onDialogPositiveClick(cigaretteName);
Thanks in advance!
If you use custom dialog class with custom view this would solve your problem. I am posting a code below which shows a custom dialog with views. first of all create a layout file for your dialog design by name dlg_add_cigarette_name inside layout folder
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#drawable/dialog_background_inset"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="16dp"
android:text="Cigrate Name:"
android:id="#+id/tv_label_total"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/layout_total_update"
android:orientation="horizontal"
android:layout_below="#+id/tv_label_total"
android:weightSum="2"
>
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.5"
android:layout_marginLeft="16dp"
android:layout_marginRight="10dp"
android:id="#+id/et_cgrate_name"
android:inputType="text"
/>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/layout_total_update"
android:layout_alignParentRight="true"
android:background="#android:color/transparent"
android:layout_marginRight="70dp"
android:text="OK"
android:layout_marginBottom="20dp"
android:layout_marginTop="20dp"
android:id="#+id/button_ok"
android:textColor="#color/colorPrimaryDark"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/layout_total_update"
android:layout_toLeftOf="#+id/button_ok"
android:layout_marginRight="30dp"
android:text="Cancel"
android:layout_marginBottom="20dp"
android:layout_marginTop="20dp"
android:background="#android:color/transparent"
android:id="#+id/button_cancel"
android:textColor="#color/colorPrimaryDark"
/>
Now inside drawable folder create a new file by name dialog_background_insetand update the file by following code
<?xml version="1.0" encoding="utf-8"?>
<inset
xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="#color/white"
android:insetRight="15dp"
android:insetLeft="15dp">
</inset>
and now in your AddCigaretteNameDialog file update the class by following code
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.drinkwater.reminder.watertracker.R;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
public class AddCigaretteNameDialog extends DialogFragment {
private static final float DIM_AMOUNT = 0.4f;
#BindView(R.id.tv_label_total)
TextView tvLabelTotal;
#BindView(R.id.et_cgrate_name)
EditText etCgrateName;
#BindView(R.id.layout_total_update)
LinearLayout layoutTotalUpdate;
#BindView(R.id.button_ok)
Button buttonOk;
#BindView(R.id.button_cancel)
Button buttonCancel;
#OnClick(R.id.button_cancel)
public void onClick(){
dismiss();
}
#OnClick(R.id.button_ok)
public void onClickOkay(){
unitCallBack.addCigarette(cigaretteName);
}
private Unbinder mUnbinder;
private AddCigaretteName unitCallBack;
private String cigaretteName;
public AddCigaretteNameDialog() {
}
public static AddCigaretteNameDialog newInstance(String title) {
AddCigaretteNameDialog frag = new AddCigaretteNameDialog();
Bundle args = new Bundle();
args.putString("title", title);
frag.setArguments(args);
return frag;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (unitCallBack == null && context instanceof AddCigaretteName) {
unitCallBack = (AddCigaretteName) context;
}
}
#Override
public void onDetach() {
super.onDetach();
unitCallBack = null;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Dialog dialog = super.onCreateDialog(savedInstanceState);
final Window window = dialog.getWindow();
if (window != null) {
window.requestFeature(Window.FEATURE_NO_TITLE);
window.setBackgroundDrawableResource(android.R.color.transparent);
WindowManager.LayoutParams windowLayoutParams = window.getAttributes();
windowLayoutParams.dimAmount = DIM_AMOUNT;
}
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
return dialog;
}
#SuppressLint("NewApi")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.test, container, false);
mUnbinder = ButterKnife.bind(this, view);
etCgrateName.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
cigaretteName=s.toString();
}
#Override
public void afterTextChanged(Editable s) {
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
final int width = getScreenWidth();
int height = getScreenHeight() / 2;
changeWindowSizes(width, ViewGroup.LayoutParams.WRAP_CONTENT);
}
private void changeWindowSizes(int width, int height) {
final Window window = getDialog().getWindow();
if (window != null) {
window.setLayout(width, height);
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
mUnbinder.unbind();
}
#Override
public int getTheme() {
return R.style.CustomDialog;
}
public interface AddCigaretteName {
void addCigarette(String name);
}
public static int getScreenWidth() {
return Resources.getSystem().getDisplayMetrics().widthPixels;
}
public static int getScreenHeight() {
return Resources.getSystem().getDisplayMetrics().heightPixels;
}
}
create a custom theme inside styles file
<style name="CustomDialog" parent="Theme.AppCompat.Light.Dialog">
<item name="android:windowAnimationStyle">#style/CustomDialogAnimation</item>
</style>
<style name="CustomDialogAnimation">
<item name="android:windowEnterAnimation">#anim/translate_left_side</item>
<item name="android:windowExitAnimation">#anim/translate_right_side</item>
</style>
create a package anim inside resfolder and create two files translate_left_sideand translate_right_side
translate_right_side
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0%" android:toXDelta="100%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="600"/>
translate_left_side
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="600"
android:fromXDelta="100%"
android:toXDelta="0%"/>
Your AddCigrateDialog is ready to appear.Now its time to call this dialog from button click.Inside Purchase make an object of AddCigaretteDialog class globally
AddCigaretteNameDialog addCigaretteNameDialog;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_cigarette:
addCigaretteNameDialog= new AddCigaretteNameDialog();
addCigaretteNameDialog= AddCigaretteNameDialog.newInstance("AddCigrateNameDialog");
addCigaretteNameDialog.show(manager,"show");
return true;
case R.id.remove_cigarette:
RemoveCigaretteNameDailog RemoveCigaretteNameDailog = new RemoveCigaretteNameDailog();
RemoveCigaretteNameDailog.show(getFragmentManager(), "add_cigarette_name");
; return true;
default:
return super.onOptionsItemSelected(item);
}
}
And yes don't forget to implement the interface of AddCigaretteDialog inside Purchase dialog
As I am using ButterKnife dependency add the following lines inside your app's gradle file
inal BUTTER_KNIFE_VERSION = "8.8.1"
implementation "com.jakewharton:butterknife:$BUTTER_KNIFE_VERSION"
annotationProcessor "com.jakewharton:butterknife-compiler:$BUTTER_KNIFE_VERSION"

date picker dialog show on edit text double click

I have a search activity with two edit text fields. I like on edit text click date picker dialog to be show. However when I click on edit text, first the keyboard is shown, then after second click the date picker dialog is shown. Could somebody help me?
Here is activity code
package com.example.firstdemoapp.activities;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import com.example.firstdemoapp.R;
import com.example.firstdemoapp.model.StatusDK;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
public class SearchingTaxActivity extends Activity implements OnClickListener,
DatePickerDialog.OnDateSetListener, OnItemSelectedListener {
private Calendar calendarFrom;
private Calendar calendarTo;
private String myFormat;
private SimpleDateFormat sdf;
private EditText dateFrom;
private EditText dateTo;
private EditText activeEditText;
private Calendar activeCalendar;
private Spinner spinnerStatusDK;
private ArrayAdapter spinnerArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_tax);
calendarFrom = Calendar.getInstance();
calendarTo = Calendar.getInstance();
myFormat="dd/MM/yyyy";
sdf = new SimpleDateFormat(myFormat, Locale.US);
dateFrom = (EditText) findViewById(R.id.dateFrom);
dateTo = (EditText) findViewById(R.id.dateTo);
spinnerStatusDK=(Spinner)findViewById(R.id.spinnerStatusDK);
spinnerArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, new StatusDK[] {
new StatusDK( 0, "0" ),
new StatusDK( 1, "1" ),
new StatusDK( 2, "2" ),
});
spinnerStatusDK.setAdapter(spinnerArrayAdapter);
spinnerStatusDK.setOnItemSelectedListener(this);
dateFrom.setOnClickListener(this);
dateTo.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == dateFrom) {
activeCalendar = calendarFrom;
activeEditText = dateFrom;
} else if (v == dateTo) {
activeCalendar = calendarTo;
activeEditText = dateTo;
}
new DatePickerDialog(SearchingTaxActivity.this, this,
activeCalendar.get(Calendar.YEAR),
activeCalendar.get(Calendar.MONTH),
activeCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
activeCalendar.set(Calendar.YEAR, year);
activeCalendar.set(Calendar.MONTH, monthOfYear);
activeCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
if (activeEditText != null) {
activeEditText.setText(sdf.format(activeCalendar.getTime()));
}
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
and the layout for the activity is:
<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="${relativePackage}.${activityClass}" >
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/dateFromTextView"
/>
<EditText
android:id="#+id/dateFrom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/edit_datefrom"
/>
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/dateToTextView"
/>
<EditText
android:id="#+id/dateTo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/edit_dateto"
/>
<Spinner
android:id="#+id/spinnerStatusDK"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
I added android:focusableInTouchMode="false" for edit text in the xml file and this helped me. Because first focus event is fired, and then click event is fired.
you can try to hide a keyboard using InputMethodManager class
private void hideKeyboard(EditText et) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
}
This is best solution which is very useful for open any DatePicker & TimePicker Dialog from EditText,
editdate.setFocusable(false);
editdate.setKeyListener(null);

Unfortunately App has stopped - error in Spinner

I have tried everything but still am not able to figure out what is wrong in this code, whenever I click on the Button 'Get Fare' , a dialog opens showing "Unfortunately app has stopped". Please help ...
Code for MetroFare.java
package com.myapp.anuj;
import com.myapp.anuj.MetroFare;
import com.myapp.anuj.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class MetroFare extends Activity implements OnClickListener, OnItemSelectedListener{
String start[] = {"Shastri Nagar", "Kashmere Gate", "Dwarka Mor"};
String dest[] = {"Pratap Nagar", "Rajiv Chowk", "Kirti Nagar"};
Spinner starting, destination;
Button getfare;
int fare = 0;
int s=0, d=0;
TextView result;
int farearray[][] = {{8,15,14}, {10,12,15}, {21,18,15}};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.kuchbhi);
getfare = (Button) findViewById(R.id.bGetFare);
result = (TextView) findViewById(R.id.tvShowFare);
getfare.setOnClickListener(this);
ArrayAdapter<String> adapterStart = new ArrayAdapter<String>(MetroFare.this, android.R.layout.simple_spinner_item, start);
ArrayAdapter<String> adapterDest = new ArrayAdapter<String>(MetroFare.this, android.R.layout.simple_spinner_item, dest);
starting = (Spinner) findViewById(R.id.spinnerStart);
destination = (Spinner) findViewById(R.id.spinnerDest);
starting.setAdapter(adapterStart);
destination.setAdapter(adapterDest);
starting.setOnItemSelectedListener(this);
destination.setOnItemSelectedListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String sfare = getString(fare);
result.setText(sfare);
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
s = starting.getSelectedItemPosition();
d = destination.getSelectedItemPosition();
fare = farearray[s][d];
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Code for kuchbhi.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Spinner
android:id="#+id/spinnerStart"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Spinner
android:id="#+id/spinnerDest"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/bGetFare"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Fare" />
<TextView
android:id="#+id/tvShowFare"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
As I mentioned, your problem is this call: getString(fare), which is attempting to retrieve a String resource with an id the value of fare. Judging from your code, I'm assuming that you're simply trying to display the String value of fare in a TextView, in which case change that call as follows:
String sfare = String.valueOf(fare);

Search keyword with values in arraylist in android

I am new to android development. I have created a search widget in ActionBar. Now I have to search my keyword with value stored in ArrayList. How can I get value of that searched keyword in a variable? Please give me some sample code for that.
You have to set an OnQueryTextListener to your searchView. Like this:
//listener to when the user changes the text
_searchView.setOnQueryTextListener(new OnQueryTextListener() {
boolean _first = true;
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String str) {
//do you arraylist filtering here
ArrayList<String> arrayList = new ArrayList<String>(); //your arraylist, that you will filter
for(String arrayItem:arrayList){
if(arrayItem.contains(str)){
//add this item to your new list
}
}
return true;
}
});
Then you just have to refresh your listAdapter with the new filtered array.
Try below code snippet
actionbar_serch.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/action_header"
android:gravity="center_vertical"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:id="#+id/edit_search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Search"
android:paddingLeft="15dip"
android:singleLine="true"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textCursorDrawable="#null" />
</LinearLayout>
</LinearLayout>
MainActivity.java
package com.example.demosearch;
import java.util.ArrayList;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
Button btn_search;
ArrayList<String> item_array;
EditText edit_search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
item_array=new ArrayList<String>();
for(int i=0;i<10;i++)
{
item_array.add("item"+i);
}
ActionBar actionBar = getSupportActionBar();
actionBar.setCustomView(R.layout.actionbar_serch);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
btn_search=(Button)findViewById(R.id.btn_search);
edit_search = (EditText) findViewById(R.id.edit_search);
edit_search.addTextChangedListener(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) {
// TODO Auto-generated method stub
String item=s.toString();
for(int i=0;i<item_array.size();i++)
{
if(item.equals(item_array.get(i)))
{
Log.e("Search item position is=", ""+i);
break;
}
}
}
});
}
}
Hope this helps you!!!!!
If it is not working please let me know i will try to help you more.

close custom Dialog android

I created a custom dialog with spinner and OK button. I have populated this spinner with some items and inflated the layout.If I click OK button dialog will dismiss.
I set the spinner
spinner.performCLick();
is there is any way to get spinner selected item and to close the dialog without pressing OK button. I have tried
button.performclick();
but no use.
see my below code it may help you.
package com.Test_dia;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class Test_diaActivity extends Activity {
private Button btn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showalert();
}
});
}
protected void showalert() {
// TODO Auto-generated method stub
final Dialog dia = new Dialog(this);
dia.setContentView(R.layout.dia);
final String a[] = { "select one", "android", "java", "php" };
Button btnok = (Button) dia.findViewById(R.id.button2);
Spinner spin = (Spinner) dia.findViewById(R.id.spinner1);
btnok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dia.dismiss();
}
});
spin.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, a));
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
if (arg2 > 0) {
Toast.makeText(Test_diaActivity.this,
"You Selected :" + a[arg2], Toast.LENGTH_SHORT)
.show();
dia.dismiss();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
dia.show();
}
}
main.xml
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click here" />
</LinearLayout>
dia.xml
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="16dp" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/spinner1"
android:text="ok" />
This code is work for me perfectly ok.
enjoy....
EDIT (removed previous non-suitable answer)
I'm going to assume that your issue is that using setOnItemSelectedListener is firing 'onItemSelected' on startup (thus selecting the first item in the spinner without any user input) and you don't want that.
If that is the case, try the following.
Set a class variable:
private int newSpinner = 0;
Then in the setOnItemSelectedListener:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,int pos, long id) {
if (newSpinner != 0) {
// Do your code thing here
dismiss();
} else {
newSpinner++
}
}
});

Categories

Resources