How to enable\disable dialog views dynamically - android

I need your help. my dialog window has 2 radiobuttons. I want to disable or enable some views on this dialog depending on which radiobutton is checked by a user.
my Layout for dialog: inc_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/inc_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginTop="16dp"
android:hint="Название дохода"
/>
<EditText
android:id="#+id/inc_value"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginTop="4dp"
android:hint="Сумма дохода"
/>
<TextView
android:id="#+id/tvChkBoxIncType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="6dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="4dp"
android:layout_marginTop="4dp"
android:text="Тип дохода:" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<RadioGroup
android:id="#+id/RadioGroup1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:id="#+id/inc_random"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="6dp"
android:onClick="onRadioButtonClicked"
android:text="Разовый" />
<RadioButton
android:id="#+id/inc_const"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="9dp"
android:checked="true"
android:onClick="onRadioButtonClicked"
android:text="Постоянный" />
</RadioGroup>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/DataPick1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:layout_marginLeft="16dp"
android:text="Начало периода:"
android:enabled="false"/>
<EditText
android:id="#+id/inc_day"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DD"
android:enabled="false" >
</EditText>
<EditText
android:id="#+id/inc_month"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MM"
android:enabled="false">
</EditText>
<EditText
android:id="#+id/inc_year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:enabled="false"
android:text="YYYY" >
</EditText>
</LinearLayout>
<EditText
android:id="#+id/inc_period"
android:layout_width="wrap_content"
android:enabled="false"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:text="Каждые Х дней" >
</EditText>
</LinearLayout>
Building of this Dialog:
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle("Добавить доход");
view = (LinearLayout) getLayoutInflater()
.inflate(R.layout.inc_dialog, null);
// устанавливаем ее, как содержимое тела диалога
adb.setView(view) .setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}) .setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getApplicationContext(),"Добавлено", Toast.LENGTH_SHORT).show();
}
}); ;
return adb.create();
}
onClick function that I call in ACTIVITY
public void onRadioButtonClicked (){
switch(view.getId()) {
case R.id.inc_const:
findViewById(R.id.DataPick1).setEnabled(true);
break;
case R.id.inc_random:
findViewById(R.id.DataPick1).setEnabled(false);
break;
}
};
If it's needed the whole Activity code. Income.java
package com.example.pocketbooker;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class Income extends Activity{
LinearLayout view;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Доходы");
setContentView(R.layout.income_const);
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.inoutgo, menu);
return super.onCreateOptionsMenu(menu);
}
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle("Добавить доход");
view = (LinearLayout) getLayoutInflater()
.inflate(R.layout.inc_dialog, null);
// устанавливаем ее, как содержимое тела диалога
adb.setView(view) .setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}) .setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getApplicationContext(),"Добавлено", Toast.LENGTH_SHORT).show();
}
}); ;
return adb.create();
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.plus:
showDialog(1);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onRadioButtonClicked (){
switch(view.getId()) {
case R.id.inc_const:
findViewById(R.id.DataPick1).setEnabled(true);
break;
case R.id.inc_random:
findViewById(R.id.DataPick1).setEnabled(false);
break;
}
};
}
So I want to change a property of a view in my dialog dynamically. How can I do that? How can I call dialog views from my Activity function?
And sorry for my english, I'm from kazakhstan.
Please, help.

Because DataPicker is inside Dialog layout so you need to pass user selected RadioButton id in onCreateDialog method. try it as:
protected Dialog onCreateDialog(int id) {
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.RadioGroup1);
AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle("Добавить доход");
view = (LinearLayout) getLayoutInflater()
.inflate(R.layout.inc_dialog, null);
int radioBtnid = radioGroup.getCheckedRadioButtonId();
// get DatePicker
DatePicker datepick1=(DatePicker)view.findViewById(R.id.DataPick1);
if(radioBtnid==R.id.inc_const){
//Enable DataPick1
datepick1.setEnabled(true);
}else if(radioBtnid==R.id.inc_random){
// Disable DataPick1
datepick1.setEnabled(false);
}
//your code ...
}

First of all pass in the View as argument to your onRadioButtonClicked() method since it is necessary for onClick method mentioned in XML layout.
Define a View as its only parameter (this will be the View that was clicked)
Also Check if the view that was passed is whether selected or not by calling isChecked() method. Your final code might look like below:
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.inc_const:
if (checked)
// Do the necessary things here if inc_const is selected
findViewById(R.id.DataPick1).setEnabled(true);
break;
case R.id.inc_random:
if (checked)
// Put the code necessary if the random is checked
findViewById(R.id.DataPick1).setEnabled(false);
break;
}
}
Let me know if this helps.

So I've made it.
I used DialogFragment
Created separate class Dialog_inc.java for my dialog
package com.example.pocketbooker;
import android.annotation.SuppressLint;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
#SuppressLint("NewApi")
public class Dialog_inc extends DialogFragment implements OnClickListener {
EditText POLE;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getDialog().setTitle("Добавить Доход");
View v = inflater.inflate(R.layout.inc_dialog, null);
v.findViewById(R.id.btnYes).setOnClickListener(this);
v.findViewById(R.id.btnNo).setOnClickListener(this);
v.findViewById(R.id.inc_const).setOnClickListener(this);
v.findViewById(R.id.inc_random).setOnClickListener(this);
POLE=(EditText) v.findViewById(R.id.inc_year);
return v;
}
public void onClick(View v) {
switch(v.getId())
{case R.id.inc_const:
POLE.setEnabled(true);
break;
case R.id.inc_random:
POLE.setEnabled(false);
break;
default:
dismiss();}
}
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
}
public void onCancel(DialogInterface dialog) {
super.onCancel(dialog);
}
}
A bit changed my layout for this, added 2 buttons. inc_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/inc_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginTop="16dp"
android:hint="Название дохода"
android:inputType="textEmailAddress" />
<EditText
android:id="#+id/inc_value"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginTop="4dp"
android:hint="Сумма дохода"
android:inputType="text" />
<TextView
android:id="#+id/tvChkBoxIncType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="6dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="4dp"
android:layout_marginTop="4dp"
android:text="Тип дохода:" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<RadioGroup
android:id="#+id/RadioGroup1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:id="#+id/inc_random"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="6dp"
android:onClick="OnRadio"
android:text="Разовый" />
<RadioButton
android:id="#+id/inc_const"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="9dp"
android:onClick="OnRadio"
android:checked="true"
android:text="Постоянный" />
</RadioGroup>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/DataPick1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:layout_marginLeft="16dp"
android:text="Начало периода:"
/>
<EditText
android:id="#+id/inc_day"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DD" >
</EditText><EditText
android:id="#+id/inc_month"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MM"
>
</EditText><EditText
android:id="#+id/inc_year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="YYYY" >
</EditText>
</LinearLayout>
<EditText
android:id="#+id/inc_period"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:onClick="onRadioButtonClicked"
android:text="Каждые Х дней" >
</EditText>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="#+id/btnYes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="yes">
</Button>
<Button
android:id="#+id/btnNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="no">
</Button>
</LinearLayout>
</LinearLayout>
And I call this dialog like this. Income.class
package com.example.pocketbooker;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.LinearLayout;
public class Income extends Activity{
LinearLayout view;
DialogFragment dlg1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Доходы");
setContentView(R.layout.income_const);
dlg1 = new Dialog_inc();
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.inoutgo, menu);
return super.onCreateOptionsMenu(menu);
}
#SuppressLint("NewApi")
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.plus:
dlg1.show(getFragmentManager(), "dlg1");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Of course it's not a beautiful code now. But I hope it can help someone. Thanks everyone for responding

Related

Item List Layout showing up in Android Studio, but not in Emulator

I am working on an Android App with a Recyclerview that contains a Listview. The problem is, that the Listview items are showing up in Android Studio, that there are no errors in the XML but still, the Listview items are not showing up on the Emulator or on a Real device. I checked the Layout for all kinds of problems - Size, Width, Layout Constraints -, but I couldn´t find any. As I am stuck here, I would kindly appreciate any help or hints from the community, thanks in advance.
The Activity:
package com.example.xxx;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import okhttp3.Credentials;
import static com.example.xxx.SimpleItemRecyclerViewAdapter.TAGG;
import static com.example.xxx.SimpleItemRecyclerViewAdapter.palNo;
/**
* An activity representing a single Main detail screen. This
* activity is only used on narrow width devices. On tablet-size devices,
* item details are presented side-by-side with a list of items
* in a {#link MainListActivity}.
*/
public final class ProductDetailActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener,
PopupMenu.OnMenuItemClickListener {
public Context context;
private RecyclerView recyclerView;
private StockBookingsRecyclerviewAdapter recyclerviewAdapter;
private RecyclerTouchListener touchListener;
public static final String TAG = "Barcode ist:" ;
public String bookingType = null;
public String itemNo = null;
public String ean = null;
public String quantity = null;
public String packageCode = null;
public String target = null;
public String source = null;
public Date date;
public String scannedCode = null;
public static final String Profile_Prefs = "Pro_File";
public static SharedPreferences profile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_detail);
TextView titleBooking = findViewById(R.id.title_booking);
TextView typeBooking = findViewById(R.id.type_booking);
TextView nameBooking = findViewById(R.id.name_booking);
TextView dateBooking = findViewById(R.id.date_booking);
Toolbar toolbar = findViewById(R.id.toolbar);
LinearLayout linearLayout = findViewById(R.id.rowFGP);
String selectedItem =null;
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.mockdata, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
String basic = Credentials.basic("xxx", "xxx");
// Apply the adapter to the spinner
recyclerView = findViewById(R.id.recyclerview2);
recyclerviewAdapter = new StockBookingsRecyclerviewAdapter(this);
Intent newIntent = getIntent();
String receivedPalNo = newIntent.getStringExtra("palNo");
String receivedNo = newIntent.getStringExtra("no");
String receivedType = newIntent.getStringExtra("type");
String receivedRack = newIntent.getStringExtra("rack");
String receivedCountItems = newIntent.getStringExtra("count_items");
RestClient.getStockBookings(getApplicationContext(),recyclerviewAdapter,basic);
Log.d(TAGG,"Intent 1" + receivedPalNo);
Log.d(TAGG, "Intent 2" + receivedNo);
Log.d(TAGG, "Intent 3" + receivedType);
Log.d(TAGG,"Intent 4" + receivedRack);
Log.d(TAGG, "Intent 5" + receivedCountItems);
//use a GradientDrawable with only one color set, to make it a solid color
GradientDrawable border = new GradientDrawable();
border.setColor(0x00000000); //white background
border.setStroke(1, 0xFF000000); //black border with full opacity
final ArrayList<StockBookings> stockBookingList = new ArrayList<>();
recyclerviewAdapter. setBookingList((ArrayList<StockBookings>) stockBookingList);
recyclerView.setAdapter(recyclerviewAdapter);
touchListener = new RecyclerTouchListener(this,recyclerView);
StockBookingsRecyclerviewAdapter finalRecyclerviewAdapter = recyclerviewAdapter;
touchListener
.setClickable(new RecyclerTouchListener.OnRowClickListener() {
#Override
public void onRowClicked(int position) {
}
#Override
public void onIndependentViewClicked(int independentViewID, int position) {
}
})
.setSwipeOptionViews(R.id.delete_task)
.setSwipeable(R.id.rowFGP, R.id.rowBGP, new RecyclerTouchListener.OnSwipeOptionsClickListener() {
#Override
public void onSwipeOptionClicked(int viewID, int position) {
stockBookingList.remove(position);
finalRecyclerviewAdapter.setStockBookingList(stockBookingList);
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onBackPressed() {
Intent setIntent = new Intent(getApplicationContext(),MainListActivity.class);
startActivity(setIntent);
}
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(this, "Selected Item: " +item.getTitle(), Toast.LENGTH_SHORT).show();
switch (item.getItemId()) {
case R.id.search_item:
// do your code
return true;
case R.id.upload_item:
// do your code
return true;
case R.id.copy_item:
// do your code
return true;
/* case R.id.print_item:
// do your code
return true;*/
case R.id.share_item:
// do your code
return true;
/*case R.id.bookmark_item:
// do your code
return true;*/
default:
return false;
}
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
navigateUpTo(new Intent(this, MainListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume() {
super.onResume();
recyclerView.addOnItemTouchListener(touchListener);
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
The Activity 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">
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="#dimen/_80sdp"
android:layout_marginBottom="12dp"
android:layout_weight="0.15"
android:background="#drawable/border_set"
android:orientation="horizontal"
app:layout_constraintBottom_toTopOf="#id/recyclerview2">
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:text="#string/product_bookings"
android:textColor="#color/black"
android:textSize="#dimen/_20sdp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/txt1"
app:layout_constraintEnd_toEndOf="#id/txt1" />
<TextView
android:id="#+id/txt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="#string/nicht_uebertragen"
android:textColor="#color/black"
android:textSize="#dimen/_10sdp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/txt1"
app:layout_constraintEnd_toEndOf="#id/txt1" />
</LinearLayout>
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview2"
android:layout_width="match_parent"
android:layout_height="#dimen/_280sdp"
android:layout_weight="0.7"
tools:itemCount="7"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:layout_constraintTop_toBottomOf="#+id/linearLayout"
tools:listitem="#layout/product_item" />
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="#dimen/_110sdp"
android:layout_weight="0.15"
android:gravity="bottom"
android:padding="5dp"
app:layout_constraintTop_toBottomOf="#id/recyclerview2"
tools:layout_editor_absoluteX="0dp">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/floating_action_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_margin="16dp"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:contentDescription="#string/fab_content_desc"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_add_circle_outline" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
The Product Item XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/background_border"
android:orientation="vertical">
<LinearLayout
android:id="#+id/rowBGP"
android:background="#color/colorPrimaryDark"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_alignParentRight="true"
android:gravity="right"
android:orientation="horizontal">
<RelativeLayout
android:id="#+id/delete_task"
android:layout_width="50dp"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="true"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/img_delete"
android:layout_width="50dp"
android:layout_marginTop="#dimen/_1sdp"
android:layout_height="59dp"
android:background="#color/light_red"
android:text="#string/edit_article"
android:textSize="12dp"
android:textStyle="bold|italic"
app:tint="#android:color/white" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/rowFGP"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#android:color/white"
android:clickable="true"
android:elevation="4dp"
android:focusable="true"
android:orientation="horizontal"
android:layout_margin="1dp"
android:visibility="visible">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:foreground="?attr/selectableItemBackground">
<TextView
android:id="#+id/title_booking"
style="#style/TextAppearance.AppCompat.Medium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="#dimen/_2sdp"
android:layout_marginBottom="32dp"
android:lines="1"
android:text="#string/product_bookings"
android:textFontWeight="900"
android:textSize="#dimen/_15sdp"
android:textStyle="bold|italic"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.888" />
<TextView
android:id="#+id/type_booking"
android:text="#string/booking_type"
style="#style/TextAppearance.AppCompat.Headline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:textSize="#dimen/_10sdp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.265"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.615" />
<TextView
android:id="#+id/name_booking"
android:text="#string/name_booking"
style="#style/TextAppearance.AppCompat.Headline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:textSize="#dimen/_15sdp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.265"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.615" />
<TextView
android:id="#+id/date_booking"
android:text="#string/date_booking"
style="#style/TextAppearance.AppCompat.Medium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:layout_marginEnd="8dp"
android:lines="1"
android:textFontWeight="900"
android:textSize="#dimen/_15sdp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.888"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
</RelativeLayout>
When you are setting the Adapter, stockBookingList is empty.
This means that when RecyclerView decides to render items on the list, it finds the itemCount to be 0.
This instructs the RecylcerView to not render anything on the list, since it won't call onCreateViewHolder or onBindViewHolder – two methods responsible for inflating your list item and setting necessary data.
If you have a static list of items, you need to provide them to the adapter.
If the list is coming from your RestClient, you need update the adapter as and when you receive data from your API.

Android Initial Login Screen then use fragments to swipe between screens once login is successful

I am trying to create an Android app, then has an initial login screen that detects if a user is Admin or User. Once logged in, the user (depending on their role) will see different tabs to swipe between. I have a basic app that starts with a login activity and the login to decipher the users roles (using static values for now). First part is ok. Now when I try to use Fragments after the login screen, I'm getting stuck.
I have a LoginActivity that has an onClikcListener on a button after user enters credentials. Depending on whether the user is Amin or General Users, it will just to a new activity either activity_vote_admin or activity_vote_user. At this point I am stuck. Any ideas if what I am trying to do is valid. Or is there a better way to do this. At the moment I am getting this error.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.confidencevotefragmentrebuild/com.example.confidencevotefragmentrebuild.activity_vote_admin}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference.
LoginActivity (this is my main activity)
...
package com.example.confidencevotefragmentrebuild;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginActivity extends AppCompatActivity {
private static EditText username;
private static EditText password;
public static TextView attempts;
private static Button submit_button;
int attempt_counter = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginButton();
}
public void loginButton() {
username = (EditText) findViewById(R.id.editText);
password = (EditText) findViewById(R.id.editText2);
attempts = (TextView) findViewById(R.id.textView_Attempts);
//Reference button view
final Button submit_button = findViewById(R.id.submit_button);
// perform click event on button
submit_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (username.getText().toString().equals("admin") &&
password.getText().toString().equals("pass")) {
Toast.makeText(LoginActivity.this, "Welcome " + username.getText(),
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LoginActivity.this, activity_vote_admin.class);
startActivity(intent);
} else if (username.getText().toString().equals("user") &&
password.getText().toString().equals("pass")) {
Toast.makeText(LoginActivity.this, "Welcome " + username.getText(),
Toast.LENGTH_SHORT).show();
Intent intentUser = new Intent(LoginActivity.this, activity_vote_user.class);
startActivity(intentUser);
} else {
Toast.makeText(LoginActivity.this, "User or Password incorrect",
Toast.LENGTH_SHORT).show();
attempt_counter--;
attempts.setText(Integer.toString(attempt_counter));
if (attempt_counter == 0) {
Toast.makeText(LoginActivity.this, "Too many failed attempts, please close app and try again",
Toast.LENGTH_SHORT).show();
submit_button.setEnabled(false);
}
}
}
}
);
}
}
...
Activity_vote_admin
...
package com.example.confidencevotefragmentrebuild;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
public class activity_vote_admin extends AppCompatActivity {
/**
* Field for selecting the number of confidence votes
*/
RatingBar mResults;
private RatingBar rBar;
Button mBtn;
/**
* Spinner field to enter the project name
*/
private Spinner mProjectSpinner;
/**
* Projects. The possible values are:
* stored locally - Needs to get values from a database. TODO
*/
int mProject = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vote_main_admin);
// Find the view pager that will allow the user to swipe between fragments
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
// Create an adapter that knows which fragment should be shown on each page
AdminFragmentPagerAdapter adapter = new AdminFragmentPagerAdapter(getSupportFragmentManager());
// Set the adapter onto the view pager
viewPager.setAdapter(adapter);
// initiate a rating bar
rBar = findViewById(R.id.rating_bar);
//float vote = rBar.getRating();
// Find all relevant views for user input
mResults = findViewById(R.id.rating_bar);
mProjectSpinner = findViewById(R.id.spinner_project);
// Run getRating method to get rating number from a rating bar
//getRating();
// Initiate button
mBtn = findViewById(R.id.voteButton);
// perform click event on button
mBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get values and then displayed in a toast
//String totalStars = "Total Stars:: " + RatingBar.getNumStars();
float vote = rBar.getRating();
String rating = "Rating : " + vote;
Toast.makeText(getApplicationContext(), rating + "\n", Toast.LENGTH_LONG).show();
}
});
projectSpinner();
}
// Setup the dropdown spinner that allows the user to select the role.
private void projectSpinner() {
// Create adapter for spinner. The list options are from the String array it will use
// the spinner will use the default layout
ArrayAdapter projectSpinnerAdapter = ArrayAdapter.createFromResource(this,
R.array.projects, android.R.layout.simple_spinner_item);
// Specify dropdown layout style - simple list view with 1 item per line
projectSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
// Apply the adapter to the project spinner
mProjectSpinner.setAdapter(projectSpinnerAdapter);
// Set the integer mSelected to the constant values
mProjectSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if(mProjectSpinner.getSelectedItem() == "This is Hint Text");
if (!TextUtils.isEmpty(selection)) {
if (selection.equals(getString(R.string.nextGEMS1_5))) {
mProject = 0 ;
return;
} else if (selection.equals(getString(R.string.nextGEMS1_6))) {
mProject = 1;
return;
} else if (selection.equals(getString(R.string.nextGEMS1_7))) {
mProject = 2;
return;
} else if (selection.equals(getString(R.string.nextGEMS1_8))) {
mProject = 3;
return;
} else if (selection.equals(getString(R.string.nextGEMS1_9))) {
mProject = 4;
return;
}
else mProject = 0;
}
}
// Because AdapterView is an abstract class, onNothingSelected must be defined
#Override
public void onNothingSelected(AdapterView<?> parent) {
mProject = 0; // User
}
});
}
}
...
activity_vote_main_admin.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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.viewpager.widget.ViewPager
android:name="com.example.confidencevotefragmentrebuild.testFragment1"
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
...
activity_login.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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".LoginActivity"
tools:showIn="#layout/activity_login">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#5fb0c9"
android:orientation="vertical"
android:scrollbarAlwaysDrawVerticalTrack="true">
<TextView
android:id="#+id/login_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:gravity="center_horizontal"
android:text="LOGIN"
android:textColor="#fff"
android:textSize="20sp"
android:textStyle="bold" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="500dp"
android:background="#ffffff"
android:elevation="4dp"
android:orientation="vertical"
android:padding="20dp"
android:layout_below="#+id/login_title"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="80dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="450dp"
android:orientation="vertical"
android:paddingTop="30dp">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="70dp">
<EditText
android:id="#+id/editText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:drawableLeft="#drawable/usericon"
android:hint="User Name"
android:inputType="textEmailAddress"
android:maxLines="1" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/editText2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:drawableLeft="#drawable/lock"
android:hint="Password"
android:inputType="textPassword"
android:maxLines="1" />
</com.google.android.material.textfield.TextInputLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:paddingTop="5dp"
android:text="Forgot Password?" />
<Button
android:id="#+id/submit_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="22dp"
android:background="#drawable/action_buttom"
android:text="Sign in"
android:textAllCaps="false"
android:textColor="#fff"
android:textSize="18sp" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="20dp"
android:orientation="horizontal"
android:paddingTop="1dp">
<TextView
android:id="#+id/attempts_text"
android:layout_width="wrap_content"
android:layout_height="25dp"
android:layout_gravity="center_horizontal"
android:paddingTop="1dp"
android:text="Number of attempts remaining: " />
<TextView
android:id="#+id/textView_Attempts"
android:layout_width="match_parent"
android:layout_height="25dp"
android:layout_gravity="center_horizontal"
android:paddingTop="1dp"
android:text="5" />
</LinearLayout>
<TextView
android:id="#+id/lnkRegister"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
android:gravity="center"
android:paddingTop="30dp"
android:text="Register here"
android:textColor="#5fb0c9"
android:textSize="16sp" />
</LinearLayout>
</RelativeLayout>
<ImageButton
android:id="#+id/conferencevote_logo"
android:layout_width="210dp"
android:layout_height="180dp"
android:layout_below="#+id/login_title"
android:layout_centerHorizontal="true"
android:layout_marginTop="2dp"
android:elevation="4dp"
android:background="#drawable/rounded_button"
android:src="#drawable/confvotenew"
/>
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
...
AdminFragemntyPagerAdapter
...
package com.example.confidencevotefragmentrebuild;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
public class AdminFragmentPagerAdapter extends FragmentPagerAdapter {
public AdminFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
return new testFragment1();
} else if (position == 1) {
return new testFragment2();
} else {
return new testFragment2();
}
}
#Override
public int getCount() {
return 3;
}
}
...
aactivity_vote_user.xml
...
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#5fb0c9"
android:orientation="vertical"
android:scrollbarAlwaysDrawVerticalTrack="true">
<TextView
android:id="#+id/vote_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:gravity="center_horizontal"
android:text="USER VOTE"
android:textColor="#fff"
android:textSize="20sp"
android:textStyle="bold"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="500dp"
android:background="#ffffff"
android:elevation="4dp"
android:orientation="vertical"
android:padding="20dp"
android:layout_below="#+id/vote_title"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="80dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="450dp"
android:orientation="vertical"
android:paddingTop="70dp">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<Spinner
android:id="#+id/spinner_project"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp"
android:hint="#string/spinner_hint"
android:maxLines="1"
android:singleLine="true"
android:backgroundTint="#color/attCobalt"
android:popupBackground="#color/myBlue"
android:dropDownSelector="#color/attBlue"
/>
</com.google.android.material.textfield.TextInputLayout
>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<RatingBar
android:id="#+id/rating_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:stepSize="1.0"
android:layout_marginTop="40dp"
android:theme="#style/rating_bar"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingTop="5dp"
android:text="Vote and Submit" />
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="#+id/voteButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="22dp"
android:background="#drawable/action_buttom"
android:text="Submit"
android:textAllCaps="false"
android:textColor="#fff"
android:textSize="18sp" />
/>
</LinearLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
<ImageButton
android:id="#+id/conferencevote_logo"
android:layout_width="210dp"
android:layout_height="180dp"
android:layout_below="#+id/login_title"
android:layout_centerHorizontal="true"
android:layout_marginTop="55dp"
android:elevation="4dp"
android:background="#drawable/rounded_button"
android:src="#drawable/confvotenew"
/>
</RelativeLayout>
...
My fragments are as follows.
...
package com.example.confidencevotefragmentrebuild;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
public class testFragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_vote_user, container, false);
}
}
...
There are two reason for this issue :
You didn't declare any button on "activity_vote_main_admin.xml", thats why your view not binding with activity and giving null pointer exception.
May be you declare the button on fragment xml and trying to bind it with activity.

My app crashed for unknown reason when I tried to setOnClickListener for a button in ListView

I'm building a Contact app using ListView. My ListView has 2 button. In this app, to test the respond ability of the buttons, I intended to set the button "Edit" so that when I click on it, it will change to "Clicked", and the button "Delete" will change to "Clicked", too. When I ran the Debug, the app stopped working and I couldn't get it work again (before I added the onClickListener, this app had worked property).
I don't know what is the error, and have tried many ways to fix.
Here is my row_listview.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_margin="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="5">
<ImageView
android:id="#+id/imgAvatar"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="1"
android:src="#drawable/if_male3_403019" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2.7"
android:orientation="vertical"
android:weightSum="2">
<TextView
android:id="#+id/tvName"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:paddingLeft="15dp"
android:text="Akai Shuichi"
android:textSize="16dp"
android:textColor="#000"
android:gravity="center_vertical"
/>
<TextView
android:id="#+id/tvNumber"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:paddingLeft="15dp"
android:text="0982xxxxxx"
android:textSize="16dp"
android:textColor="#000"
android:gravity="center_vertical"
/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.3"
android:weightSum="2"
android:orientation="vertical">
<Button
android:id="#+id/btnEdit"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:backgroundTint="#3FE0FF"
android:onClick="myClickHandler"
android:text="Edit"
android:textColor="#fff"
android:textStyle="bold" />
<Button
android:id="#+id/btnDelete"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:backgroundTint="#F73131"
android:onClick="myClickHandler"
android:text="Delete"
android:textColor="#fff"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
And here is my MainActivity.java:
package com.huy9515gmail.mycontact;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity {
#BindView(R.id.edt_inputName) EditText edtName;
#BindView(R.id.btnAdd) Button btnAdd;
#BindView(R.id.btnEdit) Button btnEdit;
#BindView(R.id.btnDelete) Button btnDelete;
#BindView(R.id.edt_inputNumber) EditText edtNumber;
#BindView(R.id.rdbtn_male) RadioButton rdbtn_male;
#BindView(R.id.rdbtn_female) RadioButton rdbtn_female;
#BindView(R.id.rdbtn_others) RadioButton rdbtn_others;
#BindView(R.id.gender) RadioGroup genderSelection;
private ListView lvContact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
lvContact = (ListView) findViewById(R.id.lv_contact);
final ArrayList<Contact> arrContact = new ArrayList<>();
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//validating contact info
if (((edtName.getText().toString().trim()) == "") || (edtNumber.getText().toString().trim() == "") || ((rdbtn_male.isChecked()==false) && (rdbtn_female.isChecked()==false) &&(rdbtn_others.isChecked()==false))) {
Toast.makeText(MainActivity.this, "Invalid contact info! Please try again!", Toast.LENGTH_SHORT).show();
}
//adding contact info
else {
Contact contact = new Contact(Gender.male, "", "");
//adding info
contact.setName(edtName.getText().toString());
contact.setNumber(edtNumber.getText().toString());
arrContact.add(contact);
}
CustomAdapter customAdapter = new CustomAdapter(MainActivity.this, R.layout.row_listview, arrContact);
lvContact.setAdapter(customAdapter);
}
});
}
public void myClickHandler(View v) {
LinearLayout vwParentRow = (LinearLayout) v.getParent();
Button btnEdit = (Button) vwParentRow.getChildAt(0);
Button btnDelete = (Button) vwParentRow.getChildAt(1);
btnEdit.setText("Clicked");
btnDelete.setText("Clicked");
}
}
And here is the row_listview.xml layout:
Instead of setting the android:onClick in XML, do the same as you did for btnAdd.
Find the view by id or use butterknife, then put the following in onCreate()
btnEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Your code here
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Your code here
}
});
Make sure you have an element in your XML file with the id like this:
android:id="#+id/btnAdd"

CalendarView Causes App to Crash

Essentially I have an issue with my calendarView widget. In the app whenever it goes from my Main class to the EditProgress class it either freezes or crashes. I tested it, and whenever the calendarView widget is in the EditProgress class the app runs very slowly, and whenever I attempt to use the widget in my .java class it simply crashes. It had complained before saying that it required API level 11, so I tried to fix this by using suppress warnings, but it still crashes or runs slowly. Thank you for any help. Below is my .java class:
package com.dwolford.workoutroutine;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class EditProgress extends Activity {
Button submit;
Button back;
Spinner exercise;
ArrayAdapter<CharSequence> adapter;
EditText reps;
CalendarView calendar;
Context context = this;
#TargetApi(11)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_progress);
exercise = (Spinner)findViewById(R.id.spinner);
adapter = ArrayAdapter.createFromResource(this, R.array.Exercises, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
exercise.setAdapter(adapter);
exercise.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText((getBaseContext()), (parent.getItemIdAtPosition(position) + 2) + " selected", Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
calendar = (CalendarView)findViewById(R.id.calendarView);
reps = (EditText)findViewById(R.id.editText);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
double repetitions = Double.parseDouble(reps.getText().toString());//Get number of repetitions on that day
String exerciseName = exercise.getSelectedItem().toString();//Get specific exercise user did
String calendarDate = calendar.getDate()+"";
}
});
back = (Button)findViewById(R.id.Back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_edit_progress, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And here is my .XML file:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="EDIT PROGRESS"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="45dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:height="50dp"
android:textSize="22dp"
android:gravity="center"
android:textStyle="bold" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BACK"
android:id="#+id/Back"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:height="50dp"
android:textSize="22dp"
android:background="#drawable/button_gradient" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:id="#+id/Submit"
android:layout_above="#+id/Back"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="38dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:height="50dp"
android:textSize="22dp"
android:background="#drawable/button_gradient" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exercise"
android:id="#+id/Exercise"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Date"
android:id="#+id/date"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:textSize="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Repetitions"
android:id="#+id/repetitions"
android:layout_alignBottom="#+id/date"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textSize="20dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_below="#+id/repetitions"
android:layout_alignRight="#+id/repetitions"
android:layout_alignEnd="#+id/repetitions"
android:layout_alignLeft="#+id/repetitions"
android:layout_alignStart="#+id/repetitions" />
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:layout_below="#+id/Exercise"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toStartOf="#+id/date"
android:layout_toLeftOf="#+id/date"
android:layout_alignRight="#+id/Exercise"
android:layout_alignEnd="#+id/Exercise" />
<CalendarView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/calendarView"
android:layout_below="#+id/date"
android:layout_centerHorizontal="true" />
Your minimum SDK used for the project is lower than API 11. That's why it's giving you that error.
You can change it in your project settings. Just increase it to API 11 and everything should work fine.

Carry selected button values to next page

I have 25 buttons in my layout xml file (called activity_button_page.xml); the code for 5 buttons is given below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".ButtonPage" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="00"
android:id="#+id/ze1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="25"
android:id="#+id/tf1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="50"
android:id="#+id/fi1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="25"
android:id="#+id/tf2"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="00"
android:id="#+id/ze2"/>
</LinearLayout>
</LinearLayout>
My objective is to have the user click up to 3 buttons, and I would like the sum of the values (given by the android:text code to appear on a textView (android:id="#+id/resulttextview") in the next page (activity_result_page.xml).
This is what I currently have in ButtonPage.java
package com.example.buttonfield;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class ButtonPage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_button_page);
Button ze1 = ((Button)this.findViewById(R.id.ze1));
ze1.setOnClickListener(this);
}
public void onClickListener(View v){
pressed=((Button)v).getText();
switch (v.getId()) {
case R.id.zero1:
pressed=zero1.getText().toString();
break;
//OR
case R.id.zero1:
pressed=R.id.zero1.getText().toString();
break;
}
new AlertDialog.Builder(this).setTitle("Info").setMessage(pressed).setNeutralButton("Okey", null).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.button_page, menu);
return true;
}
}
What is the correct way to approach this? Thanks!
Basiclly you just need to get three button's text and add them as Integer. Then use intent extra to pass the value to whatever page you like.
// button page
Button submit = (Button)findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int sum = Integer.parseInt(button1.getText()) +
Integer.parseInt(button2.getText()) +
Integer.parseInt(button3.getText());
Intent intent = new Intent(this, ResultActivity.class);
intent.putExtra("sum", sum);
startActivity(intent);
}
});
// result page
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result_page);
Bundle bundle = getIntent().getExtras();
if(bundle != null) {
int sum = bundle.getInt("sum");
TextView textView = (TextView)findViewById(R.id.your_text_view);
textView.setText(Integer.toString(sum));
}
}

Categories

Resources