Pass Date from Datepicker to Spinner selected item and load API Response in Fragment
I have a working app where user select an option from Spinner the datepicker auto open user select the date and view data. However, I am trying to include an Imagebutton(calendar) which opens a date picker and than on selection of date data should load. The process should be : select Option from spinner -> select date from datepicker by clicking Imagebutton -> load/display data.
this is the imagebutton onclick event:
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Calendar cldr = Calendar.getInstance();
int year = cldr.get(Calendar.YEAR);
int month = cldr.get(Calendar.MONTH);
int dayOfMonth = cldr.get(Calendar.DAY_OF_MONTH);
// date picker dialog
datePickerDialog = new DatePickerDialog(Dashboard.this,
AlertDialog.THEME_DEVICE_DEFAULT_DARK, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar calendar1 = Calendar.getInstance();
calendar1.set(year, month, dayOfMonth);
Date chosendate = calendar1.getTime();
calendar1.set(year, month, dayOfMonth);
chosendate = calendar1.getTime();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
Locale.JAPAN);
franchiseDate = formatter.format(chosendate);
}
}, year, month, dayOfMonth);
datePickerDialog.show();
datePickerDialog.getDatePicker().setMaxDate(cldr.getTimeInMillis());
}
this is the spinner onItemSelected event:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int
position, long l) {
selectedItem = spinner.getSelectedItem().toString();
selectedPosition = spinner.getSelectedItemPosition();
if (selectedItem.equals("Revenue by Centre")) {
// String centerDate = franchiseDate;
Bundle bundle = new Bundle();
bundle.putString("authToken", authToken);
bundle.putString("centreDate", franchiseDate);
spinner.setEnabled(false);
Centre centre = new Centre();
centre.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.multiFrame, Centre.class,
bundle);
fragmentTransaction.commit();
}
Data is displayed in fragment, date is also a var that is passed to fragment class. If I am including spinner.setOnItemSelectedListener in imageButton.setOnClickListener event than data is loading after I select new date ie select a date no data again select a date data is loading for previously selected date.
1 answer
-
answered 2022-05-07 05:08
tintin
Resolved....call the fragment in onDateSet
do you know?
how many words do you know
See also questions close to this topic
-
different between call view by name or use binding in android
i'am a newest in android kotlin
I want to know what is the difference between the two lines of code below and which one is better to use
class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMaindinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) bindins = DataBindingutil.setContentview( this, R.layout.activity_main) textview.text="text"//or binding.textview.text="text" }}
-
Get multiple times current time on single Button
I have a button showing text START when I click on it I shows me current time in textview.(I consider this time as start time). Than convert the text on Button into STOP. When I click on it again show me current time on another textview(I consider this time as stop time). And then calculate the difference between these two time. I want this same working for multiple time. I means First button show Text ENTER. When I click on it it should show current time in textview.(I will consider this time as Enter time). Than convert the text on Button into START. When I click on it again show me current time on another textview(I will consider this time as start time). Than convert the text on Button into STOP. When I click on it again show me current time on another textview(I will consider this time as STOP time). And last Than convert the text on Button into EXIT. When I click on it again show me current time on another textview(I will consider this time as Exit time).
Here is my code:
btn_start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isStarted){ Calendar calendar = Calendar.getInstance(); SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa"); String time = format.format(calendar.getTime()); tvend.setText(time); try { Date date1 = format.parse(tvend.getText().toString()); Date date2 = format.parse(tvstarttime.getText().toString()); long mills = date1.getTime() - date2.getTime(); Log.v("Data1", ""+date1.getTime()); Log.v("Data2", ""+date2.getTime()); int hours = (int) (mills/(1000 * 60 * 60)); int mins = (int) (mills % (1000*60*60)); String diff = hours + ":" + mins; diffence.setText(diff); } catch (ParseException e) { e.printStackTrace(); } btn_start.setText("START"); }else { Calendar calendar = Calendar.getInstance(); SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa"); String time1 = format.format(calendar.getTime()); tvstarttime.setText(time1); btn_start.setText("STOP"); } isStarted = !isStarted; } });
-
android emulator disable microphone when launching device
How do we disable the (virtual) microphone when launching the emulator?
Situation
When launching an Android Studio stock emulator device, the microphone is always enabled and listening.Why would we want this fix
- Convenience, Many users have a microphone headset and when the microphone is enabled, they lose noise canceling and/or stereo. It can be extremely annoying, forcing the user to disconnect the device which swaps the emulator audio + sounds to another microphone/speaker input/output.
- Security risk, the microphone is actively listening. Is the data going anywhere? Who knows...this is an unnecessary security risk for any organization, IE a dev is on a (zoom, teams, meetings) call with an open emulator that is using the microphone and listening).
Possible Solutions (based on practicality)
- flag to disable virtual audio devices (IE the mac's speaker or attached headphones w/ a microphone). I've seen 0 documentation regarding a flag like this.
- flag to provide to the emulator to disable all audio input (see answer 1). TLDR add the flag
-no-audio
- route the android studio emulator (or the mac's microphone audio input) to a virtual device that is not listening. Or have the default OS microphone input set to 0 volume. This can be done via macOSX Automator
- route the adb emulator to the mac's internal microphone instead of the current microphone to avoid it triggering the headsets microphone settings.
The preferred solution
- Microphone audio-in is disabled when booting the emulator
- Android device audio-out remains and uses the computer's default speakers
- The computer's default microphone is not triggered (at all) to avoid causing a stereo -> mono swap or noise cancellation breakage.
System Information:
- android emulator: 31.2.10.0
- MacOS 12.3.1
- Headsets tested with these issues:
- Bose NC 700
- Bose QC series
- Sony WF-1000XM4
- Sony WH-1000XM3
- any headset with a microphone connection macro that does something with the speaker (like talk through) or with the input audio like stereo -> mono.
-
How do I resolve InflateException: Binary XML file line problem?
I'm going to inflate the recycler view in the home fragment using the Navigation component. There are two problems here.
- InflateException Issues
- Only one first index appears in view in ArrayList
here is error message.
Caused by: android.view.InflateException: Binary XML file line #11 in kr.hnu.project:layout/activity_navigation: Binary XML file line #10 in kr.hnu.project:layout/content_navigation: Error inflating class fragment Caused by: android.view.InflateException: Binary XML file line #10 in kr.hnu.project:layout/content_navigation: Error inflating class fragment Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void kr.hnu.project.MyRecyclerAdapter.notifyDataSetChanged()' on a null object reference at kr.hnu.project.ui.home.HomeFragment.init(HomeFragment.java:81) at kr.hnu.project.ui.home.HomeFragment.onCreateView(HomeFragment.java:55)
And this is my code.
homefragment.java:
public class HomeFragment extends Fragment { private final static String setMsg = "SELECT sender, receiver, title, date FROM MessageDB"; DBHelper dbHelper; SQLiteDatabase readDB; Cursor cursor; ArrayList<MyItem> mailItem; MyRecyclerAdapter myAdapter; String curUser; private FragmentHomeBinding binding; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { HomeViewModel homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class); binding = FragmentHomeBinding.inflate(inflater, container, false); View root = binding.getRoot(); ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_home, container, false); NavigationActivity main = (NavigationActivity) getActivity(); curUser = main.getCurrentUserID(); dbHelper = new DBHelper(inflater.getContext()); readDB = dbHelper.getReadableDatabase(); mailItem = new ArrayList<MyItem>(); init(); myAdapter = new MyRecyclerAdapter(mailItem); LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false); binding.recyclerview.setLayoutManager(layoutManager); // 앞에 binding!!! binding.recyclerview.setAdapter(myAdapter); return root; } public void init() { cursor = readDB.rawQuery(setMsg, null); mailItem.clear(); while (cursor.moveToNext()) { if (curUser.equals(cursor.getString(cursor.getColumnIndexOrThrow("receiver")))) { mailItem.add(new MyItem(cursor.getString(cursor.getColumnIndexOrThrow("sender")), cursor.getString(cursor.getColumnIndexOrThrow("title")), cursor.getString(cursor.getColumnIndexOrThrow("date")) )); } cursor.close(); myAdapter.notifyDataSetChanged(); } }
fragment_home.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/linear" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".ui.home.HomeFragment"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerview" android:layout_width="match_parent" android:layout_height="match_parent"/>
activity_navigation.xml:
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:openDrawer="start"> <include android:id="@+id/app_bar_navigation" layout="@layout/app_bar_navigation" android:layout_width="match_parent" android:layout_height="match_parent" /> <com.google.android.material.navigation.NavigationView android:id="@+id/nav_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" android:fitsSystemWindows="true" app:headerLayout="@layout/nav_header_navigation" app:menu="@menu/activity_navigation_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>
content_navigation.xml:
<androidx.constraintlayout.widget.ConstraintLayout 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" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:showIn="@layout/app_bar_navigation"> <fragment android:id="@+id/nav_host_fragment_content_navigation" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="match_parent" android:layout_height="match_parent" app:defaultNavHost="true" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:navGraph="@navigation/mobile_navigation" /> </androidx.constraintlayout.widget.ConstraintLayout>
-
Android APP crashes while Loading the ads
I am trying to make a social media application. I am trying to insert ads in between the posts. In the below code when running app crashes while executing the adaptor. i have added the adaptor code. sorry for the big code. when i comment the ads and run, post is coming properly. problem is when i include the ad code app crashes without any error. sometimes its running continuously.
class NewpostAdapter( val context: Context, val Post: ArrayList<Newpost>): RecyclerView.Adapter<RecyclerView.ViewHolder>() { private var firebaseUser:FirebaseUser? =null companion object{ //TAG private const val TAG ="PRODUCT_TAG" //there will be 2 view type 1 for the actual content and 2 for the native ad private const val VIEW_TYPE_CONTENT =0 private const val VIEW_TYPE_AD=1 } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int):RecyclerView.ViewHolder { val view :View if (viewType == VIEW_TYPE_CONTENT){ view = LayoutInflater.from(context).inflate(R.layout.new_post,parent,false) return HolderProduct(view) } else{ //inflate/return row_native_ad.xml view = LayoutInflater.from(context).inflate(R.layout.row_native_ad,parent,false) return HolderNativeAd(view) } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { firebaseUser = FirebaseAuth.getInstance().currentUser if (getItemViewType(position)== VIEW_TYPE_CONTENT) { val post = Post[position] val holderProduct =holder as HolderProduct Picasso.get().load(post.getPostimage()).into(holderProduct.postImage) publisherInfo( holderProduct.profileImage, holderProduct.userName, holderProduct.publisheruser, post.getPublisher() ) } if (getItemViewType(position)== VIEW_TYPE_AD) { val adLoader = AdLoader.Builder(context ,context.getString(R.string.native_ad_id_test)) .forNativeAd { nativeAd -> Log.d(TAG, "onNativeAdLoaded: ") //Ad is loaded,show it //instance of our HolderNativeAd to access UI views of row_Native_ad.xml val holderNativeAd = holder as HolderNativeAd displayNativeAd(holderNativeAd,nativeAd) } .withAdListener(object : AdListener() { override fun onAdClicked() { super.onAdClicked() Log.d(TAG, "onAdClicked: ") } override fun onAdClosed() { super.onAdClosed() Log.d(TAG, "onAdClosed: ") } }) .withNativeAdOptions(NativeAdOptions.Builder().build()).build() adLoader.loadAd(AdRequest.Builder().build()) } } private fun displayNativeAd(holderNativeAd: NewpostAdapter.HolderNativeAd, nativeAd: NativeAd) { /*------Get Ad assets from the NativeAd Object-----*/ val headLine = nativeAd.headline val body = nativeAd.body val callToAction = nativeAd.callToAction val icon = nativeAd.icon val price = nativeAd.price val store = nativeAd.store val starRating = nativeAd.starRating val advertiser = nativeAd.advertiser val mediaContent = nativeAd.mediaContent /*-----Same assets aren't guaranteed to be in every nativeAd,so we need to check before displaying item-----*/ if (headLine==null){ //no content ,hide view holderNativeAd.ad_headline.visibility = View.INVISIBLE } else{ //have content ,show view holderNativeAd.ad_headline.visibility= View.VISIBLE // set data holderNativeAd.ad_headline.text=headLine } if (body==null){ //no content ,hide view holderNativeAd.ad_body.visibility = View.INVISIBLE } else{ //have content ,show view holderNativeAd.ad_body.visibility= View.VISIBLE // set data holderNativeAd.ad_body.text=body } if (icon == null){ //no content ,hide view holderNativeAd.ad_app_icon.visibility = View.INVISIBLE } else{ //have content ,show view holderNativeAd.ad_app_icon.visibility= View.VISIBLE // set data holderNativeAd.ad_app_icon.setImageDrawable(icon.drawable) } if (starRating == null){ //no content ,hide view holderNativeAd.ad_stars.visibility = View.INVISIBLE } else{ //have content ,show view holderNativeAd.ad_stars.visibility= View.VISIBLE // set data holderNativeAd.ad_stars.rating=starRating.toFloat() } if (price==null){ //no content ,hide view holderNativeAd.ad_price.visibility = View.INVISIBLE } else{ //have content ,show view holderNativeAd.ad_price.visibility= View.VISIBLE // set data holderNativeAd.ad_price.text=price } if (store==null){ //no content ,hide view holderNativeAd.ad_store.visibility = View.INVISIBLE } else{ //have content ,show view holderNativeAd.ad_store.visibility= View.VISIBLE // set data holderNativeAd.ad_store.text=store } if (advertiser==null){ //no content ,hide view holderNativeAd.ad_advertiser.visibility = View.INVISIBLE } else{ //have content ,show view holderNativeAd.ad_advertiser.visibility= View.VISIBLE // set data holderNativeAd.ad_advertiser.text=advertiser } if (mediaContent==null){ //no content ,hide view holderNativeAd.media_view.visibility = View.INVISIBLE } else{ //have content ,show view holderNativeAd.media_view.visibility= View.VISIBLE // set data holderNativeAd.media_view.setImageScaleType(ImageView.ScaleType.CENTER_CROP) holderNativeAd.media_view.setMediaContent(mediaContent) } if (callToAction==null){ //no content ,hide view holderNativeAd.ad_call_to_action.visibility = View.INVISIBLE } else{ //have content ,show view holderNativeAd.ad_call_to_action.visibility= View.VISIBLE // set data holderNativeAd.ad_call_to_action.text=callToAction //handle ad button click holderNativeAd.native_Ad_View.callToActionView=holderNativeAd.ad_call_to_action } // add nativeAd the NativeView holderNativeAd.native_Ad_View.setNativeAd(nativeAd) } override fun getItemCount(): Int { return Post.size } override fun getItemViewType(position: Int): Int { //logic to display Native Ad between content if (position % 5 == 0){ //after 5 items .show native ad return VIEW_TYPE_CONTENT } else{ //return the view type VIEW_TYPE_CONTENT to show content return VIEW_TYPE_AD } } inner class HolderProduct( itemView: View): RecyclerView.ViewHolder(itemView) { val profileImage: CircleImageView val postImage: ImageView val likeButton: ImageView val commentButton: ImageView val saveButton: ImageView val userName: TextView val likesuser: TextView val publisheruser: TextView val descriptionuser: TextView val commentsuser: TextView init { profileImage = itemView.findViewById(R.id.user_profile_image_newPost) postImage = itemView.findViewById(R.id.post_image_home2) likeButton = itemView.findViewById(R.id.post_image_like_button) commentButton = itemView.findViewById(R.id.post_image_comment_button) saveButton = itemView.findViewById(R.id.post_save_comment_button) userName = itemView.findViewById(R.id.user_name_search) likesuser = itemView.findViewById(R.id.likes_user) publisheruser = itemView.findViewById(R.id.publisher_user) descriptionuser = itemView.findViewById(R.id.description_user) commentsuser = itemView.findViewById(R.id.comments_user) } } //ViewHolder class for row_native_ad.xml inner class HolderNativeAd(itemView: View): RecyclerView.ViewHolder(itemView){ //init UI Views val ad_app_icon :ImageView =itemView.findViewById(R.id.ad_app_icon) val ad_headline:TextView=itemView.findViewById(R.id.ad_headline) val ad_advertiser:TextView=itemView.findViewById(R.id.ad_advertiser) val ad_stars: RatingBar =itemView.findViewById(R.id.ad_stars) val ad_body:TextView=itemView.findViewById(R.id.ad_body) val media_view: MediaView =itemView.findViewById(R.id.media_view) val ad_price:TextView=itemView.findViewById(R.id.ad_price) val ad_store:TextView=itemView.findViewById(R.id.ad_store) val ad_call_to_action: Button =itemView.findViewById(R.id.ad_call_to_action) val native_Ad_View: NativeAdView =itemView.findViewById(R.id.native_Ad_View) } }
-
How to fill the spinner with a custom object with coroutines and implement your onItemSelected logic related to that object?
For example, let's use this class:
data class Person ( var id : Long, var name: String, var imageUrl: String )
I need to fill my spinner with
name
values from the custom objects ofPerson
, and when some value is selected in spinner, I need to update the image according to theimageUrl
in the selected object.Is there any other way to make that than overriding toString() function in Person? For example, if I have to use Person class somewhere else where I need another toString implementation
Also I'm getting the List of Persons from api/room through kotlin coroutines
private fun collectFlows(){ lifecycleScope.launchWhenStarted { repeatOnLifecycle(Lifecycle.State.STARTED){ mainViewModel.personStateFlow.collectLatest { // update adapter's list } } }
so how to always update the list in adapter when it changes? I know how to make it with custom adapter for RecyclerView, but I'm confused about how to make such thing with spinner adapter.
-
How can i place my Spinner(DropDown) on top of a WebView in Kotlin?
im new to Android development. I think i got kinda the basics, but after 8 workhours of not getting my DropDown above my WebView, i tought i gotta ask.
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val languages = resources.getStringArray(R.array.array1) val webview = WebView(this) setContentView(webview) webview.settings.javaScriptEnabled = true webview.loadUrl("http://localhost/test/neu/index.php") // access the spinner val spinner = findViewById<Spinner>(R.id.spinner1) if (spinner != null) { val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, languages) spinner.adapter = adapter spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { Toast.makeText(this@MainActivity, getString(R.string.selected_item) + " " + "" + languages[position], Toast.LENGTH_SHORT).show() } override fun onNothingSelected(parent: AdapterView<*>) { // write code to perform some action } } } }
It does what it's supposed to do, the only thing is it places the Spinner below the WebView. If i comment out line 5-8 inside the onCreate(), it shows me a white screen with only the Spinner.
Looking for Answers to this question just brings me SO threads on how to make a Progress bar, which i dont get, but w/e. Thanks in advance
My Manifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.ttermscannerandroid51"> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.TTermScannerAndroid51"> <activity android:name=".MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application>
at last my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity"> <WebView android:id="@+id/WebView" android:layout_width="0dp" android:layout_height="0dp" android:layout_marginStart="1dp" android:layout_marginTop="1dp" android:layout_marginEnd="1dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.377" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.0"> <Spinner android:id="@+id/spinner1" android:layout_width="100dp" android:layout_height="100dp" android:spinnerMode="dropdown" /> </WebView> </androidx.constraintlayout.widget.ConstraintLayout>
-
How to build a unit conversion app in java and android studio
I'm trying to build my first project which is a unit conversion app in java and android studio. My question is how to build the app using a spinner which the user says which unit he wants to convert from and another spinner to choose the unit he wants to convert to and edit text to enter the value and another edit text to show the result. Please help me its for my junior project and thank you.
-
Reduce empty space between pickers in Android DatePicker
I have a limited space for an Android DatePicker, as is in screenshot below. How can I reduce the two empty space between the pickers, so as to have the necessary space for them?
I want to reduce only this white space, not to reduce dimensions (with scaleX property) of the entire DatePicker.
XML code of DatePicker:
DatePicker android:id="@+id/dateNascitaEmissione" android:layout_width="@dimen/emissione_dateNascita_width" android:layout_height="@dimen/emissione_dateNascita_height" android:layout_below="@id/labelPasseggeroEmissione" android:layout_toEndOf="@id/labelNascitaEmissione" android:layout_alignEnd="@id/labelPasseggeroEmissione" android:layout_gravity="top|left" android:gravity="left" android:calendarTextColor="@color/grayVeryDark" android:textSize="@dimen/emissione_dateNascita_text_size" android:calendarViewShown="false" android:datePickerMode="spinner" android:firstDayOfWeek="2" android:spinnersShown="true" android:clickable="false" android:longClickable="false" android:focusable="false" android:enabled="true" android:visibility="visible"
-
Trying to get Calendar data into a String [Solved]
Trying to store data into a string.
This is my utilities.
public class CommonDatePicker { public static void datePicker(final TextView textView, Context context) { Calendar dateCalender = Calendar.getInstance(); final int year = dateCalender.get(Calendar.YEAR); final int month = dateCalender.get(Calendar.MONTH); final int day = dateCalender.get(Calendar.DAY_OF_MONTH); DatePickerDialog datePickerDialog; datePickerDialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { monthOfYear = monthOfYear + 1; //2001-05-03 // dayOfMonth monthOfYear String formattedMonth = "" + monthOfYear; String formattedDayOfMonth = "" + dayOfMonth; if(monthOfYear < 10){ formattedMonth = "0" + monthOfYear; } if(dayOfMonth < 10){ formattedDayOfMonth = "0" + dayOfMonth ; } //editText.setText( formattedDayOfMonth + "-" + formattedMonth + "-" + year); textView.setText( year + "-" + formattedMonth + "-" + formattedDayOfMonth); } }, year, month, day); datePickerDialog.setTitle("SELECT DATE"); datePickerDialog.show(); } }
This is where I'm trying to get data. After clicking on textView the datePicker appears as expected but I want to store picked data into a string. I don't know how to do it.
This is my main.java
txt_data_collection_date.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CommonDatePicker.datePicker(txt_data_collection_date, TofsilForm10Activity.this); //String date; I want to store data in date. } });
-
Update TextView When Date is Changed in the DatePicker
I have Added A date picker View in my .xml layout
<DatePicker android:id="@+id/datePicker" android:layout_width="wrap_content" android:layout_height="150dp" android:calendarViewShown="false" android:datePickerMode="spinner" app:layout_constraintEnd_toStartOf="@+id/age" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView6" />
and a text view which should show the age of the user
val year = binding.datePicker.year.toString().toInt() val cd = Calendar.getInstance().get(Calendar.YEAR).toString().toInt() val agu = cd - year binding.age.text = "$agu\nYears"
When the app is launched, the age does not update when I change the values in the date picker. How to update the textview whenever I change the year in date picker?
-
ImageView to show image of an ImageButton, onClick
I'm trying to find a way how to implement the following: If clicked on an ImageButton (out of 4 buttons in total), I want an ImageView to show the image of that clicked ImageButton. I tried to implement an onClick method to get this job done, but I can't get the image id of the ImageButton image.
Any ideas?
-
Referencing multiple buttons efficiently in Kotlin
Hey I'm just a week into Kotlin but I'm struggling with something now. I got this list where I want to put 20 ImageButtons in efficiently with not writing everything individually. I gave all ImageButtons an id that only differs with an integer at the end, for example: takLinks1, takLinks2, takLinks3, ...
I'm trying to do it with a while loop but I can't seem to find the right syntax for Kotlin to do it. Does anyone have an idea how I could tackle this?
private lateinit var takkenLinks: ArrayList<ImageButton> private fun populateButtonList(){ var i = 1 while (i < 21) { val takLinks$i = findViewById<ImageButton>(R.id."takLinks$i") takkenLinks.add(taklinks$i) } }
-
how to debug my stack traces related to crashing the app with imagebutton
hi i have a activity that has information about my company and i must referring to this by a imagebutton in mainactivity, i wrote following java codes in infoscreen.java:
package com.journaldev.webview; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class infoscreen extends AppCompatActivity { private static final String TAG = "infoscreen"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_infoscreen); TextView theTextView = (TextView) findViewById(R.id.infotext); theTextView.setText("aboutus"); String stringFromTextView = theTextView.getText().toString(); System.out.println(stringFromTextView); Log.d(TAG, "onCreate: " + stringFromTextView); } }
my MainActivity.java file is :
infobtn = findViewById(R.id.info_btn); infobtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this,infoscreen.class)); } });
but when i run by HMD Global Nokia 7.2, app crashes and show below stack traces:
2022-01-04 13:40:00.411 19746-19746/com.journaldev.webview E/AndroidRuntime: FATAL EXCEPTION: main Process: com.journaldev.webview, PID: 19746 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.journaldev.webview/com.journaldev.webview.MainActivity}: java.lang.ClassCastException: androidx.appcompat.widget.AppCompatImageButton cannot be cast to android.widget.Button at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3271) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3410) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2017) at android.os.Handler.dispatchMessage(Handler.java:107) at android.os.Looper.loop(Looper.java:214) at android.app.ActivityThread.main(ActivityThread.java:7397) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935) Caused by: java.lang.ClassCastException: androidx.appcompat.widget.AppCompatImageButton cannot be cast to android.widget.Button at com.journaldev.webview.MainActivity.onCreate(MainActivity.java:37) at android.app.Activity.performCreate(Activity.java:7993) at android.app.Activity.performCreate(Activity.java:7982) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3246) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3410) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2017) at android.os.Handler.dispatchMessage(Handler.java:107) at android.os.Looper.loop(Looper.java:214) at android.app.ActivityThread.main(ActivityThread.java:7397) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935)
what means these stack traces? and how to fix them until i can launch app correctly?