Unknown Error - Array Adapter - java

There is an error occurring in an app of mine when I set an Adapter to a ListView. Upon removing the 60/61 line of code (mainListViewTip/Hour.setAdapter(tip/hourAdapter);), the application runs perfectly, except since the adapter is never set, no data appears in the ListView. The goal is for the values of the EditText fields to become new values in the String to be displayed in a ListView along with previous entries also.
The TipBookActivity code:
public class TipBookActivity extends Activity {
/** Called when the activity is first created. */
TextView textTip,textHour,textWage;
EditText editHour,editTip;
float wage;
int precision = 100;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textTip = (TextView) findViewById(R.id.tvTip);
textHour = (TextView) findViewById(R.id.tvHour);
textWage = (TextView) findViewById(R.id.tvWage);
editTip = (EditText) findViewById(R.id.etTip);
editHour = (EditText) findViewById(R.id.etHour);
}
public void myClickHandler (View v){
Button bSubmit = (Button) findViewById(R.id.bSubmit);
bSubmit.isClickable();
ListView mainListViewTip = (ListView) findViewById(R.id.mainListViewTip);
ListView mainListViewHour = (ListView) findViewById(R.id.mainListViewHour);
switch(v.getId()){
case R.id.bSubmit:
if(bSubmit.isPressed()){
wage = Float.parseFloat(editTip.getText().toString()) / Float.parseFloat(editHour.getText().toString());
String tip = String.format("$%.2f",wage);
textWage.setText(String.valueOf(tip) + " an hour");
textHour.setText(editHour.getText() + " Hour(s)");
textTip.setText("$" + editTip.getText());
String[] sTip = new String[] {editTip.getText().toString()};
String[] sHour = new String[] {editHour.getText().toString()};
ArrayAdapter<String> tipAdapter = new ArrayAdapter<String>(TipBookActivity.this,R.layout.main,R.id.rowTextView,sTip);
ArrayAdapter<String> hourAdapter = new ArrayAdapter<String>(TipBookActivity.this,R.layout.main,R.id.rowTextView,sHour);
mainListViewTip.setAdapter(tipAdapter);
mainListViewHour.setAdapter(hourAdapter);
Toast displayWage = Toast.makeText(this, "$" + editTip.getText() + " over " + editHour.getText() + " hour(s) for a wage of $" + wage + " an hour.", Toast.LENGTH_LONG);
displayWage.show();
}
}
}
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
MenuInflater mMain = getMenuInflater();
mMain.inflate(R.menu.main_menu,menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
ViewFlipper vf = (ViewFlipper) findViewById(R.id.vfMain);
switch (item.getItemId()){
case R.id.menuHistory:
vf.setAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_in_right));
vf.showNext();
return true;
case R.id.menuClear:
//set up next tutorials
Toast displayClear = Toast.makeText(this, "Clear History feature coming soon.", Toast.LENGTH_SHORT);
displayClear.show();
return true;
case R.id.menuSettings:
Toast displaySettings = Toast.makeText(this, "Settings Options coming soon.", Toast.LENGTH_SHORT);
displaySettings.show();
return true;
}
return false;
}
public void onBackPressed() {
finish();
}
}
The main xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/llMain" >
<ViewFlipper
android:id="#+id/vfMain"
android:layout_height="match_parent"
android:layout_width="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/rletbtv">
<EditText
android:id="#+id/etTip"
android:layout_height="wrap_content"
android:layout_width="140dp"
android:hint="Tips"
android:layout_margin="8dp"
android:inputType="numberDecimal"
android:layout_alignParentLeft="true"/>
<EditText
android:id="#+id/etHour"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:hint="Hours"
android:layout_margin="8dp"
android:inputType="numberDecimal"
android:layout_alignParentRight="true"
android:layout_toRightOf="#id/etTip"/>
<Button
android:id="#+id/bSubmit"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_margin="8dp"
android:ems="10"
android:text="Submit"
android:textSize="22sp"
android:layout_below="#id/etTip"
android:onClick="myClickHandler"/>
<TextView
android:id="#+id/tvTip"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Tips"
android:textSize="22sp"
android:layout_margin="8dp"
android:layout_below="#id/bSubmit"/>
<TextView
android:id="#+id/tvHour"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Hours"
android:textSize="22sp"
android:layout_margin="8dp"
android:layout_below="#id/bSubmit"
android:layout_toRightOf="#id/tvTip"/>
<TextView
android:id="#+id/tvWage"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Wage"
android:textSize="22sp"
android:layout_margin="8dp"
android:layout_below="#id/bSubmit"
android:layout_toRightOf="#id/tvHour"/>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="50"
android:id="#+id/mainListViewTip"/>
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="50"
android:id="#+id/mainListViewHour"/>
</LinearLayout>
</ViewFlipper>
</LinearLayout>
The simplerow xml file:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rowTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp" />
The logcat error report:
FATAL EXCEPTION: main
java.lang.NullPointerException
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:353)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:323)
at android.widget.AbsListView.obtainView(AbsListView.java:1315)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1198)
at android.widget.ListView.onMeasure(ListView.java:1109)
at android.view.View.measure(View.java:8171)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1012)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:381)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
at android.view.View.measure(View.java:8171)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
at android.view.View.measure(View.java:8171)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1012)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:381)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
at android.view.View.measure(View.java:8171)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
at android.view.View.measure(View.java:8171)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:526)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
at android.view.View.measure(View.java:8171)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
at android.view.View.measure(View.java:8171)
at android.view.ViewRoot.performTraversals(ViewRoot.java:801)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)

The problem is because the layout you are passing to the ArrayAdapter is R.layout.main. This is not the resource you want to pass; you want to pass the layout for each individual list item. The layout you pass must have a TextView with a certain ID in it, and obviously R.layout.main does not have this.
Try substituting R.layout.main in those two lines to be android.R.layout.simple_list_item_1, and removing your custom TextView ID. That should solve the error and allow your list to display properly.
Like so:
ArrayAdapter<String> tipAdapter = new ArrayAdapter<String>(TipBookActivity.this,android.R.layout.simple_list_item_1,sTip);
ArrayAdapter<String> hourAdapter = new ArrayAdapter<String>(TipBookActivity.this,android.R.layout.simple_list_item_1,sHour);
If you later want to use a custom layout for the list items, try this tutorial or this one.

yes eric is right change this two lines of arrayadapter as shown below if you have not make layout for row item of listview
ArrayAdapter<String> tipAdapter = new ArrayAdapter<String>(TipBookActivity.this,R.layout.main,R.id.rowTextView,sTip);
ArrayAdapter<String> hourAdapter = new ArrayAdapter<String>(TipBookActivity.this,R.layout.main,R.id.rowTextView,sHour);
by
ArrayAdapter<String> tipAdapter = new ArrayAdapter<String>(TipBookActivity.this,android.R.layout.simple_list_item_1,sTip);
ArrayAdapter<String> hourAdapter = new ArrayAdapter<String>(TipBookActivity.this,android.R.layout.simple_list_item_1,sHour);

I think adam want to use his own textview so that he can change the text size and color which is not possible with "android.R.layout.simple_list_item_1". Instead of that we can use adam's "simplerow xml" file. to get this we need to replace 2 lines of the code
ArrayAdapter<String> tipAdapter = new ArrayAdapter<String>(TipBookActivity.this,R.layout.main,R.id.rowTextView,sTip);
ArrayAdapter<String> hourAdapter = new ArrayAdapter<String>(TipBookActivity.this,R.layout.main,R.id.rowTextView,sHour);
to
ArrayAdapter<String> tipAdapter = new ArrayAdapter<String>(TipBookActivity.this,R.layout.samplerow,R.id.rowTextView,sTip);
ArrayAdapter<String> hourAdapter = new ArrayAdapter<String>(TipBookActivity.this,R.layout.samplerow,R.id.rowTextView,sHour);
Note: the change is "R.layout.main" to "R.layout.samplerow"

Related

How To Change Font Size Based On Spinner Clicked

Before I explain to you, I told you, I've been searching in all of questions in stackoverflow and many webistes, so don't mark it duplicate or any negative acts. I've been stuck here more than 4 days.
I wanna change a font size based on spinner clicked. Every I click dropdown list spinner, it took me to java.lang.NullPointerException. Here you go:
MyAndroidAppActivity
public class MyAndroidAppActivity extends AppCompatActivity {
private Spinner spinner1, spinnerLatin;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//this line shows back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Display data
Spinner spinnerBackgroundChange = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> spinnerArrayAdapter = ArrayAdapter.createFromResource(this, R.array.country_arrays, android.R.layout.simple_spinner_item);
spinnerArrayAdapter.setDropDownViewResource(R.layout.textview_with_background);
spinnerBackgroundChange.setAdapter(spinnerArrayAdapter);
addListenerOnSpinnerItemSelection();
addListenerOnSpinner2ItemSelection();
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new SelectedListener());
}
public void addListenerOnSpinner2ItemSelection() {
spinnerLatin = (Spinner) findViewById(R.id.spinnerLatin);
spinnerLatin.setOnItemSelectedListener(new SelectedLatin());
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
} }
SelectedListener
public class SelectedListener implements OnItemSelectedListener {
public void onItemSelected (AdapterView <?> parent, View view, int pos, long id){
((TextView) view).setTextColor(Color.RED);
switch (pos) {
case 0:
TextView dgs = (TextView) view.findViewById(R.id.sizedoa);
dgs.setTextSize(30);
break;
case 1:
TextView dgf = (TextView) view.findViewById(R.id.fontLatin);
dgf.setTextSize(30);
break;
default:
//Default image
//image.setImageResource(R.drawable.item2);
break;
}
}
#Override
public void onNothingSelected (AdapterView <?> arg0){
// TODO Auto-generated method stub
} }
main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/reldoa"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="3dp"
android:background="#android:color/white"
android:orientation="vertical">
<TextView
android:id="#+id/sizedoa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:paddingBottom="10dp"
android:paddingLeft="15dp"
android:paddingTop="5dp"
android:text="Ukuran Font"
android:textColor="#222222"
android:textSize="18sp" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true" />
</RelativeLayout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/reldoa"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="3dp"
android:background="#android:color/white"
android:orientation="vertical">
<TextView
android:id="#+id/sizelatin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:paddingBottom="10dp"
android:paddingLeft="15dp"
android:paddingTop="5dp"
android:text="Jenis Font"
android:textColor="#222222"
android:textSize="18sp" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:entries="#array/type_arrays"
android:prompt="#string/type_font"/>
</RelativeLayout>
<!-- Font latin -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relLatin"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="35dp"
android:background="#android:color/white"
android:orientation="vertical">
<TextView
android:id="#+id/fontLatin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:paddingBottom="15dp"
android:paddingLeft="15dp"
android:paddingTop="15dp"
android:text="Font Latin"
android:textColor="#226169"
android:textSize="20sp" />
</RelativeLayout>
But, the problem lays here:
Error located here
And this is the result of error:
10-05 00:20:08.848 5035-5035/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at id.or.tauhid.doadandzikir.SelectedListener.onItemSelected(SelectedListener.java:32)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:892)
at android.widget.AdapterView.access$200(AdapterView.java:49)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:860)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Can you help me to fix the problem please? I've been stuck here 4 days.
In your listener, these lines are almost certainly wrong:
TextView dgs = (TextView) view.findViewById(R.id.sizedoa);
TextView dgf = (TextView) view.findViewById(R.id.fontLatin);
The view argument passed to this method is the view inside the spinner that was clicked, which means that calling view.findViewById() will only look inside (a portion of) the spinner itself. Presumably these views are in your Fragment's or Activity's layout, and not inside the spinner.
How you fix this will depend on exactly how your app is wired together, but one potential possibility is to cast the AdapterView's context to Activity and then find the views inside that:
Activity activity = (Activity) parent.getContext();
TextView dgs = activity.findViewById(R.id.sizedoa);

Error trying to call array string from other activity

This code is for call an array string from MainActivity.java class.
TextView infoEnviada;
infoEnviada = (TextView) findViewById(R.id.reslt);
String[] array = getIntent().getStringArrayExtra("resultados");
infoEnviada.setText(array);
}
The problem is in line infoEnviada.setText(array); because it says: Cannot resolve method setText(java.lang.String[]) I need help, because i want to call that string, and print it in a ListView or TextView, if it's possible.
Error log:
03-06 16:54:45.814 6978-6978/com.example.pablo.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.pablo.myapplication.encuesta$1.onClick(encuesta.java:59)
at android.view.View.performClick(View.java:4162)
at android.view.View$PerformClick.run(View.java:17088)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4867)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
at dalvik.system.NativeStart.main(Native Method)
On click event code:
Button sig = (Button) findViewById(R.id.env); // cargo el boton
sig.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = getApplicationContext();
EditText preg5 = (EditText) findViewById(R.id.editText2);
EditText preg4 = (EditText) findViewById(R.id.editText);
EditText nom = (EditText) findViewById(R.id.editText3);
Spinner cur = (Spinner) findViewById(R.id.spinnerp);
RadioGroup gruporadio = (RadioGroup) findViewById(R.id.Grupo1);
RadioGroup gruporadio2 = (RadioGroup) findViewById(R.id.Grupo2);
RadioGroup gruporadio3 = (RadioGroup) findViewById(R.id.Grupo3);
String strNombre = nom.getText().toString();
String curso = cur.getSelectedItem().toString();
String strPregCinco = preg5.getText().toString();
String strPregCuatro = preg4.getText().toString();
if(gruporadio.getCheckedRadioButtonId() == -1 || gruporadio2.getCheckedRadioButtonId() == -1 || gruporadio3.getCheckedRadioButtonId() == -1 )
{
Toast.makeText(context,"¡No marcaste ninguna respuesta!",Toast.LENGTH_LONG).show();
}
else if (strNombre.matches("") || strPregCinco.matches("") || strPregCuatro.matches(""))
{
Toast.makeText(context,"¡Dejaste campos vacíos!",Toast.LENGTH_LONG).show();
}
else
{
ListView listaresultados = (ListView) findViewById(R.id.reslt);
ArrayList respuestas = new ArrayList();
ArrayAdapter adaptador2 = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, respuestas);
listaresultados.setAdapter(adaptador2);
respuestas.add(strNombre);
respuestas.add(curso);
respuestas.add(strPregCuatro);
respuestas.add(strPregCinco);
Intent intent = new Intent (encuesta.this, res8.class);
intent.putExtra("resultados", respuestas);
startActivity(intent);
Intent pas = new Intent(encuesta.this, MainActivity.class);
Toast.makeText(context,"¡Encuesta enviada!",Toast.LENGTH_LONG).show();
startActivity(pas);
}
}
});
The error seems to be at line 59. But actually gruporadio, gruporadio2, and gruporadio3 exists.
RadioGroup gruporadio = (RadioGroup) findViewById(R.id.Grupo1);
RadioGroup gruporadio2 = (RadioGroup) findViewById(R.id.Grupo2);
RadioGroup gruporadio3 = (RadioGroup) findViewById(R.id.Grupo3);
<RadioGroup
android:id="#+id/Grupo1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/radioButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="1/2 hora a 1 hora" />
<RadioButton
android:id="#+id/radioButton1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="1 hora o 2 horas" />
<RadioButton
android:id="#+id/radioButton2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="2 horas o más" />
</RadioGroup>
<RadioGroup
android:id="#+id/Grupo2"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/radioButton3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="1/2 hora a 1 hora" />
<RadioButton
android:id="#+id/radioButton4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="1 hora o 2 horas" />
<RadioButton
android:id="#+id/radioButton5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="2 horas o más" />
</RadioGroup>
<RadioGroup
android:id="#+id/Grupo3"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/radioButton6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Norte de Bogotá (calle 72 en adelante)" />
<RadioButton
android:id="#+id/radioButton7"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Suba (noroccidente)" />
<RadioButton
android:id="#+id/radioButton8"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Centro - Chapinero - Teusaquillo" />
<RadioButton
android:id="#+id/radioButton9"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Alrededores de Bogotá" />
<RadioButton
android:id="#+id/radioButton10"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sur de Bogotá" />
<RadioButton
android:id="#+id/radioButton11"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Occidente (Puente Aranada - Fontibón - Engativá)" />
</RadioGroup>
The problem is in line infoEnviada.setText(array); because it says:
Cannot resolve method setText(java.lang.String[]) I need help, because
i want to call that string, and print it in a ListView or TextView, if
it's possible.
the error occurs because you're trying to pass an array to the setText(...) method which is not valid.
try this:
infoEnviada.setText(Arrays.toString(array))
the problem in your code is that settext method dosnt take arrays as parameter... pass the array as String instead
infoEnviada.setText(Arrays.toString(array));

java.lang.ClassCastException: android.widget.EditText

Here is my JAVA Code. When I run my app it crashes and i get following errors in my log
11-21 00:21:48.828: E/AndroidRuntime(349): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.geekosoft.contactsonline/com.geekosoft.contactsonline.AddContact}: java.lang.ClassCastException: android.widget.EditText
11-21 00:21:48.828: E/AndroidRuntime(349): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
11-21 00:21:48.828: E/AndroidRuntime(349): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
11-21 00:21:48.828: E/AndroidRuntime(349): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
11-21 00:21:48.828: E/AndroidRuntime(349): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
11-21 00:21:48.828: E/AndroidRuntime(349): at android.os.Handler.dispatchMessage(Handler.java:99)
11-21 00:21:48.828: E/AndroidRuntime(349): at android.os.Looper.loop(Looper.java:123)
11-21 00:21:48.828: E/AndroidRuntime(349): at android.app.ActivityThread.main(ActivityThread.java:3683)
11-21 00:21:48.828: E/AndroidRuntime(349): at java.lang.reflect.Method.invokeNative(Native Method)
11-21 00:21:48.828: E/AndroidRuntime(349): at java.lang.reflect.Method.invoke(Method.java:507)
11-21 00:21:48.828: E/AndroidRuntime(349): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-21 00:21:48.828: E/AndroidRuntime(349): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-21 00:21:48.828: E/AndroidRuntime(349): at dalvik.system.NativeStart.main(Native Method)
11-21 00:21:48.828: E/AndroidRuntime(349): Caused by: java.lang.ClassCastException: android.widget.EditText
11-21 00:21:48.828: E/AndroidRuntime(349): at com.geekosoft.contactsonline.AddContact.initilizeEditContactInfo(AddContact.java:123)
11-21 00:21:48.828: E/AndroidRuntime(349): at com.geekosoft.contactsonline.AddContact.initilize(AddContact.java:68)
11-21 00:21:48.828: E/AndroidRuntime(349): at com.geekosoft.contactsonline.AddContact.onCreate(AddContact.java:42)
11-21 00:21:48.828: E/AndroidRuntime(349): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-21 00:21:48.828: E/AndroidRuntime(349): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
and here is my Java code
package com.geekosoft.contactsonline;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TableLayout;
public class AddContact extends Activity implements OnClickListener {
public static final String TAG = AddContact.class.getSimpleName();
ArrayList contactPhoneTypes, contactEmailTypes, contactIMTypes, contactAddressTypes;
String contactid;
int phoneNumbersIdStarter, emailIdStarter, imIdStarter, addressIdStarter;
LayoutInflater layoutInflater;
EditText name, number;
Spinner phoneType, emailType, addressType;
Button addPhoneField, addEmailField, addIMField, addAddressField;
TableLayout phoneFiledsCont, emailFiledsCont, imFiledsCont, addressFiledsCont;
#Override
protected void onCreate (Bundle contactsOnline) {
super.onCreate(contactsOnline);
setContentView(R.layout.add_contact);
initilize();
}
public void initilize () {
initilizeSpinnerTypes();
phoneNumbersIdStarter = 1000;
emailIdStarter = 2000;
imIdStarter = 3000;
addressIdStarter = 4000;
layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
name = (EditText) findViewById(R.id.etContactName);
addPhoneField = (Button) findViewById(R.id.bAddPhoneField);
addEmailField = (Button) findViewById(R.id.bAddEmailField);
addIMField = (Button) findViewById(R.id.bAddIMField);
addAddressField = (Button) findViewById(R.id.bAddaddressField);
phoneFiledsCont = (TableLayout) findViewById(R.id.tlPhoneFiledCont);
emailFiledsCont = (TableLayout) findViewById(R.id.tlEmailFiledsCont);
imFiledsCont = (TableLayout) findViewById(R.id.tlIMFiledsCont);
addressFiledsCont = (TableLayout) findViewById(R.id.tlAddressFiledsCont);
addPhoneField.setOnClickListener(this);
addEmailField.setOnClickListener(this);
addIMField.setOnClickListener(this);
addAddressField.setOnClickListener(this);
initilizeEditContactInfo();
}
public void initilizeSpinnerTypes() {
contactPhoneTypes = new ArrayList();
contactPhoneTypes.add(ContactsContract.CommonDataKinds.Phone.TYPE_HOME);
contactPhoneTypes.add(ContactsContract.CommonDataKinds.Phone.TYPE_WORK);
contactPhoneTypes.add(ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
contactPhoneTypes.add(ContactsContract.CommonDataKinds.Phone.TYPE_OTHER);
// contactPhoneTypes.add(ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM);
contactEmailTypes = new ArrayList();
contactEmailTypes.add(ContactsContract.CommonDataKinds.Email.TYPE_HOME);
contactEmailTypes.add(ContactsContract.CommonDataKinds.Email.TYPE_WORK);
contactEmailTypes.add(ContactsContract.CommonDataKinds.Email.TYPE_MOBILE);
contactEmailTypes.add(ContactsContract.CommonDataKinds.Email.TYPE_OTHER);
contactIMTypes = new ArrayList();
contactIMTypes.add(ContactsContract.CommonDataKinds.Im.TYPE_HOME);
contactIMTypes.add(ContactsContract.CommonDataKinds.Im.TYPE_WORK);
contactIMTypes.add(ContactsContract.CommonDataKinds.Im.TYPE_OTHER);
contactAddressTypes = new ArrayList();
contactAddressTypes.add(ContactsContract.CommonDataKinds.SipAddress.TYPE_HOME);
contactAddressTypes.add(ContactsContract.CommonDataKinds.SipAddress.TYPE_WORK);
contactAddressTypes.add(ContactsContract.CommonDataKinds.SipAddress.TYPE_OTHER);
}
public void initilizeEditContactInfo () {
contactid = getIntent().getStringExtra("contactId");
Log.d(TAG, "id = "+contactid);
Log.d(TAG, "query = "+ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
ContentResolver cr = getContentResolver();
Cursor contact = cr.query(ContactsContract.Contacts.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone._ID+" = ?",new String[]{contactid}, "DISPLAY_NAME ASC");
// Cursor contacts = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
if (contact.getCount() > 0) {
contact.moveToFirst();
String name = contact.getString(contact.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
Log.d(TAG, "name = "+name);
this.name.setText(name);
int loopCounter = 0;
if (Integer.parseInt(contact.getString(contact.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID+" = ?",new String[]{contactid}, null);
while (phones.moveToNext()) {
loopCounter++;
int phoneType = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.d(TAG, "phone = "+phoneNumber);
addTextField("phone");
EditText phoneNumberField = (EditText) findViewById(8084+phoneNumbersIdStarter);
phoneNumberField.setText(phoneNumber);
Log.d("Spinner Getting", "Spinner Id = " + (8083+phoneNumbersIdStarter));
Spinner phoneNumberSpinner = (Spinner) findViewById(8083+phoneNumbersIdStarter);
Log.d("After Spinner", "phone counter = " + phoneNumbersIdStarter);
switch (phoneType) {
case Phone.TYPE_MOBILE:
// phoneNumberSpinner.setSelection(2, false);
break;
case Phone.TYPE_HOME:
// phoneNumberSpinner.setSelection(0, false);
String phoneTypesCodes = "home = "+Phone.TYPE_HOME+"mobile = "+Phone.TYPE_MOBILE+"work = "+Phone.TYPE_WORK
+"other = "+Phone.TYPE_OTHER;
Log.d(name + "(home number)", phoneNumber + phoneTypesCodes);
break;
case Phone.TYPE_WORK:
// phoneNumberSpinner.setSelection(1, false);
break;
case Phone.TYPE_OTHER:
// phoneNumberSpinner.setSelection(3, false);
break;
}
}
phones.close();
}
}
contact.close();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bAddPhoneField:
addTextField("phone");
break;
case R.id.bAddEmailField:
addTextField("email");
break;
case R.id.bAddIMField:
addTextField("im");
break;
case R.id.bAddaddressField:
addTextField("address");
break;
}
}
public void addTextField(String fieldType) {
// for text field code is 84
// for spinner code is 83
if (fieldType.equals("phone")) {
// for phone number code is 80
phoneNumbersIdStarter++;
View view = layoutInflater.inflate(R.layout.add_phone_row, null);
EditText phoneNumberField = (EditText) view.findViewById(R.id.etContactPhone);
Spinner phoneTypeSpinner = (Spinner) view.findViewById(R.id.sContactPhoneType);
Log.d(TAG, "spinner id = " + phoneTypeSpinner.getId());
phoneNumberField.setId(8084+phoneNumbersIdStarter);
phoneTypeSpinner.setId(8083+phoneNumbersIdStarter);
Log.d("Spinner Created", "Spinner Id = " + phoneTypeSpinner.getId());
setSpinnerValues(phoneTypeSpinner, "phone");
phoneFiledsCont.addView(view);
} else if (fieldType.equals("email")) {
// for email code is 69
emailIdStarter++;
View view = layoutInflater.inflate(R.layout.add_email_row, null);
EditText emailAddressField = (EditText) view.findViewById(R.id.etContactEmail);
Spinner emailTypeSpinner = (Spinner) view.findViewById(R.id.sContactEmailType);
emailAddressField.setId(6984+emailIdStarter);
emailTypeSpinner.setId(6983+emailIdStarter);
Log.d(TAG, "inside true");
setSpinnerValues(emailTypeSpinner, "email");
Log.d(TAG, "inside true 2");
emailFiledsCont.addView(view);
} else if (fieldType.equals("im")) {
// for address code is 65
imIdStarter++;
View view = layoutInflater.inflate(R.layout.add_im_row, null);
EditText imField = (EditText) view.findViewById(R.id.etContactIM);
Spinner imTypeSpinner = (Spinner) view.findViewById(R.id.sContactIMType);
imField.setId(6584+imIdStarter);
imTypeSpinner.setId(6583+imIdStarter);
setSpinnerValues(imTypeSpinner, "im");
imFiledsCont.addView(view);
} else if (fieldType.equals("address")) {
// for im code is 73
addressIdStarter++;
View view = layoutInflater.inflate(R.layout.add_address_row, null);
EditText addressField = (EditText) view.findViewById(R.id.etContactAddress);
Spinner addressTypeSpinner = (Spinner) view.findViewById(R.id.sContactAddressType);
addressField.setId(7384+addressIdStarter);
addressTypeSpinner.setId(7383+addressIdStarter);
setSpinnerValues(addressTypeSpinner, "address");
addressFiledsCont.addView(view);
}
}
public void setSpinnerValues (Spinner spinner, String spinnerType) {
ArrayAdapter spinnerAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Iterator iter = null;
if (spinnerType.equals("phone")) {
iter = contactPhoneTypes.iterator();
} else if (spinnerType.equals("email")) {
iter = contactEmailTypes.iterator();
} else if (spinnerType.equals("im")) {
iter = contactIMTypes.iterator();
} else if (spinnerType.equals("address")) {
iter = contactAddressTypes.iterator();
}
while (iter.hasNext()) {
if (spinnerType.equals("phone")) {
spinnerAdapter.add(ContactsContract.CommonDataKinds.Phone.getTypeLabel(this.getResources(), iter.next(), getString(R.string.undefinedTypeLabel)).toString());
} else if (spinnerType.equals("email")) {
spinnerAdapter.add(ContactsContract.CommonDataKinds.Email.getTypeLabel(this.getResources(), iter.next(), getString(R.string.undefinedTypeLabel)).toString());
} else if (spinnerType.equals("im")) {
spinnerAdapter.add(ContactsContract.CommonDataKinds.Im.getTypeLabel(this.getResources(), iter.next(), getString(R.string.undefinedTypeLabel)).toString());
} else if (spinnerType.equals("address")) {
spinnerAdapter.add(ContactsContract.CommonDataKinds.Im.getTypeLabel(this.getResources(), iter.next(), getString(R.string.undefinedTypeLabel)).toString());
}
}
spinner.setAdapter(spinnerAdapter);
spinner.setPrompt(getString(R.string.selectLabel));
}
}
here is my add_contact.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="wrap_content">
<TableLayout
android:layout_width="fill_parent" android:layout_height="wrap_content">
<TableRow>
<TextView android:text="Target Account"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<Spinner android:id="#+id/accountSpinner"
android:layout_height="wrap_content" android:layout_width="fill_parent"
android:layout_weight="1" />
</TableRow>
<TableRow>
<TextView android:text="Contact Name"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<EditText android:id="#+id/etContactName"
android:layout_height="wrap_content" android:layout_width="wrap_content"
android:layout_weight="1"/>
</TableRow>
<TableRow>
<TextView android:text="Contact Phone"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</TableRow>
<TableRow>
<Button android:id="#+id/bAddPhoneField"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Add Field"/>
</TableRow>
</TableLayout>
<TableLayout android:id="#+id/tlPhoneFiledCont"
android:layout_width="fill_parent" android:layout_height="wrap_content">
</TableLayout>
<TableLayout
android:layout_width="fill_parent" android:layout_height="wrap_content">
<TableRow>
<TextView android:text="Contact Email"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</TableRow>
</TableLayout>
<Button android:id="#+id/bAddEmailField"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Add Field"/>
<TableLayout android:id="#+id/tlEmailFiledsCont"
android:layout_width="fill_parent" android:layout_height="wrap_content">
</TableLayout>
<TextView android:text="Contact IM"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<Button android:id="#+id/bAddIMField"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Add Field"/>
<TableLayout android:id="#+id/tlIMFiledsCont"
android:layout_width="fill_parent" android:layout_height="wrap_content">
</TableLayout>
<TextView android:text="Contact Address"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<Button android:id="#+id/bAddaddressField"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Add Field"/>
<TableLayout android:id="#+id/tlAddressFiledsCont"
android:layout_width="fill_parent" android:layout_height="wrap_content">
</TableLayout>
<TableLayout
android:layout_width="fill_parent" android:layout_height="wrap_content">
<TableRow>
<Button android:text="#string/save"
android:layout_height="wrap_content" android:layout_width="fill_parent"
android:id="#+id/contactSaveButton" android:layout_weight="1"/>
</TableRow>
</TableLayout>
</LinearLayout>
</ScrollView>
and here is my add_phone_row.xml
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent" >
<EditText android:id="#+id/etContactPhone"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_weight="1" android:inputType="phone" />
<Spinner android:id="#+id/sContactPhoneType"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
</TableRow>
I am creating Spinner and EditText dynamically in bellow fucntion
if (fieldType.equals("phone")) {
// for phone number code is 80
phoneNumbersIdStarter++;
View view = layoutInflater.inflate(R.layout.add_phone_row, null);
EditText phoneNumberField = (EditText) view.findViewById(R.id.etContactPhone);
Spinner phoneTypeSpinner = (Spinner) view.findViewById(R.id.sContactPhoneType);
Log.d(TAG, "spinner id = " + phoneTypeSpinner.getId());
phoneNumberField.setId(8084+phoneNumbersIdStarter);
phoneTypeSpinner.setId(8083+phoneNumbersIdStarter);
Log.d("Spinner Created", "Spinner Id = " + phoneTypeSpinner.getId());
setSpinnerValues(phoneTypeSpinner, "phone");
phoneFiledsCont.addView(view);
}
and getting their values like below lines
EditText phoneNumberField = (EditText) findViewById(8084+phoneNumbersIdStarter);
Spinner phoneNumberSpinner = (Spinner) findViewById(8083+phoneNumbersIdStarter);
and each time i add these fields also add 1 in phoneNumbersIdStarter
if I comment the following line in my code it runs great
Spinner phoneNumberSpinner = (Spinner) findViewById(8083+phoneNumbersIdStarter);
Do you have some specific reason to not access the widgets using R.id.?
I don't think a good idea to use "8083+phoneNumbersIdStarter", because the int id which is generated in class R will change in each compilation, so probably the int 8083+phoneNumbersIdStarter is referring to a widget which is not an EditText.
So, change to something like this:
Spinner phoneNumberSpinner = (Spinner) findViewById(R.id.your_spinner_id);
I found error by myself. Error was because of id confliction. Because I was adding 1 in phoneNumbersIdStarter on click of Add Phone Button. So my EditText ID starer was 8084+phoneNumbersIdStarter and Spinner ID starter 8083+phoneNumbersIdStarter thats why Spinnner was conflicting with EditText when creating fields second time.
Solved error by changing Spinner ID starter from 8083+phoneNumbersIdStarter to 9083+phoneNumbersIdStarter as shown below now it is working great.
EditText phoneNumberField = (EditText) findViewById(8084+phoneNumbersIdStarter);
Spinner phoneNumberSpinner = (Spinner) findViewById(9083+phoneNumbersIdStarter);

GridView.FATAL EXCEPTION: main android.content.res.Resources$NotFoundException: String resource ID #0x0

I want that when I click on an element of GridView displayed letter, which I clicked. But initially I got here error when I wanted to take the position of the element. If I understood correctly, gridview does not see the textview, but i don't know why.
Error:
5312-5312/standandroid.ru.words E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.content.res.Resources.getText(Resources.java:240)
at android.content.res.MiuiResources.getText(MiuiResources.java:131)
at android.widget.Toast.makeText(Toast.java:273)
at standandroid.ru.words.MainActivity$1$1.onItemClick(MainActivity.java:70)
at android.widget.AdapterView.performItemClick(AdapterView.java:298)
at android.widget.AbsListView.performItemClick(AbsListView.java:1130)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2818)
at android.widget.AbsListView$1.run(AbsListView.java:3498)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5137)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:756)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:572)
at miui.dexspy.DexspyInstaller.main(DexspyInstaller.java:171)
at dalvik.system.NativeStart.main(Native Method)
MainActivity.java :
public class MainActivity extends Activity {
TextView txt, textTV;
EditText etxt;
Button btn;
ArrayAdapter<String> adapter;
GridView gridView;
String name;
char c;
ArrayList arrayList=new ArrayList();
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView) findViewById(R.id.textView);
etxt = (EditText) findViewById(R.id.editText);
btn = (Button) findViewById(R.id.button);
textTV = (TextView) findViewById(R.id.tv);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = etxt.getText().toString();
TreeSet list = new TreeSet();
for (i = 0; i < name.length(); i++) {
c = name.charAt(i);
list.add(c);
}
arrayList = new ArrayList(list);
adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.item, R.id.tv, arrayList);
gridView = (GridView) findViewById(R.id.gridmain);
gridView.setAdapter(adapter);
ViewGrid();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, position,Toast.LENGTH_LONG).show();
}
});
}
});}
private void ViewGrid(){
gridView.setNumColumns(4);
gridView.setStretchMode(GridView.STRETCH_COLUMN_WIDTH); }}
activity_main.xml:
<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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textView"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="175dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:singleLine="true"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="48dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="44dp" />
<GridView
android:id="#+id/gridmain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="44dp"
android:layout_alignTop="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"></GridView>
</RelativeLayout>
item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tv"
android:textSize="40sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
http://i.stack.imgur.com/j5S93.png
Ohh! I see, the issue is that Toast is thinking of position as a resourceID. If you see Toast specs here, you would see that you can define resourceId or a CharSequence. So make sure you are passing the position as a String. Something like:
Toast.makeText(MainActivity.this, String.valueOf(position),Toast.LENGTH_LONG).show();

Populate spinner with key value pair in android fragment

I am trying to create a spinner with key value pair in fragment. I am getting this logcat output:
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ica.icadashboard/com.ica.icadashboard.HomeActivity}: java.lang.NullPointerException
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
android.app.ActivityThread.access$600(ActivityThread.java:141)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
android.os.Handler.dispatchMessage(Handler.java:99)
android.os.Looper.loop(Looper.java:137)
android.app.ActivityThread.main(ActivityThread.java:5041)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:511)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
dalvik.system.NativeStart.main(Native Method)
05-20 08:06:36.247: E/AndroidRuntime(2746): Caused by: java.lang.NullPointerException
android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
android.widget.ArrayAdapter.<init>(ArrayAdapter.java:128)
com.ica.placement.PlacementFragment.setSpinnerContent(PlacementFragment.java:44)
com.ica.placement.PlacementFragment.onCreateView(PlacementFragment.java:29)
android.app.Fragment.performCreateView(Fragment.java:1695)
android.app.FragmentManagerImpl.moveToState(FragmentManager.java:885)
android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1057)
android.app.BackStackRecord.run(BackStackRecord.java:682)
android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
android.app.Activity.performStart(Activity.java:5113)
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2153)
05-20 08:06:36.247: E/AndroidRuntime(2746): ... 11 more
The fragment class:
public class PlacementFragment extends Fragment {
Spinner adm_spinner;
Activity activity;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_placement, container, false);
// Now use the above view to populate the spinner.
setSpinnerContent( view );
return container;
}
private void setSpinnerContent( View view )
{
adm_spinner = (Spinner) view.findViewById( R.id.adm_spinner );
final MyData items[] = new MyData[4];
for (int i = 0; i <= 3; i++) {
items[i] = new MyData("value " + i, "" + i);
}
ArrayAdapter<MyData> adapter = new ArrayAdapter<MyData>(activity,
android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adm_spinner.setAdapter(adapter);
// spinner.setAdapter( adapter );
}
class MyData {
public MyData(String spinnerText, String value) {
this.spinnerText = spinnerText;
this.value = value;
}
public String getSpinnerText() {
return spinnerText;
}
public String getValue() {
return value;
}
public String toString() {
return spinnerText;
}
String spinnerText;
String value;
}
}
The layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Placement Analysis"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:paddingTop="5dp" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1" >
<Spinner
android:id="#+id/tp_spinner"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".5" />
<Spinner
android:id="#+id/adm_spinner"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".5" />
</LinearLayout>
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1" >
<Spinner
android:id="#+id/centre_spinner"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".5" />
<Spinner
android:id="#+id/vertical_spinner"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".5" />
</LinearLayout>
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1" >
<Button
android:id="#+id/calendar_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calendar" />
<Button
android:id="#+id/process_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Process" />
</LinearLayout>
</TableRow>
</TableLayout>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
What is the problem? Where am I going wrong? How should I populate the spinner?
You should
return view;
instead of
return container;
in your onCreateView(.....) in PlacementFragment
also change this
ArrayAdapter<MyData> adapter = new ArrayAdapter<MyData>(activity,
android.R.layout.simple_spinner_item, items);
to
ArrayAdapter<MyData> adapter = new ArrayAdapter<MyData>(getActivity(),
android.R.layout.simple_spinner_item, items);
Caused by: java.lang.NullPointerException
android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
Apart form the other answer you need to change to
ArrayAdapter<MyData> adapter = new ArrayAdapter<MyData>(getActivity(),
android.R.layout.simple_spinner_item, items);
Activity activity; activity is not initialized.
Try this..
You have not initialize Activity activity initialize it as
activity = getActivity();

Categories