Getting the value from selected RadioButton within a fragment - java

I have two RadioButtons within a RadioGroup. I also set up a Button, with a setOnClickListener function. When the button is pressed, its supposed to set the float variable gender to a specific value depending on what RadioButton is selected. However, whenever the button is pressed the app crashes.
I've tried setting up a TextView just to see if it would print anything, but the app just crashes when the button is pressed. I looked into the Logcat, and saw that it threw this error: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference
package com.example.bacwatch;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class ProfileFragment extends Fragment {
private EditText editWeight;
private Button buttonConfirm;
public float gender;
RadioGroup radioGroup;
RadioButton radioButton;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profile, container, false);
radioGroup = v.findViewById(R.id.gender_buttons);
editWeight = v.findViewById(R.id.edit_Weight);
buttonConfirm = v.findViewById(R.id.confirm_button);
editWeight.addTextChangedListener(loginTextWatcher);
// Button will input text.
buttonConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Records the gender from the selected radio button.
int radioID = radioGroup.getCheckedRadioButtonId();
radioButton = v.findViewById(radioID);
if (radioButton.getText().equals("Male")) {
gender = (float) .58;
} else {
gender = (float) .49;
}
// Records User's weight (in pounds) and stores it into a variable.
/*float weight = Float.valueOf(editWeight.getText().toString().trim()).floatValue();
// Converts pounds to kilograms.
float kilo_weight = (float) (weight/2.2046);
// Calculates total body water.
float body_water = kilo_weight*gender;*/
// Clears text entries.
editWeight.getText().clear();
}
});
return v;
}
private TextWatcher loginTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String weightInput = editWeight.getText().toString().trim();
buttonConfirm.setEnabled(!weightInput.isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
}
};
}
XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="#android:color/holo_green_light"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gender:"
android:textSize="30sp"
android:layout_centerHorizontal="true"
android:id="#+id/gender_text"/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/gender_text"
android:layout_centerHorizontal="true"
android:orientation="horizontal"
android:id="#+id/gender_buttons">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"
android:checked="true"
android:textSize="30sp"
android:id="#+id/male_button"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:textSize="30sp"
android:id="#+id/female_button"/>
</RadioGroup>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#+id/gender_buttons"
android:id="#+id/weight_box">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/weight_input">
<android.support.design.widget.TextInputEditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:hint="Weight in Pounds"
android:textSize="30sp"
android:inputType="number"
android:id="#+id/edit_Weight"/>
</android.support.design.widget.TextInputLayout>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/weight_box"
android:layout_centerHorizontal="true"
android:textSize="30sp"
android:text="Confirm"
android:enabled="false"
android:id="#+id/confirm_button"/>
</RelativeLayout>

the app crashes because you tring to get radioButtion from the view that handling the click and not your layout view
radioButton = v.findViewById(radioID);
you have to use another view name to set a difference between them
buttonConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Records the gender from the selected radio button.
int radioID = radioGroup.getCheckedRadioButtonId();
radioButton = v.findViewById(radioID);
if (radioButton.getText().equals("Male")) {
gender = (float) .58;
} else {
gender = (float) .49;
}
......

Related

RecyclerView is not showing in Activity

I have a NewsDetailsActivity file that is displaying some news details. On top of the news details I want to display some cardview in a recyclerview. The recyclerView is not showing up but the worse part is that another recyclerview (that I have in the MainActivity is showing up in my NewsDetailsActivity like if If I am calling some id from my NewsDetailsActivity.
The only thing I want is to display some information on the top of the news details using the the recyclerview id my_recycler_view_coin_details
NewsDetailsActivity
package com.noticripto.activities;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.noticripto.APIClientCoin;
import com.noticripto.adapters.CryptoListAdapter;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.noticripto.MainActivity;
import com.noticripto.R;
import com.noticripto.adapters.NewsAdapter;
import com.noticripto.model.HomePageModel;
import com.noticripto.rest.ApiClient;
import com.noticripto.rest.ApiInterface;
import com.noticripto.retrofit.CryptoList;
import com.noticripto.retrofit.Datum;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class NewsDetailActivity extends AppCompatActivity {
Toolbar toolbar;
TextView sourceName, newsTitle, newsDesc, newsDate, newsView,labelSimilar;
Button viewMore;
ImageView imagy,small_icn;
ProgressBar progressBar;
RecyclerView recyclerView3;
CryptoListAdapter adapterCoin2;
ApiInterface apiInterfaceCoin2;
List<Datum> cryptoList2 = null;
HomePageModel.News detailNews = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_detail);
apiInterfaceCoin2 = APIClientCoin.getClient().create(ApiInterface.class);
recyclerView3 = findViewById(R.id.my_recycler_view_coin_details);
initViews();
LoadNewsDetails();
getCoinList();
}
private void LoadNewsDetails() {
// Calling our api
ApiInterface apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
Map<String, String> params = new HashMap<>();
params.put("id" , getIntent().getIntExtra("pid", 0) + "");
Call<HomePageModel> call = apiInterface.getNewsDetailsById(params);
call.enqueue(new Callback<HomePageModel>() {
#Override
public void onResponse(Call<HomePageModel> call, Response<HomePageModel> response) {
// Update the news layout
detailNews = response.body().getNews().get(0);
newsTitle.setText(detailNews.getTitle());
newsDesc.setText(NewsAdapter.removeHtml(detailNews.getPostContent()));
if (detailNews.getImage().length() >=1){
Glide.with(NewsDetailActivity.this)
.load(detailNews.getImage())
.placeholder(R.drawable.image1)
.into(imagy);
}else{
imagy.setVisibility(View.GONE);
}
}
#Override
public void onFailure(Call<HomePageModel> call, Throwable t) {
progressBar.setVisibility(View.GONE);
}
});
}
private void initViews() {
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
toolbar.setNavigationIcon(R.drawable.icon_arrow_back_white);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
cryptoList2 = new ArrayList<>();
adapterCoin2 = new CryptoListAdapter(cryptoList2);
// sourceName = findViewById(R.id.source_name );
newsTitle = findViewById(R.id.news_title);
newsDesc = findViewById(R.id.news_desc);
newsDate = findViewById(R.id.news_date);
//newsView = findViewById(R.id.news_view);
labelSimilar = findViewById(R.id.label_similar_news);
//viewMore = findViewById(R.id.view_more);
progressBar = findViewById(R.id.progressBar);
imagy =findViewById(R.id.news_image);
//small_icn = findViewById(R.id.small_icn);
recyclerView3 = findViewById(R.id.my_recycler_view_coin_details);
LinearLayoutManager linearLayoutManager3 =new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
recyclerView3.setLayoutManager(linearLayoutManager3);
recyclerView3.setNestedScrollingEnabled(false);
recyclerView3.setAdapter(adapterCoin2);
adapterCoin2.notifyItemInserted(0);
recyclerView3.scrollToPosition(0);
}
public void getCoinList() {
Call<CryptoList> call2 = apiInterfaceCoin2.doGetUserList("20");
call2.enqueue(new Callback<CryptoList>() {
#Override
public void onResponse(Call<CryptoList> call, Response<CryptoList> response)
{
CryptoList list = response.body();
cryptoList2.clear();
cryptoList2.addAll(list.getData());
adapterCoin2.notifyDataSetChanged();
System.out.println("List getData = " + list.getData());
}
#Override
public void onFailure(Call<CryptoList> call, Throwable t) {
Toast.makeText(NewsDetailActivity.this, "onFailure",
Toast.LENGTH_SHORT).show();
Log.d("XXXX", t.getLocalizedMessage());
call.cancel();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.news_details_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.share){
if (detailNews != null){
// Opening sharing options
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, detailNews.getTitle());
i.putExtra(Intent.EXTRA_TEXT, detailNews.getPostContent());
startActivity(i);
}else{
Toast.makeText(this, "Lo Sentimos!", Toast.LENGTH_SHORT).show();
}
}
return super.onOptionsItemSelected(item);
}
}
crypto_list_item_in_detail_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardViewCoinDetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="3dp"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
app:cardCornerRadius="8dp"
app:cardBackgroundColor="#android:color/white">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/symbolNameDetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="roboto_bold"
android:gravity="center"
android:paddingBottom="3dp"
android:singleLine="true"
android:text="Symbol"
android:textAppearance="#android:style/TextAppearance.Large"
android:textColor="#000"
android:textSize="15dp" />
<TextView
android:id="#+id/priceDetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:textStyle="bold"
android:text="Price"
android:textSize="13dp"
android:layout_marginBottom="5dp"
android:layout_toRightOf="#+id/symbolNameDetails"
android:textAppearance="#android:style/TextAppearance.Medium"
android:textColor="#000" />
</RelativeLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
activity_news_details.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=".activities.NewsDetailActivity">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/toolbar"
android:background="#color/black"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_below="#+id/toolbar"
android:layout_height="wrap_content">
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:indeterminateTint="#color/yellow"/>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none"
android:overScrollMode="never"
android:layout_below="#+id/progressBar">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/my_recycler_view_coin_details"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="horizontal" />
<androidx.cardview.widget.CardView
android:id="#+id/wrapper_cardview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/wrapper"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/news_title"
android:text="Titulo"
android:textStyle="bold"
android:layout_below="#+id/wrapper"
android:textSize="22sp"
android:paddingLeft="16dp"
android:textAlignment="center"
android:paddingStart="16dp"
android:textColor="#color/black"
android:gravity="center_horizontal" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/wrapper_news"
android:layout_below="#id/news_title"
android:paddingLeft="10dp"
android:layout_marginTop="4dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/news_date"
android:paddingEnd="10dp"
android:paddingStart="10dp"
android:text="Date"
android:paddingRight="5dp"/>
</RelativeLayout>
<ImageView
android:layout_width="match_parent"
android:adjustViewBounds="true"
android:id="#+id/news_image"
android:src="#drawable/icon_youtube"
android:layout_below="#id/wrapper_news"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/news_desc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/news_image"
android:fontFamily="#font/roboto"
android:padding="10dp"
android:text="News Description"
android:firstBaselineToTopHeight="0dp"
android:includeFontPadding="false"
android:lineSpacingExtra="2dp"
android:textColor="#color/black"
android:textSize="17sp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/wrapper_cardview"
android:padding="10dp"
android:textSize="18sp"
android:text="Similar News"
android:visibility="gone"
android:id="#+id/label_similar_news"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/news_recy"
android:layout_below="#id/label_similar_news"/>
</RelativeLayout>
</androidx.core.widget.NestedScrollView>
</RelativeLayout>
</RelativeLayout>
And finally, I am trying to get the list from here:
CryptoListAdapter
package com.noticripto.adapters;
import android.content.Context;
import android.graphics.Color;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.noticripto.retrofit.Datum;
import com.noticripto.R;
import java.util.List;
public class CryptoListAdapter extends
RecyclerView.Adapter<CryptoListAdapter.ViewHolder> {
private List<Datum> mData;
private ItemClickListener mClickListener;
ImageView arrowImage;
RelativeLayout layout;
RelativeLayout symbolBG;
// data is passed into the constructor
public CryptoListAdapter(List<Datum> data) {
this.mData = data;
}
// Usually involves inflating a layout from XML and returning the holder
// inflates the row layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.crypto_list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
layout = view.findViewById(R.id.relativeBG);
symbolBG = view.findViewById(R.id.symbolBG);
arrowImage = view.findViewById(R.id.arrow_img);
return viewHolder;
}
// Involves populating data into the item through holder
// binds the data to the TextView in each row
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// Get the data model based on position
Datum datum = mData.get(position);
TextView symbolName = holder.symbolName;
symbolName.setText(" (" + datum.getSymbol() + ")");
// Set item views based on your views and data model
TextView name = holder.name;
name.setText(datum.getName());
TextView symbolNameDetails = holder.symbolNameDetails;
symbolNameDetails.setText(datum.getSymbol());
TextView price = holder.price;
TextView priceDetails = holder.priceDetails;
if(datum.getQuote().getUSD().getPrice() >= 1) {
price.setText("$" + String.format("%.2f", datum.getQuote().getUSD().getPrice()));
priceDetails.setText("$" + String.format("%.2f", datum.getQuote().getUSD().getPrice()));
}else{
price.setText("$" + String.format("%f", datum.getQuote().getUSD().getPrice()));
priceDetails.setText("$" + String.format("%.2f", datum.getQuote().getUSD().getPrice()));
}
//TextView marketCap = holder.marketCap;
//marketCap.setText("Market Cap: $" + String.format("%,d",
Math.round(datum.getQuote().getUSD().getMarketCap())));
//TextView volume24h = holder.volume24h;
//volume24h.setText("Volume/24h: $" + String.format("%,d",
Math.round(datum.getQuote().getUSD().getVolume24h())));
//TextView textView1h = holder.textView1h;
//textView1h.setText(String.format("1h: %.2f",
datum.getQuote().getUSD().getPercentChange1h()) + "%");
TextView textView24h = holder.textView24h;
textView24h.setText(String.format("%.2f", datum.getQuote().getUSD().getPercentChange24h()) + "%");
if(datum.getQuote().getUSD().getPercentChange24h() < 0.0){
//red
textView24h.setText(String.format("%.2f", Math.abs(datum.getQuote().getUSD().getPercentChange24h())) + "%");
textView24h.setTextColor(Color.parseColor("#ffffff"));
arrowImage.setImageResource(R.drawable.arrow_down_white);
layout.setBackgroundColor(Color.parseColor("#EA3943"));
symbolBG.setBackgroundColor(Color.parseColor("#EA3943"));
priceDetails.setTextColor(Color.parseColor("#EA3943"));
}else{
//green
textView24h.setText(String.format("%.2f",
Math.abs(datum.getQuote().getUSD().getPercentChange24h())) + "%");
textView24h.setTextColor(Color.parseColor("#ffffff"));
arrowImage.setImageResource(R.drawable.arrow_up_white);
layout.setBackgroundColor(Color.parseColor("#18C784"));
symbolBG.setBackgroundColor(Color.parseColor("#18C784"));
priceDetails.setTextColor(Color.parseColor("#18C784"));
}
//TextView textView7d = holder.textView7d;
//textView7d.setText(String.format("7d: %.2f",
datum.getQuote().getUSD().getPercentChange7d()) + "%");
}
// Returns the total count of items in the list
// total number of rows
#Override
public int getItemCount() {
return mData.size();
}
// Provide a direct reference to each of the views within a data item
// Used to cache the views within the item layout for fast access
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
// Your holder should contain a member variable
// for any view that will be set as you render a row
TextView name;
TextView price;
TextView marketCap;
TextView volume24h;
TextView textView1h;
TextView textView24h;
TextView textView7d;
TextView symbolName;
TextView priceDetails;
TextView symbolNameDetails;
// We also create a constructor that accepts the entire item row
// and does the view lookups to find each subview
ViewHolder(View itemView) {
// Stores the itemView in a public final member variable that can be used
// to access the context from any ViewHolder instance.
super(itemView);
name = itemView.findViewById(R.id.name);
price = itemView.findViewById(R.id.price);
//marketCap = itemView.findViewById(R.id.marketCap);
// volume24h = itemView.findViewById(R.id.volume24h);
//textView1h = itemView.findViewById(R.id.textView1h);
textView24h = itemView.findViewById(R.id.textView24h);
//textView7d = itemView.findViewById(R.id.textView7d);
symbolName = itemView.findViewById(R.id.symbolName);
priceDetails = itemView.findViewById(R.id.priceDetails);
symbolNameDetails = itemView.findViewById(R.id.symbolNameDetails);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view,
getAdapterPosition());
}
}
// convenience method for getting data at click position
public Datum getItem(int id) {
return mData.get(id);
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
The log doesn't say anything helpful just that the list might be empty but the same list is working on the MainActivity so, I believe the problem is inside my NewsDetailActivity.
I also tried some of the answers and none of them helped me:
RecyclerView is not showing
RecyclerView is not showing items
CardView is not showing properly in RecyclerView
Again, i just want to display my list from CryptoListAdapter under the NewsDetailActivity toolbar...in a nice cardview
This is what I want to do...
this is simple and normal! you fill your array in getCoinList() but set adapter for RecyclerView in initViews() in this way your array not filled yet but you pass it to your recycler! , you should get your array first , then pass it to adapter and set adapter to RecyclerView.

TextView in SliderView text shown and text value bug [the n'th TextView is returning its initialized value after changing (n+2)'th textView]

i have a textView in SliderView like this
activitity_slider.xml
<androidx.viewpager.widget.ViewPager
android:id="#+id/slideViewPager"
android:layout_width="match_parent"
slide_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_gravity="center"
android:background="#color/white">
<LinearLayout
android:id="#+id/HareketEkranı"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_marginBottom="10dp"
android:orientation="vertical"
>
<androidx.cardview.widget.CardView
android:id="#+id/hareket"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
app:cardBackgroundColor="#color/white"
app:cardCornerRadius="10dp">
<ImageView
android:id="#+id/HareketResmi"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:contentDescription="Hareket"/>
//android:src="#drawable/ic_armcircle"
<com.jjoe64.graphview.GraphView
android:id="#+id/haraketdatasi"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="2">
<TextView
android:id="#+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="left"
android:text="Hareket"
android:layout_weight="1"
android:textColor="#color/darkTextColor"
android:textSize="24sp" />
<TextView
android:id="#+id/HareketAdi"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:textAlignment="gravity"
android:gravity="right"
android:text="Armcircle"
android:textColor="#color/red"
android:layout_weight="1"
android:textSize="24sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="2">
<TextView
android:id="#+id/TekrarYazisiSlide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:text="Tekrar"
android:layout_weight="1"
android:textColor="#color/darkTextColor"
android:textSize="24sp" />
<TextView
android:id="#+id/TekrarSayisiSlide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:text="TekrarSayisi"
android:textAlignment="gravity"
android:gravity="right"
android:layout_weight="1"
android:textColor="#color/red"
android:textSize="24sp" />
<TextView
android:id="#+id/kesme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:text="/"
android:layout_weight="1"
android:textColor="#color/black"
android:textSize="24sp" />
<TextView
android:id="#+id/TekrarhedefiSlide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:text="25"
android:layout_weight="1"
android:textColor="#color/black"
android:textSize="24sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
</RelativeLayout>
UPDATE !
SliderAdapter.java
package gymholix.assistx;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
public class SliderAdapter extends PagerAdapter {
Context context;
LayoutInflater layoutInflater;
public SliderAdapter(Context context){
this.context = context;
}
//Arrays
public int[] slide_images = {
R.drawable.ic_armcircle,
R.drawable.ic_ropejump,
R.drawable.ic_jumpingjack,
R.drawable.ic_burpee,
R.drawable.ic_squat
};
public String[] slide_headings = {
"ArmCircle",
"RopeJump",
"JumpingJack",
"Burpee",
"Squat"
};
/*public String[] tekrar_sayisi = {
"0",
"0",
"0",
"0",
"0"*/
public int[] tekrar_sayisi = {
1,
2,
3,
4,
5
};
#Override
public int getCount() {
return slide_headings.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == (RelativeLayout) object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view =layoutInflater.inflate(R.layout.slide_layout, container, false);
ImageView slideImageView = (ImageView) view.findViewById(R.id.HareketResmi);
TextView slideHeading = (TextView) view.findViewById(R.id.HareketAdi);
TextView slideTekraSayisi = (TextView) view.findViewById(R.id.TekrarSayisiSlide);
slideImageView.setImageResource((slide_images[position]));
slideHeading.setText(slide_headings[position]);
slideTekraSayisi.setText(String.valueOf(tekrar_sayisi[position]));
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
}
}
Slider.Java
package gymholix.assistx;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.content.Context;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Slider extends AppCompatActivity {
private LinearLayout mDotLayout;
private String asd;
private int asdf;
TextView DenemeSayiCek;
int position;
View view;
int count;
View viewFix;
Context context;
//Sensors---------------------------------------------------------------------------------------
private Accelerometer accelerometer;
private Gyroscope gyroscope;
public double[] acc={3.00,2.00,1.00};
public double[] gyr={3.00,2.00,1.00};
//Sensors---------------------------------------------------------------------------------------
//Main------------------------------------------------------------------------------------------
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Antreman antreman = new Antreman();
context = this;
setContentView(R.layout.activity_slider);
ViewPager AktifHareket = findViewById(R.id.slideViewPager);
mDotLayout = findViewById(R.id.dotsLayout);
SliderAdapter sliderAdapter = new SliderAdapter(this);
AktifHareket.setAdapter((sliderAdapter));
addDotsIndicator();
//Saydir Buton------------------------------------------------------------------------------
TextView Deneme = findViewById(R.id.deneme);
TextView Deneme4 = findViewById(R.id.deneme4);
TextView Deneme3 = findViewById(R.id.deneme3);
TextView Deneme2 = findViewById(R.id.deneme2);
Button Saydir = findViewById(R.id.SaydirSlide);
Button Saydir2 = findViewById(R.id.Saydir2Slide);
Saydir.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
position = AktifHareket.getCurrentItem();
view = AktifHareket.getChildAt(position);
count = AktifHareket.indexOfChild(view);
viewFix = AktifHareket.getChildAt(count);
DenemeSayiCek = viewFix.findViewById(R.id.TekrarSayisiSlide);
asd = DenemeSayiCek.getText().toString();
asdf = Integer.parseInt(asd);
asdf++;
DenemeSayiCek.setText(String.valueOf(asdf));
Deneme.setText(String.valueOf(asd));
Deneme2.setText(String.valueOf(position));
Deneme3.setText(String.valueOf(asdf));
Deneme4.setText(String.valueOf(SliderAdapter.POSITION_NONE));
}
});
//Saydir Buton------------------------------------------------------------------------------
//ImageButton-------------------------------------------------------------------------------
ImageView logoImage = findViewById(R.id.logo);
logoImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
antreman.AntremanSayfasi(context);
}
});
antreman.AntremanSayfasi(context);//Açılışta Sayfayı açsın diye
//ImageButton-------------------------------------------------------------------------------
//Sensors-----------------------------------------------------------------------------------
accelerometer = new Accelerometer(this);
gyroscope = new Gyroscope(this);
accelerometer.setListner(new Accelerometer.Listner() {
#Override
public void onTranslation(float ax, float ay, float az) {
setAccValue(ax, ay, az);
Antreman.GetSensorValues.OnAccelerometerChangeValues = acc;
}
});
gyroscope.setListner(new Gyroscope.Listner() {
#Override
public void onRotation(float gx, float gy, float gz) {
setGyroValue(gx, gy, gz);
Antreman.GetSensorValues.OnGyroscopeChangeValues = gyr;
//OnSensorChangeValues.add(1, String.valueOf(gyr) );
}
});
/* Saydir2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});*/
//Sensors-----------------------------------------------------------------------------------
}
//Sensors---------------------------------------------------------------------------------------
protected void onResume(){
super.onResume();
accelerometer.register();
gyroscope.register();
}
protected void onPouse(){
super.onPause();
accelerometer.unregister();
gyroscope.unregister();
}
//Sensors---------------------------------------------------------------------------------------
//SensorsValueGetAndSet-------------------------------------------------------------------------
public double[] setAccValue(float ac, float bc, float cc){
this.acc[0] = ac;
this.acc[1] = bc;
this.acc[2] = cc;
return acc;
}
public double[] setGyroValue(float qq, float wq, float eq){
this.gyr[0] = qq;
this.gyr[1] = wq;
this.gyr[2] = eq;
return gyr;
}
public void getAccValue(float ac, float bc, float cc){
ac = (float) acc[0];
bc = (float) acc[1];
cc = (float) acc[2];
}
public void getGyroValue(float qq, float wq, float eq){
qq = (float) gyr[0];
wq = (float) gyr[1];
eq = (float) gyr[2];
}
//SensorsValueGetAndSet-------------------------------------------------------------------------
public void addDotsIndicator(){
TextView[] mDots = new TextView[3];
for(int i = 0; i < mDots.length; i++){
mDots[i] = new TextView(this);
mDots[i].setText(Html.fromHtml("•"));
mDots[i].setTextSize(35);
mDots[i].setTextColor(getResources().getColor(R.color.colorPrimaryDark));
mDotLayout.addView(mDots[i]);
}
}
//----------------------------------------------------------------------------------------------
}
the weird thing about this code is; while running the button changes the text value correctly in the first pager, and the seckond one but when it comes the third one while it changes the value it resets the first pagers shown value but the getText() method inherits the correct value but the text is frozen and it cant be changed any more, after that the other page's values cant be changed either, but the getText() method still works fine and gets the correct value.
any idea will speed up my debuging process thanx anyway...
adding this snipped solved the problem, it is a must to define borders to the pager
#Override
protected void onCreate(Bundle savedInstanceState) {
...
int size = sliderAdapter.slide_headings.length;
AktifHareket.setOffscreenPageLimit(size);

Switch case with radio buttons

I am new to here and java. I am developing an android app with radio buttons which calculates the SGPA of a student. Every subject has it's own credits which gets multiplies by the respective grade and after the addition of all products of the subject, The sum is divided by the total credits...
So far i've completed the xml code properly but i am stuck in the java main activity... I just need an example of only one button or subject and rest i will do on my own... I want to use switch case to first check which radio button is clicked and then do the respective calculations.
XML CODE
<TextView
android:id="#+id/maths"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#F44336"
android:text="MATHEMATICS"
android:textAlignment="center"
android:textAllCaps="true"
android:textAppearance="?android:textAppearanceLarge"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#F44336"
android:orientation="horizontal">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="7"
android:orientation="horizontal">
<RadioButton
android:id="#+id/Omaths"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="O"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/Aplusmaths"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="A+"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/Amaths"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="A"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/Bplusmaths"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="B+"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/Bmaths"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="B"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/Cmaths"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="C"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/Pmaths"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="P"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
</LinearLayout>
AND THE JAVA MAIN ACTIVITY CODE IS
package droidmentor.bnv_with_viewpager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
import droidmentor.bnv_with_viewpager.Fragment.CallsFragment;
import droidmentor.bnv_with_viewpager.Fragment.ChatFragment;
import droidmentor.bnv_with_viewpager.Fragment.ContactsFragment;
import static droidmentor.bnv_with_viewpager.R.id.Amaths;
import static droidmentor.bnv_with_viewpager.R.id.Bmaths;
import static droidmentor.bnv_with_viewpager.R.id.Bplusmaths;
import static droidmentor.bnv_with_viewpager.R.id.Cmaths;
import static droidmentor.bnv_with_viewpager.R.id.Pmaths;
public class MainActivity extends AppCompatActivity {
BottomNavigationView bottomNavigationView;
//This is our viewPager
private ViewPager viewPager;
//Fragments
ChatFragment chatFragment;
CallsFragment callsFragment;
ContactsFragment contactsFragment;
MenuItem prevMenuItem;
//Instance Variables For Each Subject
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.viewpager);
//Initializing the bottomNavigationView
bottomNavigationView = (BottomNavigationView)findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_call:
viewPager.setCurrentItem(0);
break;
case R.id.action_chat:
viewPager.setCurrentItem(1);
break;
case R.id.action_contact:
viewPager.setCurrentItem(2);
break;
}
return false;
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (prevMenuItem != null) {
prevMenuItem.setChecked(false);
}
else
{
bottomNavigationView.getMenu().getItem(0).setChecked(false);
}
Log.d("page", "onPageSelected: "+position);
bottomNavigationView.getMenu().getItem(position).setChecked(true);
prevMenuItem = bottomNavigationView.getMenu().getItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
/* //Disable ViewPager Swipe
viewPager.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
return true;
}
});
*/
setupViewPager(viewPager);
}
//This method is called when button is pressed
public void calculate(View view) {
display(9);
}
//This method returns the SGPA
private void display(int number) {
TextView sgpa = (TextView) findViewById(R.id.sgpa);
sgpa.setText("" + number);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
callsFragment=new CallsFragment();
chatFragment=new ChatFragment();
contactsFragment=new ContactsFragment();
adapter.addFragment(callsFragment);
adapter.addFragment(chatFragment);
adapter.addFragment(contactsFragment);
viewPager.setAdapter(adapter);
}
}
I know i can use the user input method with edit text but i have to use radio buttons... :)
try do this to get selected button:
int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
View radioButton = radioButtonGroup.findViewById(radioButtonID);
int idx = radioButtonGroup.indexOfChild(radioButton);
Note that if you use textview or other view inside radioGroup not equal to radiobutton you get wrong index.
To get the text of selected button:
RadioButton r = (RadioButton) radioButtonGroup.getChildAt(idx);
String selectedtext = r.getText().toString();

Crash on creating a list size >1 to pass into list view (Index out of bounds)

Im trying to create a dice rolling tool as part of a larger application. However if i try to roll more than 1 dice in my dice roll function the application crashes. Howver as im new to Java i cant seem to find the cause of the index out of bounds error.
DiceActvity.Java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import java.util.ArrayList;
import java.util.List;
public class DiceActivity extends AppCompatActivity
{
ListView LVDiceList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dice);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Radio button
final RadioButton rbGreater = (RadioButton) findViewById(R.id.greaterThanRadioB);
final RadioButton rbLess = (RadioButton) findViewById(R.id.lessThanRadioB);
//Edit boxes
final EditText txtDiceType = (EditText) findViewById(R.id.diceTypeEdTxt);
final EditText txtNumberDice = (EditText) findViewById(R.id.numDiceEdTxt);
final EditText txtFilterNum = (EditText) findViewById(R.id.filterNumEdTxt);
//Buttons
Button btnRoll = (Button) findViewById(R.id.rollButton);
Button btnDiscard = (Button) findViewById(R.id.discardButton);
//Display Array
final List<Integer> diceList = new ArrayList<Integer>(10);
//Array Adapter
final ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this, android.R.layout.simple_spinner_item, diceList);
//Set adapter
LVDiceList = (ListView) findViewById(R.id.diceResultListV);
LVDiceList.setAdapter(adapter);
//Roll the dice
btnRoll.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Hide soft keyboard
Utils.hideKeyboard(DiceActivity.this);
//Validation of fields
//If both fields >0
if (Integer.valueOf(txtDiceType.getText().toString()) > 0 && Integer.valueOf(txtNumberDice.getText().toString()) > 0)
{
int number = Integer.valueOf(txtNumberDice.getText().toString());
int sides = Integer.valueOf(txtDiceType.getText().toString());
//Populate array
for (int i=0;i <number; i++)
{
diceList.add(i, rollDice(sides,number).get(i));
}
//Update the list view
adapter.notifyDataSetChanged();
}
return;
}
});
//Clear the list of results
btnDiscard.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
diceList.clear();
adapter.notifyDataSetChanged();
}
});
//Radio Button Validation
rbGreater.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(rbGreater.isChecked() == true)
{
rbLess.setChecked(false);
}
}
});
rbLess.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(rbLess.isChecked() == true)
{
rbGreater.setChecked(false);
};
}
});
}
//Returns a list of rolled dice results
private List<Integer> rollDice(int chance, int amount)
{
final List<Integer> rollArray = new ArrayList<Integer>(amount);
int result;
//Gives a random number between 1 and X,Y number of times
{
//BASE Equation||Min + (int)(Math.random() * ((Max - Min) + 1))
//1 = minimum roll
result = 1 + (int) (Math.random() * ((chance - 1) + 1));
rollArray.add(result);
}
return rollArray;
}
}
content_dice.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="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="garethgriffiths.tabletopcompanion.DiceActivity"
tools:showIn="#layout/activity_dice">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/textView_NumDice"
android:id="#+id/numDiceTextV"
android:layout_alignBottom="#+id/numDiceEdTxt"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:textSize="25dp"
android:textStyle="bold"
android:textAlignment="gravity"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="4"
android:id="#+id/numDiceEdTxt"
android:maxLength="3"
android:text="#string/edText_NumDice"
android:gravity="right"
android:selectAllOnFocus="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/numDiceTextV"
android:layout_toEndOf="#+id/numDiceTextV"
android:numeric="integer"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/textView_DiceType"
android:id="#+id/diceTypeTextV"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/numDiceTextV"
android:layout_alignBottom="#+id/diceTypeEdTxt"
android:layout_toLeftOf="#+id/diceTypeEdTxt"
android:layout_toStartOf="#+id/diceTypeEdTxt"
android:textSize="25dp"
android:textStyle="bold"
android:textAlignment="gravity"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="4"
android:id="#+id/diceTypeEdTxt"
android:maxLength="2"
android:text="#string/edText_DiceType"
android:layout_below="#+id/numDiceEdTxt"
android:layout_alignLeft="#+id/numDiceEdTxt"
android:layout_alignStart="#+id/numDiceEdTxt"
android:gravity="right"
android:selectAllOnFocus="true"
android:numeric="integer"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radioB_LessThan"
android:id="#+id/lessThanRadioB"
android:layout_above="#+id/discardButton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="36dp"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radioB_GreaterThan"
android:id="#+id/greaterThanRadioB"
android:layout_alignTop="#+id/lessThanRadioB"
android:layout_toRightOf="#+id/lessThanRadioB"
android:layout_toEndOf="#+id/lessThanRadioB"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="4"
android:maxLength="3"
android:id="#+id/filterNumEdTxt"
android:layout_alignTop="#+id/greaterThanRadioB"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:text="#string/edText_NumFilter"
android:gravity="center"
android:selectAllOnFocus="true"
android:numeric="integer"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_Discard"
android:id="#+id/discardButton"
android:layout_alignTop="#+id/rollButton"
android:layout_toLeftOf="#+id/rollButton"
android:layout_toStartOf="#+id/rollButton"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_Roll"
android:id="#+id/rollButton"
android:layout_marginTop="108dp"
android:layout_below="#+id/diceTypeTextV"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/diceResultListV"
android:scrollIndicators="right"
android:visibility="visible"
android:layout_below="#+id/discardButton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
Heres a small Class used to hide softkeyboard thats called in DiceActivity
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
/**
* http://stackoverflow.com/questions/1109022/close-hide-the-android-soft-keyboard
* Used to close soft keyboard
*/
public class Utils
{
public static void hideKeyboard(Activity activity)
{
// Check if no view has focus:
View view = activity.getCurrentFocus();
if (view != null)
{
InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
Your method private List<Integer> rollDice(int chance, int amount) returns a list of Integer. And according to your comment inside the method it should have multiple numbers in it.
But this method always returns only one number.
Now you invoke this method here:
for (int i=0;i <number; i++)
{
diceList.add(i, rollDice(sides,number).get(i));
}
You are invoking this method in a loop. Storing the results in a NEW list.
You get an exception because in the second loop get(i) is 1 and there is only 1 entry in this list on index 0.
To correct this is should read: .get(0)
Also this kind of implementation is very messy. Please take a paper and a pencil to figure it out.

onActivityResult in fragment doesn't update edittext

I have a sample barcode scanner app using this library.
onActivityResult does not update the textView nor editText.
I did some search around and noticed that this is a common problem.
onActivityResult i get my value that i pass through, i can log and toast the value but does not work on setText() method.
Edit: I'm using fragments.
Fragment A is where the button, edit & textview are, Fragment B is the barcode scanner and i use popBackStack() to return to fragment A(received data from Fragment B);
Here is my code:
package com.gilbert.apptastic.barcodefragment;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
public static final int DIALOG_FRAGMENT = 1;
public TextView textView;
public TextView textView2;
public TextView textView3;
public TextView textView4;
public EditText editText;
public Button button;
public String barcode;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
textView = (TextView)rootView.findViewById(R.id.textView);
textView2 = (TextView)rootView.findViewById(R.id.textView2);
textView3 = (TextView)rootView.findViewById(R.id.textView3);
textView4 = (TextView)rootView.findViewById(R.id.textView4);
editText = (EditText)rootView.findViewById(R.id.editText);
button = (Button)rootView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanBarcode();
}
});
// setText();
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == DIALOG_FRAGMENT && resultCode == Activity.RESULT_OK) {
// System.out.println("ok");
barcode = data.getExtras().getString("barcode");
// edit_barcode.setText(value);
setText();
Toast.makeText(getActivity(), barcode, Toast.LENGTH_SHORT).show();
// System.out.println(barcode);
// edit_barcode.setText(barcode);
}
}
public void setText() {
System.out.println(barcode);
textView.setText(barcode);
textView2.setText(barcode);
textView3.setText(barcode);
textView4.setText(barcode);
editText.setText(barcode);
}
public void scanBarcode(){
Barcode barcode = new Barcode();
barcode.setTargetFragment(PlaceholderFragment.this, DIALOG_FRAGMENT);
FragmentTransaction fragmentTransaction =
getActivity().getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container, barcode);
fragmentTransaction.addToBackStack("VIEW");
fragmentTransaction.commit();
}
}
Barcode Class:
package com.gilbert.apptastic.barcodefragment;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import me.dm7.barcodescanner.zbar.Result;
import me.dm7.barcodescanner.zbar.ZBarScannerView;
public class Barcode extends Fragment implements ZBarScannerView.ResultHandler {
private ZBarScannerView mScannerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mScannerView = new ZBarScannerView(getActivity());
return mScannerView;
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
#Override
public void handleResult(Result rawResult) {
if(!rawResult.getContents().isEmpty()){
mScannerView.startCamera();
// Toast.makeText(getActivity(),"Success",Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.putExtra("barcode", rawResult.getContents());
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent);
getFragmentManager().popBackStack();
}else {
// Toast.makeText(getActivity(),"Fail",Toast.LENGTH_SHORT).show();
getFragmentManager().popBackStack();
mScannerView.startCamera();
}
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera();
}
}
my layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment">
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Scan"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_above="#+id/button">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textView2"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/textView3"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/textView4"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:hint="Barcode"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</RelativeLayout>
Try these
1 ) Instead of
barcode = data.getExtras
try
barcode = data.getStringExtra("barcode")
2) Instead of initiating barcode
String barcode;
Try doing this in your onActivityResult,
String barcode = data.getExtras().getString("barcode");
3 ) Instead of putting data directly into intent, use a bundle.
Bundle b = new Bundle();
b.putString ("barcode", rawResult.getContent());
Intent i = new intent();
i.putExtras (b);
In your onActivityResult
Bundle b = getIntent.getExtras();
String s = b.getString("barcode");
Then use s where you need it.

Categories