No errors in Android studio but application crashes - android

I am new to android development and tried to make a simple calculator app. The last thing that I changed was try to concatenate two string into one and display the new string in the EditText. There are no errors in my project when I look at it in Android Studio, however when I run the application on my phone it stops working. Is this a phone problem or ... ?
package com.example.jeff.calculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
double total = 0;
double transaction = 0;
String Back = "";
String currentString = "";
String transactionString = "";
EditText calcInput = (EditText) findViewById(R.id.EtCalc);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonSetup();
}
private void concatenation() {
transactionString = transactionString + currentString;
calcInput.setText(String.valueOf(transactionString));
}
private void buttonSetup() {
Button button0 = (Button) findViewById(R.id.Btn0);
Button button1 = (Button) findViewById(R.id.Btn1);
Button button2 = (Button) findViewById(R.id.Btn2);
Button button3 = (Button) findViewById(R.id.Btn3);
Button button4 = (Button) findViewById(R.id.Btn4);
Button button5 = (Button) findViewById(R.id.Btn5);
Button button6 = (Button) findViewById(R.id.Btn6);
Button button7 = (Button) findViewById(R.id.Btn7);
Button button8 = (Button) findViewById(R.id.Btn8);
Button button9 = (Button) findViewById(R.id.Btn9);
button0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentString = "0";
calcInput.setText(String.valueOf(transactionString));
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentString = "1";
concatenation();
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentString = "2";
concatenation();
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentString = "3";
concatenation();
}
});
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentString = "4";
concatenation();
}
});
button5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentString = "5";
concatenation();
}
});
button6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentString = "6";
concatenation();
}
});
button7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentString = "7";
concatenation();
}
});
button8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentString = "8";
concatenation();
}
});
button9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentString = "9";
concatenation();
}
});
// (EditText) inputTxt = (EditText) findViewById(R.id.input);
// Store EditText in Variable
// String str = inputTxt.getText().toString();
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
LOGCAT
09-07 23:54:12.649 22823-22823/com.example.jeff.calculator I/art﹕ Late-enabling -Xcheck:jni
09-07 23:54:12.718 22823-22823/com.example.jeff.calculator D/AndroidRuntime﹕ Shutting down VM
09-07 23:54:12.719 22823-22823/com.example.jeff.calculator E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.jeff.calculator, PID: 22823
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.jeff.calculator/com.example.jeff.calculator.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2290)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5373)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.Activity.findViewById(Activity.java:2072)
at com.example.jeff.calculator.MainActivity.<init>(MainActivity.java:22)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2280)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
            at android.app.ActivityThread.access$800(ActivityThread.java:156)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:211)
            at android.app.ActivityThread.main(ActivityThread.java:5373)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)

Do not call methods that you are inheriting from Activity until after super.onCreate() has been called, unless specifically told otherwise.
Also, you cannot call findViewById() until you call setContentView(), as there are no widgets to find.
Replace:
EditText calcInput = (EditText) findViewById(R.id.EtCalc);
with:
EditText calcInput;
and add:
calcInput = (EditText) findViewById(R.id.EtCalc);
after your call to setContentView() in onCreate().

You are defining a variable
EditText calcInput = (EditText) findViewById(R.id.EtCalc);
It means that when the class is initialized, your are trying to to find an element in a null windows.
You can't do it.
Just use:
EditText calcInput;
Then init the variable in your onCreate method.
Something like:
public class MainActivity extends AppCompatActivity {
//...
EditText calcInput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonSetup();
calcInput = (EditText) findViewById(R.id.EtCalc);
}
}

You have to move this line :
EditText calcInput = (EditText) findViewById(R.id.EtCalc);
below the following line:
setContentView(R.layout.activity_main);

Related

Not able to start activity in android

this is error m getting.. i have interview.. n i need to show this app.. but getting error.. plz help.. the app was running an hour back fluently.. i was trying to put logout button on main activity to come back on login activity but lost login button function itself...
01-18 11:59:14.938 7321-7321/info.androidhive.materialdesign E/AndroidRuntime: FATAL EXCEPTION: main
Process: info.androidhive.materialdesign, PID: 7321
java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.materialdesign/info.androidhive.materialdesign.activity.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2373)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2435)
at android.app.ActivityThread.access$900(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1324)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5375)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at info.androidhive.materialdesign.activity.MainActivity.onClickButtonListener3(MainActivity.java:51)
at info.androidhive.materialdesign.activity.MainActivity.onCreate(MainActivity.java:45)
at android.app.Activity.performCreate(Activity.java:6865)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2326)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2435) 
at android.app.ActivityThread.access$900(ActivityThread.java:153) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1324) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5375) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 
this is my Login.java
package info.androidhive.materialdesign.activity;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import info.androidhive.materialdesign.R;
import info.androidhive.materialdesign.db.sqlitedb;
public class Login extends Activity {
sqlitedb sqlitehelper;
SQLiteDatabase db;
private static Button btn_login, btn_back;
EditText emailEditText, passwordEditText;
int i;
int flag;
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn_login = (Button) findViewById(R.id.login_1);
emailEditText = (EditText)findViewById(R.id.uemail);
passwordEditText = (EditText)findViewById(R.id.upass);
sqlitehelper = new sqlitedb(getApplicationContext());
db = sqlitehelper.getWritableDatabase();
onClickButtonListener1();
onClickButtonListener2();
btn_login.setClickable(true);
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public void onClickButtonListener1()
{
btn_back = (Button)findViewById(R.id.back_1);
btn_back.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent i = new Intent("info.androidhive.materialdesign.activity.Home");
// startActivity(i);
finish();
}
}
);
}
public void onClickButtonListener2()
{
btn_login = (Button) findViewById(R.id.login_1);
btn_login.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
onLoginClick(v);
}
}
);
}
public void onLoginClick(View v) {
if (v.getId() == R.id.login_1)
{
String contactEmail = emailEditText.getText().toString();
String contactPassword = passwordEditText.getText().toString();
String password = sqlitehelper.getSingleEntry(contactEmail);
if (contactPassword.equals(password))
{
Intent i = new Intent("info.androidhive.materialdesign.activity.MainActivity");
startActivity(i);
finish();
}
else
{
Toast temp = Toast.makeText(Login.this, "Email and password don't match", Toast.LENGTH_SHORT);
temp.show();
}
}
}
}
You initialize the login button in the onCreate() here:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn_login = (Button) findViewById(R.id.login_1);
and then you call the onClickButtonListener2(); in which you initialize the button again in here:
public void onClickButtonListener2()
{
btn_login = (Button) findViewById(R.id.login_1);
So just do this:
call this onClickButtonListener2(); method in onCreate() and modify code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn_login = (Button) findViewById(R.id.login_1);
emailEditText = (EditText)findViewById(R.id.uemail);
passwordEditText = (EditText)findViewById(R.id.upass);
sqlitehelper = new sqlitedb(getApplicationContext());
db = sqlitehelper.getWritableDatabase();
btn_login.setClickable(true);
onClickButtonListener1();
onClickButtonListener2();
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
and change the onClickButtonListener2(); to:
public void onClickButtonListener2(){
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String contactEmail = emailEditText.getText().toString();
String contactPassword = passwordEditText.getText().toString();
String password = sqlitehelper.getSingleEntry(contactEmail);
if (contactPassword.equals(password)){
Intent i = new Intent("info.androidhive.materialdesign.activity.MainActivity");
startActivity(i);
YourActivity.this.finish();
}else{
Toast temp = Toast.makeText(Login.this, "Email and password don't match", Toast.LENGTH_SHORT);
temp.show();
}
}
}
);
}
Hope it helps!!!

Return to main menu when clicking on button

When I click on the menu button I want to return to the main menu, activity with which the app starts with. What must follow the app.mobiledevicesecurity part? I thought it must be the starting class name? I am new to android studio development. Any help will be appreciated.
Logcat details:
09-01 19:02:04.755 1988-1988/app.mobiledevicesecurity E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: app.mobiledevicesecurity, PID: 1988
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=app.mobiledevicesecurity.MainActivity }
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1781)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1501)
at android.app.Activity.startActivityForResult(Activity.java:3745)
at android.app.Activity.startActivityForResult(Activity.java:3706)
at android.app.Activity.startActivity(Activity.java:4016)
at android.app.Activity.startActivity(Activity.java:3984)
at app.mobiledevicesecurity.Result$2.onClick(Result.java:46)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Result.java:
package app.mobiledevicesecurity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Result extends Activity
{
private static Button playbtn;
private static Button menubutton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
OnClickPlayButtonListener();
OnClickMenuButtonListener();
TextView textResult = (TextView) findViewById(R.id.textResult);
Bundle b = getIntent().getExtras();
int score = b.getInt("score");
textResult.setText("You scored" + " " + score + " for the quiz.");
}
public void OnClickPlayButtonListener() {
playbtn = (Button) findViewById(R.id.btn);
playbtn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Quiz");
startActivity(intent);
}
}
);
}
public void OnClickMenuButtonListener() {
menubutton = (Button) findViewById(R.id.menubtn);
menubutton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.MainActivity");
startActivity(intent);
}
}
);
}
}
Any suggestions with what I must replace the MainActivity text?
try to put like this:
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
this works for me...

How do I link these buttons to their layouts?

I was wondering if you guys can help me on my app. It’s something really easy for you guys that I’m missing. I’m trying to link buttons on one layout to navigate to other layouts. These six buttons should go to their six different layouts…
Button 7 should go to the layout Number7
I already did Button 1 and it works to number1.
Here’s a screenshot of the layout and here is my code to my main.java: http://imgur.com/zLJ3cdE
package com.example.isthisyourluckyday;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(Main.this, Number1.class));
}
});
}
}
Also….. Here is number7.java which should link to the number7 layout
package com.example.isthisyourluckyday;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
public class Number7 extends Activity {
Button button7;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.number7);
}}
If you guys can please help me out I’d really appreciate it.
If the first button works, where is the problem with the others ?
Below all the code :
public class Main extends Activity implements View.OnClickListener {
private final Button button1;
private final Button button2;
private final Button button3;
private final Button button4;
private final Button button5;
private final Button button6;
private final Button button7;
/** Called when the activity is first created. */
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
button5 = (Button) findViewById(R.id.button5);
button6 = (Button) findViewById(R.id.button6);
button7 = (Button) findViewById(R.id.button7);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
button4.setOnClickListener(this);
button5.setOnClickListener(this);
button6.setOnClickListener(this);
button7.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.equals(button1))
startActivity(new Intent(Main.this, Number1.class));
else if(v.equals(button2))
startActivity(new Intent(Main.this, Number2.class));
else if(v.equals(button3))
startActivity(new Intent(Main.this, Number3.class));
else if(v.equals(button4))
startActivity(new Intent(Main.this, Number4.class));
else if(v.equals(button5))
startActivity(new Intent(Main.this, Number5.class));
else if(v.equals(button6))
startActivity(new Intent(Main.this, Number6.class));
else if(v.equals(button7))
startActivity(new Intent(Main.this, Number7.class));
}
}
The Main class can implement OnClickListener to have only one onClick() function.
I did not test this properly, but you get the idea. It is similar to the other answer, but the code is a bit cleaner and has less repetition in my opinion.
package com.example.isthisyourluckyday;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Main extends Activity implements View.OnClickListener {
final Button[] buttons = new Button[7];
final Class[] classes = { Number1.class, Number3.class, Number3.class,
Number4.class, Number5.class, Number6.class, Number7.class };
/** Called when the activity is first created. */
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttons[0] = (Button) findViewById(R.id.button1);
buttons[1] = (Button) findViewById(R.id.button2);
buttons[2] = (Button) findViewById(R.id.button3);
buttons[3] = (Button) findViewById(R.id.button4);
buttons[4] = (Button) findViewById(R.id.button5);
buttons[5] = (Button) findViewById(R.id.button6);
buttons[6] = (Button) findViewById(R.id.button7);
for(Button b : buttons){
b.setOnClickListener(this);
}
}
#Override
public void onClick(View v) {
for(int i=0; i<buttons.length; i++){
if(buttons[i].equals(v)){
Intent intent = new Intent(Main.this, classes[i]);
startActivity(intent);
}
}
}
}
When you start an activity like this
startActivity(new Intent(Main.this, Number1.class));
you are telling Android to start the Number1 activity. So if you want to start another activity you just do the same thing you did:
final Button b7 = (Button) findViewById(R.id.button7);
b7.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Main.this, Number7.class));
}
});
This is not elegant, but will do the trick.
You could also define a "tag" on each button like
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tag="1"
android:onClick="choose"/>
then in your activity add a method
public void choose(View view) {
String number = view.getTag().toString();
Intent intent=new Intent();
intent.setComponent(new ComponentName("com.example.isthisyourluckyday", "com.example.isthisyourluckyday.Number"+number));
startActivity(intent);
}

setOnClickListener and findByViewId

this part of my code is having a problem
insertButton = (Button) findByViewId(R.id.button1);
insertButton.setOnClickListener(new OnClickListener();
it keeps saying method undefined for findByViewId, method for setOnClickListener not applicable and OnClickListener cannot be resolved
here is my full code
package edu.nyp.project;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AddData extends Activity {
Button insertButton = null;
EditText shopText= null;
EditText dealText= null;
EditText locationText= null;
EditText websiteText= null;
EditText categoryText= null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adddata);
insertButton = (Button) findByViewId(R.id.button1);
insertButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
DBAdapter dbAdapter = new
DBAdapter(getApplicationContext());
try{
dbAdapter.open();
String shop = shopText.getText().toString();
String deal = dealText.getText().toString();
String location = locationText.getText().toString();
String website = websiteText.getText().toString();
String category = categoryText.getText().toString();
}
catch(Exception e){
Log.d("Add Data ", e.getMessage());
}
finally{
if (dbAdapter != null)
dbAdapter.close();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.adddata, menu);
return true;
}
}
may i know what is wrong?
Import below line in your activity
import android.view.View.OnClickListener;
try
insertButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
}
}
Use findViewById method instead of findByViewId.
insertButton = (Button) findViewById(R.id.button1);
insertButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
//Code for action listener.
}
});
Only thing that i can find unusual about the above code is :
insertButton = (Button) findByViewId(R.id.button1);
So replace it with:
insertButton = (Button) findViewById(R.id.button1);
The rest of the code is fine. I mean the below code is perfectly fine:
insertButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
DBAdapter dbAdapter = new
DBAdapter(getApplicationContext());
try{
dbAdapter.open();
String shop = shopText.getText().toString();
String deal = dealText.getText().toString();
String location = locationText.getText().toString();
String website = websiteText.getText().toString();
String category = categoryText.getText().toString();
}
catch(Exception e){
Log.d("Add Data ", e.getMessage());
}
finally{
if (dbAdapter != null)
dbAdapter.close();
}
}
});
The above kind of syntax always works for me.

Error when setting OnClickListener in android

I'm beginner in android and I wrote the following simple program that just shows the text of the button I press on a TextView (I always get a runtime error):
package com.hmz.secondapp;
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 AppPageActivity extends Activity {
Button btnPlus;
Button btnMinus;
Button btnMul;
Button btnDiv;
TextView resultTextView;
View.OnClickListener operations = new View.OnClickListener() {
public void onClick(View v) {
Button pressedButton = (Button) v;
String buttonLabel = pressedButton.getText().toString();
resultTextView.setText(buttonLabel);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.app_page);
btnPlus.setOnClickListener(operations);
btnMinus.setOnClickListener(operations);
btnMul.setOnClickListener(operations);
btnDiv.setOnClickListener(operations);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.app_page, menu);
return true;
}
}
Your btnPlus object is null. You need to instantiate it in the onCreate method like
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.app_page);
btnPlus = (Button)findViewById(R.id.YOUR_BUTTON_ID);
btnMinus = (Button)findViewById(R.id.YOUR_BUTTON_ID);
btnMul = (Button)findViewById(R.id.YOUR_BUTTON_ID);
btnDiv = (Button)findViewById(R.id.YOUR_BUTTON_ID);
btnPlus.setOnClickListener(operations);
btnMinus.setOnClickListener(operations);
btnMul.setOnClickListener(operations);
btnDiv.setOnClickListener(operations);
}
Also instantiate the resultTextView object before you use setText method.
From your code the problem is seems that you are not initializing the buttons (btnPlus,btnMinus,btnMul,btnDiv) and the TextView resultTextView.
btnPlus = (Button)findViewById(Button Id);
btnMinus = (Button)findViewById(Button Id);
btnMul = (Button)findViewById(Button Id);
btnDiv = (Button)findViewById(Button Id);
resultTextView = (Button)findViewById(TextView Id);
First initialize these Views then you can apply any operation on these views like Click Events and setting the text.

Categories

Resources