Getting checked Checkbox data in array - java

I have an android app where I display a form with some Checkboxes.I want to query firestore on the basis of checked checkboxes. I'm unable to get the array/arraylist of checked checkboxes. For testing purposes I've added a textview . If my test works I want to set the text of textview using members of newly populated array/arraylist.
When I check any checkbox and click on the button,my app crashes. Suppose I checked box4. The condition
(item4.isChecked) should be true and hence item4 must be added to my arraylist whose size is now not equal to zero
if(item4.isChecked()){
testingArrayList.add("item4");
}
Why am I getting the error that length of array is zero?
Here is my code:
package com.example.XX;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FieldPath;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
public class todayQuestionFragment extends Fragment {
FirebaseFirestore db = FirebaseFirestore.getInstance();
CheckBox item1;
CheckBox item2;
CheckBox item3;
CheckBox item4;
CheckBox item5;
CheckBox item6;
CheckBox item7;
CheckBox item8;
CheckBox item9;
CheckBox item10;
Button button;
ProgressBar progressBar;
TextView textView;//just for testing
public todayQuestionFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_today_question, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
item1=view.findViewById(R.id.checkBox_item1);
item2=view.findViewById(R.id.checkBox_item2);
item3=view.findViewById(R.id.checkBox_item3);
item4=view.findViewById(R.id.checkBox_item4);
item5=view.findViewById(R.id.checkBox_item5);
item6=view.findViewById(R.id.checkBox_item6);
item7=view.findViewById(R.id.checkBox_item7);
item8=view.findViewById(R.id.checkBox_item8);
item9=view.findViewById(R.id.checkBox_item9);
item10=view.findViewById(R.id.checkBox_item10);
textView=view.findViewById(R.id.testingCheckBox);
Button button=view.findViewById(R.id.toMainQueryButton);
final NavController navController= Navigation.findNavController(view);
final ArrayList<String> testingArrayList = new ArrayList<String>();
if(item1.isChecked()){
testingArrayList.add("item1");
}
if(item2.isChecked()){
testingArrayList.add("item2");
}if(item3.isChecked()){
testingArrayList.add("item3");
}if(item4.isChecked()){
testingArrayList.add("item4");
}
if(item5.isChecked()){
testingArrayList.add("item5");
}
if(item6.isChecked()){
testingArrayList.add("item6");
}
if(item7.isChecked()){
testingArrayList.add("item7");
}if(item8.isChecked()){
testingArrayList.add("item8");
}if(item9.isChecked()){
testingArrayList.add("item9");
}
if(item10.isChecked()){
testingArrayList.add("item10");
}
final String[] testArray = new String[testingArrayList.size()];
for(int j =0;j<testingArrayList.size();j++){
testArray[j] = testingArrayList.get(j);
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(testArray[0]);
}
});
}
}
Logcat:
2020-06-12 14:48:10.772 4622-4622/com.example.XX E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.XX, PID: 4622
java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at com.example.XX.todayQuestionFragment$1.onClick(todayQuestionFragment.java:140)
at android.view.View.performClick(View.java:7201)
at android.view.View.performClickInternal(View.java:7170)
at android.view.View.access$3500(View.java:806)
at android.view.View$PerformClick.run(View.java:27582)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7710)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

Found my error. All my logic with if conditions and arraylist/array needs to be added INSIDE the onClickListener of my button

Related

Recycler View on Fragment Activity

I am making 50 data appear in my code, but I am putting it in a recycler view in a fragment because I have a dropdown menu, but when I put the code to call everything I get these two lines of error:
package com.example.tallerof.ui.gallery;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.tallerof.R;
import com.example.tallerof.adapters.UsuariosAdapter;
import java.util.ArrayList;
public class GalleryFragment extends Fragment {
private GalleryViewModel galleryViewModel;
ArrayList<String> ListadeDatos;
RecyclerView recyclerView;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
recyclerView=(RecyclerView) findViewById(R.id.Recycler1); /* Error #1 Cannot resolve method findViewById in GalleryFragment*/
recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)); /* Error #2 required type: context provide: Gallery Fragment*/
ListadeDatos=new ArrayList<String>();
for(int i=0; i<=50; i++){
ListadeDatos.add("Dato # "+i+"");
}
UsuariosAdapter adapter= new UsuariosAdapter(ListadeDatos);
recyclerView.setAdapter(adapter);
return null;
}
}
you must to do this.
recyclerView = getActivity().findViewbyId(R.id.Recycler1);
Regards.

I m doing barcode scanner. But I can display my resultCode in textview.

I want to display the scan result from ZXING. I integrated ZXING into my android app, the scan works ok. Now I want to display the barcode number result in textview. I'm using zxing library in my project. I set up result.setText(resultCode) but it's not works. so this is code i m'follow from the tutorial.
package com.example.norhanom.barcodeqrcode;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View; //view button or textfield
import android.widget.Toast; //to show and create message for user,appears
as floating view over app
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import com.google.zxing.Result;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class MainActivity extends AppCompatActivity {
private ZXingScannerView scannerView;
TextView result;
private ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView)findViewById(R.id.textView1);
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("loading");
pd.setCancelable(false);
pd.setCanceledOnTouchOutside(false);
}
public void scanCode(View view){
scannerView = new ZXingScannerView(this); // Programmatically initialize
the scanner view
scannerView.setResultHandler(new ZXingScannerResultHandler());
setContentView(scannerView); //Set the scanner view as the content view
scannerView.startCamera(); //scannerView open camera
}
#Override
public void onPause()
{
super.onPause();
scannerView.stopCamera(); //stop camera on pause
}
class ZXingScannerResultHandler implements ZXingScannerView.ResultHandler
{
#Override
public void handleResult(Result result1)
{
String resultCode = result1.getText(); //get the result
Toast.makeText(MainActivity.this,resultCode,Toast.LENGTH_LONG).show();
//show result
setContentView(R.layout.activity_main);
scannerView.stopCamera(); //camera stop
}
}
}
After using setContentView the next time, you should reassign the views.
//inside handleResult
setContentView(R.layout.activity_main);
result = (TextView)findViewById(R.id.textView1);
result.setText(resultCode);
scannerView.stopCamera();

android studio cannot resolve method(), ignoring import

I'm a total noob at android studio, and I have a (to me) weird problem. I have inserted a button in my XML document:
<Button
android:layout_width="match_parent"
android:layout_height="127dp"
android:text="SUM"
android:id="#+id/button"
android:layout_row="15"
android:layout_column="0" />
And in the java code I would like a to make it do something when i click on it. However in code (I know there is way too many import):
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class TestActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
R.id.button.onCliclistener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent action) {
DO THIS WHEN CLICKED ON
}
});
}
BUT it says: Cannot resolve method() and Cannot resolve symbol, to the onCliclistener and ActionListener. And it says: unused import statement, to thier imports. It's probably a stupid question, but what am I doing wrong?
Nicolaj
Try making reference to your button in your onCreate method and then create an onClick method.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class TestActivity extends AppCompatActivity implements View.OnClickListener {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
btn = (Button) findViewById(R.id.button); //Reference to the button
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
DO THIS WHEN CLICKED ON
}
}
I expect it will be helpful for you!

In Fragments, Instances are not getting saved

Please have a look at the below code
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class InputFragment extends Fragment {
private SeekBar daysAsCustomerSeek;
private View view;
//Following variables will save the application state and load back
//on resume
private final String DAYS_AS_CUSTOMER_VALUE_HOLDER = "days as customer value";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
//Intializing instance variables
view = inflater.inflate(R.layout.input, container,false);
daysAsCustomerSeek = (SeekBar)view.findViewById(R.id.days_as_customer_seekbar);
//Set default max values
daysAsCustomerSeek.setMax(210);
return view;
}
//This method will save the instances
#Override
public void onSaveInstanceState(Bundle savedInstanceStateBundle)
{
savedInstanceStateBundle.putInt(DAYS_AS_CUSTOMER_VALUE_HOLDER, daysAsCustomerSeek.getProgress());
}
//This method will restore the instances
#Override
public void onActivityCreated(Bundle savedInstanceStateBundle)
{
super.onActivityCreated(savedInstanceStateBundle);
if(savedInstanceStateBundle!=null)
{
daysAsCustomerSeek.setProgress(savedInstanceStateBundle.getInt(DAYS_AS_CUSTOMER_VALUE_HOLDER));
}
}
}
The problem is when I turn the device or navigate back to this fragment, non of its states were saved! Instead, everything was recreated! Why is this? Why this code is not showing the state?
Add:
super.onSaveInstanceState(savedInstanceStateBundle);
in onSaveInstanceState method.
someFragment.setRetainInstance(true);

Android crashing on activity start

Android crashes whenever this activity is started. here is the code.
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class SettingsActivity extends Activity {
EditText vname, vphone, vemail, vaddress;
TextView textDeviceID;
Button settings_submit;
#Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.settingmenu);
vname = (EditText) findViewById(R.id.get_name);
vphone = (EditText) findViewById(R.id.get_phone);
vemail = (EditText) findViewById(R.id.get_email);
vaddress = (EditText) findViewById(R.id.get_address);
settings_submit = (Button) findViewById(R.id.settings_submit);
settings_submit.setOnClickListener(settings_submitOnClickListener);
TextView textDeviceID = (TextView) findViewById(R.id.deviceid);
super.onCreate(savedInstanceState);
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(
you should tell us more details. But I see that everything looks fine, except that
super.onCreate(savedInstanceState);
should go before setContentView() and all other stuff. By the way, check your xml for bad config controls too.

Categories