I want to be able to display the next prime number each time the button is clicked but cannot find a way for it to work. Anybody help please?
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button primeButton = (Button) findViewById(R.id.primeButton);
primeButton.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View v){
TextView primeText = (TextView) findViewById(R.id.primeText);
int max = 500;
for(int i=2; i<=max; i++) {
boolean isPrimeNumber = true;
for (int j = 2; j <= i; j++) {
if (i % j == 0 ) {
isPrimeNumber = false;
break;
}
}
if (isPrimeNumber){
primeText.setText(Integer.toString(i));
}
}
}
}
);
}
}
Try this
public class MainActivity extends Activity {
Button b;
int max = 500;
TextView vTextView;
int j = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
vTextView = (TextView) findViewById(R.id.textView1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for (int i = j; i <= max; i++) {
if (isPrimeNumber(i)) {
vTextView.setText(i+"");
j = i+1;
break;
}
}
}
});
}
public boolean isPrimeNumber(int number) {
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
To find out a prime number, prime numbers between two numbers and sum of a prime number
public class MainActivity extends AppCompatActivity {
private EditText etInput;
private EditText et_from, et_to;
private Button btnCheck, btn_print;
private TextView tvResult;
private int inputnumber;
private int fromNumber, toNumber;
private boolean isPrimeNumber = true;
private TextView tv_prime_sum;
private int primeNumbersSum;
private TextView tv_check;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViews();
btnCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(etInput.getText().toString().trim() != null && etInput.getText().toString().trim().length() > 0)) {
etInput.setError("Please enter the number");
} else {
inputnumber = Integer.parseInt(etInput.getText().toString());
for (int i = 2; i <= inputnumber / 2; i++) {
if (inputnumber % i == 0) {
isPrimeNumber = false;
break;
}
}
if (isPrimeNumber) {
tv_check.setText("The given number " + inputnumber + " is a prime number");
} else {
tv_check.setText("The given number " + inputnumber + " is not a prime number");
}
isPrimeNumber = true;
}
}
});
btn_print.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(et_from.getText().toString().trim() != null && et_from.getText().toString().trim().length() > 0)) {
et_from.setError("Please enter the number");
} else if (!(et_to.getText().toString().trim() != null && et_to.getText().toString().trim().length() > 0)) {
et_to.setError("Please enter the number");
} else {
fromNumber = Integer.parseInt(et_from.getText().toString());
toNumber = Integer.parseInt(et_to.getText().toString());
if (fromNumber > toNumber) {
fromNumber = fromNumber - toNumber;
toNumber = fromNumber + toNumber;
fromNumber = toNumber - fromNumber;
}
StringBuilder stringBuilder = new StringBuilder();
for (int j = fromNumber; j <= toNumber; j++) {
for (int i = 2; i <= j / 2; i++) {
if (j % i == 0) {
isPrimeNumber = false;
break;
} else {
isPrimeNumber = true;
}
}
if (isPrimeNumber) {
Log.v("Primenumber", "list" + j);
primeNumbersSum = primeNumbersSum + j;
stringBuilder.append(j);
stringBuilder.append(",");
} else {
}
}
tvResult.setText(stringBuilder.toString());
tv_prime_sum.setText("Total sum of prime numbers: " + primeNumbersSum);
isPrimeNumber = true;
primeNumbersSum = 0;
}
}
});
}
private void findViews() {
etInput = findViewById(R.id.et_input);
btnCheck = findViewById(R.id.btn_check);
tvResult = findViewById(R.id.tv_result);
tv_prime_sum = findViewById(R.id.tv_prime_sum);
et_from = findViewById(R.id.et_from);
et_to = findViewById(R.id.et_to);
btn_print = findViewById(R.id.btn_print);
tv_check = findViewById(R.id.tv_check);
}
}
<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="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/et_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="enter the number"
android:inputType="number"
android:visibility="visible" />
<Button
android:id="#+id/btn_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/et_input"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:text="Check" />
<TextView
android:id="#+id/tv_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btn_check"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:text="print the number is prime or not" />
<EditText
android:id="#+id/et_from"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_check"
android:hint="from number"
android:inputType="number" />
<EditText
android:id="#+id/et_to"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/et_from"
android:hint="to number"
android:inputType="number" />
<Button
android:id="#+id/btn_print"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/et_to"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:text="Print" />
<TextView
android:id="#+id/tv_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btn_print"
android:layout_centerHorizontal="true"
android:text="prints the list of prime numbers" />
<TextView
android:id="#+id/tv_prime_sum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_result"
android:layout_centerHorizontal="true"
android:layout_margin="10dp" />
</RelativeLayout>
Related
I'm trying to create my own multi button "custom view" that get it's attributes from an xml file.
When trying to create a custom view with more than 3 button, some button are truncated (please see screenshot attached).
Maybe someone encounter an issue like that (maybe the problem related to wrong use of ConstraintLayout "Packed Chain" style).
Please notice that i have a Boolean parameter named "reversedOrder" in order to support some language that are written from RTL
My Programmatic code is:
public class MultiButton extends ConstraintLayout
{
public static final int MAX_NUMBER_OF_BUTTONS = 5;
#StyleableRes
private int indexNumOfButtons = 0;
#StyleableRes
private int indexOfOrder = 1;
#StyleableRes
private int indexOfActiveButtonIndex = 2;
#StyleableRes
private int indexOfBackgroundSelectorResource = 3;
#StyleableRes
private int indexOfTextcolorSelectorResource = 4;
private int numOfButtons;
private int activeButtonIndex;
private boolean reversedOrder;
private Button[] allButtons;
private View.OnClickListener[] additionalOnClickListeners;
public MultiButton(Context context, AttributeSet attrs )
{
super(context,attrs);
init(context,attrs);
}
private void init(Context context, AttributeSet attrs)
{
int[] sets = {R.attr.numOfButtons, R.attr.reversedOrder, R.attr.activeButtonIndex,R.attr.backgroundSelector,R.attr.textColorSelector};
TypedArray typedArray = context.obtainStyledAttributes(attrs, sets);
numOfButtons = typedArray.getInt(indexNumOfButtons,1);
if (numOfButtons < 0)
{
numOfButtons = 1;
}
else if (numOfButtons > MAX_NUMBER_OF_BUTTONS)
{
numOfButtons = MAX_NUMBER_OF_BUTTONS;
}
allButtons = new Button[numOfButtons];
int height = getHeight();
for (int i =0; i<numOfButtons; i++)
{
allButtons[i] = new Button(context);
allButtons[i].setText("" +i);
allButtons[i].setHeight(height);
allButtons[i].setWidth(0);
}
additionalOnClickListeners = new View.OnClickListener[numOfButtons];
int backgroundSelectorResourceId = typedArray.getResourceId(indexOfBackgroundSelectorResource,0); //context.getResources().getDrawable(R.drawable.btn);
int textColorSelectorResourceId = typedArray.getResourceId(indexOfTextcolorSelectorResource,0);
reversedOrder = typedArray.getBoolean(indexOfOrder,false);
for (int i=0; i< numOfButtons; i++)
{
int currentIndex = reversedOrder ? (numOfButtons-i-1) : i;
allButtons[currentIndex].setId(generateViewId());
addView(allButtons[currentIndex]);
if (backgroundSelectorResourceId != 0) {
Drawable buttonDrawable = context.getResources().getDrawable(backgroundSelectorResourceId);
if (buttonDrawable != null) {
buttonDrawable.mutate();
allButtons[currentIndex].setBackground(buttonDrawable);
}
}
if (textColorSelectorResourceId != 0)
{
ColorStateList colorStateList = context.getResources().getColorStateList(textColorSelectorResourceId);
if (colorStateList !=null) {
allButtons[currentIndex].setTextColor(colorStateList);
}
}
allButtons[currentIndex].setOnClickListener(new DefaultButtonListener(currentIndex));
}
ConstraintSet set = new ConstraintSet();
set.clone(this);
int[] chainIds = new int[numOfButtons];
float[] chainWeights = new float[numOfButtons];
for (int i=0; i<numOfButtons; i++)
{
int currentIndex = reversedOrder ? (numOfButtons-i-1) : i;
chainIds[currentIndex] = allButtons[currentIndex].getId();
chainWeights[currentIndex] = 1;
}
for (int i=1; i< numOfButtons ; i++)
{
if (reversedOrder)
{
set.connect(allButtons[i - 1].getId(), ConstraintSet.LEFT, allButtons[i].getId(), ConstraintSet.RIGHT);
}
else
{
set.connect(allButtons[i-1].getId(), ConstraintSet.RIGHT, allButtons[i].getId(),ConstraintSet.LEFT);
}
}
if (reversedOrder)
{
set.connect(allButtons[0].getId(),ConstraintSet.RIGHT,ConstraintSet.PARENT_ID,ConstraintSet.RIGHT);
set.connect(allButtons[numOfButtons-1].getId(),ConstraintSet.LEFT,ConstraintSet.PARENT_ID,ConstraintSet.LEFT);
}
else
{
set.connect(allButtons[0].getId(),ConstraintSet.LEFT,ConstraintSet.PARENT_ID,ConstraintSet.LEFT);
set.connect(allButtons[numOfButtons-1].getId(),ConstraintSet.RIGHT,ConstraintSet.PARENT_ID,ConstraintSet.RIGHT);
}
set.createHorizontalChain(ConstraintSet.PARENT_ID,ConstraintSet.LEFT, ConstraintSet.PARENT_ID,ConstraintSet.RIGHT,chainIds,chainWeights,ConstraintSet.CHAIN_PACKED);
set.applyTo(this);
activeButtonIndex = typedArray.getInt(indexOfActiveButtonIndex,0);
if (activeButtonIndex < 0 && activeButtonIndex > MAX_NUMBER_OF_BUTTONS -1)
{
activeButtonIndex = 0;
}
allButtons[activeButtonIndex].setSelected(true);
}
}
xml layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/helloWorld"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.example.customviewapp.MultiButton
android:layout_width="300dp"
android:layout_height="50dp"
app:layout_constraintTop_toBottomOf="#id/helloWorld"
android:layout_marginTop="15dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:numOfButtons="4"
app:activeButtonIndex="0"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
My program include icons on the tabLayout. I saw only one way to resize icon on tabItem from stackOverflow. I tried to do this way that I saw. But only I can resize first icon on the tabLayout.
MainActivity.java
LinearLayout lilcon;
private Integer[] images;
Integer[] domesticImages = {
R.drawable.ic_directions_bus_black_24dp,
R.drawable.ic_flight_takeoff_black_24dp,
R.drawable.ic_directions_boat_black_24dp,
R.drawable.ic_train_black_24dp,
R.drawable.ic_hotel,
R.drawable.ic_rent_a_car
};
private Integer[] domesticImagesClicked = {
R.drawable.ic_directions_bus_clicked_24dp,
R.drawable.ic_flight_takeoff_clicked_24dp,
R.drawable.ic_directions_boat_clicked_24dp,
R.drawable.ic_train_clicked_24dp,
R.drawable.ic_hotel_clicked,
R.drawable.ic_rent_a_car_clicked
};
private Integer[] abroadImages = {
R.drawable.ic_flight_takeoff_black_24dp,
R.drawable.ic_hotel,
R.drawable.ic_directions_bus_black_24dp,
R.drawable.ic_directions_boat_black_24dp,
R.drawable.ic_train_black_24dp,
R.drawable.ic_rent_a_car
};
private Integer[] abroadImagesClicked = {
R.drawable.ic_flight_takeoff_clicked_24dp,
R.drawable.ic_hotel_clicked,
R.drawable.ic_directions_bus_clicked_24dp,
R.drawable.ic_directions_boat_clicked_24dp,
R.drawable.ic_train_clicked_24dp,
R.drawable.ic_rent_a_car_clicked
};
Integer[] domesticImagesTablet = {
R.drawable.ic_tablet_destination_bus,
R.drawable.ic_tablet_airplane,
R.drawable.ic_tablet_boat,
R.drawable.ic_tablet_train,
R.drawable.ic_tablet_hotel,
R.drawable.ic_tablet_rent_a_car
};
private Integer[] domesticImagesClickedTablet = {
R.drawable.ic_tablet_destination_bus_clicked,
R.drawable.ic_tablet_airplane_clicked,
R.drawable.ic_tablet_boat_clicked,
R.drawable.ic_tablet_train_clicked,
R.drawable.ic_tablet_hotel_clicked,
R.drawable.ic_tablet_rent_a_car_clicked
};
private Integer[] abroadImagesTablet = {
R.drawable.ic_tablet_airplane,
R.drawable.ic_tablet_hotel,
R.drawable.ic_tablet_destination_bus,
R.drawable.ic_tablet_boat,
R.drawable.ic_tablet_train,
R.drawable.ic_tablet_rent_a_car
};
private Integer[] abroadImagesClickedTablet = {
R.drawable.ic_tablet_airplane_clicked,
R.drawable.ic_tablet_hotel_clicked,
R.drawable.ic_tablet_destination_bus_clicked,
R.drawable.ic_tablet_boat_clicked,
R.drawable.ic_tablet_train_clicked,
R.drawable.ic_tablet_rent_a_car_clicked
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
Log.i("stack", "ResultCreated");
init();
initData();
attachFragments();
/* registerCartOperationsReceiver();*/
registerHandlers();
}
void init() {
lilcon = view.findViewById(R.id.licon);
}
void initData(){
if (isDomestic) {
images = domesticImages;
} else {
images = abroadImages;
}
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
/* if (tabletSize) {
if (isDomestic) {
lilcon.setBackgroundResource(R.drawable.ic_tablet_destination_bus_clicked);
// tab.setIcon(domesticImagesTablet[i]);
tabLayout.getTabAt(0).setCustomView(lilcon);
}else{
lilcon.setBackgroundResource(R.drawable.ic_tablet_airplane_clicked);
// tab.setIcon(domesticImagesTablet[i]);
tabLayout.getTabAt(0).setCustomView(lilcon);
}
}else{}*/
if (tab != null && tab.getIcon() != null) {
int i = tab.getPosition();
if (isDomestic) {
tab.setIcon(domesticImagesClicked[i]);
// lilcon.setBackgroundResource(domesticImages[i]);
// tab.setCustomView(lilcon);
} else{
tab.setIcon(abroadImagesClicked[i]);
// lilcon.setBackgroundResource(domesticImages[i]);
// tab.setCustomView(lilcon);
}
}
/* int pos = tab.getPosition();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
View aview = tabLayout.getTabAt(i).getCustomView();
ImageView img = aview.findItemById(R.id.icon);
if (i == pos) {
if (isDomestic)
img.setImageResource(domesticImagesClicked[i];
else
img.setImageResource(abroadImagesClicked[i];
} else {
if (isDomestic)
img.setImageResource(domesticImages[i];
else
img.setImageResource(abroadImages[i];
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
if (tab != null && tab.getIcon() != null) {
int i = tab.getPosition();
/* boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
if (tabletSize) {
if (isDomestic) {
lilcon.setBackgroundResource(R.drawable.ic_tablet_destination_bus_clicked);
// tab.setIcon(domesticImagesTablet[i]);
tabLayout.getTabAt(0).setCustomView(lilcon);
// lilcon.setBackgroundResource(R.drawable.ic_tablet_destination_bus_clicked);
// tab.getTabAt(0).setCustomView(lilcon);
// lilcon.setBackgroundResource(domesticImages[i]);
// tab.setCustomView(lilcon);
}else{
// tab.setIcon(abroadImagesTablet[i]);
lilcon.setBackgroundResource(R.drawable.ic_tablet_airplane_clicked);
// tab.setIcon(domesticImagesTablet[i]);
tabLayout.getTabAt(0).setCustomView(lilcon);
//tab.setIcon(abroadImages[i]);
// lilcon.setBackgroundResource(domesticImages[i]);
// tab.setCustomView(lilcon);
}
}
else{}*/
if (isDomestic) {
tab.setIcon(domesticImages[i]);
// lilcon.setBackgroundResource(domesticImages[i]);
// tab.setCustomView(lilcon);
}else{
tab.setIcon(abroadImages[i]);
// lilcon.setBackgroundResource(domesticImages[i]);
// tab.setCustomView(lilcon);
}
}
}
#Override
public void onTabReselected(TabLayout.Tab tab) { }
void attachFragments() {
try {
for (int i = 0; i < tabLayout.getTabCount(); i++) {
}
boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
if (tabletSize) {
if (isDomestic){
// tabLayout.getTabAt(0).setIcon(R.drawable.ic_icon_bus);
lilcon.setBackgroundResource(R.drawable.ic_tablet_destination_bus_clicked);
tabLayout.getTabAt(0).setCustomView(lilcon);
} else {
// tabLayout.getTabAt(0).setIcon(R.drawable.ic_flight_takeoff_clicked_24dp);
lilcon.setBackgroundResource(R.drawable.ic_tablet_airplane_clicked);
tabLayout.getTabAt(0).setCustomView(lilcon);
}
}else {
if (isDomestic){
tabLayout.getTabAt(0).setIcon(R.drawable.ic_directions_bus_clicked_24dp);
// lilcon.setBackgroundResource(R.drawable.ic_directions_bus_clicked_24dp);
// tabLayout.getTabAt(0).setCustomView(lilcon);
} else {
tabLayout.getTabAt(0).setIcon(R.drawable.ic_flight_takeoff_clicked_24dp);
// lilcon.setBackgroundResource(R.drawable.ic_flight_takeoff_clicked_24dp);
// tabLayout.getTabAt(0).setCustomView(lilcon);
}}
// tabLayout.getTabAt(0).setCustomView(vehicleTypeImageView(1,true));
if (tabletSize){
}else{}
for (int i = 1; i < tabLayout.getTabCount(); i++) {
if (isDomestic) {
tabLayout.getTabAt(i).setIcon(domesticImages[i]);
// lilcon.setBackground(domesticImages[i]);
// tabLayout.getTabAt(i).setCustomView(lilcon);
} else {
tabLayout.getTabAt(i).setIcon(abroadImages[i]);
// lilcon.setBackgroundResource(abroadImages[i]);
// tabLayout.getTabAt(i).setCustomView(lilcon);
}
}
/* for (int i = 1; i < tabLayout.getTabCount(); i++) {
if (isDomestic)
lilcon.setImageResource(domesticImages[i]);
else
lilcon.setImageResource(abroadImages[i]);
tabLayout.getTabAt(i).setCustomView(lilcon);
}*/
// herhangi bir tab item seçildiğinde tetiklenecek yer
tabLayout.addOnTabSelectedListener(this);
}
customtab.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/licon"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:id="#+id/icon"
android:layout_gravity="center_horizontal" />
</LinearLayout>
Try to do it like this
Prepare your tabs somewhere in your activity
for (int i = 0; i < tabLayout.getTabCount(); i++) {
View view1 = getLayoutInflater().inflate(R.layout.customtab, null);
ImageView img = view1.findViewById(R.id.icon);
img.setScaleType(ScaleType.FIT_XY);
if (domestic)
img.setImageResource(domesticImages[i]);
else
img.setImageResource(abroadImages[i]);
tabLayout.getTabAt(i).setCustomView(view1);
}
Then,
#Override
public void onTabSelected(TabLayout.Tab tab) {
int pos = tab.getPosition();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
View aview = tabLayout.getTabAt(i).getCustomView();
ImageView img = aview.findViewById(R.id.icon);
if (i == pos) {
if (isDomestic)
img.setImageResource(domesticImagesClicked[i];
else
img.setImageResource(abroadImagesClicked[i];
} else {
if (isDomestic)
img.setImageResource(domesticImages[i];
else
img.setImageResource(abroadImages[i];
}
}
}
Your customtab xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/licon"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:id="#+id/icon"
android:layout_gravity="center_horizontal" />
</LinearLayout>
I am getting tired fixing this problem. the app does not execute it always show me this error Binary XML file line #26: Error inflating class EditText. I don't understand how to fix this problem.
This is my activity_members.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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:orientation="vertical">
<android.support.constraint.ConstraintLayout
android:id="#+id/newMeetScreen"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible"
tools:layout_editor_absoluteX="384dp">
<ImageView
android:id="#+id/imageView3"
android:layout_width="0dp"
android:layout_height="54dp"
android:src="#drawable/gradient"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/edit_search"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="11dp"
android:layout_marginTop="7dp"
android:layout_marginEnd="13dp"
android:layout_marginBottom="7dp"
android:background="#drawable/radius_edit_text"
android:drawableLeft="#drawable/ic_search"
android:drawablePadding="3dp"
android:hint="Поиск"
android:imeOptions="actionGo"
android:inputType="text"
android:textColor="#color/colorPrimaryDark"
android:textColorHint="#9b9a9a"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/btnDone"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="#+id/btnDone"
android:layout_width="52dp"
android:layout_height="50dp"
android:background="#android:drawable/list_selector_background"
android:src="#drawable/ic_done"
android:textColor="#color/colorProjectTextWhite"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/edit_search"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
<android.support.v7.widget.RecyclerView
android:background="#color/colorBackgroundLight"
android:id="#+id/membersList"
android:scrollbars="vertical"
android:layout_marginTop="0dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
And this is my MembersActivity.java class.
public class MembersActivity extends AppCompatActivity {
private static final int REQUEST_CODE_READ_CONTACTS = 1;
private static boolean READ_CONTACTS_GRANTED = false;
RecyclerView members;
ArrayList<String> contacts = new ArrayList<String>();
ArrayList<String> tell = new ArrayList<String>();
UserAdapter adapter;
User user;
ArrayList<User> users = new ArrayList<>();
ImageButton btnDone;
StringBuilder stringBuilder = null;
EditText editSearch;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_members);
members = findViewById(R.id.membersList);
btnDone = findViewById(R.id.btnDone);
editSearch = findViewById(R.id.edit_search);
int hasReadContactPermission = ContextCompat.checkSelfPermission(Objects.requireNonNull(this), Manifest.permission.READ_CONTACTS);
if (hasReadContactPermission == PackageManager.PERMISSION_GRANTED) {
READ_CONTACTS_GRANTED = true;
} else {
ActivityCompat.requestPermissions(Objects.requireNonNull(this), new
String[]{Manifest.permission.READ_CONTACTS}, REQUEST_CODE_READ_CONTACTS);
}
if (READ_CONTACTS_GRANTED) {
getContacts();
}
btnDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stringBuilder = new StringBuilder();
int i=0;
char ch = ',';
do{
User user = adapter.checkedUsers.get(i);
if(i == adapter.checkedUsers.size()-1) ch = '.';
stringBuilder.append(user.getName() + ch);
if(i != adapter.checkedUsers.size() -1) {
stringBuilder.append("\n");
}
i++;
} while (i < adapter.checkedUsers.size());
if(adapter.checkedUsers.size() > 0) {
Intent intent = new Intent();
intent.putExtra("names", stringBuilder.toString());
setResult(RESULT_OK, intent);
finish();
} else {
Toast.makeText(MembersActivity.this, "Пожалуйста, выберите друзей", Toast.LENGTH_LONG).show();
}
}
});
editSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
adapter.getFilter().filter(charSequence);
return;
}
#Override
public void afterTextChanged(Editable editable) {
}
});
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_READ_CONTACTS:
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
READ_CONTACTS_GRANTED = true;
}
}
if (READ_CONTACTS_GRANTED) {
getContacts();
}
else {
Toast.makeText(this, "Требуется установить разрешения", Toast.LENGTH_LONG).show();
}
}
public void getContacts() {
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI =
ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID =
ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
StringBuffer output = new StringBuffer();
ContentResolver contentResolver = Objects.requireNonNull(this).getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
contacts.add(name);
Cursor phoneCursor =
contentResolver.query(PhoneCONTENT_URI, null,
Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null);
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
tell.add(phoneNumber);
}
}
}
}
if(tell.size() > contacts.size()) {
for(int i=0; i <contacts.size(); i++) {
user = new User(tell.get(i), contacts.get(i));
users.add(user);
}
} else {
for(int i=0; i < tell.size(); i++) {
user = new User(tell.get(i), contacts.get(i));
users.add(user);
}
}
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
adapter = new UserAdapter(users, this);
members.setLayoutManager(mLayoutManager);
members.setItemAnimator(new DefaultItemAnimator());
members.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
members.setAdapter(adapter);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
}
Please, help me fix this problem.
You need to set the width and height of your EditText in your layout file you cannot set these properties to 0dp. If you want to set this according to screen size then you can use layout_weight in your xml.Here you can know about layout_weight usage
If you are using constraintLayout in your layout you can see this link. Responsive layout designing with constraint layout
Hi this is one of my old apps I am trying to fix, when I run this code I get a black screen but the app does not close. There are no errors and the fonts are fine so why is it not working? It works up until I start a new activity with this class. Thanks in advance. Also if you are able to suggest a better timer to use that would be great as when I used to use this app it did not work correctly.
<?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:weightSum="1"
android:gravity="end">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/MainQuestion"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/SecondsLeft"
android:layout_gravity="center_horizontal"
/>
<Button
android:layout_width="115dp"
android:layout_height="87dp"
android:id="#+id/Question1"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="115dp"
android:layout_height="87dp"
android:id="#+id/Question2"
android:text=""
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="115dp"
android:layout_height="87dp"
android:id="#+id/Choice3"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="115dp"
android:layout_height="87dp"
android:id="#+id/Choice4"
android:layout_gravity="center_horizontal" />
</LinearLayout>
package com.steam.mytriviaapp;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.*;
import android.os.CountDownTimer;
import android.content.Intent;
//necessary imports//
public class SportsCat extends AppCompatActivity {//extension needed for app//
TextView Question;//new textview variable to show the random question//
Button Choice1;//new button variable for answers//
Button Choice2;//^//
Button Choice3;//^//
Button Choice4;//^//
TextView SecondsLeft;//new textview variable//
int QuestionCounter =0;//question counter int set to 0//
public static Integer Points = 0;// points set/reset to 0 depending on if it is first game since it was opened //
boolean[] numbers = new boolean [4];//new boolean array with 4 numbers and are auto set to false, then later if true, they cannot be used, so it will not use samequestion//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sports_cat);//all of these linked to their respective xml variable to change sizing etc//
SecondsLeft = findViewById(R.id.SecondsLeft);
Question = findViewById(R.id.MainQuestion);
Choice1 = findViewById(R.id.Question1);
Choice2 = findViewById(R.id.Question2);
Choice3 = findViewById(R.id.Choice3);
Choice4 = findViewById(R.id.Choice4);
for(int k=0;k<=4;k++)
{
Body();
}
}
public void Body() {//new object//
String[] ArraySportsQuestions = {"Which NBA team holds the record for the most season wins in the Eastern Conference in history?",
"Which of these soccer players has won the most FIFA Ballon d'Ors after 2010?",
"Since what year was table tennis an Olympic sport?", "Which of these athletes had a video game made in honour of him?", "How many national sports does Canada have?"};//questions to be used//
final String[] ArraySportsQ1 = {"Boston Celtics", "Miami Heat", "Chicago Bulls", "Cleveland Cavaliers"};//question answers//
final String[] ArraySportsQ2 = {"Lionel Messi", "Cristiano Ronaldo", "Neymar", "Luis Suarez"};
final String[] ArraySportsQ3 = {"1988", "1974", "1984", "1996"};
final String[] ArraySportsQ4 = {"Shaun White", "Micheal Jordan", "Lionel Messi", "Shaun Federer"};
final String[] ArraySportsQ5 = {"2", "1", "3", "4"};
String[][] arrayofQs = {ArraySportsQ1, ArraySportsQ2, ArraySportsQ3,
ArraySportsQ4, ArraySportsQ5};//2D array//
QuestionCounter++;
Random gen = new Random();//new random generator gen//
int num = gen.nextInt(4);
while(numbers[num] = true)//makes sure it is not the same number//
{
num = gen.nextInt(4);
}
numbers[num] = true;
int x = gen.nextInt(3);
int y = gen.nextInt(3);
while(y==x) //^//
{
y = gen.nextInt(3);
}
int z = gen.nextInt(3);
while(z==x||z==y) {
z = gen.nextInt(3);
}
int u = gen.nextInt(3);
while(u==x||u==y||u==z) {
u = gen.nextInt(3);
}
new CountDownTimer(10000, 1000) {//android made countdown timer that icustomised//
public void onTick(long millisUntilFinished) {
SecondsLeft.setText("seconds remaining: " + millisUntilFinished /
1000);
}
public void onFinish() {
SecondsLeft.setText("done!");
}
}.start();
Typeface font2 = Typeface.createFromAsset(getAssets(), "subway.ttf");
Question.setTypeface(font2);
Question.setText(ArraySportsQuestions[num]);//randomising of questions andanswers//
Choice1.setText(arrayofQs[num][x]);//sets the answer to the set for thequestion, for example is num = 3, answer set 3, and then the buttons below to randomstrings in this inner array//
Choice2.setText(arrayofQs[num][y]);
Choice3.setText(arrayofQs[num][z]);
Choice4.setText(arrayofQs[num][u]);
Choice1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Choice1.getText().equals(ArraySportsQ1[1])||Choice1.getText().equals(ArraySportsQ2[
1]) || Choice1.getText().equals(ArraySportsQ3[1]) ||
Choice1.getText().equals(ArraySportsQ4[1]) ||
Choice1.getText().equals(ArraySportsQ5[1]))// these are the answers//
{
Points++;
Toast.makeText(SportsCat.this, "Correct!" ,
Toast.LENGTH_LONG).show();//a notification type message at the bottom of the screendisappearing after//
if(QuestionCounter==4)
{
Intent j = new Intent(getApplicationContext(),gamedone.class);
startActivity(j);
}else{
Body();
}
}else
{
Toast.makeText(SportsCat.this, "Incorrect" ,
Toast.LENGTH_LONG).show();
if(QuestionCounter==4)
{
Intent j = new Intent(getApplicationContext(),gamedone.class);
startActivity(j);
}else
{
Body();
}
}
}
});
Choice2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Choice1.getText().equals(ArraySportsQ1[1])||Choice1.getText().equals(ArraySportsQ2[
1]) || Choice1.getText().equals(ArraySportsQ3[1]) ||
Choice1.getText().equals(ArraySportsQ4[1]) ||
Choice1.getText().equals(ArraySportsQ5[1]))
{Points++;
Toast.makeText(SportsCat.this, "Correct!" ,
Toast.LENGTH_LONG).show();
if(QuestionCounter==4)
{
Intent j = new Intent(getApplicationContext(),gamedone.class);
startActivity(j);
}else{
Body();
}
}else
{
Toast.makeText(SportsCat.this, "Incorrect" ,
Toast.LENGTH_LONG).show();
if(QuestionCounter==4)
{
Intent j = new Intent(getApplicationContext(),gamedone.class);
startActivity(j);
}else{
Body();
}
}
}
});
Choice3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Choice1.getText().equals(ArraySportsQ1[1])||Choice1.getText().equals(ArraySportsQ2[
1]) || Choice1.getText().equals(ArraySportsQ3[1]) ||
Choice1.getText().equals(ArraySportsQ4[1]) ||
Choice1.getText().equals(ArraySportsQ5[1]))
{Points++;
Toast.makeText(SportsCat.this, "Correct!" ,
Toast.LENGTH_LONG).show();
if(QuestionCounter==4)
{
Intent j = new Intent(getApplicationContext(),gamedone.class);
startActivity(j);
}else{
Body();
}
}else
{
Toast.makeText(SportsCat.this, "Incorrect" ,
Toast.LENGTH_LONG).show();
if(QuestionCounter==4)
{
Intent j = new Intent(getApplicationContext(),gamedone.class);
startActivity(j);
}else{
Body();
}
}
}
});
Choice4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Choice1.getText().equals(ArraySportsQ1[1])||Choice1.getText().equals(ArraySportsQ2[
1]) || Choice1.getText().equals(ArraySportsQ3[1]) ||
Choice1.getText().equals(ArraySportsQ4[1]) ||
Choice1.getText().equals(ArraySportsQ5[1]))
{Points++;
Toast.makeText(SportsCat.this, "Correct!" ,
Toast.LENGTH_LONG).show();
if(QuestionCounter==4)
{
Intent j = new Intent(getApplicationContext(),gamedone.class);
startActivity(j);
}else{
Body();
}}else
{
Toast.makeText(SportsCat.this, "Incorrect" ,
Toast.LENGTH_LONG).show();
if(QuestionCounter==4)
{
Intent j = new Intent(getApplicationContext(),gamedone.class);
startActivity(j);
}else{
Body();
}
Toast.makeText(SportsCat.this, "Incorrect" ,
Toast.LENGTH_LONG).show();
}
}
});
}}
SO i have json file which contain this code :
{
"gejala": "Apakah hawar berwarna kuning terang menuju ujung daun",
"gejala_kode": "GJL0025",
"penyakit_kode": "PNY0012",
"gambar_gejala":"hawar_daun",
"child": null
}
hawar_daun is name of the image i put on my drawable folder.
my xml part :
<RelativeLayout
android:id="#+id/big_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView4"
android:background="#drawable/bubble1"
android:layout_marginTop="20dip">
<TextView
android:layout_width="match_parent"
android:layout_height="200dp"
android:text="null"
android:textSize="17dp"
android:id="#+id/ask"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/gambargejala"
/>
</RelativeLayout>
and this is part of my java code which i want to put the image.
public class KonsultasiBerdasarkanGejalaActivity extends AppCompatActivity {
public static final String ASK_GEJALA = "Apakah terdapat tanda-tanda ini?" ;
int qIndex = 0;
int level = 0;
TextView header;
TextView ask;
ImageView askgambar;
Button ya;
Button tidak;
ScrollView lyContainer;
boolean calculate = false;
boolean fromTidak = false;
int calcCount = 0;
int yaCount = 0;
int tidakCount = 0;
boolean lastQuestion = false;
PohonKeputusan pohonKeputusan;
Padi padi;
String[] gejalaPadi;
ArrayList<PenyakitPadi> allPenyakit;
ArrayList<PenyakitPadi> relPenyakitPadiArr;
ArrayList<PohonKeputusan> pohonKeputusanObjArr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_konsultasi_start);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
setTitle(" Menu Konsultasi");
toolbar.setSubtitle(" Berdasarkan Gejala");
lyContainer = (ScrollView) findViewById(R.id.lyContainer);
Intent padiIntent = getIntent();
padi = padiIntent.getExtras().getParcelable("padiObj");
gejalaPadi = padi.gejala;
relPenyakitPadiArr = setRelatedPenyakit();
try {
pohonKeputusanObjArr = setRelatedGejala(initiatePohonKeputusan());
Log.e("pohonKeputusanObjArr", String.valueOf(pohonKeputusanObjArr.size()));
Log.e("pohonKeputusanObjArr", String.valueOf(pohonKeputusanObjArr.toString()));
} catch (IOException e) {
e.printStackTrace();
}
pohonKeputusan = pohonKeputusanObjArr.get(qIndex);
//Log.e("pohonKeputusan", String.valueOf(pohonKeputusan.gejala_kode));
String namaPadi = padi.nama;
if (namaPadi != null) {
namaPadi = namaPadi.substring(0,1).toUpperCase() + namaPadi.substring(1).toLowerCase();
header = (TextView) findViewById(R.id.textView4);
String ni = header.getText().toString();
ni = ni + "\"" + namaPadi + "\"";
header.setText(ni);
}
ask = (TextView) findViewById(R.id.ask);
askgambar=(ImageView) findViewById(R.id.gambargejala);
}
public ArrayList<PohonKeputusan> setRelatedGejala(ArrayList<PohonKeputusan> phk){
ArrayList<PohonKeputusan> phkObjArr = new ArrayList<PohonKeputusan>();
for (int i = 0; i < phk.size(); i++){
boolean result = false;
PohonKeputusan phkObj = phk.get(i);
String gejalaKode = phkObj.gejala_kode;
for (int i2 = 0; i2 < gejalaPadi.length; i2++){
if(gejalaKode.equals(gejalaPadi[i2])){
result = true;
break;
}
}
if(result == true) phkObjArr.add(phkObj);
}
return phkObjArr;
}
public void rollbackQuestion(ArrayList<PohonKeputusan> phk){
qIndex = 0;
pohonKeputusan = phk.get(qIndex);
}
public void setQuestion(PohonKeputusan phk){
ask.setText(phk.gejala);
------------------------------------??????????----------------------------
}
What code i must input in that last line on that last line to set the image from name file from json?
Thanks you.
If I understand correctly you're trying to convert a String into a resource ID.
If that is the case, you can use getResources().getIdentifier(name, type, package)
Here is an example.
public void setQuestion(PohonKeputusan phk){
ask.setText(phk.gejala);
askgambar.setImageResource(getResources().getIdentifier(phk. gambar_gejala, "drawable", getPackageName()));
}