I am learning android and here struggling to disable the button id btnWicketIndia when TextView id wicketsIndiaText has " \ 10 " value.
Also please tell me the way I write code is correct or can optimize.
MainActivity.java
package me.jatinsoni.cricketscorecard;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
int scoreIndia = 0;
int wicketsIndia = 0;
int scoreSA = 0;
int wicketsSA = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// India Buttons
Button btnSixerIndia = findViewById(R.id.sixerIndia);
Button btnFourIndia = findViewById(R.id.fourIndia);
Button btnSingleIndia = findViewById(R.id.singleIndia);
Button btnTwoIndia = findViewById(R.id.twoIndia);
Button btnNoIndia = findViewById(R.id.noIndia);
Button btnWideIndia = findViewById(R.id.wideIndia);
Button btnWicketIndia = findViewById(R.id.wicketIndia);
// South Africa Buttons
Button btnSixerSA = findViewById(R.id.sixerSA);
Button btnFourSA = findViewById(R.id.fourSA);
Button btnSingleSA = findViewById(R.id.singleSA);
Button btnTwoSA = findViewById(R.id.twoSA);
Button btnNoSA = findViewById(R.id.noSA);
Button btnWideSA = findViewById(R.id.wideSA);
Button btnWicketSA = findViewById(R.id.wicketSA);
// Reset button
Button btnResetScore = findViewById(R.id.resetScore);
btnSixerIndia.setOnClickListener(this);
btnFourIndia.setOnClickListener(this);
btnSingleIndia.setOnClickListener(this);
btnTwoIndia.setOnClickListener(this);
btnNoIndia.setOnClickListener(this);
btnWideIndia.setOnClickListener(this);
btnWicketIndia.setOnClickListener(this);
btnSixerSA.setOnClickListener(this);
btnFourSA.setOnClickListener(this);
btnSingleSA.setOnClickListener(this);
btnTwoSA.setOnClickListener(this);
btnNoSA.setOnClickListener(this);
btnWideSA.setOnClickListener(this);
btnWicketSA.setOnClickListener(this);
btnResetScore.setOnClickListener(this);
displayScoreIndia(scoreIndia, wicketsIndia);
displayScoreSA(scoreSA, wicketsSA);
}
#Override
public void onClick(View v) {
// Get Buttons IDs
switch (v.getId()) {
// India Buttons
case R.id.sixerIndia: {
scoreIndia += 6;
displayScoreIndia(scoreIndia, wicketsIndia);
break;
}
case R.id.fourIndia: {
scoreIndia += 4;
displayScoreIndia(scoreIndia, wicketsIndia);
break;
}
case R.id.singleIndia: {
scoreIndia += 1;
displayScoreIndia(scoreIndia, wicketsIndia);
break;
}
case R.id.twoIndia: {
scoreIndia += 2;
displayScoreIndia(scoreIndia, wicketsIndia);
break;
}
case R.id.noIndia: {
scoreIndia += 1;
displayScoreIndia(scoreIndia, wicketsIndia);
break;
}
case R.id.wideIndia: {
scoreIndia += 1;
displayScoreIndia(scoreIndia, wicketsIndia);
break;
}
case R.id.wicketIndia: {
if (String.valueOf(wicketsIndia).equals(" / 10")) {
btnWicketIndia.setEnabled(false);
}
wicketsIndia += 1;
displayScoreIndia(scoreIndia, wicketsIndia);
break;
}
// South Africa Buttons
case R.id.sixerSA: {
scoreSA += 6;
displayScoreSA(scoreSA, wicketsSA);
break;
}
case R.id.fourSA: {
scoreSA += 4;
displayScoreSA(scoreSA, wicketsSA);
break;
}
case R.id.singleSA: {
scoreSA += 1;
displayScoreSA(scoreSA, wicketsSA);
break;
}
case R.id.twoSA: {
scoreSA += 2;
displayScoreSA(scoreSA, wicketsSA);
break;
}
case R.id.noSA: {
scoreSA += 1;
displayScoreSA(scoreSA, wicketsSA);
break;
}
case R.id.wideSA: {
scoreSA += 1;
displayScoreSA(scoreSA, wicketsSA);
break;
}
case R.id.wicketSA: {
wicketsSA += 1;
displayScoreSA(scoreSA, wicketsSA);
break;
}
case R.id.resetScore: {
scoreIndia = 0;
scoreSA = 0;
wicketsIndia = 0;
wicketsSA = 0;
displayScoreIndia(scoreIndia, wicketsIndia);
displayScoreSA(scoreSA, wicketsSA);
break;
}
}
}
#SuppressLint("SetTextI18n")
public void displayScoreIndia(int score, int wickets) {
TextView scoreIndiaText = findViewById(R.id.scoreIndiaText);
TextView wicketsIndiaText = findViewById(R.id.wicketsIndiaText);
scoreIndiaText.setText(String.valueOf(score));
wicketsIndiaText.setText(" / " + String.valueOf(wickets));
}
#SuppressLint("SetTextI18n")
public void displayScoreSA(int score, int wickets) {
TextView scoreSAText = findViewById(R.id.scoreSAText);
TextView wicketsSAText = findViewById(R.id.wicketsSAText);
scoreSAText.setText(String.valueOf(score));
wicketsSAText.setText(" / " + String.valueOf(wickets));
}
}
XML Code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="#drawable/cricketground" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#99000000">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<!-- INDIA COLUMN -->
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center_horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:layout_marginTop="16dp"
android:src="#drawable/ic_india" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="INDIA"
android:textColor="#FFFFFF"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginBottom="32dp"
android:gravity="center_horizontal">
<TextView
android:id="#+id/scoreIndiaText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textSize="40sp"
android:fontFamily="sans-serif-thin"
android:textColor="#FFFFFF"/>
<TextView
android:id="#+id/wicketsIndiaText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" / 0"
android:textSize="20sp"
android:fontFamily="sans-serif-thin"
android:textColor="#FFFFFF"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<Button
android:id="#+id/sixerIndia"
style="#style/CircleButton"
android:text="Sixer"/>
<Button
android:id="#+id/fourIndia"
style="#style/CircleButton"
android:text="Four"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<Button
android:id="#+id/singleIndia"
style="#style/CircleButton"
android:text="Single"/>
<Button
android:id="#+id/twoIndia"
style="#style/CircleButton"
android:text="Two"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<Button
android:id="#+id/noIndia"
style="#style/CircleButton"
android:text="No"/>
<Button
android:id="#+id/wideIndia"
style="#style/CircleButton"
android:text="Wide"/>
</LinearLayout>
<Button
android:id="#+id/wicketIndia"
style="#style/RoundedButtons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="16dp"
android:layout_marginLeft="16dp"
android:layout_gravity="center_horizontal"
android:text="wicket" />
</LinearLayout>
<!-- PARTITION -->
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#33FFFFFF" />
<!--SOUTH AFRICA COLUMN -->
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center_horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:layout_marginTop="16dp"
android:src="#drawable/ic_south_africa" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SOUTH AFRICA"
android:textColor="#FFFFFF"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginBottom="32dp"
android:gravity="center_horizontal">
<TextView
android:id="#+id/scoreSAText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textSize="40sp"
android:fontFamily="sans-serif-thin"
android:textColor="#FFFFFF"/>
<TextView
android:id="#+id/wicketsSAText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" / 0"
android:textSize="20sp"
android:fontFamily="sans-serif-thin"
android:textColor="#FFFFFF"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<Button
android:id="#+id/sixerSA"
style="#style/CircleButton"
android:text="Sixer"/>
<Button
android:id="#+id/fourSA"
style="#style/CircleButton"
android:text="Four"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<Button
android:id="#+id/singleSA"
style="#style/CircleButton"
android:text="Single"/>
<Button
android:id="#+id/twoSA"
style="#style/CircleButton"
android:text="Two"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<Button
android:id="#+id/noSA"
style="#style/CircleButton"
android:text="No"/>
<Button
android:id="#+id/wideSA"
style="#style/CircleButton"
android:text="Wide"/>
</LinearLayout>
<Button
android:id="#+id/wicketSA"
style="#style/RoundedButtons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="16dp"
android:layout_marginLeft="16dp"
android:layout_gravity="center_horizontal"
android:text="wicket" />
</LinearLayout>
</LinearLayout>
<Button
android:id="#+id/resetScore"
style="?android:attr/borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="reset"
android:textColor="#FFFFFF"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
</FrameLayout>
</RelativeLayout>
You are comparing int. So just use
if (wicketsIndia == 10) {
btnWicketIndia.setEnabled(false);
}
EDIT:
int wicketsSA = 0;
Button btnWicketIndia; // DECLARE IT HERE
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
btnWicketIndia = findViewById(R.id.wicketIndia); // ASSIGN HERE
...
}
I'd have a look at the pattern you have chosen.
Use a ViewModel to hold the scores and wickets of the "home team" and the "away team".
Make some observers of the data in your activity/widget and respond to the changes.
You will need to add Google's/Android dependency to your App Gradle file:
// ViewModel and LiveData
implementation "android.arch.lifecycle:extensions:1.1.1"
Here is an example showing a ViewModel and an Activity using an observer like pattern:
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.view.View;
//Extend FRAGMENT ACTIVITY
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get handle on the ViewModel:
final ViewModelMain viewModelMain = ViewModelProviders.of(this).get(ViewModelMain.class);
//Observe the data in the viewmodel class:
viewModelMain.homeWickets.observe(this, new Observer<Integer>() {
#Override
public void onChanged(#Nullable Integer integer) {
//MAKE CHANGES WHEN THE VALUE FOR THE HOME WICKETS CHANGE LIKE SET ON CLICK METHODS TO NULL?
}
});
viewModelMain.homeScore.observe(this, new Observer<Integer>() {
#Override
public void onChanged(#Nullable Integer integer) {
//MAKE CHANGES WHEN THE VALUE FOR THE HOME SCORE CHANGE LIKE SET ON CLICK METHODS TO NULL?
}
});
//HOW TO SET A VIEW MODEL VALUE LIKE AFTER CLICKING A BUTTON:
View v = new View(getApplicationContext());
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewModelMain.setHomeScore(viewModelMain.getHomeScore().getValue() + 1);
}
});
}
}
import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.MutableLiveData;
import android.support.annotation.NonNull;
public class ViewModelMain extends AndroidViewModel {
public ViewModelMain(#NonNull Application application) {
super(application);
// Set all values to 0 when constructed?
this.awayScore.postValue(0);
this.homeScore.postValue(0);
this.homeWickets.postValue(0);
this.awayWickets.postValue(0);
}
public MutableLiveData<Integer> awayScore = new MutableLiveData<>();
public MutableLiveData<Integer> homeScore = new MutableLiveData<>();
public MutableLiveData<Integer> homeWickets = new MutableLiveData<>();
public MutableLiveData<Integer> awayWickets = new MutableLiveData<>();
//SETTERS -> POST THE DATA TO THE MUTABLE FIELDS
public void setAwayScore(Integer awayScore) {
this.awayScore.postValue(awayScore);
}
public void setAwayWickets(Integer awayWickets) {
this.awayWickets.postValue(awayWickets);
}
public void setHomeScore(Integer homeScore) {
this.homeScore.postValue(homeScore);
}
public void setHomeWickets(Integer homeWickets) {
this.homeWickets.postValue(homeWickets);
}
//STANDARD JAVA GETTERS
public MutableLiveData<Integer> getAwayScore() {
return awayScore;
}
public MutableLiveData<Integer> getAwayWickets() {
return awayWickets;
}
public MutableLiveData<Integer> getHomeScore() {
return homeScore;
}
public MutableLiveData<Integer> getHomeWickets() {
return homeWickets;
}
}
\ is a special character. So if you get a text that contains \, you must add \ before.
if (wicketsIndiaText.getText().toString().equals(" \\ 10 ")) {
btnWicketIndia.setEnabled(false);
}
Related
In the below code, I've set the new Intent in the autocomplete_next TextView, but in my Mobile, when I run the app, and When I try to move to the next activity, It does not go the next Activity, Instead of that, it comes back again to the same previous Activity. In the Android Studio LOGCAT, I've seen the RenderScript: SETAFFINITY ret = -1 . I got no trace about this error on Google? Please Help me to fix my issue. Thank You in Advance...
activity_calculator.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="match_parent"
tools:context=".CalculatorActivity"
android:layout_centerHorizontal="true">
<TableLayout
android:id="#+id/tableinput"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Operand 1 : "
android:textSize="20dp"
android:textAlignment="textStart"
/>
<EditText
android:id="#+id/oper1_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:layout_weight="1"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<TextView
android:id="#+id/autocomplete_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Operand 2 : "
android:textSize="20dp"
android:textAlignment="textStart"
android:layout_weight="0"/>
<EditText
android:id="#+id/oper2_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:layout_weight="1"/>
</TableRow>
</TableLayout>
<GridLayout
android:id="#+id/calculator"
android:layout_below="#id/tableinput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true">
<Button
android:id="#+id/add_btn"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:textColor="#android:color/white"
android:layout_margin="2dp"
android:textSize="20dp"
android:layout_row="0"
android:layout_column="0"
android:text="Add"/>
<Button
android:id="#+id/sub_btn"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:textColor="#android:color/white"
android:layout_margin="2dp"
android:textSize="20dp"
android:layout_row="0"
android:layout_column="1"
android:text="Sub"/>
<Button
android:id="#+id/min_btn"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:textColor="#android:color/white"
android:layout_margin="2dp"
android:textSize="20dp"
android:layout_row="0"
android:layout_column="2"
android:text="Min"/>
<Button
android:id="#+id/mul_btn"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:textColor="#android:color/white"
android:layout_margin="2dp"
android:textSize="20dp"
android:layout_row="1"
android:layout_column="0"
android:text="Multiply"/>
<Button
android:id="#+id/div_btn"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:textColor="#android:color/white"
android:layout_margin="2dp"
android:textSize="20dp"
android:layout_row="1"
android:layout_column="1"
android:text="Divide"/>
<Button
android:id="#+id/pow_btn"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:textColor="#android:color/white"
android:layout_margin="2dp"
android:textSize="20dp"
android:layout_row="2"
android:layout_column="1"
android:text="Power"/>
<Button
android:id="#+id/max_btn"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:textColor="#android:color/white"
android:layout_margin="2dp"
android:textSize="20dp"
android:layout_row="1"
android:layout_column="2"
android:text="Max"/>
<Button
android:id="#+id/rem_btn"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:textColor="#android:color/white"
android:layout_margin="2dp"
android:textSize="20dp"
android:layout_row="2"
android:layout_column="0"
android:text="Remainder"/>
<Button
android:id="#+id/clear_btn"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:textColor="#android:color/white"
android:layout_margin="2dp"
android:textSize="20dp"
android:layout_row="2"
android:layout_column="2"
android:text="clear"/>
</GridLayout>
<TableRow
android:layout_below="#id/calculator"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<TextView
android:id="#+id/video_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ans: "
android:textSize="20dp"
android:textAlignment="textStart"
android:layout_weight="0"/>
<EditText
android:id="#+id/ans_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:layout_weight="1"/>
</TableRow>
</RelativeLayout>
CalculatorActivity.java (Activity which calls another Activity)
package com.example.lab_excercise_2;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.lang.Math;
public class CalculatorActivity extends AppCompatActivity {
private EditText oper1, oper2, ans;
private Button add_btn, sub_btn, div_btn, mul_btn, rem_btn, max_btn, min_btn, pow_btn, clear_btn;
private Integer oper1_text, oper2_text;
private TextView video_next,autocomplete_next;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
add_btn = findViewById(R.id.add_btn);
sub_btn = findViewById(R.id.sub_btn);
mul_btn = findViewById(R.id.mul_btn);
div_btn = findViewById(R.id.div_btn);
rem_btn = findViewById(R.id.rem_btn);
min_btn = findViewById(R.id.min_btn);
max_btn = findViewById(R.id.max_btn);
pow_btn = findViewById(R.id.pow_btn);
clear_btn = findViewById(R.id.clear_btn);
oper1 = findViewById(R.id.oper1_edit_text);
oper2 = findViewById(R.id.oper2_edit_text);
ans = findViewById(R.id.ans_edit_text);
video_next = findViewById(R.id.video_textView);
autocomplete_next = findViewById(R.id.autocomplete_textView);
add_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
oper1_text=Integer.parseInt(oper1.getText().toString());
oper2_text=Integer.parseInt(oper2.getText().toString());
ans.setText(String.valueOf(oper1_text+oper2_text));
}
});
sub_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
oper1_text=Integer.parseInt(oper1.getText().toString());
oper2_text=Integer.parseInt(oper2.getText().toString());
ans.setText(String.valueOf(oper1_text-oper2_text));
}
});
mul_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
oper1_text=Integer.parseInt(oper1.getText().toString());
oper2_text=Integer.parseInt(oper2.getText().toString());
ans.setText(String.valueOf(oper1_text*oper2_text));
}
});
div_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
oper1_text=Integer.parseInt(oper1.getText().toString());
oper2_text=Integer.parseInt(oper2.getText().toString());
ans.setText(String.valueOf(oper1_text/oper2_text));
}
});
rem_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
oper1_text=Integer.parseInt(oper1.getText().toString());
oper2_text=Integer.parseInt(oper2.getText().toString());
ans.setText(String.valueOf(oper1_text%oper2_text));
}
});
max_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
oper1_text=Integer.parseInt(oper1.getText().toString());
oper2_text=Integer.parseInt(oper2.getText().toString());
ans.setText((oper1_text>oper2_text ? oper1_text: oper2_text).toString());
}
});
min_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
oper1_text=Integer.parseInt(oper1.getText().toString());
oper2_text=Integer.parseInt(oper2.getText().toString());
ans.setText((oper1_text<oper2_text ? oper1_text: oper2_text).toString());
}
});
pow_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
oper1_text=Integer.parseInt(oper1.getText().toString());
oper2_text=Integer.parseInt(oper2.getText().toString());
Double pow = Math.pow(oper1_text,oper2_text);
ans.setText(pow.toString());
}
});
clear_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
oper1.setText("");
oper2.setText("");
ans.setText("");
}
});
video_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent videoIntent = new Intent(CalculatorActivity.this,VideoActivity.class);
startActivity(videoIntent);
}
});
autocomplete_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent autocompleteIntent = new Intent(CalculatorActivity.this,AutocompleteActivity.class);
startActivity(autocompleteIntent);
}
});
}
}
activity_autocomplete.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="match_parent"
tools:context=".AutocompleteActivity">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textSize="30sp"
android:textAlignment="center"
android:layout_width="wrap_content"
android:text="Date-Time Picker Autocomplete"
android:textStyle="bold"
android:textColor="#color/colorPrimary"
android:layout_margin="20dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="#+id/setTime_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:textColor="#android:color/white"
android:text="Set Time"
android:layout_weight="1"
android:layout_margin="20dp"/>
<TextView
android:id="#+id/time_text"
android:textSize="20sp"
android:textAlignment="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:layout_weight="3"/>
</TableRow>
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="#+id/setDate_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:textColor="#android:color/white"
android:text="Set Date"
android:layout_margin="20dp"
android:layout_weight="1" />
<TextView
android:id="#+id/date_text"
android:textSize="20sp"
android:textAlignment="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:layout_weight="3"/>
</TableRow>
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/label_text"
android:textSize="20sp"
android:textAlignment="center"
android:layout_width="wrap_content"
android:text="Label "
android:textStyle="bold"
android:textColor="#color/colorPrimary"
android:layout_margin="20dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<MultiAutoCompleteTextView
android:id="#+id/label_edit"
android:textSize="20sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:layout_weight="3" />
</TableRow>
<Button
android:id="#+id/setalarm_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:textColor="#android:color/white"
android:layout_margin="20dp"
android:text="Set Time" />
</TableLayout>
</RelativeLayout>
AutocompleteActivity.java (Activity which was called by the above Activity)
package com.example.lab_excercise_2;
import androidx.appcompat.app.AppCompatActivity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.MultiAutoCompleteTextView;
import android.widget.TextView;
import android.widget.TimePicker;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class AutocompleteActivity extends AppCompatActivity {
private Button setTime, setDate, setalarm;
private TextView time_text, date_text, label_text;
private Calendar calendar = Calendar.getInstance();
private String date_string, time_string, label_string;
private String[] labels = {"Wake Up","Time to School","Time to College","Time to Work","Complete Activity","Finish Project"};
private MultiAutoCompleteTextView label_autocomplete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_autocomplete);
setTime = findViewById(R.id.setTime_btn);
setDate = findViewById(R.id.setDate_btn);
setalarm = findViewById(R.id.setalarm_btn);
time_text = findViewById(R.id.time_text);
date_text = findViewById(R.id.date_text);
label_autocomplete = findViewById(R.id.label_edit);
label_text = findViewById(R.id.label_textView);
setDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDateDialog(setDate);
}
});
setTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showTimeDialog(setTime);
}
});
setalarm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nextpage(v);
}
});
label_autocomplete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent alarmIntent = new Intent(AutocompleteActivity.this,AlarmActivity.class);
startActivity(alarmIntent);
}
});
label_text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent alarmIntent = new Intent(AutocompleteActivity.this,AlarmActivity.class);
startActivity(alarmIntent);
}
});
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,labels);
label_autocomplete.setAdapter(adapter);
label_autocomplete.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
}
public void showTimeDialog(final Button time){
TimePickerDialog.OnTimeSetListener timeSetListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
calendar.set(Calendar.HOUR_OF_DAY,hourOfDay);
calendar.set(Calendar.MINUTE,minute);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
time_text.setText(simpleDateFormat.format(calendar.getTime()));
}
};
new TimePickerDialog(AutocompleteActivity.this,timeSetListener,calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE),false).show();
}
public void showDateDialog(final Button date){
DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
calendar.set(Calendar.YEAR,year);
calendar.set(Calendar.MONTH,month);
calendar.set(Calendar.DAY_OF_MONTH,dayOfMonth);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yy-MM-dd");
date_text.setText(simpleDateFormat.format(calendar.getTime()));
}
};
new DatePickerDialog(AutocompleteActivity.this, dateSetListener,calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)).show();
}
public void nextpage(View view){
date_string = date_text.getText().toString();
time_string = time_text.getText().toString();
label_string = label_autocomplete.getText().toString();
Intent nextIntent = new Intent(this,Autocomplete2Activity.class);
nextIntent.putExtra("date",date_string);
nextIntent.putExtra("time",time_string);
nextIntent.putExtra("label",label_string);
startActivity(nextIntent);
}
}
LOGCAT
2020-03-02 19:55:10.865 4078-4136/com.example.lab_excercise_2E/RenderScript: SETAFFINITY ret = -1
2020-03-02 19:55:10.865 4078-4137/com.example.lab_excercise_2 E/RenderScript: SETAFFINITY ret = -1
2020-03-02 19:55:10.865 4078-4139/com.example.lab_excercise_2 E/RenderScript: SETAFFINITY ret = -1
2020-03-02 19:55:10.865 4078-4138/com.example.lab_excercise_2 E/RenderScript: SETAFFINITY ret = -1
2020-03-02 19:55:10.865 4078-4140/com.example.lab_excercise_2 E/RenderScript: SETAFFINITY ret = -1
2020-03-02 19:55:10.865 4078-4142/com.example.lab_excercise_2 E/RenderScript: SETAFFINITY ret = -1
2020-03-02 19:55:10.865 4078-4141/com.example.lab_excercise_2 E/RenderScript: SETAFFINITY ret = -1`
[Solved. I solved it myself]
Tips: if you want to access a child in the firebase realtime database for collecting data and then by using that data u store or upload something at that child on the firebase realtime database again, then you can't access it. Either u have to create another child or u must not use that child. (I don't no the actual solution but It works for me)]
I want to create a child under the reference of the user phone number. That child will store one or more childs. These child will be called "serialNo" of the item. And under serialNo child, the item name and amount of piece will store. I want to create like this:
[N: B: I've created this on firebase directly, not by my application.]
But when I put my data object as .setValue(dtObject) the previous one will always be replaced.
"orderNo: 1" child was replaced by "orderNo: 2" child
I also use .updateChildren(dtMap) but everytime previous orderNo child was replaced.
My Code of confirm Fragment(from where I upload):
package com.binarysoftwareltd.airaid;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
import java.util.Map;
public class AddressFragment extends Fragment {
private int orderNo = 1;
private int orderSerial = 0;
private DatabaseReference dbReference, dbr;
private static final String STATE_USER = "user";
private String mUser;
private View oldView;
private TextView numWarning;
private EditText nameField, phoneField, areaField, addressField,
detailsField;
private CardView confirmCV;
private int len;
private String nameOfPerson, phoneNumber, areaName, addressOfOrder,
detailsOfOrder;
private int[] serialNos = new int[100];
private String[] names = new String[100];
private int[] pieces = new int[100];
private String imageUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mUser = savedInstanceState.getString(STATE_USER);
} else {
// Probably initialize members with default values for a new
instance
mUser = "NewUser";
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString(STATE_USER, mUser);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
if (oldView != null) {
return oldView;
}
View v = inflater.inflate(R.layout.fragment_address, container,
false);
initializeAll(v);
Bundle bundle = getArguments();
if (bundle != null) {
len = bundle.getInt("cValue");
imageUri = bundle.getString("imgUri");
serialNos = bundle.getIntArray("mSerialNos");
names = bundle.getStringArray("mNames");
pieces = bundle.getIntArray("mPieces");
}
confirmCV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
collectAllData();
if (!phoneNumber.equals("")) {
checkOrderSerial();
} else {
phoneField.requestFocus();
Toast.makeText(getContext(), orderSerial,
Toast.LENGTH_SHORT).show();
}
}
});
oldView = v;
return v;
}
private void checkOrderSerial() {
dbr=FirebaseDatabase.getInstance().getReference(phoneNumber).
child("currentOrderSerial");
dbr.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Integer value = dataSnapshot.getValue(Integer.class);
if (value != null)
orderSerial = value;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
showConfirmDialog();
}
private void showConfirmDialog() {
AlertDialog.Builder alb = new AlertDialog.Builder(getContext());
alb.setIcon(R.drawable.question);
alb.setTitle("Confirm");
alb.setMessage("Are you sure want to order?");
alb.setPositiveButton(R.string.exit_no, new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alb.setNegativeButton(R.string.exit_yes, new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
setOrderSerial();
}
});
AlertDialog ald = alb.create();
ald.show();
}
private void setOrderSerial() {
dbr = FirebaseDatabase.getInstance().getReference(phoneNumber);
if (orderNo <= orderSerial) {
orderNo = orderSerial;
orderNo += 1;
}
OrderSerial osObject = new OrderSerial(orderNo);
dbr.setValue(osObject);
uploadAllData();
}
private void uploadAllData() {
dbReference =
FirebaseDatabase.getInstance().getReference(phoneNumber).child("orderNo:
"+orderNo);
DataTemplate dtObject;
int i;
for (i = 0; i < len; i++) {
if (pieces[i] != 0) {
dtObject = new DataTemplate(names[i],pieces[i]);
dbReference.child("serialNo:
"+serialNos[i]).setValue(dtObject);
}
}
}
private void collectAllData() {
nameOfPerson = nameField.getText().toString();
phoneNumber = phoneField.getText().toString();
areaName = areaField.getText().toString();
addressOfOrder = addressField.getText().toString();
detailsOfOrder = detailsField.getText().toString();
}
private void initializeAll(View v) {
numWarning = v.findViewById(R.id.numWarning);
nameField = v.findViewById(R.id.nameField);
phoneField = v.findViewById(R.id.phoneField);
areaField = v.findViewById(R.id.areaField);
addressField = v.findViewById(R.id.addressField);
detailsField = v.findViewById(R.id.detailsField);
confirmCV = v.findViewById(R.id.confirmCV);
}
}
My OrderSerial Class::
package com.binarysoftwareltd.airaid;
public class OrderSerial {
private int currentOrderSerial;
public OrderSerial() {
}
public OrderSerial(int currentOrderSerial) {
this.currentOrderSerial = currentOrderSerial;
}
public int getCurrentOrderSerial() {
return currentOrderSerial;
}
public void setCurrentOrderSerial(int currentOrderSerial) {
this.currentOrderSerial = currentOrderSerial;
}
}
The XML code of the AddressFragment:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/app_main_bg"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="120dp"
android:text="#string/address_fragment_title"
android:textColor="#color/pureBlack"
android:textSize="25sp"
android:textStyle="bold" />
<TextView
android:gravity="center"
android:id="#+id/numWarning"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="15dp"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
android:text="#string/number_warning"
android:textColor="#color/img_warning"
android:textSize="15sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="15dp"
android:gravity="center_vertical"
android:weightSum="8"
android:orientation="horizontal">
<ImageView
android:contentDescription="#string/name_field"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:src="#drawable/ic_person"/>
<EditText
android:id="#+id/nameField"
android:layout_marginStart="5dp"
android:layout_width="0dp"
android:layout_weight="7"
android:layout_height="70dp"
android:hint="#string/name_field" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="15dp"
android:gravity="center_vertical"
android:weightSum="8"
android:orientation="horizontal">
<ImageView
android:contentDescription="#string/phone_field"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:src="#drawable/ic_phone"/>
<EditText
android:id="#+id/phoneField"
android:layout_marginStart="5dp"
android:inputType="phone"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="4"
android:hint="#string/phone_field" />
<EditText
android:id="#+id/areaField"
android:layout_marginStart="10dp"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="3"
android:hint="#string/area_field" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="15dp"
android:gravity="center_vertical"
android:weightSum="8"
android:orientation="horizontal">
<ImageView
android:contentDescription="#string/address_fragment_title"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:src="#drawable/ic_location"/>
<EditText
android:id="#+id/addressField"
android:layout_marginStart="5dp"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="7"
android:hint="#string/address_fragment_title" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="15dp"
android:gravity="center_vertical"
android:weightSum="8"
android:orientation="horizontal">
<ImageView
android:contentDescription="#string/details_field"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:src="#drawable/ic_details"/>
<EditText
android:id="#+id/detailsField"
android:layout_marginStart="5dp"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="7"
android:hint="#string/details_field" />
</LinearLayout>
<androidx.cardview.widget.CardView
android:id="#+id/confirmCV"
android:layout_width="match_parent"
android:layout_height="40dp"
android:clickable="true"
android:focusable="true"
android:layout_marginStart="15dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="15dp"
app:cardCornerRadius="18dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/card_view_bg"
android:gravity="center">
<ImageView
android:contentDescription="#string/order_now"
android:layout_width="30dp"
android:layout_height="30dp"
android:src="#drawable/ic_confirm" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:text="#string/order_now"
android:textColor="#color/pureWhite"
android:textSize="18sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
</ScrollView>
here my JSON::
{
"23" : {
"currentOrderSerial" : 2,
"orderNo: 2" : {
"serialNo: 1" : {
"name" : "napa Extra",
"piece" : 200
}
}
}
}
[I use phone number as primary Identifier for every user. That's why phone numbers must be required.]
Please help to fix this...
Thanks in Advance...
I created a android studio button for my app and when I click on the register button it doesn't work . I don't get any errors it just doesn't work . When the user clicks the quiz button I want to go to the quiz activity
MainActivity.java
package com.littlekidsmath.yoong.mathlearningforkids;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;
import java.util.zip.Inflater;
public class MainActivity extends AppCompatActivity implements View.OnClickListener,AdapterView.OnItemSelectedListener{
Button addBtn, subBtn, multiBtn, divisionBtn,quiz;
String[] levels = {"Easy","Medium","Hard"};
SharedPreferences prefs;
Switch settings;
Spinner language;
public String[] languages = {GameActivity.ENG,GameActivity.ARABIC,"বাংলা",GameActivity.FRENCH,GameActivity.GERMAN,GameActivity.MALAY};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = getSharedPreferences("MyPref",MODE_PRIVATE);
settings = (Switch) findViewById(R.id.settings);
if(prefs.getBoolean("SOUND", false)){
settings.setChecked(true);
}
settings.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
prefs.edit().putBoolean("SOUND",b).commit();
}
});
addBtn = (Button) findViewById(R.id.addtion);
subBtn = (Button) findViewById(R.id.sub);
multiBtn = (Button) findViewById(R.id.multi);
divisionBtn = (Button) findViewById(R.id.divide);
quiz = (Button) findViewById(R.id.quiz);
language = (Spinner) findViewById(R.id.language);
addBtn.setOnClickListener(this);
subBtn.setOnClickListener(this);
multiBtn.setOnClickListener(this);
divisionBtn.setOnClickListener(this);
quiz.setOnClickListener(this);
language.setOnItemSelectedListener(this);
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,languages);
language.setAdapter(adapter);
int pos = 0;
//
for(int i=0;i<languages.length;i++){
if(prefs.getString(GameActivity.LANGUAGE,"").equals(languages[i])){
pos = i;
break;
}
}
language.setSelection(pos);
if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.BANGLA)){
setBangla();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.ARABIC)){
setArabic();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.FRENCH)){
setFrence();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.GERMAN)){
setGerman();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.ENG)){
setEnglish();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.MALAY)){
setMalay();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.addtion: {
levelChooseDialog("+");
break;
}
case R.id.sub: {
levelChooseDialog("-");
break;
}
case R.id.multi: {
levelChooseDialog("X");
break;
}
case R.id.divide: {
levelChooseDialog("/");
break;
}
case R.id.quiz: {
Intent intent = new Intent(MainActivity.this, HomeScreen.class);
startActivity(intent);
}
}
}
public void levelChooseDialog(final String operator){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View view = View.inflate(this,R.layout.level_dialog,null);
builder.setView(view);
ListView listView = (ListView) view.findViewById(R.id.listview);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,levels);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int level = 0;
if (position == 0){
level = 0;
}else if(position == 1){
level = 1;
}else {
level = 2;
}
startActivity(new Intent(MainActivity.this,LessonActivity.class).putExtra("level",level)
.putExtra("operator",operator));
}
});
builder.create().show();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
prefs.edit().putString(GameActivity.LANGUAGE,languages[position]).commit();
if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.BANGLA))
{
setBangla();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.ARABIC)){
setArabic();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.FRENCH)){
setFrence();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.GERMAN)){
setGerman();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.ENG)){
setEnglish();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.MALAY)){
setMalay();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void setBangla(){
addBtn.setText(Languages.BANGLA[0]);
subBtn.setText(Languages.BANGLA[1]);
multiBtn.setText(Languages.BANGLA[3]);
divisionBtn.setText(Languages.BANGLA[2]);
settings.setText(Languages.BANGLA[4]);
levels[0] = Languages.BANGLA[7];
levels[1] = Languages.BANGLA[8];
levels[2] = Languages.BANGLA[9];
}
public void setArabic(){
addBtn.setText(Languages.ARABIC[0]);
subBtn.setText(Languages.ARABIC[1]);
multiBtn.setText(Languages.ARABIC[3]);
divisionBtn.setText(Languages.ARABIC[2]);
settings.setText(Languages.ARABIC[4]);
levels[0] = Languages.ARABIC[7];
levels[1] = Languages.ARABIC[8];
levels[2] = Languages.ARABIC[9];
}
public void setMalay(){
addBtn.setText(Languages.MALAY[0]);
subBtn.setText(Languages.MALAY[1]);
multiBtn.setText(Languages.MALAY[3]);
divisionBtn.setText(Languages.MALAY[2]);
settings.setText(Languages.MALAY[4]);
levels[0] = Languages.MALAY[7];
levels[1] = Languages.MALAY[8];
levels[2] = Languages.MALAY[9];
}
public void setFrence(){
addBtn.setText(Languages.FRENCH[0]);
subBtn.setText(Languages.FRENCH[1]);
multiBtn.setText(Languages.FRENCH[3]);
divisionBtn.setText(Languages.FRENCH[2]);
settings.setText(Languages.FRENCH[4]);
levels[0] = Languages.FRENCH[7];
levels[1] = Languages.FRENCH[8];
levels[2] = Languages.FRENCH[9];
}
public void setGerman(){
addBtn.setText(Languages.GERMAN[0]);
subBtn.setText(Languages.GERMAN[1]);
multiBtn.setText(Languages.GERMAN[3]);
divisionBtn.setText(Languages.GERMAN[2]);
settings.setText(Languages.GERMAN[4]);
levels[0] = Languages.GERMAN[7];
levels[1] = Languages.GERMAN[8];
levels[2] = Languages.GERMAN[9];
}
public void setEnglish(){
addBtn.setText(Languages.ENGLISH[0]);
subBtn.setText(Languages.ENGLISH[1]);
multiBtn.setText(Languages.ENGLISH[3]);
divisionBtn.setText(Languages.ENGLISH[2]);
settings.setText(Languages.ENGLISH[4]);
levels[0] = Languages.ENGLISH[7];
levels[1] = Languages.ENGLISH[8];
levels[2] = Languages.ENGLISH[9];
}
}
activity_main.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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorAccent"
android:gravity="center_vertical"
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="com.littlekidsmath.yoong.mathlearningforkids.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/addtion"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/activity_horizontal_margin"
android:drawableTop="#drawable/add"
android:paddingBottom="25dp"
android:paddingTop="25dp"
android:text="Addition" />
<Button
android:id="#+id/sub"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/activity_horizontal_margin"
android:drawableTop="#drawable/minus"
android:paddingBottom="25dp"
android:paddingTop="25dp"
android:text="Subtraction" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/multi"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/activity_horizontal_margin"
android:drawableTop="#drawable/cancel"
android:paddingBottom="25dp"
android:paddingTop="25dp"
android:text="Multiplication" />
<Button
android:id="#+id/divide"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/activity_horizontal_margin"
android:drawableTop="#drawable/division"
android:paddingBottom="25dp"
android:paddingTop="25dp"
android:text="Division" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/quiz"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/activity_horizontal_margin"
android:paddingBottom="20dp"
android:paddingTop="20dp"
android:text="Quiz" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:padding="#dimen/activity_horizontal_margin">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:text=""
android:textColor="#color/white"
android:textSize="18sp" />
<Switch
android:id="#+id/settings"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingRight="#dimen/activity_horizontal_margin"
android:text="Sound"
android:textColor="#color/white"
android:textSize="18sp" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/activity_horizontal_margin"
android:text="Language" />
<Spinner
android:id="#+id/language"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="7dp"
android:background="#color/white"
android:padding="10dp"></Spinner>
</LinearLayout>
Can anyone help please? When click on the quiz button the application will close. I want it to go to quiz page which called HomeScreen.java
looks good to me, did u declare the second activity in the manifest file? :
<activity android:name="HomeScreen"/>
If that doesn't work, use some break points and the debugger, hope it helps.
I am trying to generate Multiplication Table of any number that is input by user. I have developed the interface for the application but cannot understand where to start with the logical part(coding). What i want is when a user inputs a number into the EditText then in the TextView (id: printArea) should show the table of the input number in the format as given in image 2. [Just to show you example i used TextView in the printArea part and i do not know what to use instead]
<?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"
tools:context=".MainActivity"
android:weightSum="1">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="Please Enter a Number: "
android:textSize="20sp" />
<EditText
android:id="#+id/num"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_marginLeft="30dp"
android:textSize="20sp" />
</LinearLayout>
<Button
android:id="#+id/calculate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/log"
android:onClick="submitNumber"
android:text="Get Table" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:id="#+id/printArea" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/clear"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="1dp"
android:text="Clear" />
<Button
android:id="#+id/credits"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:layout_marginRight="1dp"
android:text="Credits" />
<Button
android:id="#+id/exit"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:layout_marginRight="2dp"
android:text="Exit" />
</LinearLayout>
</LinearLayout>
and the MainActivity.java is:
package com.example.tara.multiplicationtable;
import android.content.Intent;
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.TextView;
public class MainActivity extends AppCompatActivity {
EditText num;
Button credits;
Button calculate;
Button clear;
Button exit;
TextView printArea;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num = new EditText(this);
clear = new Button(this);
calculate = new Button(this);
credits = new Button(this);
calculate = new Button(this);
printArea = new TextView(this);
num = (EditText) findViewById(R.id.num);
credits = (Button) findViewById(R.id.credits);
clear = (Button) findViewById(R.id.clear);
exit = (Button) findViewById(R.id.exit);
printArea = (TextView) findViewById(R.id.printArea);
calculate = (Button) findViewById(R.id.calculate);
calculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//change the integer value into string
int num1 = Integer.parseInt(num.getText().toString());
// Perform action on click
for (int i = 1; i <= 10; i++) {
printArea.setText(num1 + "X" + i + "=" + i * num1);
}
}
});
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
num.setText("");
}
});
credits.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, Credits.class);
startActivity(i);
}
});
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
System.exit(0);
}
});
}
}
when application is launched it should show like thisThe initial state of application
and i want to make the application show the table like this if user input is 2 The Final Result
Make a Listview and then in its adapter add your table data.
Make adapter's layout like this:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="*" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="=" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4" />
Here are the codes that i used to build the Multiplication Table that i imagined to build. The code for activity_main.xml file will be:
<?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"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginEnd="1dp"
android:layout_marginStart="2dp"
android:text="#string/Enter_number"
android:textSize="16sp" />
<EditText
android:id="#+id/num"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginEnd="2dp"
android:layout_marginStart="1dp"
android:digits="0123456789"
android:hint="#string/hidden_text"
android:inputType="number"
android:maxLength="3"
android:textSize="16sp" />
</LinearLayout>
<Button
android:id="#+id/calculate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/calculate"
android:imeOptions="actionDone"
android:textSize="16sp"/>
<!--android:onClick="submitNumber"-->
<TextView
android:id="#+id/printArea"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:textSize="20sp"
android:background="#drawable/backimage" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginEnd="1dp"
android:layout_marginStart="2dp"
android:textSize="16sp"
android:text="#string/clear"
/>
<Button
android:id="#+id/credits"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginEnd="1dp"
android:layout_marginStart="1dp"
android:textSize="16sp"
android:text="#string/credits" />
<Button
android:id="#+id/exit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="2dp"
android:layout_marginStart="1dp"
android:layout_weight="1"
android:textSize="16sp"
android:text="#string/exit" />
</LinearLayout>
</LinearLayout>
The Code for the MainActivity.java file will be:
package com.example.tara.multiplicationtable;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText num;
Button credits;
Button calculate;
Button clear;
Button exit;
TextView printArea;
//private static final String result = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num = new EditText(this);
clear = new Button(this);
calculate = new Button(this);
credits = new Button(this);
calculate = new Button(this);
printArea = new TextView(this);
num = (EditText) findViewById(R.id.num);
credits = (Button) findViewById(R.id.credits);
clear = (Button) findViewById(R.id.clear);
exit = (Button) findViewById(R.id.exit);
calculate = (Button) findViewById(R.id.calculate);
printArea = (TextView) findViewById(R.id.printArea);
calculate.setOnClickListener(new View.OnClickListener() {
// Perform action on Get Table Button click
public void onClick(View v) {
if (num.getText().length() == 0 ){
printArea.setText(R.string.err_msg);
}
else {
//change the integer value into string
printArea.setText("");
int num1 = Integer.parseInt(num.getText().toString());
String result;
for (int i = 1; i <= 10; i++) {
result = (num1 + " X " + i + " = " + i * num1);
printArea.append("\n" + result);
}
}
}
});
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
num.setText("");
printArea.setText("");
}
});
credits.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Credits.class));
}
});
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Good Bye, User!", Toast.LENGTH_SHORT).show();
finish();
}
});
}
}
Thank you everyone for the guidance.
(Very first thing i want to make clear is that i am COMPLETELY NEWBIE, very beginner in android, in fact in programming/coding!)
The menu is referred in onCreateOptionMenu and the calling method is also onOptionsItemSelected to open up menu but the method for each option/item is set as onMenuItemClick and onMenuItemLongClick which is ideal for context menu options/items!
The problem is onMenuItemClick have input parameters as (View v, int position) and I cannot change it to only (View v) or to (MenuItem item).
What I want is clicking on each item of menu should bring out new activity!
I also tried putting all my switch-case-break statements to onOptionsItemSelected method but it is still not working!
I also tried in fragment class, setHasOptionsMenu (true); but it did not work!
onMenuItemClick doesn't get called
(Deprecated) Fragment onOptionsItemSelected not being called
Below is the activity_main_menu.xml layout
<?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"
android:background="#color/menu_item_background">
<include layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Below is the fragment_main.xml layout
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.coffeeshop.MainFragment">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
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"
android:background="#color/menu_item_background">
<EditText
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/EditTextHint"
android:inputType="textNoSuggestions" />
<EditText
android:id="#+id/usercontact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/usercontactHint"
android:inputType="textNoSuggestions" />
<EditText
android:id="#+id/useremail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/useremailHint"
android:inputType="textEmailAddress" />
<TextView
style="#style/HeaderTextStyle"
android:layout_marginTop="16dp"
android:text="#string/Toppings" />
<CheckBox
android:id="#+id/whippedCreamcheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingEnd="24dp"
android:paddingLeft="24dp"
android:paddingStart="24dp"
android:text="#string/WhippedCream"
android:textSize="16sp" />
<CheckBox
android:id="#+id/Chocolatebox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingEnd="24dp"
android:paddingLeft="24dp"
android:paddingStart="24dp"
android:text="#string/Chocolate"
android:textSize="16sp" />
<TextView
style="#style/HeaderTextStyle"
android:layout_marginTop="16dp"
android:text="#string/quantity" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginTop="16dp"
android:onClick="decrement"
android:text="#string/minus" />
<TextView
android:id="#+id/quantity_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="16dp"
android:text="#string/Zero"
android:textColor="#android:color/black"
android:textSize="20sp" />
<Button
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginTop="16dp"
android:onClick="increment"
android:text="#string/plus" />
</LinearLayout>
<TextView
style="#style/HeaderTextStyle"
android:layout_marginTop="16dp"
android:text="#string/OrderSummary" />
<TextView
android:id="#+id/order_summary_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="#string/Price"
android:textColor="#android:color/black"
android:textSize="20sp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/orderButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onClick="submitOrder"
android:text="#string/Order" />
<Button
android:id="#+id/placeOrder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:onClick="placeOrder"
android:text="#string/PlaceOrder" />
</LinearLayout>
</LinearLayout>
</ScrollView>
Below is the MainMenu.java class file from where i am trying to handle fragment menu!
package com.example.android.coffeeshop5profile;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ActionMenuView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.yalantis.contextmenu.lib.ContextMenuDialogFragment;
import com.yalantis.contextmenu.lib.MenuObject;
import com.yalantis.contextmenu.lib.MenuParams;
import com.yalantis.contextmenu.lib.interfaces.OnMenuItemLongClickListener;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* This app displays an order form to order coffee.
*/
public class MainMenu extends AppCompatActivity implements ActionMenuView.OnMenuItemClickListener, OnMenuItemLongClickListener {
private FragmentManager fragmentManager;
private ContextMenuDialogFragment mMenuDialogFragment;
int quantity = 1;
int price = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
fragmentManager = getSupportFragmentManager();
initToolbar();
initMenuFragment();
addFragment(new MainFragment(), true, R.id.container);
}
private void initMenuFragment() {
MenuParams menuParams = new MenuParams();
menuParams.setActionBarSize((int) getResources().getDimension(R.dimen.tool_bar_height));
menuParams.setMenuObjects(getMenuObjects());
menuParams.setClosableOutside(false);
mMenuDialogFragment = ContextMenuDialogFragment.newInstance(menuParams);
mMenuDialogFragment.setItemLongClickListener(this);
}
private List<MenuObject> getMenuObjects() {
List<MenuObject> menuObjects = new ArrayList<>();
MenuObject close = new MenuObject();
close.setResource(R.drawable.icn_close);
MenuObject send = new MenuObject("Send message");
send.setResource(R.drawable.icn_1);
MenuObject like = new MenuObject("Like profile");
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.icn_2);
like.setBitmap(b);
MenuObject addFr = new MenuObject("Add to friends");
BitmapDrawable bd = new BitmapDrawable(getResources(),
BitmapFactory.decodeResource(getResources(), R.drawable.icn_3));
addFr.setDrawable(bd);
MenuObject addFav = new MenuObject("Add to favorites");
addFav.setResource(R.drawable.icn_4);
MenuObject block = new MenuObject("Block user");
block.setResource(R.drawable.icn_5);
menuObjects.add(close);
menuObjects.add(send);
menuObjects.add(like);
menuObjects.add(addFr);
menuObjects.add(addFav);
menuObjects.add(block);
return menuObjects;
}
private void initToolbar() {
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
TextView mToolBarTextView = (TextView) findViewById(R.id.text_view_toolbar_title);
setSupportActionBar(mToolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mToolbar.setNavigationIcon(R.drawable.btn_back);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
mToolBarTextView.setText(R.string.title_text);
}
protected void addFragment(Fragment fragment, boolean addToBackStack, int containerId) {
invalidateOptionsMenu();
String backStackName = fragment.getClass().getName();
boolean fragmentPopped = fragmentManager.popBackStackImmediate(backStackName, 0);
if (!fragmentPopped) {
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(containerId, fragment, backStackName)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
if (addToBackStack)
transaction.addToBackStack(backStackName);
transaction.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.context_menu:
if (fragmentManager.findFragmentByTag(ContextMenuDialogFragment.TAG) == null) {
mMenuDialogFragment.show(fragmentManager, ContextMenuDialogFragment.TAG);
}
break;
case R.drawable.icn_3:
Intent userProfileIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(userProfileIntent);
break;
case R.drawable.icn_4:
Intent wishListIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(wishListIntent);
break;
}
return false; //Turning this true or to super.OnOptionsItemSelected did nothing!
}
#Override
public void onBackPressed() {
if (mMenuDialogFragment != null && mMenuDialogFragment.isAdded()) {
mMenuDialogFragment.dismiss();
} else {
finish();
}
}
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.drawable.icn_3:
Intent userProfileIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(userProfileIntent);
break;
case R.drawable.icn_4:
Intent wishListIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(wishListIntent);
break;
} return true;
}
#Override
public void onMenuItemLongClick(View clickedView, int position) {
Toast.makeText(this, "Long clicked on position: " + position, Toast.LENGTH_SHORT).show();
}
public void submitOrder(View view) {
String orderSummaryString = createOrderSummary(quantity);
displayMessage(orderSummaryString);
}
public void placeOrder(View view) {
TextView useremail = (TextView) findViewById(R.id.useremail);
String useremailString = useremail.getText().toString();
String orderSummaryString = createOrderSummary(quantity);
sendMail(useremailString, "Coffee Order By: " + useremailString, orderSummaryString);
}
private void sendMail(String email, String subject, String messageBody) {
Session session = createSessionObject();
try {
Message message = createMessage(email, subject, messageBody, session);
new SendMailTask().execute(message);
} catch (MessagingException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private Message createMessage(String email, String subject, String messageBody, Session session)
throws MessagingException, UnsupportedEncodingException {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("clientaddress#gmail.com", "Coffee Order By"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));
message.setSubject(subject);
message.setText(messageBody);
return message;
}
private Session createSessionObject() {
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
return Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("clientaddress#gmail.com", "************");
}
});
}
public class SendMailTask extends AsyncTask<Message, Void, Void> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(MainMenu.this, "Please wait", "Sending mail", true, false);
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
#Override
public Void doInBackground(Message... messages) {
try {
Transport.send(messages[0]);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
/**
* This method is called when the plus button is clicked.
*/
public void increment(View view) {
if (quantity < 100) {
quantity = quantity + 1;
displayQuantity(quantity);
} else {
Toast.makeText(this, "You have reached maximum numbers of coffees to be allowed!", Toast.LENGTH_SHORT).show();
}
}
/**
* This method is called when the minus button is clicked.
*/
public void decrement(View view) {
if (quantity >= 2) {
quantity = quantity - 1;
displayQuantity(quantity);
} else {
Toast.makeText(this, "You can not place order in negative number!", Toast.LENGTH_SHORT).show();
}
}
public String createOrderSummary(int quantity) {
CheckBox whippedCreamCheckbox = (CheckBox) findViewById(R.id.whippedCreamcheckbox);
boolean hasWhippedCream = whippedCreamCheckbox.isChecked();
CheckBox chocolatebox = (CheckBox) findViewById(R.id.Chocolatebox);
boolean hasChocolate = chocolatebox.isChecked();
price = 5;
if (hasWhippedCream) {
price = price + 1;
}
if (hasChocolate) {
price = price + 2;
}
int finalPrice = quantity * price;
EditText usernameTextView = (EditText) findViewById(R.id.username);
String usernameString = usernameTextView.getText().toString();
EditText usercontact = (EditText) findViewById(R.id.usercontact);
String userContactString = usercontact.getText().toString();
EditText useremail = (EditText) findViewById(R.id.useremail);
String userEmailString = useremail.getText().toString();
String OrderSummary = getString(R.string.username) + ": " + usernameString;
OrderSummary += "\n" + getString(R.string.ContactNumber) + " " + userContactString;
OrderSummary += "\n" + getString(R.string.eAddress) + " " + userEmailString;
OrderSummary += "\n" + getString(R.string.AddedWhippedCream) + " " + hasWhippedCream;
OrderSummary += "\n" + getString(R.string.AddedChocolate) + " " + hasChocolate;
OrderSummary += "\n" + getString(R.string.quantity) + ": " + quantity;
OrderSummary += "\n" + getString(R.string.totalprice) + finalPrice;
OrderSummary += "\n" + getString(R.string.thankyou);
return OrderSummary;
}
/**
* This method displays the given quantity value on the screen.
*/
public void displayQuantity(int number) {
TextView quantityTextView = (TextView) findViewById(
R.id.quantity_text_view);
quantityTextView.setText(String.format("%d", number));
}
/**
* This method displays the given text on the screen.
*/
public void displayMessage(String message) {
TextView orderSummaryTextView = (TextView) findViewById(R.id.order_summary_text_view);
orderSummaryTextView.setText(message);
}
}
Below is the MainFragment.java class file
package com.example.android.coffeeshop5profile;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MainFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
setHasOptionsMenu(true);
setMenuVisibility(false);
return rootView;
}
}
Following is the Activity_main.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:id="#+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/blue_grey_700"
android:orientation="vertical"
android:weightSum="4"
tools:context=".legacy.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3"
android:gravity="center_vertical"
android:orientation="vertical">
<ImageView
android:id="#+id/google_icon"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center"
android:layout_marginBottom="10dp"
android:contentDescription="#string/desc_google_icon"
android:src="#drawable/googleg_color" />
<TextView
android:id="#+id/title_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_gravity="center"
android:text="#string/title_text"
android:textColor="#android:color/white"
android:textSize="36sp" />
<TextView
android:id="#+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/signed_out"
android:textColor="#android:color/white"
android:textSize="14sp" />
<TextView
android:id="#+id/detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fadeScrollbars="true"
android:gravity="center"
android:maxLines="5"
android:padding="10dp"
android:scrollbars="vertical"
android:textColor="#android:color/white"
android:textSize="14sp" />
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/blue_grey_900">
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible"
tools:visibility="gone" />
<LinearLayout
android:id="#+id/sign_out_and_disconnect"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="horizontal"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:visibility="gone"
tools:visibility="visible">
<Button
android:id="#+id/sign_out_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/sign_out"
android:theme="#style/ThemeOverlay.MyDarkButton" />
<Button
android:id="#+id/disconnect_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/disconnect"
android:theme="#style/ThemeOverlay.MyDarkButton" />
<Button
android:id="#+id/secondpage"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/secondpage"
android:theme="#style/ThemeOverlay.MyDarkButton" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
below is the res/menu/context_main_menu.xml file
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/context_menu"
android:title="#string/context_menu"
android:icon="#drawable/btn_add"
android:orderInCategory="100"
app:showAsAction="always" />
</menu>
...unfortunately, 30000 characters limit has been reached so i cant upload mainActivity.java file!
Kindly help!
Best regards,
sagar
try this code on
Change the following code
onMenuItemClick(MenuItem item)
to
onMenuItemClick(View clickedView, int position)
like this
`#override
public void onMenuItemClick(View clickedView, int position) {
switch (position) {
case 1:
startActivity(new Intent(MainActivity.this, UserProfile.class));
break;
case 2:
startActivity(new Intent(MainActivity.this, UserProfile.class));
break;
}
}`
i hope this help you
If onOptionsItemSelected() method is not called in fragment then just make sure you return false from the onOptionsItemSelected() method of Activity.