Sending Data from Alert Dialog to New Activity - java

I am new to Android development and I am trying to send data via EditText to TextView from an alert dialog inflated in the MainActivity to a different activity (NewGame.java). I have tried intent.putExtra (see below) however I am getting null pointer exceptions as it seems I cannot access the views from the dialog layout xml file.
I know there are a few other ways to create an alert dialog so perhaps this way is not best for what i am trying to achieve?
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button newGame, prevGames, newSquad, savedSquads;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
newGame = findViewById(R.id.buttonNewGame);
newGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater= getLayoutInflater();
builder.setView(R.layout.new_game_dialog);
final View myView= inflater.inflate(R.layout.new_game_dialog, null);
EditText enterTeam1, enterTeam2, enterDate, enterTime, enterLocation;
enterTeam1 = myView.findViewById(R.id.etTeam1);
enterTeam2 = myView.findViewById(R.id.etTeam2);
enterDate = myView.findViewById(R.id.etDate);
enterTime = myView.findViewById(R.id.etTime);
enterLocation = myView.findViewById(R.id.etLocation);
builder.setTitle("New Game")
.setCancelable(true)
.setPositiveButton("Start", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(MainActivity.this, NewGame.class);
intent.putExtra("TEAM1", enterTeam1.getText().toString());
intent.putExtra("TEAM2", enterTeam2.getText().toString());
intent.putExtra("DATE", enterDate.getText().toString());
intent.putExtra("TIME", enterTime.getText().toString());
intent.putExtra("LOCATION", enterLocation.getText().toString());
startActivity(intent);
}
})
.setNegativeButton("Cancel", null);
builder.create();
builder.show();
}
});
NewGame.java
public class NewGame extends AppCompatActivity {
TextView team1, team2, date, time, location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_game);
team1 = findViewById(R.id.tvTeam1);
team2 = findViewById(R.id.tvTeam2);
date = findViewById(R.id.tvDate);
time = findViewById(R.id.tvTime);
location = findViewById(R.id.tvLocation);
team1.setText(getIntent().getStringExtra("TEAM1"));
team2.setText(getIntent().getStringExtra("TEAM2"));
date.setText(getIntent().getStringExtra("DATE"));
time.setText(getIntent().getStringExtra("TIME"));
location.setText(getIntent().getStringExtra("LOCATION"));
}
}
dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/tvNewGame"
android:textAlignment="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Game"
android:textColor="#color/black"
android:textSize="30dp" />
<EditText
android:id="#+id/etTeam1"
android:layout_width="211dp"
android:layout_height="53dp"
android:ems="10"
android:hint="Team 1"
android:inputType="textPersonName" />
<EditText
android:id="#+id/etTeam2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Team 2"
android:inputType="textPersonName"/>
<EditText
android:id="#+id/etDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Date"
android:inputType="date" />
<EditText
android:id="#+id/etTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Time"
android:inputType="textPersonName" />
<EditText
android:id="#+id/etLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Location"
android:inputType="textPersonName"/>
</LinearLayout>
activity_new_game.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=".NewGame">
<TextView
android:id="#+id/tvTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:text="time"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tvNewGame"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Game"
android:textColor="#color/black"
android:textSize="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.085" />
<TextView
android:id="#+id/tvTeam1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:text="team1"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.192" />
</androidx.constraintlayout.widget.ConstraintLayout>

I believe you are having this problem because you are actually inflating 2 views. And referencing the wrong one when you use findById.
LayoutInflater inflater= getLayoutInflater();
builder.setView(R.layout.new_game_dialog);
final View myView= inflater.inflate(R.layout.new_game_dialog, null);
should look like this
LayoutInflater inflater= getLayoutInflater();
final View myView= inflater.inflate(R.layout.new_game_dialog, null);
builder.setView(myView);

Related

set.Visibility(View.GONE) not making the Button and EditText gone, and it's showing up like I didn't even add the code

Trying to make two login, one for admin, one for user. They share the same layout, but admin has additional TextFields and Buttons to add data to the menu. So when logging in with user credentials, the TextFields and Buttons will be setVisibility(View.GONE), but it's not working at all, in fact it's showing up like setVisibility(View.GONE) was added at all. Any advice would be appreciated.
loginpage.java
DatabaseHelper myDB;
EditText LoginEMail;
EditText LoginPassword;
Button LoginBtn;
LinearLayout linearLayout;
View add_image;
View add_name;
View add_desc;
View add_data;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginpage);
LoginEMail = findViewById(R.id.LoginEMail);
LoginPassword = findViewById(R.id.LoginPassword);
LoginBtn = findViewById(R.id.LoginBtn);
myDB = new DatabaseHelper(this);
linearLayout = findViewById(R.id.linearLayout);
linearLayout = new LinearLayout(this);
add_image = new View(this);
add_name = new View(this);
add_desc = new View(this);
add_data = new View(this);
}
public void Login(View view) {
Intent intent = new Intent(loginpage.this, MenuSelection.class);
if (LoginEMail.getText().toString().equals("admin") && (LoginPassword.getText().toString().equals("admin"))) {
startActivity(intent);
linearLayout.setVisibility(View.VISIBLE);
}
else if(LoginEMail.getText().toString().equals("user") && (LoginPassword.getText().toString().equals("user"))) {
startActivity(intent);
linearLayout.setVisibility(View.GONE);
add_image.setVisibility(View.GONE);
add_name.setVisibility(View.GONE);
add_desc.setVisibility(View.GONE);
add_data.setVisibility(View.GONE);
}
else
Toast.makeText(loginpage.this, "Incorrect E-mail or Password.", Toast.LENGTH_SHORT).show();
}
loginpage.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">
<EditText
android:id="#+id/LoginEMail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="E-Mail"
android:inputType="textEmailAddress"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.504"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.204" />
<EditText
android:id="#+id/LoginPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Password"
android:inputType="textPassword"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.495"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.338" />
<Button
android:id="#+id/LoginBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Log In"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.602"
android:onClick="Login"/>
</androidx.constraintlayout.widget.ConstraintLayout>
menu_selection.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"
android:gravity="center_horizontal"
android:orientation="vertical">
<ListView
android:id="#+id/menu_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0">
<ImageButton
android:id="#+id/add_image"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#color/black" />
<EditText
android:id="#+id/add_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Name" />
<EditText
android:id="#+id/add_desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Description" />
<Button
android:id="#+id/add_data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Instead of add_image = new View(this); you need to associate the variable add_image to the view in your XML layout using the findViewById(R.id.add_image) method. Similarly for the other 3 views that you have initialized this way.
You also need to delete the line linearLayout = new LinearLayout(this);. The previous line setting this variable is correct.

Send data inside recyclerview with button in Fragment

I have 2 layouts where first layout for Fragment and second layout for RecyclerView. I have created CardView in RecyclerView, every CardView has some data. And I have created button below RecyclerView where the function of button for sending Data on CardView. My problem is I don't know how to send data when i click button in Fragment.
Fragment Layout :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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/container_daftar_alamat"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:scrollbars="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".ui.menu.menu_signin.menu.MenuAddressFragment">
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_marginTop="15dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal">
<Button
android:id="#+id/buttonMoveTambahAlamat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:background="#null"
android:drawableStart="#drawable/ic_tambah_alamat"
android:drawablePadding="10dp"
android:text="Tambah Alamat"
android:textAllCaps="false"
android:textColor="#color/colorRed"
android:textSize="14sp"
android:textStyle="normal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:text="Daftar Alamat"
android:textColor="#color/colorRed"
android:textSize="14sp"
android:textStyle="bold" />
</RelativeLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rc_tambah_alamat"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/gunakanAlamat"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginStart="10dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="100dp"
android:background="#drawable/bg_button_red"
android:text="Gunakan Alamat"
android:textAllCaps="false"
android:textColor="#android:color/white"
android:textSize="16sp" />
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</FrameLayout>
RecyclerView Layout :
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
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="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="12dp"
android:layout_marginRight="15dp"
android:layout_marginBottom="12dp"
android:orientation="vertical"
app:cardBackgroundColor="#color/colorWhite"
app:cardCornerRadius="4dp"
app:cardElevation="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<RadioButton
android:id="#+id/radioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/radioButton">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/nameUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:justificationMode="inter_word"
android:text="Muhammad Rafi Bahrur Rizki"
android:textColor="#color/colorBlack"
android:textSize="14sp"
android:textStyle="bold"
tools:ignore="UnusedAttribute" />
<TextView
android:id="#+id/addressUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:maxLines="1"
android:text="(Alamat Kantor)"
android:textSize="14sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/streetName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:justificationMode="inter_word"
android:text="Mangga Dua Square Lantai 1 Jakarta,"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp"
tools:ignore="UnusedAttribute" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/blokAddressUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="Blok C no. 148 - 150"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/cityAddressUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="DKI Jakarta - 15025"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/countryAddressUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="DKI Jakarta - 15025"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/phoneUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="0812951825"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp" />
</TableRow>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<Button
android:id="#+id/buttonEdit"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginStart="8dp"
android:drawableStart="#drawable/ic_edit"
android:text="Edit"
android:textAllCaps="false"
android:textSize="12sp" />
<Button
android:id="#+id/buttonDelete"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginStart="10dp"
android:layout_toEndOf="#id/buttonEdit"
android:drawableStart="#drawable/ic_delete"
android:text="Hapus"
android:textAllCaps="false"
android:textSize="12sp" />
</RelativeLayout>
</TableLayout>
</RelativeLayout>
</androidx.cardview.widget.CardView>
When i select RadioButton, only data in RadioButton will be obtained. And when i click button, the data will be send to another activity.
Adapter RecyclerView :
public class AdapterGetAddress extends RecyclerView.Adapter<AdapterGetAddress.ViewHolder> {
Context context;
private List<ModelGetAddress> modelGetAddressList;
private BaseApiService baseApiService;
private int previousSelected = -1;
public AdapterGetAddress(Context context, List<ModelGetAddress> modelGetAddressList) {
this.context = context;
this.modelGetAddressList = modelGetAddressList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_address, parent, false);
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
final ModelGetAddress adapterAddress = modelGetAddressList.get(position);
}
#Override
public int getItemCount() {
return modelGetAddressList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView nameUser, addressUser, streetName, blokAddressUser, cityAddressUser, countryUser, phoneUser;
private RadioButton radioButton;
public ViewHolder(#NonNull View itemView) {
super(itemView);
nameUser = itemView.findViewById(R.id.nameUser);
addressUser = itemView.findViewById(R.id.addressUser);
streetName = itemView.findViewById(R.id.streetName);
countryUser = itemView.findViewById(R.id.countryAddressUser);
blokAddressUser = itemView.findViewById(R.id.blokAddressUser);
cityAddressUser = itemView.findViewById(R.id.cityAddressUser);
phoneUser = itemView.findViewById(R.id.phoneUser);
radioButton = itemView.findViewById(R.id.radioButton);
radioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
previousSelected = getAdapterPosition();
notifyItemRangeChanged(0, modelGetAddressList.size());
// I want this All String will be send when i click button in Fragment
String getNameUser = nameUser.getText().toString();
String getAddressUser = streetName.getText().toString();
String getCountryUser = countryUser.getText().toString();
String getBlokUser = blokAddressUser.getText().toString();
String getCityUser = cityAddressUser.getText().toString();
String getPhoneUser = phoneUser.getText().toString();
}
});
}
}
}
Code in Fragment :
public class MenuAddressFragment extends Fragment {
private Button gunakanAlamat;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_menu_address, container, false);
gunakanAlamat = view.findViewById(R.id.gunakanAlamat);
gunakanAlamat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Here's were i'm stuck
}
});
return view;
}
}
You can solve this via an interface.
public interface ItemClickedCallback{
void onItemClicked(String nameUser //, the other data you wanna pass );
}
pass it through the constructor of your adapter.
Use this adapter constructor
ItemClickedCallback callback;
public AdapterGetAddress(Context context, List<ModelGetAddress> modelGetAddressList, ItemClickedCallback callback) {
this.context = context;
this.modelGetAddressList = modelGetAddressList;
this.callback= callback;
}
When checking a radio button of any item; call the interface method, like this.
radioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
previousSelected = getAdapterPosition();
notifyItemRangeChanged(0, modelGetAddressList.size());
// I want this All String will be send when i click button in Fragment
String getNameUser = nameUser.getText().toString();
String getAddressUser = streetName.getText().toString();
String getCountryUser = countryUser.getText().toString();
String getBlokUser = blokAddressUser.getText().toString();
String getCityUser = cityAddressUser.getText().toString();
String getPhoneUser = phoneUser.getText().toString();
callback.onItemClicked(getNameUser //, the rest..);
}
});
Now, when you initialize the adapter in the fragment, create the new interface via the constructor and assign the data to class variables like this.
public class MenuAddressFragment extends Fragment {
private Button gunakanAlamat;
private String nameUser_;
// the rest...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu_address, container, false);
AdapterGetAddress adapter = new AdapterGetAddress(getActivity, list, new ItemClickedCallback() {
#Override
public void onItemClicked(String userName //, the rest..) {
// assign to the class variable like this
nameUser_ = userName;
// the rest..
}
}););
gunakanAlamat = view.findViewById(R.id.gunakanAlamat);
gunakanAlamat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Use the data as you want..
}
});
return view;
}
}

Fragment not inflating and app closing

I have implemented Android Tab Layout. I have created five fragments named, one_fragment, two fragment....five fragment.
My XML name five_fragment.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.unss.pa.bdapp.one_fragment"
android:background="#FFFFFF">
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1"
android:paddingRight="15dp"
android:paddingLeft="15dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Give your feedback to improve this app better."
android:textSize="20dp"
android:textStyle="bold"
android:textColor="#800000"
android:typeface="serif"
android:layout_marginTop="20dp"
android:id="#+id/textView05"
android:textAlignment="center"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Your name"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textSize="20dp"
android:typeface="serif"
android:textColor="#000000"
android:layout_marginTop="20dp"
android:textAlignment="center"
android:id="#+id/textView01" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text=""
android:ems="10"
android:background="#drawable/edit_text"
android:id="#+id/editText01"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="\nYour email*"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textSize="20dp"
android:typeface="serif"
android:textColor="#000000"
android:layout_marginTop="20dp"
android:textAlignment="center"
android:id="#+id/textView02" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:background="#drawable/edit_text"
android:id="#+id/editText2" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="\nYour feedback"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textSize="20dp"
android:typeface="serif"
android:textColor="#000000"
android:layout_marginTop="20dp"
android:id="#+id/textView03"
android:textAlignment="center"/>
<EditText
android:layout_width="match_parent"
android:layout_height="175dp"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/editText3"
android:layout_weight="0.23"
android:background="#drawable/edit_text"/>
<Button
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#drawable/send"
android:id="#+id/button01f"
android:layout_gravity="center_horizontal"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="\n"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textSize="2dp"
android:typeface="serif"
android:textColor="#000000"
android:layout_marginTop="20dp"
android:id="#+id/textView07" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
Adapter in my Main Activity
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new ListContentFragment(), "Screen1");
adapter.addFragment(new one_fragment(), "Screen2");
adapter.addFragment(new CardContentFragment(), "Screen3");
adapter.addFragment(new two_fragment(), "Screen4");
adapter.addFragment(new CardContentFragment(), "Screen5");
adapter.addFragment(new TileContentFragment(), "Screen6");
adapter.addFragment(new three_fragment(), "Screen7");
adapter.addFragment(new five_fragment(), "Feedback");
viewPager.setAdapter(adapter);
}
My five_fragment.java
public class five_feedback extends Fragment implements View.OnClickListener{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
public Button btn;
public EditText t1;
public EditText t2;
public EditText t3;
public five_feedback() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
btn = (Button) getView().findViewById(R.id.button01f);
t1 = (EditText) getView().findViewById(R.id.editText01) ;
t2 = (EditText) getView().findViewById(R.id.editText2) ;
t3 = (EditText) getView().findViewById(R.id.editText3) ;
btn.setOnClickListener(this);
return inflater.inflate(R.layout.five_fragment, container, false);
}
#Override
public void onClick(View v) {
if( t2.getText().toString().trim().equals("")){
Snackbar.make(v, "Email Required",
Snackbar.LENGTH_LONG).show();
} else {
String to = "pbharadwaj777#gmail.com";
String message = t2.getText().toString();
String subject = "Feedback";
Intent mEmail = new Intent(Intent.ACTION_SEND);
mEmail.putExtra(Intent.EXTRA_EMAIL, new String[]{ to});
mEmail.putExtra(Intent.EXTRA_SUBJECT, subject);
mEmail.putExtra(Intent.EXTRA_TEXT, message);
// prompts to choose email client
mEmail.setType("message/rfc822");
startActivity(Intent.createChooser(mEmail, "Choose an email client to send your feedback!"));
}
}
}
When I install the open, I am able to open the app. I can slide from screen 1 to screen 7. However when I open Feedback, the app crashes. What is the issue?
The issue is you are trying to access the view before you actually inflated it. Change your onCreateView to the following or alternatively you could move your findViewById and setOnClickListener code to the onViewCreated function of the Fragment.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.five_fragment, container, false);
btn = (Button) view.findViewById(R.id.button01f);
t1 = (EditText) view.findViewById(R.id.editText01) ;
t2 = (EditText) view.findViewById(R.id.editText2) ;
t3 = (EditText) view.findViewById(R.id.editText3) ;
btn.setOnClickListener(this);
return view;
}

Why am I unable to get a Dialog when clicking the image?

I want the user to choose that whether they'd like to take picture or choose one from gallery.
I set up an OnClickListener on my Image but when I'm clicking the image, nothing is happening.
Here is my SettingUpUserProfile.java file's code:
public class SettingUpUserProfile extends AppCompatActivity {
public static final int TAKE_PHOTO_REQUEST = 0;
protected ImageView userProfilePicture;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting_up_user_profile);
userProfilePicture = (ImageView) findViewById(R.id.userProfilePicture);
userProfilePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(SettingUpUserProfile.this);
builder.setTitle(null);
builder.setItems(R.array.pickImage_options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int position) {
switch (position) {
case 0:
Intent intentCaptureFromCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intentCaptureFromCamera, TAKE_PHOTO_REQUEST);
break;
case 1:
// Choose from gallery.
}
}
});
}
});
}
}
and here is my activity_setting_up_user_profile.xml file's code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/light_purple"
tools:context="com.abc.xyz.SettingUpUserProfile">
<TextView
android:id="#+id/settingUpUserProfileText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:text="#string/settingUpUserProfileText1"
android:textColor="#color/white"
android:textStyle="bold"
android:textSize="30sp"
android:gravity="center_horizontal|center_vertical"/>
<ImageView
android:id="#+id/userProfilePicture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/settingUpUserProfileText1"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginTop="100dp"
android:clickable="true"
android:src="#drawable/ic_face_white_48dp" />
<TextView
android:id="#+id/settingUpUserProfileText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/userProfilePicture"
android:layout_marginTop="5dp"
android:text="#string/settingUpUserProfileText2"
android:textColor="#color/white"
android:textSize="15sp"
android:gravity="center_horizontal|center_vertical"/>
<EditText
android:id="#+id/userName"
android:background="#drawable/phone_number_edit_text_design"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/settingUpUserProfileText2"
android:layout_marginTop="80dp"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:gravity="center_horizontal|center_vertical"
android:hint="#string/hint_userName"
android:textColor="#color/white"
android:textColorHint="#E0E0E0"
android:textCursorDrawable="#null"
android:inputType="textPersonName"/>
<Button
android:id="#+id/buttonAllSet"
android:background="#color/white"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/userName"
android:layout_marginTop="20dp"
android:text="#string/button_allSet"
android:textStyle="bold"
android:textColor="#color/light_purple"
android:layout_marginEnd="120dp"
android:layout_marginStart="120dp"
android:gravity="center_horizontal|center_vertical"/>
</RelativeLayout>
I'm really unable to figure out what is wrong here.
Kindly, let me know.
I'm new to StackOverflow so please cooperate.
Thanks in advance.
Add Below lines to your onClick() method
AlertDialog alertDialog = builder.create();
alertDialog.show();

EditText is declared and LogCat is still giving nullpointerexception

Ok, so I am getting a nullpointerexception in logcat when I am running my app, however I looked at other StackOverflow questions that were similar to mine and found that I had done everything right, so where is my error coming from?
here is my MainActivity:
public double inchSnow, durationStorm, peakSnow, peakTime, finalSnow, windSpeed, snowGround, result, avgSnow;
EditText inSnow, durnStorm, pSnow, pTime, fSnow, wSpeed, sGround;
protected void onCreate(Bundle savedInstanceState) {
final AlertDialog.Builder invalidNumber = new AlertDialog.Builder(actContext);
invalidNumber.setTitle("Blank Field!");
invalidNumber.setMessage("Seems like a field has been left blank, can you fix it?");
invalidNumber.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
inSnow = (EditText) findViewById(R.id.inchesSnow);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getZip = (Button) findViewById(R.id.calculate);
final Intent intent = new Intent(this, com.boreas.snowdaycalculator.result.class);
getZip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
inchSnow = new Integer(inSnow.getText().toString()).intValue();
}catch (NumberFormatException ex){
final AlertDialog alertDialog = invalidNumber.create();
invalidNumber.show();
}
Intent myIntent = new Intent(MainActivity.this, result.class);
myIntent.putExtra("inchSnow",inchSnow);
startActivity(myIntent);
}
});
}
My MainActivity xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="521dp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrollView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="520px"
android:layout_alignTop="#+id/scrollView"
android:layout_alignLeft="#+id/scrollView">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/inchesSnow"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:hint="Inches of Snow"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/durationStorm"
android:layout_below="#+id/inchesSnow"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:hint="Duration of Storm"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/peakRate"
android:layout_below="#+id/durationStorm"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:hint="Peak Snow Rate"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/peakRateTime"
android:layout_below="#+id/peakRate"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:hint="Time of Peak Snow Rate"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberSigned"
android:ems="10"
android:id="#+id/finalRate"
android:layout_below="#+id/peakRateTime"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:hint="Final Snow Rate"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberSigned"
android:ems="10"
android:id="#+id/windSpeed"
android:layout_below="#+id/finalRate"
android:layout_alignParentLeft="true"
android:hint="Wind Speed"
android:layout_alignParentRight="true"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/snowGround"
android:layout_below="#+id/windSpeed"
android:layout_alignParentLeft="true"
android:hint="Snow Already on Ground"
android:layout_alignParentRight="true"/>
</RelativeLayout>
</ScrollView>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate Chances"
android:id="#+id/calculate"
android:layout_marginBottom="150dp"
android:layout_alignBottom="#+id/scrollView"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
Anyone have any ideas on what I am doing wrong? Thanks.
You need to place
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
before all other calls in method. findViewById() will return null until you set the content view. And more importantly, super.onCreate(savedInstanceState) will create the activity to work with.
Put the line:
inSnow = (EditText) findViewById(R.id.inchesSnow);
after the line:
setContentView(R.layout.activity_main);

Categories