Android app crashes when starting a new Intent - java

I'm writing a program where after clicking this button another program will be started.
However, the program force closed when I click the corresponding button.
here's the code.
package com.example.pc.multi_functionapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button)findViewById(R.id.button_1);
Button button2 = (Button)findViewById(R.id.button_2);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent int1 = new Intent(MainActivity.this, Accelerometer.class);
startActivity(int1);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent int2 = new Intent(MainActivity.this, Locator.class);
startActivity(int2);
}
});
}
}
Here's the XML code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:layout_gravity="center_horizontal"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:id="#+id/button_1"
android:text="Android Accelerometer"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:id="#+id/button_2"
android:text="Android Current Location"
/>
</LinearLayout>
Here's the android manifest code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.pc.multi_functionapp">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Locator"></activity>
<activity android:name=".Accelerometer" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</man
For the program itself, Accelerometer and Locator work properly if I running it one by one.
I'm creating this program in purpose, these two programs can be run in one app, no need to open it in a different app.
I'm expecting after I click the first button, the accelerometer program will be started and when I click the second button, the Locator program will be started.
what happened is, when I click it the program just force closed.
please help me so the button works properly when clicked.
Edit :
Accelerometer Code
package com.example.pc.multi_functionapp;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class Accelerometer extends AppCompatActivity implements SensorEventListener {
private static final String TAG = "MainActivity";
private SensorManager sensorManager;
Sensor accelerometer;
TextView xValue, yValue, zValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
xValue = (TextView) findViewById(R.id.xValue);
yValue = (TextView) findViewById(R.id.yValue);
zValue = (TextView) findViewById(R.id.zValue);
Log.d(TAG, "onCreate: initializing Sensor Services");
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(Accelerometer.this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
Log.d(TAG, "onCreate: Registered accelerometer listener");
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
Log.d(TAG, "onSensorChanged: X: " + sensorEvent.values[0] + "Y: " + sensorEvent.values[1] + "Z: " + sensorEvent.values[2]);
xValue.setText("xValue: " + sensorEvent.values[0]);
yValue.setText("yValue: " + sensorEvent.values[1]);
zValue.setText("xValue: " + sensorEvent.values[2]);
}
}
Locator Code
package com.example.pc.multi_functionapp;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class Locator extends AppCompatActivity {
TextView textView1, textView2, textView3, textView4, textView5;
FusedLocationProviderClient fusedLocationProviderClient;
Button btLocation;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btLocation = findViewById(R.id.bt_location);
textView1 = findViewById(R.id.text_view1);
textView2 = findViewById(R.id.text_view2);
textView3 = findViewById(R.id.text_view3);
textView4 = findViewById(R.id.text_view4);
textView5 = findViewById(R.id.text_view5);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
btLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(Locator.this
, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
getLocation();
}
else {
ActivityCompat.requestPermissions(Locator.this
, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 44);
}
}
});
}
private void getLocation() {
fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
Location location = task.getResult();
if (location != null){
try {
Geocoder geocoder = new Geocoder(Locator.this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1 );
textView1.setText(Html.fromHtml("<font color='#6200EE'><B>Latitude :</b><br></font>" + addresses.get(0).getLatitude()));
textView2.setText(Html.fromHtml("<font color='#6200EE'><B>Longitude :</b><br></font>" + addresses.get(0).getLongitude()));
textView3.setText(Html.fromHtml("<font color='#6200EE'><B>Country Name :</b><br></font>" + addresses.get(0).getCountryName()));
textView4.setText(Html.fromHtml("<font color='#6200EE'><B>Locality :</b><br></font>" + addresses.get(0).getLocality()));
textView5.setText(Html.fromHtml("<font color='#6200EE'><B>Address :</b><br></font>" + addresses.get(0).getAddressLine(0)));
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
}
Before CLicked
After Clicked

Oh, your error is simple.
I think you have copied the Activities and you have forgotten to change the layout in the setContentView() of all of your Activities. all of them are R.layout.activity_main so the app is starting the activity_main.xml but the view are getting findViewById() from their real resources.

Crash maybe because of the two reasons.
Make sure you have separate layout for all your activities.
Make sure your activities added in the AndroidManifest.xml file.

Related

"Button button1 = (Button)findViewById(R.id.button_1) " goes run in Android [duplicate]

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 10 months ago.
I'm a beginner in Android , so please pardon my ignorance.
As I was learning Android programming,I followed the book and the codes are as follows:
FirstActivity.java
package com.example.activitytest;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class FirstActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
Button button1 = (Button)findViewById(R.id.button_1);
button1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Toast.makeText(FirstActivity.this, "You clicked Button 1", Toast.LENGTH_SHORT).show();
}
});
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.activitytest">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Activitytest">
<activity
android:name=".FirstActivity"
android:label="This is FirstActivity"
android:exported="true">
<intent-filter>
<action android:name = "android.intent.action.MAIN"/>
<category android:name = "android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
first_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/button_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/button_1"
tools:ignore="MissingConstraints"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="1dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
And android studio reports that:
error: cannot find symbol
Button button1 = (Button)findViewById(R.id.button_1);
^
symbol: class Button
location: class FirstActivity
and then I search stackoverflow to find the method to debug.
I once tried this method:
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button)rootView.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onButtonClick((Button) view);
}
});
But it still does not work.As I am just a beginner, I can't find a way to debug.
Can someone help me? Thank you for that.
As I can see in your code that in xml you have assigned the id to the button which is
android:id="#+id/button_1"
but you are trying to access the wrong id here
Button buttonClick = (Button)rootView.findViewById(R.id.button);
and if you are in activity there is no need of rootView you can simply access the button with findViewById(R.id.button_1)
Also it is missing in your first_layout.xml
tools:context=".FirstActivity"
add this to the constraintLayout in xml
also add import
import android.widget.Button;
And I will suggest you to use viewBinding it will help you a lot in this case
add this line
import android.widget.Button;
FirstActivity.java
package com.example.activitytest;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.widget.Button;
public class FirstActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
Button button1 = (Button)findViewById(R.id.button_1);
button1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Toast.makeText(FirstActivity.this, "You clicked Button 1", Toast.LENGTH_SHORT).show();
}
});
}
}

getApplicationContext() method getting error

I am a Android beginner, making a simple Service example.
but in a single code getApplicationContext() method behaves differently, Please check comment of MainActivity.
MainActivity.java
package com.avisingh.servicetest;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button alertButton = (Button)findViewById(R.id.alert_btn);
alertButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); //If i placing here getApplicationContext() method then getting error;
builder.setTitle("Warning");
builder.setMessage("Are you sure to open media played in this app?");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(getApplicationContext(),PlayerActivity.class)); // here getApplicationContext() and MainActivity.this both working
}
});
builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show(); //getting error here.
}
});
}
}
PlayerActivity.java
package com.avisingh.servicetest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class PlayerActivity extends AppCompatActivity{
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_activity);
final Button startBtn = (Button)findViewById(R.id.start_btn);
final Button stopBtn = (Button)findViewById(R.id.stop_btn);
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(getApplicationContext(),MyServices.class));
}
});
stopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getApplicationContext(),MyServices.class));
}
});
}
}
MyServices.java
package com.avisingh.servicetest;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;
public class MyServices extends Service {
MediaPlayer mediaPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
//return null;
throw new UnsupportedOperationException("Not implemented");
}
#Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.one_man);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mediaPlayer.start();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
}
}
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.avisingh.servicetest">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".PlayerActivity"/>
<service android:name=".MyServices"/>
</application>
activity_main
<?xml version="1.0" encoding="utf-8"?>
<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="com.avisingh.servicetest.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/alert_btn"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:id="#+id/alert_btn"/>
</RelativeLayout>
player_activity
<?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">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="#string/start_btn"
android:id="#+id/start_btn"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="#string/stop_btn"
android:id="#+id/stop_btn"/>
</RelativeLayout>
Error:
08-14 14:17:58.916 6874-6874/com.avisingh.servicetest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.avisingh.servicetest, PID: 6874
java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at android.support.v7.app.AppCompatDelegateImplV9.createSubDecor(AppCompatDelegateImplV9.java:359)
at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:289)
at android.support.v7.app.AppCompatDialog.setContentView(AppCompatDialog.java:83)
at android.support.v7.app.AlertController.installContent(AlertController.java:225)
at android.support.v7.app.AlertDialog.onCreate(AlertDialog.java:257)
at android.app.Dialog.dispatchOnCreate(Dialog.java:373)
at android.app.Dialog.show(Dialog.java:274)
at com.avisingh.servicetest.MainActivity$1.onClick(MainActivity.java:42)
at android.view.View.performClick(View.java:4759)
at android.view.View$PerformClick.run(View.java:19770)
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:5247)
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:912)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707)
//If i placing here getApplicationContext() method then getting error
Correct. That is because the Application object does not know anything about themes, and your dialog needs a theme based on Theme.AppCompat. Always use your Activity context for creating dialogs.
You may wish to read Dave Smith's awesome blog post on the uses of different types of Context object for more on this.

A Button which does not work

I am trying to make a quiz app in Android Studio 1.5 and my title screen "Begin" Button does not work.
It is supposed to lead from the MainActivity to the second Activity named questionone.
Here is the Button from the layout:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Begin"
android:id="#+id/begin"
android:layout_marginTop="45dp"
android:layout_below="#+id/textView"
android:layout_alignRight="#+id/textView"
android:layout_alignEnd="#+id/textView"
android:clickable="true"
android:background="#ffffff"
android:onClick="toDo" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exit"
android:id="#+id/exit"
android:layout_marginTop="27dp"
android:layout_below="#+id/begin"
android:layout_alignLeft="#+id/begin"
android:layout_alignStart="#+id/begin"
android:clickable="true"
android:onClick="toDo"
android:background="#ffffff" />
Here is the code from my MainActivity Java file:
package com.example.noot_a_normal_pc.kmtomiles;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import static android.widget.Toast.makeText;
public class MainActivity extends AppCompatActivity {
Button buttonBegin, buttonExit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonBegin = (Button) findViewById(R.id.begin);
buttonExit = (Button) findViewById(R.id.exit);
}
public void buttonBegin (View view){
Intent intent = new Intent (this, question.class);
startActivity(intent);
}
public void toDo(View v) {
if (v.equals(buttonExit)) {
Toast.makeText(getApplicationContext(), "Why would you want to exit such a great app?", Toast.LENGTH_LONG).show();
}
}
}
Here is also my Android Manifest file:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".questionone">
</activity>
</application>
</manifest>
Your problem is that you have put android:onClick="toDo" twice, and so buttonBegin is never used.
As an alternative, I would recommend this after you remove any android:onClick from the XML
public class MainActivity extends AppCompatActivity
implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.begin).setOnClickListener(this);
findViewById(R.id.exit).setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.begin:
// handle begin
break;
case R.id.exit:
// handle exit
break;
}
}
}
Also, based on the Activity name "questionone", I would strongly suggest you avoid the thought that you need one new Activity per question.
You only need one generic Activity to display any question.
In your MainActivity, I would recommend implementing an OnClickListener...
package com.example.noot_a_normal_pc.kmtomiles;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import static android.widget.Toast.makeText;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button buttonBegin, buttonExit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonBegin = (Button) findViewById(R.id.begin);
buttonBegin.setOnClickListener(this);
buttonExit = (Button) findViewById(R.id.exit);
buttonExit.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.equals(buttonExit)) {
Toast.makeText(getApplicationContext(), "Why would you want to exit such a great app?", Toast.LENGTH_LONG).show();
}
else if (v.equals(buttonBegin)) {
//run your app!
}
}
}
your Button xml is wrong, change it like below:(onClick field is changed from toDo to buttonBegin)
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Begin"
android:id="#+id/begin"
android:layout_marginTop="45dp"
android:layout_below="#+id/textView"
android:layout_alignRight="#+id/textView"
android:layout_alignEnd="#+id/textView"
android:clickable="true"
android:background="#ffffff"
android:onClick="buttonBegin" />
Your button will newer call "buttonBegin(View v)" because in his XML you set "toDo(View v)" in onClick attribute.
So you should make it look like this:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Begin"
android:id="#+id/begin"
android:layout_marginTop="45dp"
android:layout_below="#+id/textView"
android:layout_alignRight="#+id/textView"
android:layout_alignEnd="#+id/textView"
android:clickable="true"
android:background="#ffffff"
android:onClick="buttonBegin" />
But better and cleaner idea to accomplish what you want is setting onClickListener on your button. Something like this:
buttonBegin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent (this, question.class);
startActivity(intent);
}
});
If user clicks on you button then code inside onClick(View v){ //code } will run.

Error: has stopped unexpectedly. please try again - Android

I wonder what is the reason of this error happen...
I was developing a CRUD and for some reason burst it. Many codes and take you to analyze, is there anything I can do to know where this error is being triggered
MainActivity.java
package br.com.crud.Activitys;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import br.com.crud.R;
public class MainActivity extends Activity
{
Button btnView;
Button btnCadastro;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnCadastro = (Button) findViewById(R.id.btnCadastro);
btnView = (Button) findViewById(R.id.btnView);
btnView.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v){
}
});
btnCadastro.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), NovoProdutoActivity.class);
startActivityForResult(i, 1);
}
});
}
}
NovoProdutoActivity.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.crud.Activitys;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import br.com.crud.R;
/**
*
* #author muky
*/
public class NovoProdutoActivity extends Activity{
Button btnSalvar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.novo_produto);
btnSalvar = (Button) findViewById(R.id.btnSalvar);
btnSalvar.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Produto Salvo com Sucesso", 6).show();
}
});
}
}
LogCat
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="br.com.crud"
android:versionCode="1"
android:versionName="1.0">
<application android:label="#string/app_name" >
<activity android:name="MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- View Cadastro de Produto -->
<activity
android:name="NovoProdutoActivity"
android:label="NovoProduto"/>
<!-- View Listar Produtos -->
<activity
android:name="ListaProdutoActivity"
android:label="ListarProdutos"/>
</application>
</manifest>
Your main activity in code is br.com.crud.Activitys.MainActivity while the manifest says it is br.com.crud.MainActivity. Make sure the full class names agree in manifest and in code.

Button's don't work when clicked on, Code is correct

I tried test files like HelloWorld and Count Down timer. Neither of the buttons on my app seem to work. These segments of code are ones I downloaded from the internet, and they have been reported to work. I don't know what the issue could be. I am also very new eclipse and android app programming.
activity_main.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:textColor="#FF0000"
android:background="#000000"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FF0000"
android:text="CountDown Timer Demo"
/>
<Button
android:text="Seizure Detected"
android:id="#+id/start"
android:textColor="#FF0000"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<Button
android:text="Override"
android:id="#+id/stop"
android:textColor="#FF0000"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<Button
android:text="click me"
android:id="#+id/Button01"
android:textColor="#FF0000"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<TextView
android:id="#+id/tv"
android:textColor="#FF0000"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="sexy"/>
</LinearLayout>
CountDownTest.java >In the src folder
package com.example.epilepsytestapp;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class CountDownTest extends Activity {
Button start, stop;
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button)this.findViewById(R.id.start);
stop = (Button)this.findViewById(R.id.stop);
tv = (TextView)this.findViewById(R.id.tv);
tv.setText("10"); // startting from 10.
final MyCounter timer = new MyCounter(10000,1000);
start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
timer.start();
}
});
stop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
timer.cancel();
}
});
}
public class MyCounter extends CountDownTimer{
public MyCounter(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
System.out.println("Timer Completed.");
tv.setText("Timer Completed.");
}
#Override
public void onTick(long millisUntilFinished) {
tv.setText((millisUntilFinished/1000)+"");
System.out.println("Timer : " + (millisUntilFinished/1000));
}
}
}
Here is Helloworld.java
package com.example.epilepsytestapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class HelloWorld extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) this.findViewById(R.id.Button01);
button.setOnClickListener(new OnClickListener() {
//#Override
public void onClick(View v) {
Toast.makeText(HelloWorld.this, "Hello World", Toast.LENGTH_SHORT).show();
}
});
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.epilepsytestapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity android:name=".CountDownTest"/>
<activity
android:name="com.example.epilepsytestapp.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN"
android:name=".CountDownTest"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
try this.Your hello world code
package com.example.epilepsytestapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.Button01);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(this, "Hello World", Toast.LENGTH_SHORT).show();
}
});
}
}

Categories

Resources