date picker displayed when text box is focused - java

I am just getting into android apps and now trying to work with an interface that allows the user to enter date into a text box. The date dialog should only display when a text box is focused.After a date is selected from the dialog, it will be displayed in the text box. The problem now is the date dialog is displayed even the text box is not focused. Can someone help me to figuring out my problem? Thank.
TimeSheet.xml
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<EditText
android:layout_width="190dp"
android:layout_height="wrap_content"
android:id="#+id/txtdate"
android:layout_x="131dp"
android:layout_y="192dp"
android:hint="Touch here to select a date"/>
</AbsoluteLayout>
TimeSheet.java
package com.example.project.project;
import android.app.DatePickerDialog;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.ArrayAdapter;
import android.view.View;
import android.os.Bundle;
import android.widget.Button;
import java.util.List;
import java.util.ArrayList;
import android.content.Context;
import android.content.ContentValues;
import android.widget.Toast;
import com.example.project.project.API.TimeSheetAPI;
import com.example.project.project.database.MyDatabaseHelper;
public class TimeSheet extends AppCompatActivity {
private Spinner spinner,spinner2;
private Button btnSaved;
private MyDatabaseHelper dbHelper;
private TimeSheetAPI ts;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timesheet);
ts=new TimeSheetAPI(this);
}
public void onStart()
{
super.onStart();
EditText txtDate=(EditText)findViewById(R.id.txtdate);
txtDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus)
{
if(hasFocus)
{
DateDialog dialog=new DateDialog(v);
FragmentTransaction ft=getFragmentManager().beginTransaction();
dialog.show(ft,"DatePicker");
}
}
});
}
DateDialog.java
package com.example.project.project;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import java.util.Calendar;
/**
* Created by tongws on 9/14/2015.
*/
#SuppressLint("ValidFragment")
public class DateDialog extends DialogFragment implements DatePickerDialog.OnDateSetListener {
EditText txtdate;
public DateDialog(View view)
{
txtdate=(EditText)view;
}
public Dialog onCreateDialog(Bundle savedInstanceState)
{
final Calendar c=Calendar.getInstance();
int year=c.get(Calendar.YEAR);
int month=c.get(Calendar.MONTH);
int day=c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(),this,year,month,day);
}
public void onDateSet(DatePicker view,int year, int month, int day)
{
String date=day+"-"+(month+1)+"-"+year;
txtdate.setText(date);
}
}

Your EditText has been focused once the activity started. To clear default focus on EditText, add focus to the parent layout. This can be done by adding this line of code into your parent view.
android:focusableInTouchMode="true"
For example,
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1"
android:focusableInTouchMode="true">
<EditText
android:layout_width="190dp"
android:layout_height="wrap_content"
android:id="#+id/txtdate"
android:layout_x="131dp"
android:layout_y="192dp"
android:hint="Touch here to select a date"/>
</AbsoluteLayout>

Related

app crashes when getting a reference on android studio

I'm a newbie in programming and stuff.. I'm using the android-youtube-player package from Pierfrancesco Soffritti.. and when I try to Get a reference to YouTubePlayer and run the app it crashes..
`
package com.example.youtuuuuuuuuuuuuuuube;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.YouTubePlayer;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.AbstractYouTubePlayerListener;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.YouTubePlayerListener;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.options.IFramePlayerOptions;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.ui.DefaultPlayerUiController;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.ui.PlayerUiController;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.ui.menu.YouTubePlayerMenu;
public class MainActivity extends AppCompatActivity {
private YouTubePlayer youTubePlayer;
private YouTubePlayerView youTubePlayerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void playvideo(View v){
youTubePlayer.loadVideo("S0Q4gqBUs7c", 1f);
}
}
`
my XML code
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView
android:id="#+id/youtube_player_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:videoId="S0Q4gqBUs7c"
app:autoPlay="true"
/>
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="playvideo"
android:text="Button" />
I tried to get the reference using OnStart() method, added a button but all of that don't work :(

How to add firebase to a fragment in android studio

I am making an android ecommerce app and I downloaded an app template but in that template there is no firebase in the fragment and I want when the user clicks checkout button the products he selected should go to the firebase database but all videos I see they use activities .So please help me.
CartFragment.java
package com.example.shoppingcart.views;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;
import com.example.shoppingcart.R;
import com.example.shoppingcart.adapters.CartListAdapter;
import com.example.shoppingcart.cartholder;
import com.example.shoppingcart.databinding.FragmentCartBinding;
import com.example.shoppingcart.dataholder;
import com.example.shoppingcart.models.CartItem;
import com.example.shoppingcart.productholder;
import com.example.shoppingcart.viewmodels.ShopViewModel;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.firestore.FirebaseFirestore;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
public class CartFragment extends Fragment implements CartListAdapter.CartInterface {
private static final String TAG = "CartFragment";
private ImageView productImage;
private TextView productname;
private TextView productprice;
private TextView productcategory;
private Spinner productquantity;
UUID uuid = UUID.randomUUID();
String randomUUID = uuid.toString().trim();
ShopViewModel shopViewModel;
FragmentCartBinding fragmentCartBinding;
NavController navController;
Button button;
private void finishActivity() {
if (getActivity() != null) {
getActivity().finish();
}
}
public CartFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
fragmentCartBinding = FragmentCartBinding.inflate(inflater, container, false);
return fragmentCartBinding.getRoot();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
navController = Navigation.findNavController(view);
final CartListAdapter cartListAdapter = new CartListAdapter(this);
fragmentCartBinding.cartRecyclerView.setAdapter(cartListAdapter);
fragmentCartBinding.cartRecyclerView.addItemDecoration(new DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL));
shopViewModel = new ViewModelProvider(requireActivity()).get(ShopViewModel.class);
shopViewModel.getCart().observe(getViewLifecycleOwner(), new Observer<List<CartItem>>() {
#Override
public void onChanged(List<CartItem> cartItems) {
cartListAdapter.submitList(cartItems);
fragmentCartBinding.placeOrderButton.setEnabled(cartItems.size() > 0);
}
});
shopViewModel.getTotalPrice().observe(getViewLifecycleOwner(), new Observer<Double>() {
#Override
public void onChanged(Double aDouble) {
fragmentCartBinding.orderTotalTextView.setText("Total: PKR " + aDouble.toString());
}
});
button = (Button) getView().findViewById(R.id.placeOrderButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(CartFragment.this.getActivity(), CheckoutActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finishActivity();
}
});
}
#Override
public void deleteItem(CartItem cartItem) {
shopViewModel.removeItemFromCart(cartItem);
}
#Override
public void changeQuantity(CartItem cartItem, int quantity) {
shopViewModel.changeQuantity(cartItem, quantity);
}
}
fragment_cart.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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">
<LinearLayout
android:orientation="vertical"
tools:context=".views.CartFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/cartRecyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
tools:listitem="#layout/cart_row"
tools:itemCount="2"
/>
<Space
android:layout_width="match_parent"
android:layout_height="16dp" />
<TextView
android:id="#+id/orderTotalTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_margin="8dp"
android:text="Total: PKR 26"
android:textAppearance="#style/TextAppearance.MaterialComponents.Headline6" />
<Button
android:id="#+id/placeOrderButton"
style="#style/Widget.MaterialComponents.Button.UnelevatedButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_margin="8dp"
android:text="Proceed To Checkout"
android:textAppearance="#style/TextAppearance.MaterialComponents.Caption" />
</LinearLayout>
</ScrollView>
What kind of firebase database you have to use because both of the methods are similar...
activity and fragment method is same not any kind of change to the method ...
i will show you firestore method because i don't know which one you have to use
in fragment first initilize
FirebaseFirestore firebaseFirestore;
oncreateview initialize
firebaseFirestore = FirebaseFirestore.getInstance();
after you can perform all your crud operation and all thing but first two line is require
simple use bro...

GridView goes messy

When I scroll past an item and come back to it, it changes it's position until I click on it, then it will correctly align itself. How can I solve this. Sorry I am still at the start of the project so my code is a bit messy.
This is my code:
package com.example.r_corp.androidslauncher;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
PackageManager packageManager;
Intent mainIntent = null;
static ArrayList<app> appList;
static GridView gridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_all_apps_layout);
gridView = (GridView)findViewById(R.id.GridView);
gridView.setNumColumns(4);
packageManager = getPackageManager();
mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
appList = getApps();
show();
}
public ArrayList<app> getApps(){
List<ResolveInfo>apps = packageManager.queryIntentActivities(mainIntent, 0);
ArrayList<app> Apps = new ArrayList();
for(ResolveInfo ri : apps){
app App = new app();
App.icon = ri.loadIcon(packageManager);
App.Name = ri.loadLabel(packageManager).toString();
Apps.add(App);
}
return Apps;
}
public void show(){
ArrayAdapter<app> adapter = new ArrayAdapter<app>(this, R.layout.item,
appList) {
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.item,null);
}
ImageView appIcon = (ImageView) convertView
.findViewById(R.id.imageView);
appList.get(position).icon.setBounds(10,10,10,10);
appIcon.setImageDrawable(appList.get(position).icon);
appIcon.setLayoutParams(new RelativeLayout.LayoutParams(85, 85));
appIcon.setScaleType(ImageView.ScaleType.CENTER_CROP);
appIcon.setPadding(8, 8, 8, 8);
TextView appName = (TextView) convertView
.findViewById(R.id.textView);
appName.setText(appList.get(position).Name);
return convertView;
}
};
gridView.setFocusable(true);
gridView.setAdapter(adapter);
}
}
class app{
Drawable icon;
String Name;
}
show_all_apps_layout:
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:stretchMode="columnWidth"
android:focusableInTouchMode="true"
android:horizontalSpacing="5dp"
android:verticalSpacing="5dp"
android:id="#+id/GridView"/>
item:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
app:srcCompat="#mipmap/ic_launcher" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView"
android:layout_centerHorizontal="true"
android:text="TextView" />
</RelativeLayout>
Thanks in advance for your helpfulness.

How can I pass an Intent to layout which contains ListView? (Android Studio)

I am trying to pass an Intent from my mainScreen Activity class to a new android class with a layout that contains a ListView ..
MainActivityScreen Code :
(TimePassed is in the format of 'HH:MM:SS')
public void MoveToShiftsPage(View view) {
Intent shiftsIntent=new Intent(this,Shifts.class);
shiftsIntent.putExtra("time",TimePassed);
startActivity(shiftsIntent);
}
"MoveToShiftsPage" in the MainActivity.xml file :
<ImageButton
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#mipmap/payment"
android:id="#+id/shiftbtn"
android:onClick="MoveToShiftsPage"
/>
Shifts.xml File( the layout which contains the ListView and the Intent sent to it)
<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" tools:context=".MainScreen"
>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:id="#+id/MyListView"
android:clickable="true"
style="#style/Base.Widget.AppCompat.ListView.DropDown">
</ListView>
/>
and the Shift.class which gets the Intent and it's supposed to represent the ListView with the time that passed :
import android.app.Activity;
import android.content.Intent;
import android.app.ListFragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.util.List;
/**
* Created by user on 19/09/2015.
*/
public class Shifts extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shifts);
Intent MyIntent=getIntent();
String TimePassed=MyIntent.getStringExtra("time");
String [] timepass=TimePassed.split(":");
ListAdapter theAdapter=new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_activated_1,timepass);
ListView thelist=(ListView)findViewById(R.id.MyListView);
thelist.setAdapter(theAdapter);
}
}
Unfortunately whenever I click on the image button which is supposed to be sent to the shift activity class and represents the layout with the ListView the app crashes ..
what should I do ?
try this one hopefully it works
Intent MyIntent=this.getIntent();

The Original Fragment won't go to back of stack, it stays visible

I am having some issues with FragmentTransactions. I have sucessfuly called on a fragment from the onClick method but the original mainFragment won't "disappear" or go to back of stack. I have followed the Android Development tutorial on Fragment Transcation. I think the issue is in my Survey.java class or my Details.java class. Any help is appreciated.
Update: (Added Photos below)
Before: http://imm.io/q9vt
After Clicking "Survey Button": http://imm.io/q9wf
See code for all below:
Code from Main.java
package mycompany.nst;
import mycompany.nst.R;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
public class Main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
Fragment _surveyFrag = new Survey();
public void focusFragment(Fragment mainFragment) {
FragmentManager FragMgr = getFragmentManager();
FragmentTransaction transaction = FragMgr.beginTransaction();
try {
transaction.replace(R.id.mainFragment, _surveyFrag);
transaction.addToBackStack(null);
transaction.commit();
} catch(Exception e){};
transaction = null;
FragMgr = null;
}
public void survey_onClick(View view) {
Log.i("onClick", "SURVEY BEGIN");
focusFragment(_surveyFrag);
}
}
Code from main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/hsdarker"
android:baselineAligned="false"
android:orientation="horizontal" >
<fragment
android:id="#+id/listFragment"
android:name="mycompany.nst.ListFragment"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
class="mycompany.nst.ListFragment" >
<!-- Preview: layout=#layout/list -->
</fragment>
<fragment
android:id="#+id/mainFragment"
android:name="mycompany.nst.Details"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/listFragment"
class="mycompany.nst.Details" >
<!-- Preview: layout=#layout/details -->
</fragment>
</RelativeLayout>
Code from Details.java <-- The original fragment
package mycompany.nst;
import mycompany.nst.R;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Details extends Fragment {
/** Called when the activity is first created. */
#Override
public View onCreateView(LayoutInflater LIdetails, ViewGroup VGdetails, Bundle SaveInstancedState) {
Log.i("DetailsFragment", "onCreateView");
// Inflate the layout for this fragment
return LIdetails.inflate(R.layout.details, VGdetails, false);
}
}
Code from Details.java <-- The new fragment
package mycompany.nst;
import mycompany.nst.R;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Survey extends Fragment {
/** Called when the activity is first created. */
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.i("SurveyFragment", "onCreateView");
// Inflate the layout for this fragment
return inflater.inflate(R.layout.survey, container, false);
}
}
You can't replace or remove a fragment that's defined in XML- it becomes a non-removable part of the layout. However, if you define the fragments in code, you can replace and remove them at will.

Categories