getting null pointer exception - java

I am getting a NullPointerException when I try to access text view which is defined in view class. I am accessing it from setting class. A small part of my code is:
view class
public class view1 extends menu {
public static TextView text1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
text1=(TextView)findViewById(R.id.textfile1);
text1.setText("product");
}
public void small(String mytext) { // this is my method which I want to access
text1.setText(mytext);
}
}
setting class
public class Setting extends Activity {
private Spinner spinner1;
private Button apply;
TextView small1;
private view1 view11;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setting);
//setContentView(R.layout.view);
addItemsOnSpinner1();
addListenerOnSpinnerItemSelection();
}
public void addItemsOnSpinner1() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
List<String> list = new ArrayList<String>();
list.add("Small");
list.add("Medium");
list.add("Large");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
apply = (Button) findViewById(R.id.apply);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
apply.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String mytext = "Something else";
view11.small(mytext);
}
Stack trace
01-17 00:11:02.064: E/AndroidRuntime(4191): FATAL EXCEPTION: main
01-17 00:11:02.064: E/AndroidRuntime(4191): java.lang.NullPointerException
01-17 00:11:02.064: E/AndroidRuntime(4191): at com.ramanrayat.notelet.Setting$1.onClick(Setting.java:106)
01-17 00:11:02.064: E/AndroidRuntime(4191): at android.view.View.performClick(View.java:4240)
01-17 00:11:02.064: E/AndroidRuntime(4191): at android.view.View$PerformClick.run(View.java:17721)
01-17 00:11:02.064: E/AndroidRuntime(4191): at android.os.Handler.handleCallback(Handler.java:730)
01-17 00:11:02.064: E/AndroidRuntime(4191): at android.os.Handler.dispatchMessage(Handler.java:92)
01-17 00:11:02.064: E/AndroidRuntime(4191): at android.os.Looper.loop(Looper.java:137)
01-17 00:11:02.064: E/AndroidRuntime(4191): at android.app.ActivityThread.main(ActivityThread.java:5103)
01-17 00:11:02.064: E/AndroidRuntime(4191): at java.lang.reflect.Method.invokeNative(Native Method)
01-17 00:11:02.064: E/AndroidRuntime(4191): at java.lang.reflect.Method.invoke(Method.java:525)
01-17 00:11:02.064: E/AndroidRuntime(4191): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-17 00:11:02.064: E/AndroidRuntime(4191): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-17 00:11:02.064: E/AndroidRuntime(4191): at dalvik.system.NativeStart.main(Native Method)
setting.xml code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="38dp"
android:text="Setting"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="40dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="57dp"
android:gravity="center"
android:text="Font Size"
android:textSize="30dp" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="30dp" />
<Button
android:id="#+id/apply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignRight="#+id/textView2"
android:layout_below="#+id/spinner1"
android:layout_marginTop="58dp"
android:text="Apply" />
</RelativeLayout>

Chnage
if(String.valueOf(spinner1.getSelectedItem())=="Small")
TO
if(String.valueOf(spinner1.getSelectedItem()).equals("Small"))
Use .equals or .equalsIgnoreCase to compare strings
Instead of making textview static you should use intents to pass values between activities.
Intent intent = new Intent(ActivityName.this,Settings.class);
intent.putExtra("key",text1.getText().toString());
startActivity(intent);
Then
String value = getIntent().getStringExtra("key");
Change
public static TextView text1;
to
public TextView text1;
Also follow java naming conventions

Replace
public static TextView text1;
with
TextView text1;
text1 can not be static.
Next time, please click on the file name in the error log and indicate which line number in your code listing is the line that the error actually points to.
Learn to start all your class names with capital letters (athough, this is not what's causing the problem). And while I'm at it, please stop using numbers in class names and in variables, especially the number 1, which can be ambiguously read as an "l" in some fonts.

Look for your LogCat, it will told you where is NPE.
The other question is : don't use equals to compare String instead of ==
== is compare two object's address and equals is compare their value.
if(String.valueOf(spinner1.getSelectedItem()).equals("Small")) {
String mytext = "Something else ";
view11.small(mytext); // view11 is clas view1 reference
}
else if(String.valueOf(spinner1.getSelectedItem()).equals("Medium")) {
finish();
}

Related

Error when trying to add splash screen - android app

I'm an android newbie
I was following this tutorial Android splash screen howto, it's a little outdated, but anyways.
I just add the new layout file splash.xml into res/layout, and then the image into drawable/mdpi, then I change the main image into MainActivity.java, ie:
setContentView(R.layout.activity_main);
to
setContentView(R.layout.splash);
Being activity_main the name of the default layout, activity_main.xml, and splash the name of the other layout called splash.xml.
But application stops, says the application has unfortunately stopped, and I can't even access it.
I don't know what am I missing here, here's the interesting code on MainActivity.java:
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.splash);
relativeLayout=(RelativeLayout) findViewById(R.id.containerImg);
relativeLayout.setDrawingCacheEnabled(true);
cameraSurfaceView = (SurfaceView)
findViewById(R.id.surfaceView1);
// cameraSurfaceView.setLayoutParams(new FrameLayout.LayoutParams(640, 480));
cameraSurfaceHolder = cameraSurfaceView.getHolder();
cameraSurfaceHolder.addCallback(this);
// cameraSurfaceHolder.setType(SurfaceHolder.
// SURFACE_TYPE_PUSH_BUFFERS);
btnCapture = (Button)findViewById(R.id.button1);
btnCapture.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
camera.takePicture(cameraShutterCallback,
cameraPictureCallbackRaw,
cameraPictureCallbackJpeg);
}
});
}
My activity_main.xml:
<FrameLayout 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"
tools:context=".MainActivity" >
<RelativeLayout
android:id="#+id/containerImg"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<SurfaceView
android:id="#+id/surfaceView1"
android:layout_width="1276px"
android:layout_height="745px"
android:layout_centerInParent="true" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/surfaceView1"
android:layout_alignLeft="#+id/surfaceView1"
android:layout_marginLeft="20px"
android:src="#drawable/mark3" />
</RelativeLayout>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|center_vertical"
android:background="#drawable/camera" />
</FrameLayout>
My splash.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:src="#drawable/splash"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY"/>
</LinearLayout>
Any ideas?
Maybe I should use the same activity_main.xml for this purposes, not really sure...
Thanks in advance!
EDIT
Logcat:
3774-3774/com.kkoci.photo E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.kkoci.photo/com.kkoci.photo.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2295)
at android.app.ActivityThread.access$700(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:175)
at android.app.ActivityThread.main(ActivityThread.java:5279)
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:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.kkoci.photo.MainActivity.onCreate(MainActivity.java:65)
at android.app.Activity.performCreate(Activity.java:5283)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2295)
at android.app.ActivityThread.access$700(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:175)
at android.app.ActivityThread.main(ActivityThread.java:5279)
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:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
relativeLayout=(RelativeLayout) findViewById(R.id.containerImg);
relativeLayout.setDrawingCacheEnabled(true);
cameraSurfaceView = (SurfaceView)findViewById(R.id.surfaceView1);
these are the views present in your activity_main xml file.. when you change your layout file why you are accessing these?

Unable to start activity: NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
Hi I am encountering a null pointer error when I click on the activity Links. The purpose of my feature is to call a list of links in the form of list view. Below is the logcat and as far as I understand it is coming from my onItemClickListener, but I can't seem to point out the null error.:
sitesList.setOnItemClickListener(new OnItemClickListener()
Links.java
package com.example.sgrecipe;
import java.io.FileNotFoundException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class Links extends Activity {
private SitesAdapter mAdapter;
private ListView sitesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("StackSites", "OnCreate()");
setContentView(R.layout.activity_main);
//Get reference to our ListView
sitesList = (ListView)findViewById(R.id.sitesList);
//Set the click listener to launch the browser when a row is clicked.
sitesList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,long id) {
String url = mAdapter.getItem(pos).getLink();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
/*
* If network is available download the xml from the Internet.
* If not then try to use the local file from last time.
*/
if(isNetworkAvailable()){
Log.i("StackSites", "starting download Task");
SitesDownloadTask download = new SitesDownloadTask();
download.execute();
}else{
mAdapter = new SitesAdapter(getApplicationContext(), -1, SitesXmlPullParser.getStackSitesFromFile(Links.this));
sitesList.setAdapter(mAdapter);
}
}
//Helper method to determine if Internet connection is available.
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
/*
* AsyncTask that will download the xml file for us and store it locally.
* After the download is done we'll parse the local file.
*/
private class SitesDownloadTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... arg0) {
//Download the file
try {
Downloader.DownloadFromUrl("https://dl.dropboxusercontent.com/u/5724095/XmlParseExample/stacksites.xml", openFileOutput("StackSites.xml", Context.MODE_PRIVATE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
//setup our Adapter and set it to the ListView.
mAdapter = new SitesAdapter(Links.this, -1, SitesXmlPullParser.getStackSitesFromFile(Links.this));
sitesList.setAdapter(mAdapter);
Log.i("StackSites", "adapter size = "+ mAdapter.getCount());
}
}
}
activity_links.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"
tools:context=".Links" >
<ListView
android:id="#+id/sitesList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
row_site.xml (for the listview)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp" >
<ProgressBar
android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/iconImg"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginRight="8dp" />
<TextView
android:id="#+id/nameTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/iconImg"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/aboutTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/iconImg"
android:textSize="12sp"
android:layout_below="#id/nameTxt"
/>
</RelativeLayout>
Here is the logcat:
02-23 15:13:10.856: E/AndroidRuntime(8201): FATAL EXCEPTION: main
02-23 15:13:10.856: E/AndroidRuntime(8201): Process: com.example.sgrecipe, PID: 8201
02-23 15:13:10.856: E/AndroidRuntime(8201): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sgrecipe/com.example.sgrecipe.Links}: java.lang.NullPointerException
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2292)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2350)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.access$800(ActivityThread.java:163)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1257)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.os.Handler.dispatchMessage(Handler.java:102)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.os.Looper.loop(Looper.java:157)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.main(ActivityThread.java:5335)
02-23 15:13:10.856: E/AndroidRuntime(8201): at java.lang.reflect.Method.invokeNative(Native Method)
02-23 15:13:10.856: E/AndroidRuntime(8201): at java.lang.reflect.Method.invoke(Method.java:515)
02-23 15:13:10.856: E/AndroidRuntime(8201): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
02-23 15:13:10.856: E/AndroidRuntime(8201): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
02-23 15:13:10.856: E/AndroidRuntime(8201): at dalvik.system.NativeStart.main(Native Method)
02-23 15:13:10.856: E/AndroidRuntime(8201): Caused by: java.lang.NullPointerException
02-23 15:13:10.856: E/AndroidRuntime(8201): at com.example.sgrecipe.Links.onCreate(Links.java:36)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.Activity.performCreate(Activity.java:5389)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2256)
Any help is really appreciate, thank you!
Change following line
setContentView(R.layout.activity_main);
to
setContentView(R.layout.activity_links);
Seems like your using different layouts:
setContentView(R.layout.activity_main);
vs
activity_links.xml

Fatal exception:main Android Eclipse

I am new on android and trying to develop simple calculator but this Fatal exception : main occurs please help.
I did comment my onClickListner to check but it did'nt helped at all.
package com.example.calculatorsinglescreen;
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.Toast;
public class MainActivity extends ActionBarActivity {
EditText value1,value2,myoperator,result;
Button ok;
String strvalue1,strvalue2,stroperator,strresult;
int ivalue1,ivalue2,ioperator,iresult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
value1 = (EditText) findViewById(R.id.txtvalue1);
value2 = (EditText) findViewById(R.id.txtvalue2);
myoperator = (EditText) findViewById(R.id.txtoperator);
result = (EditText) findViewById(R.id.txtresult);
ok = (Button) findViewById(R.id.btnok);
strvalue1 = value1.getText().toString();
strvalue2 = value2.getText().toString();
stroperator = myoperator.getText().toString();
ivalue1 = Integer.parseInt(strvalue1);
ivalue2 = Integer.parseInt(strvalue2);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (stroperator.equals("+")) {
Toast msg = Toast.makeText(MainActivity.this, "If is running", Toast.LENGTH_LONG);
msg.show();
}
}
});
}
#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);
}
}
This is my XML file :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android: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.calculatorsinglescreen.MainActivity" >
<TextView
android:id="#+id/value1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_margin="20dp"
android:text="Value 1" />
<TextView
android:id="#+id/value2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/value1"
android:layout_margin="20dp"
android:text="Value 2" />
<TextView
android:id="#+id/operator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/value2"
android:layout_margin="20dp"
android:text="Operator" />
<EditText
android:id="#+id/txtvalue1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/value1"
android:layout_alignBaseline="#+id/value1"
android:layout_alignParentRight="true"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/txtoperator"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/operator"
android:layout_below="#+id/txtvalue2"
android:layout_toRightOf="#+id/operator"
android:layout_alignParentRight="true"
android:ems="10" />
<EditText
android:id="#+id/txtvalue2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/value2"
android:layout_toRightOf="#+id/value2"
android:layout_below="#+id/txtvalue1"
android:layout_alignParentRight="true"
android:ems="10" />
<Button
android:id="#+id/btnok"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Ok" />
<TextView
android:id="#+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/btnok"
android:layout_margin="40dp"
android:text="Result" />
<EditText
android:id="#+id/txtresult"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/result"
android:layout_toRightOf="#+id/result"
android:ems="10" />
Here is my LogCat to get a clearer view :
10-18 17:51:25.468: D/AndroidRuntime(742): Shutting down VM
10-18 17:51:25.468: W/dalvikvm(742): threadid=1: thread exiting with uncaught exception (group=0x40015560)
10-18 17:51:25.488: E/AndroidRuntime(742): FATAL EXCEPTION: main
10-18 17:51:25.488: E/AndroidRuntime(742): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.calculatorsinglescreen/com.example.calculatorsinglescreen.MainActivity}: java.lang.NumberFormatException: unable to parse '' as integer
10-18 17:51:25.488: E/AndroidRuntime(742): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
10-18 17:51:25.488: E/AndroidRuntime(742): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
10-18 17:51:25.488: E/AndroidRuntime(742): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
10-18 17:51:25.488: E/AndroidRuntime(742): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
10-18 17:51:25.488: E/AndroidRuntime(742): at android.os.Handler.dispatchMessage(Handler.java:99)
10-18 17:51:25.488: E/AndroidRuntime(742): at android.os.Looper.loop(Looper.java:123)
10-18 17:51:25.488: E/AndroidRuntime(742): at android.app.ActivityThread.main(ActivityThread.java:3683)
10-18 17:51:25.488: E/AndroidRuntime(742): at java.lang.reflect.Method.invokeNative(Native Method)
10-18 17:51:25.488: E/AndroidRuntime(742): at java.lang.reflect.Method.invoke(Method.java:507)
10-18 17:51:25.488: E/AndroidRuntime(742): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-18 17:51:25.488: E/AndroidRuntime(742): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-18 17:51:25.488: E/AndroidRuntime(742): at dalvik.system.NativeStart.main(Native Method)
10-18 17:51:25.488: E/AndroidRuntime(742): Caused by: java.lang.NumberFormatException: unable to parse '' as integer
10-18 17:51:25.488: E/AndroidRuntime(742): at java.lang.Integer.parseInt(Integer.java:362)
10-18 17:51:25.488: E/AndroidRuntime(742): at java.lang.Integer.parseInt(Integer.java:332)
10-18 17:51:25.488: E/AndroidRuntime(742): at com.example.calculatorsinglescreen.MainActivity.onCreate(MainActivity.java:34)
10-18 17:51:25.488: E/AndroidRuntime(742): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
10-18 17:51:25.488: E/AndroidRuntime(742): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
10-18 17:51:25.488: E/AndroidRuntime(742): ... 11 more
this is the error
java.lang.ClassCastException: android.widget.TextView
check your line 24 and see if you cast the right widget in java -(xml), this error means incompatible cast widget lol...
if everything seems correct-(mean widgets are cast in java to with their respective class) then clean rebuild and restart..
EDIT: It worked.. you've solved it but there is a new error which is
java.lang.NumberFormatException:
its because of this on these lines
ivalue1 = Integer.parseInt(strvalue1);
ivalue2 = Integer.parseInt(strvalue2);
ioperator = Integer.parseInt(stroperator);
so change these to this
Integer.valueOf(strvalue1); do that as follows
and also looking at your codes.. your string values are pullled from the edittext during oncreate which means when the app starts in oncreate before the Onresume(which is called when the app shows on the), and during oncreate the user cant flirt with your app, and going further to input values, so at the end your strings are empty when you pull from the edittext, so basically what im saying is remove these lines
strvalue1 = value1.getText().toString();
and put them in the click events ... i am lucid enough to you??..
EDIT2: OVERALL CODE
for button click
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
strvalue1 = value1.getText().toString();
strvalue2 = value2.getText().toString();
stroperator = myoperator.getText().toString();
ivalue1 = Integer.valueOf(strvalue1);
ivalue2 = Integer.valueOf(strvalue2);
if (stroperator.equals("+")) {
Toast.makeText(MainActivity.this, "If is running", Toast.LENGTH_LONG).show();
}
}
});
remove ioperator = Integer.parseInt(stroperator); from the code.I think Your trying to convert the operator to Integer.
ioperator = Integer.parseInt(stroperator);
if you mean operator like this +,-,/,* , you only can convert to thr char or stay in string and do something like this:
private int plus(int ivalue1 , int ivalue2 , String operator ){
if(operator.equal("+")){
return ivalue1 + ivalue2;
}
return 0;
}

Can't get simple android calculator app to run

I have been spending a little time going over some of Google's android tutorials, and decided to throw together my own simple calculator application. I know a good bit of JAVA, and have messed around a little bit of Android back a few SDKs ago. I think the code is fine, but I just can't get the bastard to run. I have been trying to find an answer based on my LogCat stuff, but have had no luck. First, here is my MainActivity.java:
package com.AppliedArgonautics.calculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
EditText editText1 = (EditText)findViewById(R.id.editText1);
EditText editText2 = (EditText)findViewById(R.id.editText2);
TextView textView1 = (TextView)findViewById(R.id.textView1);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void Add(){
float num1 = Float.parseFloat(editText1.getText().toString());
float num2 = Float.parseFloat(editText2.getText().toString());
float result = num1 + num2;
textView1.setText(Float.toString(result));
}
public void Subtract(){
float num1 = Float.parseFloat(editText1.getText().toString());
float num2 = Float.parseFloat(editText2.getText().toString());
float result = num1 - num2;
textView1.setText(Float.toString(result));
}
public void Multiply(){
float num1 = Float.parseFloat(editText1.getText().toString());
float num2 = Float.parseFloat(editText2.getText().toString());
float result = num1 * num2;
textView1.setText(Float.toString(result));
}
public void Divide(){
float num1 = Float.parseFloat(editText1.getText().toString());
float num2 = Float.parseFloat(editText2.getText().toString());
float result = num1 / num2;
textView1.setText(Float.toString(result));
}
public void Clear(){
editText1.setText("");
editText2.setText("");
textView1.setText("");
}
}
My manifest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.AppliedArgonautics.calculator"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
then, the 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" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="32dp"
android:onClick="Add"
android:text="Add" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button1"
android:layout_below="#+id/button1"
android:layout_marginTop="45dp"
android:onClick="Multiply"
android:text="Multiply" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/button3"
android:layout_alignParentRight="true"
android:layout_marginRight="28dp"
android:onClick="Subtract"
android:text="Subtract" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button3"
android:layout_alignBottom="#+id/button3"
android:layout_alignLeft="#+id/button2"
android:onClick="Divide"
android:text="Divide" />
<Button
android:id="#+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button1"
android:layout_centerHorizontal="true"
android:onClick="Clear"
android:text="Clear" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/button1"
android:layout_marginTop="37dp"
android:ems="10"
android:inputType="phone" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/editText1"
android:layout_alignLeft="#+id/button2"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/editText1"
android:ems="10"
android:inputType="phone" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button5"
android:layout_below="#+id/editText1"
android:layout_marginTop="56dp"
android:text="TextView" />
</RelativeLayout>
This is what LogCat shows when I try to run it:
/Trace ( 3186): error opening trace file: No such file or directory (2)
D/AndroidRuntime( 3186): Shutting down VM
W/dalvikvm( 3186): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
E/AndroidRuntime( 3186): FATAL EXCEPTION: main
E/AndroidRuntime( 3186): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.AppliedArgonautics.calculator/com.AppliedArgonautics.calculator.MainActivi ty}: java.lang.NullPointerException
E/AndroidRuntime( 3186): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
E/AndroidRuntime( 3186): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
E/AndroidRuntime( 3186): at android.app.ActivityThread.access$600(ActivityThread.java:130)
E/AndroidRuntime( 3186): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
E/AndroidRuntime( 3186): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime( 3186): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime( 3186): at android.app.ActivityThread.main(ActivityThread.java:4745)
E/AndroidRuntime( 3186): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 3186): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime( 3186): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
E/AndroidRuntime( 3186): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime( 3186): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime( 3186): Caused by: java.lang.NullPointerException
E/AndroidRuntime( 3186): at android.app.Activity.findViewById(Activity.java:1825)
E/AndroidRuntime( 3186): at com.AppliedArgonautics.calculator.MainActivity.<init>(MainActivity.java:10)
E/AndroidRuntime( 3186): at java.lang.Class.newInstanceImpl(Native Method)
E/AndroidRuntime( 3186): at java.lang.Class.newInstance(Class.java:1319)
E/AndroidRuntime( 3186): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
E/AndroidRuntime( 3186): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
E/AndroidRuntime( 3186): ... 11 more
W/ActivityManager( 160): Force finishing activity com.AppliedArgonautics.calculator/.MainActivity
I would really appreciate it if someone could have a look at this. I thought it would be cool to learn android, but am getting very frustrated with my inability to get even a simple program like this to launch. Thank you.
There may be lot of issues in your code, but first to get you started:
Create EditText and TextView as instance variables. Assign views to those variables in onCreate.
public class MainActivity extends Activity {
EditText editText1;
EditText editText2;
TextView textView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1 = (EditText)findViewById(R.id.editText1);
editText2 = (EditText)findViewById(R.id.editText2);
textView1 = (TextView)findViewById(R.id.textView1);
}
.........
}
I did here for adding the values.. Your created the button in xml but, not using in java code..
we need to do our stuff under button click listener...
public class MainActivity extends Activity {
EditText editText1 ;
EditText editText2 ;
TextView textView1 ;
float num1, num2,result;
Button add;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1 = (EditText)findViewById(R.id.editText1);
editText2 = (EditText)findViewById(R.id.editText2);
textView1 = (TextView)findViewById(R.id.textView1);
add = (Button)findViewById(R.id.button1);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
num1 = Float.parseFloat(editText1.getText().toString());
num2 = Float.parseFloat(editText2.getText().toString());
result = num1 + num2;
textView1.setText(Float.toString(result));
}
});
}
}
Apply the same thing for all methods...
Hope, this will helps you..
I loaded up your application, and ran the application in debug mode. It broke on the line
EditText editText1 = (EditText)findViewById(R.id.editText1);
It was throwing a null pointer exception because you have not yet loaded your layout. This happens in your OnCreate function.
The solution is to shift the findViewById command into your onCreate function after the SetContentView command. Ie:
public class MainActivity extends Activity {
EditText editText1;
EditText editText2;
TextView textView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1 = (EditText)findViewById(R.id.editText1);
editText2 = (EditText)findViewById(R.id.editText2);
textView1 = (TextView)findViewById(R.id.textView1);
}
Your next issues are that the functions that your Add, Subtract, etc functions all need to take a parameter of type View. This is the reference back to the button that was clicked. (Otherwise you get an IllegalStateException when it can't find the function to call)
Then it's going to fail on Float.parseFloat(editText1.getText().toString()) because the the editText contains blank, not a number. You'll want to either force the edit texts to always have a valid number, or modify your functions to cater for empty strings.
Good luck from here! :)
write these
EditText editText1;
EditText editText2;
TextView textView1 ;
instead of these
EditText editText1 = (EditText)findViewById(R.id.editText1);
EditText editText2 = (EditText)findViewById(R.id.editText2);
TextView textView1 = (TextView)findViewById(R.id.textView1);
and change this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
to
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1 = (EditText)findViewById(R.id.editText1);
editText2 = (EditText)findViewById(R.id.editText2);
textView1 = (TextView)findViewById(R.id.textView1);
}
You are getting error because you are trying to access the views without specifying which layout you are considering.
setContentView(R.layout.activity_main);
specifies the layout you are considering

app on android crashes on the virtual device when clicking any button [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Trying to write my first app on android.
But the app crashes(FC) on the virtual device when clicking any of buttons.
Please take a look..
the MainActivity.java:
public class MainActivity extends Activity {
public EditText t1 = null, t2 = null;
Button b1 = null, b2 = null;
TextView tv1 = null,tv2 = null;
int a = 0, b = 0, S1 = 0, S2 = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1=(EditText)findViewById(R.id.editText1);
t2=(EditText)findViewById(R.id.EditText2);
b1=(Button)findViewById(R.id.button1);
b2=(Button)findViewById(R.id.button2);
tv1=(TextView)findViewById(R.id.TextView1);
tv2=(TextView)findViewById(R.id.TextView2);
}
public void onClick1()
{
tv1.clearComposingText();
a=Integer.parseInt(t1.getText().toString());
tv1.setText(S1+=a);
}
public void onClick2()
{
tv2.clearComposingText();
b=Integer.parseInt(t2.getText().toString());
tv2.setText(S2+=b);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
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" >
<Button
android:id="#+id/button1"
android:layout_width="80dp"
android:layout_height="60dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="30dp"
android:text="Add"
android:onClick="onClick1" />
<Button
android:id="#+id/button2"
android:layout_width="80dp"
android:layout_height="60dp"
android:layout_alignBaseline="#+id/button1"
android:layout_alignBottom="#+id/button1"
android:layout_marginLeft="26dp"
android:layout_toRightOf="#+id/button1"
android:text="Add"
android:onClick="onClick2" />
<EditText
android:id="#+id/editText1"
android:layout_width="80dp"
android:layout_height="60dp"
android:layout_alignLeft="#+id/button1"
android:layout_below="#+id/button1"
android:layout_marginTop="24dp"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/EditText2"
android:layout_width="80dp"
android:layout_height="60dp"
android:layout_alignBaseline="#+id/editText1"
android:layout_alignBottom="#+id/editText1"
android:layout_alignLeft="#+id/button2"
android:ems="10" />
<TextView
android:id="#+id/TextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/editText1"
android:layout_centerVertical="true"
android:text="" />
<TextView
android:id="#+id/TextView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/TextView1"
android:layout_alignLeft="#+id/EditText2"
android:text="" />
and logcat log file:
10-14 17:36:35.714: E/AndroidRuntime(697): FATAL EXCEPTION: main
10-14 17:36:35.714: E/AndroidRuntime(697): java.lang.IllegalStateException: Could not find a method onClick1(View) in the activity class com.example.blot.MainActivity for onClick handler on view class android.widget.Button with id 'button1'
10-14 17:36:35.714: E/AndroidRuntime(697): at android.view.View$1.onClick(View.java:2131)
10-14 17:36:35.714: E/AndroidRuntime(697): at android.view.View.performClick(View.java:2485)
10-14 17:36:35.714: E/AndroidRuntime(697): at android.view.View$PerformClick.run(View.java:9080)
10-14 17:36:35.714: E/AndroidRuntime(697): at android.os.Handler.handleCallback(Handler.java:587)
10-14 17:36:35.714: E/AndroidRuntime(697): at android.os.Handler.dispatchMessage(Handler.java:92)
10-14 17:36:35.714: E/AndroidRuntime(697): at android.os.Looper.loop(Looper.java:123)
10-14 17:36:35.714: E/AndroidRuntime(697): at android.app.ActivityThread.main(ActivityThread.java:3683)
10-14 17:36:35.714: E/AndroidRuntime(697): at java.lang.reflect.Method.invokeNative(Native Method)
10-14 17:36:35.714: E/AndroidRuntime(697): at java.lang.reflect.Method.invoke(Method.java:507)
10-14 17:36:35.714: E/AndroidRuntime(697): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-14 17:36:35.714: E/AndroidRuntime(697): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-14 17:36:35.714: E/AndroidRuntime(697): at dalvik.system.NativeStart.main(Native Method)
10-14 17:36:35.714: E/AndroidRuntime(697): Caused by: java.lang.NoSuchMethodException: onClick1
10-14 17:36:35.714: E/AndroidRuntime(697): at java.lang.ClassCache.findMethodByName(ClassCache.java:247)
10-14 17:36:35.714: E/AndroidRuntime(697): at java.lang.Class.getMethod(Class.java:962)
10-14 17:36:35.714: E/AndroidRuntime(697): at android.view.View$1.onClick(View.java:2124)
10-14 17:36:35.714: E/AndroidRuntime(697): ... 11 more
Simply try this.....
- First remove the onClick1() and onClick2() methods.
- Use Anonymous Inner class for registering and implementing the method onClick() of Interface OnClickListener
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
tv1.clearComposingText();
a=Integer.parseInt(t1.getText().toString());
tv1.setText(S1+=a);
}
});
b2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
tv2.clearComposingText();
b=Integer.parseInt(t2.getText().toString());
tv2.setText(S2+=b);
}
});
It would seem that your app doesn't know what to do when someone clicks on your button.
you forgot to pass View in onClick1():
public void onClick1(View v){
//your code here
}
public void onClick2(View v){
//your code here
}
For further reading: Best practice for defining button events in android
Like the error tells you it needs a parameter 'View' in the method.
Change your onclick methods to accept the View parameter. You have to do the same for all your other button onclick methods.
public void onClick1(View v) {
// Code
|
The OnClick method must accepts View parameter
public void OnClick1(View view) {
...
}
The same for OnClick2
Btw it's advise but you should read carefully the error messages:
java.lang.IllegalStateException: Could not find a method onClick1(View)
Notice that it hints that it needs View parameter.
Other things I noticed:
you should use #+id syntax to declare a new id for a resource. Once you've done this you should use #id to refer to the resouce. In other words you need to have "#+id/button1" only once (in the Button1 declaration), after that use "#id/button1" to refer to it. The same counts for all other ids of course (EditText and so on...)
xml files don't like it when you have capital letters it the method name. Change the method names to "onclick1" instead of "onClick1" and it should work. At least it worked for me after copy pasting your project into my own IDE...
also add the View parameter as mentioned in the other answers here.
you should add the listener programmatically
b1.setonClickListener(this);
then in your activity. implement the interface onclickListener.
in your override method onclick. use a switch statement to determine what view is accessing it.
or you can create a new onclicklistener.
b1.setonClickListener(new onclicklistner....)

Categories