My listview have 19 rows and i need to get all edittext data from listview and store into arraylist.
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int itemCount = mListView.getCount();
Log.d("count", ""+itemCount);
final ArrayList<String> collection = new ArrayList<>();
for(int i=0; i<itemCount; i++){
view1 = mListView.getChildAt(i);
Log.d("Position: ", ""+view1);
EditText tt = (EditText)view1.findViewById(R.id.etqty);
value = tt.getText().toString();
collection.add(value);
}
//int position = contractstoreAdapter.getItem();
Log.d("number", String.valueOf(collection));
}
});
Here is my error.
09-07 08:09:05.526 8669-8669/com.example.chintatt.cbi E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.chintatt.cbi, PID: 8669
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.example.chintatt.cbi.Fragment_orderstock$1.onClick(Fragment_orderstock.java:107)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
ListView doesn't always contain the data, cause a child view is created every time it comes into display
You must have used some adapter to store the data right? Try to get all the info from there. Not from the ListView but from the adapter in which the data contains.
Hope this will help You
If u can tell how u are storing the data in Adapter it would help me further to tell your answer precisely
for (int i = 0; i <= mListView.getLastVisiblePosition() - mListView.getFirstVisiblePosition(); i++)
I believe this should be the loop that you need to implement.
EditText tt = (EditText)view1
Use above line
EditText tt = (EditText)view1.findViewById(R.id.etqty);
Why are you calling findViewById(), whether you get edittext in your view itself
Related
I'm creating radio buttons like this in a fragment programmatically in a for loop (i++)
for (int i = 1; i < priceList.length(); i++) {
JSONObject priceObj = (JSONObject) priceList.get(i);
String catName = priceObj.getString("categoryName");
String uid = i*(i+100)+20;
RadioButton rdbtn = new RadioButton(getActivity().getApplicationContext());
rdbtn.setId((row * 2) + i);
rdbtn.setText(catName);
rdbtn.setTextColor(R.color.colorPrimary);
ll.addView(rdbtn);
}
linearLayout.removeAllViews();
linearLayout.addView(ll);
i want to add that uid as tag, but if i add .setTag(uid) it is giving error like below
FATAL EXCEPTION: main
Process: com.vistaraitsolutions.hoteladmin, PID: 13629
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RadioButton.setTag(java.lang.Object)' on a null object reference
at com.vistaraitsolutions.hoteladmin.FragmentStepThreeBooking.addRadioButtons(FragmentStepThreeBooking.java:226)
at com.vistaraitsolutions.hoteladmin.FragmentStepThreeBooking$1.onResponse(FragmentStepThreeBooking.java:161)
at com.vistaraitsolutions.hoteladmin.FragmentStepThreeBooking$1.onResponse(FragmentStepThreeBooking.java:157)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:72)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6856)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
and that tadio buttons not yet added to linear layout yet, aftre loop ony im adding radio group to layout! now i need to set tags.
this is code with setTag()
for (int i = 1; i < priceList.length(); i++) {
JSONObject priceObj = (JSONObject) priceList.get(i);
String catName = priceObj.getString("categoryName");
String uid = i*(i+100)+20;
RadioButton rdbtn = new RadioButton(getActivity().getApplicationContext());
rdbtn.setId((row * 2) + i);
rdbtn.setText(catName);
//rdbtn.setTag(url); here im adding setTag
rdbtn.setTextColor(R.color.colorPrimary);
ll.addView(rdbtn);
}
linearLayout.removeAllViews();
linearLayout.addView(ll);
please help me
I am using com.weiwangcn.betterspinner, but instead of declare it in XML file, I create it programmatically. Below is my code, short and simple.
final MaterialBetterSpinner spinnerSoftener = new MaterialBetterSpinner(getActivity());
spinnerSoftener.setId((View.generateViewId()));
spinnerSoftener.setHint("Softener");
spinnerSoftener.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
List<Mill_Softener_Type> softenerList = presenter.getSoftener();
if(softenerList.size() == 0)
{
spinnerSoftener.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_dropdown_item, new ArrayList<>()));
spinnerSoftener.setEnabled(false);
}
else
{
System.out.println("softener size: " + softenerList.size());
spinnerSoftener.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_dropdown_item, softenerList));
spinnerSoftener.setEnabled(true);
}
container.addView(spinnerSoftener);
The problem is when I click on the spinner, it will throw a NullPointerException. Below is the error code:
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:337)
at android.widget.AdapterView.checkFocus(AdapterView.java:732)
at android.widget.AdapterView$AdapterDataSetObserver.onInvalidated(AdapterView.java:855)
at android.widget.AbsListView$AdapterDataSetObserver.onInvalidated(AbsListView.java:6187)
at android.database.DataSetObservable.notifyInvalidated(DataSetObservable.java:50)
at android.widget.BaseAdapter.notifyDataSetInvalidated(BaseAdapter.java:59)
at android.widget.ArrayAdapter$ArrayFilter.publishResults(ArrayAdapter.java:546)
at android.widget.Filter$ResultsHandler.handleMessage(Filter.java:282)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
softenerList isn't null, I can print out its size from else part. I don't know what is the problem, any idea?
List<Mill_Softener_Type> softenerList = new ArrayList<>();
softenerList = presenter.getSoftener();
here presenter.getSoftener(); return null values, so you have to check first if it is giving null values reference.
List<Mill_Softener_Type> softenerList = presenter.getSoftener();
if (softenerList != null){
if(softenerList.size() == 0) {
// your code
} else {
// your code
}
container.addView(spinnerSoftener);
}
Generally, I don't see why you can't use XML here, but the list is not null, since you say you can print the size and the stacktrace says otherwise.
Regardless, I would re-write that without the new ArrayList<> because if you have an empty list, you'll have an empty adapter. No need to treat it any differently.
final Context context = getActivity();
final MaterialBetterSpinner spinnerSoftener = new MaterialBetterSpinner(context);
spinnerSoftener.setId((View.generateViewId()));
spinnerSoftener.setHint("Softener");
spinnerSoftener.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
List<Mill_Softener_Type> softenerList = presenter.getSoftener();
if(softenerList != null)
{
int size = softenerList.size();
System.out.println("softener size: " + size);
spinnerSoftener.setAdapter(new ArrayAdapter<>(context, android.R.layout.simple_spinner_dropdown_item, softenerList));
spinnerSoftener.setEnabled(size > 0);
}
container.addView(spinnerSoftener);
And if you still get exceptions, then they are likely caused elsewhere in the code, whether that is in yours or in the library you are using.
I have 3 Radio buttons each radio buttons to do some performs, Using this Radio Buttons I am filtering my Results E.g for RB1 for DATE-WISE RB2 for customernames and RB3 for Productname.
Above two radio buttons working good(RB2 and RB3), but when I choose RB3(DATE-WISE) my Application Crashed.
final RadioGroup rgroup = (RadioGroup)findViewById(R.id.radioType);
final RadioButton Ta = (RadioButton)findViewById(R.id.type_a);
final RadioButton Tb = (RadioButton)findViewById(R.id.type_b);
final RadioButton Tc = (RadioButton)findViewById(R.id.type_c);
rgroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (rgroup.getCheckedRadioButtonId() == Ta.getId()) {
cus_names = listItems.get(cus_name.getSelectedItemPosition());
btn1.setVisibility(View.VISIBLE);
btn2.setVisibility(View.VISIBLE);
created_date1.setVisibility(View.VISIBLE);
created_date2.setVisibility(View.VISIBLE);
cus_name.setVisibility(View.GONE);
po_id.setVisibility(View.GONE);
}
else if (rgroup.getCheckedRadioButtonId() == Tb.getId()) {
cus_name.setSelection(0);
cus_name.setVisibility(View.VISIBLE);
btn1.setVisibility(View.GONE);
btn2.setVisibility(View.GONE);
created_date1.setVisibility(View.GONE);
created_date2.setVisibility(View.GONE);
po_id.setVisibility(View.GONE);
}
else if (rgroup.getCheckedRadioButtonId() == Tc.getId()) {
po_id.setSelection(0);
po_id.setVisibility(View.VISIBLE);
btn1.setVisibility(View.GONE);
btn2.setVisibility(View.GONE);
created_date1.setVisibility(View.GONE);
created_date2.setVisibility(View.GONE);
cus_name.setVisibility(View.GONE);
}
}
});
My Logcat:
07-28 11:47:53.243 13244-13244/com.example.Minal E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.Minal, PID: 13244
java.lang.ArrayIndexOutOfBoundsException: length=0; index=-1
at java.util.ArrayList.get(ArrayList.java:310)
at com.example.Minal.Purchase_Pending$1.onCheckedChanged(Purchase_Pending.java:180)
at android.widget.RadioGroup.setCheckedId(RadioGroup.java:173)
at android.widget.RadioGroup.-wrap0(RadioGroup.java)
at android.widget.RadioGroup$CheckedStateTracker.onCheckedChanged(RadioGroup.java:351)
at android.widget.CompoundButton.setChecked(CompoundButton.java:159)
at android.widget.CompoundButton.toggle(CompoundButton.java:115)
at android.widget.RadioButton.toggle(RadioButton.java:76)
at android.widget.CompoundButton.performClick(CompoundButton.java:120)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
In your case the reason is cus_name.getSelectedItemPosition() return -1 (it is not a index of your listItem) and your listItem size is 0.
So you should check both of it before get value for prevent ArrayIndexOutOfBoundsException like
if(cus_name.getSelectedItemPosition() > -1 && cus_name.getSelectedItemPosition() < listItems.size()){
cus_names = listItems.get(cus_name.getSelectedItemPosition());
}
Hope this help
You have written below line at wrong position, so whenever you will get empty list it will crash your app,
cus_names = listItems.get(cus_name.getSelectedItemPosition());
So try below code for all three condition not in onle,
if(listItmes != null & listItems.size() > 0)
cus_names = listItems.get(cus_name.getSelectedItemPosition());
This question already has answers here:
Proper way to avoid parseInt throwing a NumberFormatException for input string: ""
(7 answers)
Closed 6 years ago.
I've tried lot of things found here, but it keeps crashing. I wanna know what do i need to add in order to show a Toast message when button is clicked and EditText is empty.
INFO: The app is supposed to send the two values in the EditText's to another activity, showing Toast's in the following exceptions:the first value higher than 6; the second value higher than (firstvalue*14); and if the fields are empty (which is my problem)
Here's my code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView saludo_bienvenida;
EditText et1_creditos;
EditText et2_faltas;
Button boton_ingresar;
Button boton_info;
String numero_creditos;
String numero_faltas_actuales;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
saludo_bienvenida = (TextView) findViewById(R.id.saludo_bienvenida);
et1_creditos = (EditText) findViewById(R.id.edittext1_numero_creditos);
et2_faltas = (EditText) findViewById(R.id.edittext2_numero_faltas);
boton_ingresar = (Button) findViewById(R.id.boton_ingresar);
boton_info = (Button) findViewById(R.id.boton_info);
if (boton_ingresar != null) {
boton_ingresar.setOnClickListener(this);
}
if (boton_info != null) {
boton_info.setOnClickListener(this);
}
et1_creditos.setInputType(InputType.TYPE_CLASS_NUMBER);
et2_faltas.setInputType(InputType.TYPE_CLASS_NUMBER);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.boton_ingresar:
numero_creditos = et1_creditos.getText().toString();
numero_faltas_actuales = et2_faltas.getText().toString();
int numero_creditos1 = Integer.parseInt(numero_creditos);
int numero_faltas_actuales1 = Integer.parseInt(numero_faltas_actuales);
int o = numero_creditos1 * 14;
if (numero_creditos1>6) {
Toast.makeText(getApplicationContext(), "Ingrese un número válido de créditos", Toast.LENGTH_LONG).show();
}else if (numero_faltas_actuales1 > o){
Toast.makeText(getApplicationContext(), "El número de faltas ingresadas es mayor que el número de horas del curso", Toast.LENGTH_LONG).show();
}else{
Intent intent = new Intent(MainActivity.this,Resultados.class);
intent.putExtra("numero_creditos",numero_creditos);
intent.putExtra("numero_faltas_actuales",numero_faltas_actuales);
startActivity(intent);
}
break;
case R.id.boton_info:
Intent informacion = new Intent(MainActivity.this,Informacion.class);
startActivity(informacion);
break;
}
}
}
This is the log:
06-17 01:36:17.419 2738-2738/absence_counter.app.jorgepasco.com.absencecounter E/AndroidRuntime: FATAL EXCEPTION: main
Process: absence_counter.app.jorgepasco.com.absencecounter, PID: 2738
java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at absence_counter.app.jorgepasco.com.absencecounter.MainActivity.onClick(MainActivity.java:60)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
So thanks you for your log !
You can see on your log that you have a problem when you parseInt. You try to parseInt an empty String.
So when the user do not write anything, you have to set a default value yourself.
You can do something like that before your parse:
if(numero_creditos.equals(""))
numero_creditos = "0";
But if I were you, I would force the user to right directly an integer
Please, show us your log box.
Perhaps the app crash because you don't have any default case in your switch case. So if v.getId() is not what you think, it will crash.
Simply, add that at the end of your switch case:
switch(v.getId()){
case: ...
case: ...
default: Toast.makeText(getApplicationContext(),"v.getId = " + v.getId());
}
But I would be easier for me to solve your problem with your log box !
et1_creditos.getText() can maybe send a null value. Then null.toString() has no sense because null does not have toString().
try:
String creditos = et1_creditos.getText()
if(creditos != null){
//stuff here
}
It is failing on this line.
int numero_creditos1 = Integer.parseInt(numero_creditos);
If your numeor_creditos is empty it won't be integer.
Try
int numero_creditos1;
if(TextUtils.isEmpty(numero_creditos){
numero_creditos1 = 0;
} else {
numero_creditos1 = Integer.parseInt(numero_creditos);
}
I'm getting a "Error:(99, 95) error: local variable i is accessed from within inner class; needs to be declared final" for trying to use the "i" variable from a For loop in the OnClick method.
I tried to put this "i" inside a global variable but then I get a "ArrayIndexOutOfBoundsException".
But I can't think in another way to do so.
private void createTextViews(TextView[] textViewArray, LinearLayout linearLayout){
for (int i = 0; i < keys.length; i++) {
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(20, 0, 0, 20);
TextView newView = new TextView(getActivity());
newView.setLayoutParams(layoutParams);
newView.setText("Watch the Trailer " + (i + 1));
newView.setTextSize(22);
newView.setTextColor(getResources().getColor(R.color.words));
newView.setBackgroundColor(getResources().getColor(R.color.button));
newView.setHighlightColor(getResources().getColor(R.color.background));
newView.setPadding(5, 5, 5, 5);
newView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(YOUTUBE_URL+keys[i]));
startActivity(intent);
}
});
linearLayout.addView(newView);
textViewArray[i] = newView;
}
}
How can I do this?
--------------
EDIT
Here's the log for the ArrayIndexOutOfBoundsExeption:
11-03 01:08:13.866 32159-32159/app.com.example.android.popularmovies E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: app.com.example.android.popularmovies, PID: 32159
java.lang.ArrayIndexOutOfBoundsException: length=3; index=3
at app.com.example.android.popularmovies.Detail_ActivityFragment$1.onClick(Detail_ActivityFragment.java:99)
at android.view.View.performClick(View.java:4456)
at android.view.View$PerformClick.run(View.java:18465)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
you must init new final int value
add final int ex = i;
before setOnClickListener
and don't forget to change
Uri.parse(YOUTUBE_URL + keys[i]));
to
Uri.parse(YOUTUBE_URL + keys[ex]));
The reason you are getting the out of bound exception is because in the last loop you are i++ing although it is not entering the loop again but the i that is a class variable is now out of bound. So the whole approach of putting i as a class variable will not work in your case.
A way to achieve this is to actually save i in a tag in the view and then read that tag from the view that is clicked.
newView.setTag(i)
Then in the onClick
v.getTag()
above can be used to get the i