Display random month from a button click on android? - java

I am trying to create an app that lets the user click a button and it will display a random month. I have created a string array in my strings.xml file. Bellow is my main.java, strings.xml and activity.xml. I try to run the app and it just force closes.
package com.example.datebutton;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.graphics.Color;
public class Main extends Activity
{
Button btn;
#Override
public void onCreate(Bundle b)
{
super.onCreate(b);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn1);
final String[] months = getResources().getStringArray(R.array.Months);
final TextView tv =(TextView)findViewById(R.id.text1);
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
int rand = (int) (Math.random() * 12);
tv.setText(months[rand]);
}
});
}
}
here is my activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="#+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="updateMonth"
android:text="#string/app_name" />
<TextView
android:id="#+id/text1"
android:layout_width="68dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_vertical"
android:text="#array/Months" />
</LinearLayout>
here is my strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">DateButton</string>
<string-array name="Months">
<item>January</item>
<item>Feburary</item>
<item>March</item>
<item>April</item>
<item>May</item>
<item>June</item>
<item>July</item>
<item>August</item>
<item>September</item>
<item>October</item>
<item>November</item>
<item>December</item>
</string-array>
</resources>
I'm still getting errors and the app still says unfortunately your app closed. The logcat is below.
09-11 16:55:17.472: W/Resources(1638): Converting to string: TypedValue{t=0x1/d=0x7f0c0000 a=-1 r=0x7f0c0000}
09-11 16:55:17.512: D/AndroidRuntime(1638): Shutting down VM
09-11 16:55:17.512: W/dalvikvm(1638): threadid=1: thread exiting with uncaught exception (group=0xb3a8fba8)
09-11 16:55:17.532: E/AndroidRuntime(1638): FATAL EXCEPTION: main
09-11 16:55:17.532: E/AndroidRuntime(1638): Process: com.example.datebutton, PID: 1638
09-11 16:55:17.532: E/AndroidRuntime(1638): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.datebutton/com.example.datebutton.Main}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.Button
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.ActivityThread.access$800(ActivityThread.java:135)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.os.Handler.dispatchMessage(Handler.java:102)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.os.Looper.loop(Looper.java:136)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.ActivityThread.main(ActivityThread.java:5017)
09-11 16:55:17.532: E/AndroidRuntime(1638): at java.lang.reflect.Method.invokeNative(Native Method)
09-11 16:55:17.532: E/AndroidRuntime(1638): at java.lang.reflect.Method.invoke(Method.java:515)
09-11 16:55:17.532: E/AndroidRuntime(1638): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
09-11 16:55:17.532: E/AndroidRuntime(1638): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
09-11 16:55:17.532: E/AndroidRuntime(1638): at dalvik.system.NativeStart.main(Native Method)
09-11 16:55:17.532: E/AndroidRuntime(1638): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.Button
09-11 16:55:17.532: E/AndroidRuntime(1638): at com.example.datebutton.Main.onCreate(Main.java:24)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.Activity.performCreate(Activity.java:5231)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
09-11 16:55:17.532: E/AndroidRuntime(1638): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
09-11 16:55:17.532: E/AndroidRuntime(1638): ... 11 more

You forgot to add the line: setContentView(R.layout.activity); before trying to instantiate your button object btn.

To use layout in you Activity you have to connect them both together. Below is how your code should look like:
#Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity);
btn = (Button) findViewById(R.id.btn1);
final String[] months = getResources().getStringArray(R.array.Months);
final TextView tv =(TextView)findViewById(R.id.text1);
btn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
int r, g, b;
int rand = (int) (Math.random() * 12);
tv.setText(months[rand]);
}
});
}

Related

.com.process stopped unexpectedly in Android emulator and mobile

I am trying to make a simple android app that will add two numbers and display the output.However, I am getting the following error continuously.
"calculator.com.process stopped unexpectedly"
I used API 10 for rendering layout and API 17 as compiler and Target SDK.
Could post the code finally after all these trouble.
This is the code of main_activity.java
package com.example.calculator;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
EditText txtNum1;
EditText txtNum2;
TextView Display;
Button bCal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtNum1=(EditText) findViewById(R.id.Num1);
txtNum1=(EditText) findViewById(R.id.Num2);
Display=(TextView)findViewById(R.id.tvDisplay);
bCal=(Button)findViewById(R.id.bAdd);
bCal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View Tawfiq) {
// TODO Auto-generated method stub
double x=Double.parseDouble(txtNum1.getText().toString());
double y=Double.parseDouble(txtNum2.getText().toString());
double total=x+y;
Display.setText("Sum is"+total);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The xml code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/bAdd"
android:layout_width="match_parent"
android:layout_height="match_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"
tools:context="com.example.calculator.MainActivity" >
<EditText
android:id="#+id/Num1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:ems="10"
android:inputType="numberDecimal" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/Num2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Num1"
android:layout_below="#+id/Num1"
android:layout_marginTop="33dp"
android:ems="10"
android:inputType="numberDecimal" />
<Button
android:id="#+id/bAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvDisplay"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Button" />
<TextView
android:id="#+id/tvDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Num2"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="Sum"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
This is the logcat.
01-24 16:06:39.840: D/AndroidRuntime(1130): Shutting down VM
01-24 16:06:39.870: W/dalvikvm(1130): threadid=1: thread exiting with uncaught exception (group=0xb60164f0)
01-24 16:06:39.950: E/AndroidRuntime(1130): FATAL EXCEPTION: main
01-24 16:06:39.950: E/AndroidRuntime(1130): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.calculator/com.example.calculator.MainActivity}: java.lang.ClassCastException: android.widget.RelativeLayout
01-24 16:06:39.950: E/AndroidRuntime(1130): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
01-24 16:06:39.950: E/AndroidRuntime(1130): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
01-24 16:06:39.950: E/AndroidRuntime(1130): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
01-24 16:06:39.950: E/AndroidRuntime(1130): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
01-24 16:06:39.950: E/AndroidRuntime(1130): at android.os.Handler.dispatchMessage(Handler.java:99)
01-24 16:06:39.950: E/AndroidRuntime(1130): at android.os.Looper.loop(Looper.java:130)
01-24 16:06:39.950: E/AndroidRuntime(1130): at android.app.ActivityThread.main(ActivityThread.java:3683)
01-24 16:06:39.950: E/AndroidRuntime(1130): at java.lang.reflect.Method.invokeNative(Native Method)
01-24 16:06:39.950: E/AndroidRuntime(1130): at java.lang.reflect.Method.invoke(Method.java:507)
01-24 16:06:39.950: E/AndroidRuntime(1130): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-24 16:06:39.950: E/AndroidRuntime(1130): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-24 16:06:39.950: E/AndroidRuntime(1130): at dalvik.system.NativeStart.main(Native Method)
01-24 16:06:39.950: E/AndroidRuntime(1130): Caused by: java.lang.ClassCastException: android.widget.RelativeLayout
01-24 16:06:39.950: E/AndroidRuntime(1130): at com.example.calculator.MainActivity.onCreate(MainActivity.java:27)
01-24 16:06:39.950: E/AndroidRuntime(1130): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-24 16:06:39.950: E/AndroidRuntime(1130): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
01-24 16:06:39.950: E/AndroidRuntime(1130): ... 11 more
You are having problem at line no-27
Caused by: java.lang.ClassCastException: android.widget.RelativeLayout
01-24 16:06:39.950: E/AndroidRuntime(1130): at com.example.calculator.MainActivity.onCreate(MainActivity.java:27)
Change the relativeLayouts Id in the xml file.
It should not be same as for the add button.
android:id="#+id/relativeLayout"
Change it as above.
Two id in the same layout cannot be same.
Your add button and the relative layout is having the same id,.
And during the findViewById(), relative layout is being caste in the Button.
That's why class cast exception is coming.
Edit:
I compiled your code:-
the next mistake you have made is-
txtNum1=(EditText) findViewById(R.id.Num2);
It should be
txtNum2=(EditText) findViewById(R.id.Num2);
Mistake-You are not assigning the reference to the second edittext.

OnCreate forces activities crash: ImageButton ClassCastException

I am trying to define buttons, something like setOnClickListener. I do that in the OnCreate method and when I run my code on android emulator it throws errors.
package com.example.yyy;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import android.os.Build;
public class MainActivity extends ActionBarActivity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
Button start = (Button)findViewById(R.id.start);
start.setOnClickListener(this);
Button hs =(Button)findViewById(R.id.hs);
hs.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v)
{
switch(v.getId())
{
case R.id.start:
Intent find = new Intent(this, Find.class);
startActivity(find);
break;
case R.id.hs:
Toast t = Toast.makeText(this, "w8", Toast.LENGTH_SHORT);
t.show();
break;
default: break;
}
}
}
This is LogCat of this application.
03-19 21:53:13.063: D/dalvikvm(1242): GC_FOR_ALLOC freed 67K, 5% free 3046K/3188K, paused 80ms, total 84ms
03-19 21:53:13.103: I/dalvikvm-heap(1242): Grow heap (frag case) to 4.937MB for 1987216-byte allocation
03-19 21:53:13.233: D/dalvikvm(1242): GC_FOR_ALLOC freed 2K, 3% free 4984K/5132K, paused 127ms, total 127ms
03-19 21:53:14.993: D/AndroidRuntime(1242): Shutting down VM
03-19 21:53:14.993: W/dalvikvm(1242): threadid=1: thread exiting with uncaught exception (group=0xb1a63ba8)
03-19 21:53:15.003: E/AndroidRuntime(1242): FATAL EXCEPTION: main
03-19 21:53:15.003: E/AndroidRuntime(1242): Process: com.example.yyy, PID: 1242
03-19 21:53:15.003: E/AndroidRuntime(1242): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.yyy/com.example.yyy.MainActivity}: java.lang.ClassCastException: android.widget.ImageButton cannot be cast to android.widget.Button
03-19 21:53:15.003: E/AndroidRuntime(1242): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
03-19 21:53:15.003: E/AndroidRuntime(1242): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
03-19 21:53:15.003: E/AndroidRuntime(1242): at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-19 21:53:15.003: E/AndroidRuntime(1242): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-19 21:53:15.003: E/AndroidRuntime(1242): at android.os.Handler.dispatchMessage(Handler.java:102)
03-19 21:53:15.003: E/AndroidRuntime(1242): at android.os.Looper.loop(Looper.java:136)
03-19 21:53:15.003: E/AndroidRuntime(1242): at android.app.ActivityThread.main(ActivityThread.java:5017)
03-19 21:53:15.003: E/AndroidRuntime(1242): at java.lang.reflect.Method.invokeNative(Native Method)
03-19 21:53:15.003: E/AndroidRuntime(1242): at java.lang.reflect.Method.invoke(Method.java:515)
03-19 21:53:15.003: E/AndroidRuntime(1242): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-19 21:53:15.003: E/AndroidRuntime(1242): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-19 21:53:15.003: E/AndroidRuntime(1242): at dalvik.system.NativeStart.main(Native Method)
03-19 21:53:15.003: E/AndroidRuntime(1242): Caused by: java.lang.ClassCastException: android.widget.ImageButton cannot be cast to android.widget.Button
03-19 21:53:15.003: E/AndroidRuntime(1242): at com.example.yyy.MainActivity.onCreate(MainActivity.java:28)
03-19 21:53:15.003: E/AndroidRuntime(1242): at android.app.Activity.performCreate(Activity.java:5231)
03-19 21:53:15.003: E/AndroidRuntime(1242): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-19 21:53:15.003: E/AndroidRuntime(1242): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
03-19 21:53:15.003: E/AndroidRuntime(1242): ... 11 more
03-19 21:53:25.683: I/Process(1242): Sending signal. PID: 1242 SIG: 9
And this is main layout.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
tools:context="com.example.yyy.MainActivity"
tools:ignore="MergeRootFrame" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="#drawable/cv"
/>
<ImageButton
android:id="#+id/hs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/imageView1"
android:layout_marginRight="19dp"
android:src="#drawable/bt_hs_3d"
/>
<ImageButton
android:id="#+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginRight="48dp"
android:layout_toLeftOf="#+id/hs"
android:src="#drawable/bt_st_3d"
/>
</RelativeLayout>
</FrameLayout>
This line in the logcat tells you what your problem is:
03-19 21:53:15.003: E/AndroidRuntime(1242): Caused by: java.lang.ClassCastException: android.widget.ImageButton cannot be cast to android.widget.Button
You have defined an ImageButton in your XML somewhere, and then in your onCreate method you are trying to cast it to a standard Button by doing this:
Button start = (Button)findViewById(R.id.start);
start.setOnClickListener(this);
Change your code to this:
ImageButton start = (ImageButton)findViewById(R.id.start);
start.setOnClickListener(this);
you are casting imagebutton to button thats why it throws this exception.change
Button start = (Button)findViewById(R.id.start);
to
ImageButton start = (ImageButton)findViewById(R.id.start);
The error is Obvious:
03-19 21:53:15.003: E/AndroidRuntime(1242): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.yyy/com.example.yyy.MainActivity}: java.lang.ClassCastException: android.widget.ImageButton cannot be cast to android.widget.Button
findViewById(R.id.start), returns ImageButton, which you're casting to Button, and hence the crash.
Button start = (Button)findViewById(R.id.start);
I would suggest 2 options:
1) Replace Button in OnCreate method to ImageButton.
Read the following example, it has been nicely explained:
[http://www.mkyong.com/android/android-imagebutton-example/][1]
2) Add android:onClick attribute to as follows...
<ImageButton
android:id="#+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginRight="48dp"
android:layout_toLeftOf="#+id/hs"
android:onClick="onStartAction"
android:src="#drawable/bt_st_3d"/>
And you need to implement
public void onStartAction(View v) {
//DO Some thing here....
}

Android application keep crashing

in the last few days I tried to develop android applications with no success, for some reason my application keep crashing.
the application keeps throwing few exceptions that I didn't succeeded to handle with.
MainActivity.java :
package com.mobIce.digicoin.digitalcoin;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
private List<Coin> coins;
public MainActivity(){
coins = new ArrayList<Coin>();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
populateCoins();
populateListView();
}
}
private void populateCoins() {
coins.add(new Coin("Bitcoin", "650", "4", "http://coinmarketcap.com/img/Bitcoin.png"));
coins.add(new Coin("Dogecoin", "100", "400", "http://coinmarketcap.com/img/Bitcoin.png"));
coins.add(new Coin("fafaf", "8065", "400", "http://coinmarketcap.com/img/Bitcoin.png"));
}
private void populateListView() {
ArrayAdapter<Coin> adapter = new MyListAdapter();
ListView list = (ListView) findViewById(R.id.coinsListView);
list.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
private class MyListAdapter extends ArrayAdapter<Coin> {
public MyListAdapter()
{
super(MainActivity.this, R.layout.coin_layout, coins);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View itemView = convertView;
if(itemView == null)
itemView = getLayoutInflater().inflate(R.layout.coin_layout, parent, false);
//find the coin to work with.
Coin currentCoin = coins.get(position);
//fill the view
try{
TextView coinName = (TextView) itemView.findViewById(R.id.coinName);
coinName.setText(currentCoin.getName());
TextView coinPrice = (TextView) itemView.findViewById(R.id.coinPrice);
coinPrice.setText(currentCoin.getPrice());
TextView coinPercentage = (TextView) itemView.findViewById(R.id.coinPercentage);
coinPercentage.setText(currentCoin.getPercentage());
}
catch (NullPointerException e){ }
return itemView;
}
}
}
activity_main.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.mobIce.digicoin.digitalcoin.MainActivity"
tools:ignore="MergeRootFrame" />
fragment_main.xml:
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/coinsListView"
android:paddingLeft="30dp" />
</LinearLayout>
coin_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="match_parent"
android:padding="8dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="coinName"
android:id="#+id/coinName"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/coinIcon"
android:layout_marginTop="35dp"
android:layout_marginLeft="20dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/coinIcon"
android:maxHeight="80dp"
android:maxWidth="80dp"
android:minHeight="80dp"
android:minWidth="80dp"
android:src="#drawable/dogecoin"
android:longClickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:baselineAlignBottom="false"
android:clickable="false"
android:adjustViewBounds="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/coinPrice"
android:layout_marginLeft="35dp"
android:layout_alignTop="#+id/coinIcon"
android:layout_toRightOf="#+id/coinName"
android:layout_marginTop="25dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/coinPercentage"
android:layout_below="#+id/coinPrice"
android:layout_alignLeft="#+id/coinPrice"
android:layout_alignStart="#+id/coinPrice" />
</RelativeLayout>
logcat trace:
03-17 08:59:33.977 1107-1107/com.mobIce.digicoin.digitalcoin D/AndroidRuntime﹕ Shutting down VM
03-17 08:59:33.977 1107-1107/com.mobIce.digicoin.digitalcoin W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb1a38ba8)
03-17 08:59:33.987 1107-1107/com.mobIce.digicoin.digitalcoin E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.mobIce.digicoin.digitalcoin, PID: 1107
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobIce.digicoin.digitalcoin/com.mobIce.digicoin.digitalcoin.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.mobIce.digicoin.digitalcoin.MainActivity.populateListView(MainActivity.java:47)
at com.mobIce.digicoin.digitalcoin.MainActivity.onCreate(MainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            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:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
03-17 09:04:09.857 1149-1149/com.mobIce.digicoin.digitalcoin D/AndroidRuntime﹕ Shutting down VM
03-17 09:04:09.857 1149-1149/com.mobIce.digicoin.digitalcoin W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb1a38ba8)
03-17 09:04:09.867 1149-1149/com.mobIce.digicoin.digitalcoin E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.mobIce.digicoin.digitalcoin, PID: 1149
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobIce.digicoin.digitalcoin/com.mobIce.digicoin.digitalcoin.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.mobIce.digicoin.digitalcoin.MainActivity.populateListView(MainActivity.java:50)
at com.mobIce.digicoin.digitalcoin.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            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:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
03-17 09:06:36.697 1192-1192/com.mobIce.digicoin.digitalcoin D/AndroidRuntime﹕ Shutting down VM
03-17 09:06:36.697 1192-1192/com.mobIce.digicoin.digitalcoin W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb1a38ba8)
03-17 09:06:36.717 1192-1192/com.mobIce.digicoin.digitalcoin E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.mobIce.digicoin.digitalcoin, PID: 1192
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobIce.digicoin.digitalcoin/com.mobIce.digicoin.digitalcoin.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.mobIce.digicoin.digitalcoin.MainActivity.populateListView(MainActivity.java:50)
at com.mobIce.digicoin.digitalcoin.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            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:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
03-17 09:13:38.647 1239-1239/com.mobIce.digicoin.digitalcoin D/AndroidRuntime﹕ Shutting down VM
03-17 09:13:38.647 1239-1239/com.mobIce.digicoin.digitalcoin W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb1a38ba8)
03-17 09:13:38.747 1239-1239/com.mobIce.digicoin.digitalcoin E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.mobIce.digicoin.digitalcoin, PID: 1239
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobIce.digicoin.digitalcoin/com.mobIce.digicoin.digitalcoin.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.mobIce.digicoin.digitalcoin.MainActivity.populateListView(MainActivity.java:50)
at com.mobIce.digicoin.digitalcoin.MainActivity.onCreate(MainActivity.java:37)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            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:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
03-17 09:13:45.127 1239-1239/com.mobIce.digicoin.digitalcoin I/Process﹕ Sending signal. PID: 1239 SIG: 9
03-17 09:19:34.847 1285-1285/com.mobIce.digicoin.digitalcoin D/AndroidRuntime﹕ Shutting down VM
03-17 09:19:34.847 1285-1285/com.mobIce.digicoin.digitalcoin W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb1a38ba8)
03-17 09:19:34.857 1285-1285/com.mobIce.digicoin.digitalcoin E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.mobIce.digicoin.digitalcoin, PID: 1285
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobIce.digicoin.digitalcoin/com.mobIce.digicoin.digitalcoin.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.mobIce.digicoin.digitalcoin.MainActivity.populateListView(MainActivity.java:50)
at com.mobIce.digicoin.digitalcoin.MainActivity.onCreate(MainActivity.java:37)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            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:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
03-17 09:20:11.987 1285-1285/com.mobIce.digicoin.digitalcoin I/Process﹕ Sending signal. PID: 1285 SIG: 9
Your coinsListView is in the fragment layout and not in activity layout. You cannot access it with findViewById() in populateListView() called from activity onCreate(). Instead, move the list view population to the fragment's onCreateView() after the inflation, calling findViewById() on the rootView layout you just inflated.

NULLPOINT EXCEPTION ERROR during Simple Android app development [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
i am trying to develop this simple app using Android ADT and I got null point exception error. It is returning null point exception error at line 32 which is
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
counter++;
display.setText("your total is" + counter);
}
});
My whole java code is
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.*;
public class MainActivity extends ActionBarActivity {
int counter;
Button add , subtract;
TextView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 0;
add = (Button) findViewById(R.id.badd1);
subtract = (Button) findViewById(R.id.bsub1);
display = (TextView) findViewById(R.id.textView1);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
counter++;
display.setText("your total is" + counter);
}
});
subtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
counter--;
display.setText("your total is" + counter);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
MY xml CODE IS
<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:gravity="center_horizontal"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.newboston.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="your total is 0"
android:textSize="45dp" />
<Button
android:id="#+id/badd1"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_marginTop="34dp"
android:layout_centerHorizontal="true"
android:text="add one"
android:textSize="20dp" />
<Button
android:id="#+id/bsub1"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/badd1"
android:layout_below="#+id/badd1"
android:layout_marginTop="34dp"
android:text="subtract one"
android:textSize="20dp" />
</RelativeLayout>
My logCat file is
03-25 23:10:29.219: D/AndroidRuntime(1211): Shutting down VM
03-25 23:10:29.229: W/dalvikvm(1211): threadid=1: thread exiting with uncaught exception (group=0xb2b10ba8)
03-25 23:10:29.279: E/AndroidRuntime(1211): FATAL EXCEPTION: main
03-25 23:10:29.279: E/AndroidRuntime(1211): Process: com.example.newboston, PID: 1211
03-25 23:10:29.279: E/AndroidRuntime(1211): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.newboston/com.example.newboston.MainActivity}: java.lang.NullPointerException
03-25 23:10:29.279: E/AndroidRuntime(1211): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
03-25 23:10:29.279: E/AndroidRuntime(1211): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
03-25 23:10:29.279: E/AndroidRuntime(1211): at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-25 23:10:29.279: E/AndroidRuntime(1211): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-25 23:10:29.279: E/AndroidRuntime(1211): at android.os.Handler.dispatchMessage(Handler.java:102)
03-25 23:10:29.279: E/AndroidRuntime(1211): at android.os.Looper.loop(Looper.java:136)
03-25 23:10:29.279: E/AndroidRuntime(1211): at android.app.ActivityThread.main(ActivityThread.java:5017)
03-25 23:10:29.279: E/AndroidRuntime(1211): at java.lang.reflect.Method.invokeNative(Native Method)
03-25 23:10:29.279: E/AndroidRuntime(1211): at java.lang.reflect.Method.invoke(Method.java:515)
03-25 23:10:29.279: E/AndroidRuntime(1211): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-25 23:10:29.279: E/AndroidRuntime(1211): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-25 23:10:29.279: E/AndroidRuntime(1211): at dalvik.system.NativeStart.main(Native Method)
03-25 23:10:29.279: E/AndroidRuntime(1211): Caused by: java.lang.NullPointerException
03-25 23:10:29.279: E/AndroidRuntime(1211): at com.example.newboston.MainActivity.onCreate(MainActivity.java:32)
03-25 23:10:29.279: E/AndroidRuntime(1211): at android.app.Activity.performCreate(Activity.java:5231)
03-25 23:10:29.279: E/AndroidRuntime(1211): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-25 23:10:29.279: E/AndroidRuntime(1211): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
03-25 23:10:29.279: E/AndroidRuntime(1211): ... 11 more
03-25 23:10:36.449: I/Process(1211): Sending signal. PID: 1211 SIG: 9
If you're using more than one layout file (e.g layout-land, layout-sw360dp), make sure all elements you reference exist on all of them.

Android.widget textView to android.widget.button

I am new to Android. I am trying to build this tiny app however every time I add the code in bold:
d = (Button) findViewById (R.id.tvDis);
the app crashes and if I remove this line, everything works fine. I am runing this on android 2.2 api 8 version and nexus s emulator.
package com.maximusstudios.numtowords;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
/**Called when the activity is first created.*/
int counter;
Button add, sub;
TextView d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 0;
add = (Button) findViewById (R.id.bAdd);
**d = (Button) findViewById (R.id.tvDis);**
sub = (Button) findViewById(R.id.bSub);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
XML CODE:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Your Total is 0"
android:textSize="20dp"
android:layout_gravity="center"
android:gravity="center"
android:id="#+id/tvDis"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add one"
android:layout_gravity="center"
android:textSize="20dp"
android:id="#+id/bAdd"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add one"
android:layout_gravity="center"
android:textSize="20dp"
android:id="#+id/bSub"
/>
</LinearLayout>
Error list:
02-10 18:00:21.452: D/AndroidRuntime(910): Shutting down VM
02-10 18:00:21.452: W/dalvikvm(910): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
02-10 18:00:21.472: E/AndroidRuntime(910): FATAL EXCEPTION: main
02-10 18:00:21.472: E/AndroidRuntime(910): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.maximusstudios.numtowords/com.maximusstudios.numtowords.MainActivity}: java.lang.ClassCastException: android.widget.TextView
02-10 18:00:21.472: E/AndroidRuntime(910): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
02-10 18:00:21.472: E/AndroidRuntime(910): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
02-10 18:00:21.472: E/AndroidRuntime(910): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
02-10 18:00:21.472: E/AndroidRuntime(910): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
02-10 18:00:21.472: E/AndroidRuntime(910): at android.os.Handler.dispatchMessage(Handler.java:99)
02-10 18:00:21.472: E/AndroidRuntime(910): at android.os.Looper.loop(Looper.java:123)
02-10 18:00:21.472: E/AndroidRuntime(910): at android.app.ActivityThread.main(ActivityThread.java:4627)
02-10 18:00:21.472: E/AndroidRuntime(910): at java.lang.reflect.Method.invokeNative(Native Method)
02-10 18:00:21.472: E/AndroidRuntime(910): at java.lang.reflect.Method.invoke(Method.java:521)
02-10 18:00:21.472: E/AndroidRuntime(910): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
02-10 18:00:21.472: E/AndroidRuntime(910): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
02-10 18:00:21.472: E/AndroidRuntime(910): at dalvik.system.NativeStart.main(Native Method)
02-10 18:00:21.472: E/AndroidRuntime(910): Caused by: java.lang.ClassCastException: android.widget.TextView
02-10 18:00:21.472: E/AndroidRuntime(910): at com.maximusstudios.numtowords.MainActivity.onCreate(MainActivity.java:23)
02-10 18:00:21.472: E/AndroidRuntime(910): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-10 18:00:21.472: E/AndroidRuntime(910): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
02-10 18:00:21.472: E/AndroidRuntime(910): ... 11 more
Change to
d = (TextView) findViewById (R.id.tvDis);
Your casting was wrong. With your code, when you do (Button), you are trying to cast the TextView that is returned by findViewById() into a Button, which doesn't work due to them being incompatible types.
You define d as a TextView and try to cast it to a Button
Should be
d = (TextView) findViewById (R.id.tvDis);
The error you're getting is a ClassCastException

Categories