I'm working on a app in Android Studio with multiple activities, and I am trying to make button1 go to my SecondActivity and button2 to my ThirdActivity. Whenever I run button in my app it crashes.
This is my MainActivity.java:
package hobby_pc.medispeak;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
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.button1);
Button button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View v) {
goToSecondActivity();
}
});
button2.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View v) {
goToThirdActivity();
}
});
}
private void goToSecondActivity()
{
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
private void goToThirdActivity()
{
Intent intent = new Intent(this, ThirdActivity.class);
startActivity(intent);
}
This is my activity_main.xml:
<?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"
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="hobby_pc.medispeak.MainActivity"
android:background="#ffffff">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Welkom"
android:textSize="#dimen/abc_text_size_title_material_toolbar"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Medicijnenzoeken"
android:id="#+id/button1"
android:layout_marginTop="111dp"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Goochempie"
android:id="#+id/button2"
android:layout_below="#+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="72dp" />
</RelativeLayout>
This is my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="hobby_pc.medispeak">
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".SplashScreen"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="com.Medispeak.androidsplashscreenexample.MAINACTIVITY" />
</intent-filter>
</activity>
<category android:name="android.intent.category.DEFAULT" />
<activity android:name=".ThirdActivity" />
<activity android:name=".SecondActivity" />
<receiver android:name=".AlarmReceiver"></receiver>
</application>
This is the error I get when it crashes:
06-02 14:13:25.900 21384-21384/hobby_pc.medispeak E/AndroidRuntime: FATAL EXCEPTION: main
Process: hobby_pc.medispeak, PID: 21384
java.lang.RuntimeException: Unable to start activity ComponentInfo{hobby_pc.medispeak/hobby_pc.medispeak.ThirdActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2702)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
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:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at hobby_pc.medispeak.ThirdActivity.onCreate(ThirdActivity.java:34)
at android.app.Activity.performCreate(Activity.java:6289)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2655)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
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:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
It seems you haven't declared ThirdActivity in your AndroidManifest.xml.
you can see the crash reason in this line : java.lang.RuntimeException: Unable to start activity ComponentInfo{hobby_pc.medispeak/hobby_pc.medispeak.ThirdActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
I think in your onCreate method in thirdActivity, you are trying to setText for a textView that is not bound to view.
use findViewById() before calling setText() on textView
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at hobby_pc.medispeak.ThirdActivity.onCreate(ThirdActivity.java:34)
There's your problem, a NullPointerException in your ThirdActivity class at line 34. You have apparently called setText() on a TextView without initializing it with findViewById(R.id.some_id) first.
Related
I am having troubles and I can't figure out what the problem is.
There is no alert in my code, neither a red line or something.
HotelMapActivity.java
public class HotelMapActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_hotel);
}
public void onClick(View v){
Intent intent = null;
switch (v.getId()){
case R.id.button1:
intent = new Intent(this, Map1.class);
break;
}
startActivity(intent);
}
}
This my button xml layout
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.together.Activities.Map.HotelMapActivity">
<android.support.v7.widget.AppCompatButton
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:onClick="onClick"
tools:context=".Activities.Map.HotelMapActivity"
android:text="google map"/>
<android.support.v7.widget.AppCompatButton
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#id/button1"
android:onClick="onClick"
tools:context=".Activities.Map.HotelMapActivity"
android:text="place"/>
<android.support.v7.widget.AppCompatButton
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#id/button2"
android:onClick="onClick"
tools:context=".Activities.Map.HotelMapActivity"
android:text="Geo coding"/>
</RelativeLayout>
This is my Map1 Class
public class Map1 extends AppCompatActivity implements OnMapReadyCallback {
SupportMapFragment fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map1);
fragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.fragment1);
fragment.getMapAsync(this);
}
//비동기적인 방식으로 구글맵을 생성
#Override
public void onMapReady(GoogleMap map) {
//지도 종류
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//현재 위치 표현 옵션
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
map.setMyLocationEnabled(true);
//줌컨트롤 표시 여부 ( 1 ~ 21 )
map.getUiSettings().setZoomControlsEnabled(true);
}
This is my Map1 activity
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context="com.example.together.Activities.Map.Map1">
<fragment
android:id="#+id/fragment1"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="333dp"
android:layout_height="465dp"
android:layout_marginStart="36dp"
android:layout_marginTop="132dp"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
I want to know what makes error occured
because nothing show to me what error is
This is my error code
Caused by: android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class fragment
Caused by: java.lang.RuntimeException: API key not found. Check that <meta-data android:name="com.google.android.geo.API_KEY" android:value="your API key"/> is in the <application> element of AndroidManifest.xml
at com.google.maps.api.android.lib6.drd.p.b(:com.google.android.gms.dynamite_mapsdynamite#17455084#17.4.55 (100700-248795830):22)
at com.google.maps.api.android.lib6.auth.d.a(:com.google.android.gms.dynamite_mapsdynamite#17455084#17.4.55 (100700-248795830):10)
at com.google.maps.api.android.lib6.impl.d.a(:com.google.android.gms.dynamite_mapsdynamite#17455084#17.4.55 (100700-248795830):41)
at com.google.android.gms.maps.internal.CreatorImpl.a(:com.google.android.gms.dynamite_mapsdynamite#17455084#17.4.55 (100700-248795830):61)
at com.google.android.gms.maps.internal.CreatorImpl.newMapFragmentDelegate(:com.google.android.gms.dynamite_mapsdynamite#17455084#17.4.55 (100700-248795830):25)
at com.google.android.gms.maps.internal.j.a(:com.google.android.gms.dynamite_mapsdynamite#17455084#17.4.55 (100700-248795830):73)
at hm.onTransact(:com.google.android.gms.dynamite_mapsdynamite#17455084#17.4.55 (100700-248795830):4)
at android.os.Binder.transact(Binder.java:667)
at com.google.android.gms.internal.maps.zza.transactAndReadException(Unknown Source:7)
at com.google.android.gms.maps.internal.zzf.zzc(Unknown Source:8)
at com.google.android.gms.maps.MapFragment$zzb.zzc(Unknown Source:31)
at com.google.android.gms.maps.MapFragment$zzb.createDelegate(Unknown Source:2)
at com.google.android.gms.dynamic.DeferredLifecycleHelper.zza(Unknown Source:44)
at com.google.android.gms.dynamic.DeferredLifecycleHelper.onInflate(Unknown Source:5)
at com.google.android.gms.maps.MapFragment.onInflate(Unknown Source:44)
at android.app.Fragment.onInflate(Fragment.java:1443)
at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3555)
at android.app.FragmentController.onCreateView(FragmentController.java:102)
at android.app.Activity.onCreateView(Activity.java:6323)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:389)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:780)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
2019-06-07 20:34:58.118 31313-31313/com.example.blogapp E/AndroidRuntime: at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.together.Activities.Map.Map1.onCreate(Map1.java:22)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
This is my Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.together">
<!-- 맵 이용하기 위함 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- 다음 지도 -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- 대략적인 위치 참조 권한 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- 정확한 위치 참조 권한 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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"
android:usesCleartextTraffic="true">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="i input my key in here" />
<activity android:name=".Activities.Map.Map1"></activity>
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
<activity android:name=".Activities.MyPetInfo.MyPetRegActivity" />
<activity android:name=".Activities.MyPetInfo.MyPetListActivity" />
<activity android:name=".Activities.Petching.MatchesActivity" />
<activity android:name=".Activities.Petching.SettingsActivity" />
<activity android:name=".Activities.Map.HotelMapActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Activities.GoodbyePet.GoodbyePetActivity" />
<activity android:name=".Activities.PetHospital.PetHospitalActivity" />
<activity android:name=".Activities.PetGroup.PetGroupActivity" />
<activity android:name=".Activities.Petching.PetchingActivity" />
<activity android:name=".Activities.PetHotel.PetHotelActivity" />
<activity android:name=".Activities.PetHotel.HotelListDataActivity" />
<activity android:name=".Activities.PetHotel.HotelDetailActivity" />
<activity android:name=".Activities.Chat.MessageActivity" />
<activity android:name=".Activities.Chat.ChatsActivity" />
<activity android:name=".Activities.OptionActivity" />
<activity android:name=".Activities.FollowersActivity" />
<activity android:name=".Activities.EditProfileActivity" />
<activity android:name=".Activities.CommentsActivity" />
<activity android:name=".Activities.LoginActivity" />
<activity android:name=".Activities.RegisterActivity" />
<activity android:name=".Activities.PostActivity" />
<activity android:name=".Activities.HomeActivity" />
<activity
android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
android:theme="#style/Base.Theme.AppCompat" />
</application>
</manifest>
Add the key on your AndroidManifest:
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY"/>
Try below code
android:name="com.google.android.gms.maps.MapFragment"
to
class="com.google.android.gms.maps.SupportMapFragment"
Because in your Java file you used the
fragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.fragment1);
fragment.getMapAsync(this);
MapFragment does not casting into SupportMapFragment.
I hope its work for you.
There have been recent updates to the google API. The google API client has also been updated. google-api-client.
I built a simple project that squares a given number. In that app as soon as i click the button "Calculate" it say's "Unfortunately, SquareCalculator has stopped". What should i do to resolve the problem?
Below is my entire code:-
MainActivity.java
package thenerdimite.squarecalculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
protected void calculate (View v){
EditText input = (EditText) findViewById(R.id.etInput);
TextView output = (TextView) findViewById(R.id.tvOutput);
int base = Integer.valueOf(input.getText().toString());
int result = base * base;
String formattedResult = String.format("%,d", result);
output.setText("Result: " + formattedResult);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context="thenerdimite.squarecalculator.MainActivity">
<EditText
android:id="#+id/etInput"
android:layout_width="245dp"
android:layout_height="41dp"
android:layout_marginTop="15dp"
android:ems="10"
android:inputType="number"
tools:layout_editor_absoluteX="16dp"
tools:layout_editor_absoluteY="62dp"
android:layout_below="#+id/tvInput"
android:layout_alignStart="#+id/tvInput" />
<Button
android:id="#+id/btnCalculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/etInput"
android:layout_below="#+id/etInput"
android:layout_marginTop="20dp"
android:onClick="Calculate"
android:text="Calculate"
android:textSize="18sp" />
<TextView
android:id="#+id/tvOutput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result:"
android:textAppearance="#style/TextAppearance.AppCompat.Display1"
android:layout_below="#+id/btnCalculate"
android:layout_alignStart="#+id/btnCalculate"
android:layout_marginTop="18dp" />
<TextView
android:id="#+id/tvInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter an Integer:"
android:textAppearance="#style/TextAppearance.AppCompat.Display1"
android:layout_marginStart="19dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
logcat
04-25 09:28:05.060 3596-3596/thenerdimite.squarecalculator D/AndroidRuntime: Shutting down VM
04-25 09:28:05.060 3596-3596/thenerdimite.squarecalculator W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa5007678)
04-25 09:28:05.060 3596-3596/thenerdimite.squarecalculator E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not find method Calculate(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'btnCalculate'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
04-25 09:28:06.740 3596-3596/? I/Process: Sending signal. PID: 3596 SIG: 9
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="thenerdimite.squarecalculator">
<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>
</application>
</manifest>
Using the documentation of Button
You see the method need to be public and accept a View
In order for this to work, the method must be public and accept a View as its only parameter.
So it should be
public void Calculate (View v){
Using the xml notation, of course, you should call it calculate and correct the XML
From what I see, the problem is that your button action is android:onClick="Calculate" but should be android:onClick="calculate"
you need to make the method public, protected and private methods are not accessible by xml.
public void calculate (View v){
EditText input = (EditText) findViewById(R.id.etInput);
TextView output = (TextView) findViewById(R.id.tvOutput);
int base = Integer.valueOf(input.getText().toString());
int result = base * base;
String formattedResult = String.format("%,d", result);
output.setText("Result: " + formattedResult);
}
Change android:onClick="Calculate" to android:onClick="calculate".
Also calculate method should be public.
In XML you have "Calculate" with capital "C" while method is called "calculate". Change XML and it should work.
https://developer.android.com/reference/android/widget/Button.html
I am trying to show another activity by clicking a button with Intent class but it stills gives error which is
" unfortunately my application has stopped"
and I think the code is correct
this is the `main activity class
course=(EditText) findViewById(R.id.editText);
hour=(EditText) findViewById(R.id.editText1);
add= (Button) findViewById(R.id.button);
view_= (Button) findViewById(R.id.button1);
view_.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,ViewActivity.class);
startActivity(intent);
}
});
}
}
and this is ViewActivity class
TextView tv;
Button ed, de, view_;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
tv = (TextView) findViewById(R.id.details);
ed = (Button) findViewById(R.id.ed);
de = (Button) findViewById(R.id.delete);
view_= (Button) findViewById(R.id.button1);
Intent intent = getIntent();
view_.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
In additional I had added the .ViewActivity on the AndroidManifest.xml
<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=".ViewActivity" />
</application>'
locat >>
FATAL EXCEPTION: main
Process: com.example.android.intent, PID: 11316
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.intent/com.example.android.intent.ViewActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.android.intent.ViewActivity.onCreate(ViewActivity.java:34)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
view layout file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TableRow
android:layout_width="80dp"
android:layout_height="50dp" >
<TextView
android:text="Course"
android:layout_width="80dp"
android:layout_height="50dp"
android:id="#+id/course"
android:layout_marginLeft="50dp"
android:layout_marginTop="10dp"
android:textSize="24sp" />
<TextView
android:text="Hour"
android:layout_width="80dp"
android:layout_height="50dp"
android:id="#+id/hour"
android:layout_marginLeft="170dp"
android:layout_marginTop="10dp"
android:textSize="24sp"
android:layout_marginRight="30dp" />
</TableRow>
</TableLayout>
<Button
android:text="Edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="45dp"
android:id="#+id/ed"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="38dp"
android:layout_marginStart="38dp"
android:onClick="" />
<Button
android:text="Delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="19dp"
android:layout_marginEnd="19dp"
android:id="#+id/delete"
android:layout_alignBaseline="#+id/ed"
android:layout_alignBottom="#+id/ed"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="" />
<TextView
android:layout_width="350dp"
android:layout_height="350dp"
android:id="#+id/details"
android:layout_above="#+id/delete"
android:layout_centerHorizontal="true" />
<Button
android:text="Refresh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/delete"
android:layout_toLeftOf="#+id/delete"
android:layout_toStartOf="#+id/delete"
android:layout_marginRight="28dp"
android:layout_marginEnd="28dp"
android:id="#+id/button4"
android:onClick="" />
Can anyone help , thanks :)
Change your manifest like this,You added the ViewActivity inside another activity.
<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 = ".ViewActivity"/>
</application>'
Add this to your view layout,
<Button
android:text="Close View Activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button1" />
You haven't close the activity tag. Change AndroidManifest.xml to:
<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=".ViewActivity">
</activity>
</application>
Change this
view_= (Button) findViewById(R.id.button1);
To
view_= (Button) findViewById(R.id.button4);
There is no Button button1 in your ViewActivity class's XML, so when you try to access button1, NullPointerException occurs.
Try this in your manifest. You put one activity in another. Put seperate.
<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=".ViewActivity" />
</application>
I just want to ask you why using intent makes my system crashed? I've used same codes before and it works, then when I use it again now it won't. What do you think the problem guys?
MANIFEST
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<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>
<activity
android:name=".Login"
android:label="#string/title_activity_login" >
</activity>
</application>
MainActivity
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void okay(View view) {
Intent i = new Intent(this, Login.class);
startActivity(i);
2nd Activity (If I clicked the main activity, I just want this activity pop)
public class Login extends ActionBarActivity {
ListView listView;
ArrayAdapter<String> adapter;
String[] grocery_categories = {"Beverages", "Bakery", "Canned Goods", "Condiments", "Dairy", "Snacks", "Frozen Foods",
"Meat", "Produce", "Cleaners", "Paper Goods", "Personal Care", "Others"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
listView = (ListView) findViewById(R.id.list_view);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, grocery_categories);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
String grocery = (String) listView.getAdapter().getItem(position);
Intent intent = new Intent(listView.getContext(),Login.class);
listView.getContext().startActivity(intent);
//or create other intents here
}
});
}
XML of MainActivity
<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=".MainActivity"
android:id="#+id/rl_main_activity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/mobile_grocery_bckgrnd"
android:src="#drawable/mobile_grocery"
android:scaleType="centerCrop"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MOBILE GROCERY"
android:id="#+id/mobile_grocery_app"
android:textSize="45dp"
android:textColor="#000000"
android:gravity="center"
android:textStyle="bold|italic"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Application"
android:id="#+id/application"
android:textColor="#000000"
android:textSize="25dp"
android:layout_below="#+id/mobile_grocery_app"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/username"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/application"
android:layout_alignEnd="#+id/application"
android:layout_marginBottom="135dp"
android:hint="Username"
android:textColorHint="#000000"
/>
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/password"
android:layout_alignTop="#+id/username"
android:layout_alignRight="#+id/username"
android:layout_alignEnd="#+id/username"
android:layout_marginTop="52dp"
android:hint="Password"
android:textColorHint="#000000"
android:password="true" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK"
android:id="#+id/ok"
android:layout_below="#+id/password"
android:layout_alignLeft="#+id/application"
android:layout_alignStart="#+id/application"
android:onClick="okay" />
XML of Login Activity (2nd Activity)
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/login_bckgrnd"
android:src="#drawable/login_bckgrnd"
android:scaleType="centerCrop"
/>
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.admin.mobilegroceryapp" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<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>
<activity
android:name=".Login"
android:label="#string/title_activity_login" >
</activity>
</application>
</manifest>
logcat
.085 2019-2087/? I/InputDispatcher﹕ Delivering touch to current input target: action: 0x0
09-29 01:54:28.085 2019-2087/? I/InputDispatcher﹕ Delivering touch to current input target: action: 0x0
09-29 01:54:28.085 2019-2087/? I/InputDispatcher﹕ Delivering touch to current input target: action: 0x0
09-29 01:54:28.085 2019-2087/? I/InputDispatcher﹕ Delivering touch to current input target: action: 0x0
09-29 01:54:28.085 2019-2087/? I/InputDispatcher﹕ Delivering touch to current input target: action: 0x0
09-29 01:54:28.190 2019-2088/? I/InputReader﹕ Touch event's action is 0x1 (deviceType=0) [pCnt=1, s=]
09-29 01:54:28.285 30351-30351/? I/dalvikvm﹕ Could not find method android.graphics.Bitmap.getAllocationByteCount, referenced from method com.facebook.imagepipeline.a.d.a.a
09-29 01:54:28.285 30351-30351/? W/dalvikvm﹕ VFY: unable to resolve virtual method 625: Landroid/graphics/Bitmap;.getAllocationByteCount ()I
09-29 01:54:28.285 30351-30351/? D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0006
09-29 01:54:28.355 30482-30482/? D/dalvikvm﹕ WAIT_FOR_CONCURRENT_GC blocked 0ms
09-29 01:54:28.355 2019-2074/? D/BatteryService﹕ update start
09-29 01:54:28.360 2019-2079/? D/KeyguardViewMediator﹕ setHidden false
09-29 01:54:28.360 1732-1732/? I/SurfaceFlinger﹕ id=13169 Removed TcreenSaver idx=4 MapSz=10
Hope some pro help me to my problem. Somebody says It's simple but I can't resolved sir.
You need to add Login Activity to your AndroidManifest.xml so that the android operating system can find the Activity that the intent is referencing.
<activity
android:name=".Activities.Login"
android:label="Login" />
You really need to show us your stacktrace for any useful feedback. I suspect you aren't declaring the Login activity in your AndroidManifest.xml correctly.
LogCat will contain the error stacktrace. Most likely you will see a giant block of red text that will indicate the part we are interested in. Below is an example of one of my stacktraces. Hopefully it helps you find it.
java.lang.RuntimeException: Unable to start activity ComponentInfo{package.name.ThingDetailActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'long com.package.api.model.Thing.getId()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Method.java)
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)
I am trying to solve this java lang error:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.sebasdeldihotmail.mediocre11/com.sebasdeldihotmail.mediocre11.SignUpOrLogInActivity}: java.lang.ClassCastException: com.sebasdeldihotmail.mediocre11.SignUpOrLogInActivity cannot be cast to android.app.Activity
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2039)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2153)
at android.app.ActivityThread.access$700(ActivityThread.java:137)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5031)
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:792)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: com.sebasdeldihotmail.mediocre11.SignUpOrLogInActivity cannot be cast to android.app.Activity
at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2030)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2153)
at android.app.ActivityThread.access$700(ActivityThread.java:137)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5031)
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:792)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
at dalvik.system.NativeStart.main(Native Method)
i have checked again and again the code and i can't find what is making the app crash, maybe some fresh eyes can help to find the issue.
Here is the SignUpOrSignIn class
public class SignUpOrLogInActivity extends Fragment {
private static final String TAG = "MainFragment";
Button signIn;
Button signUp;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.signinorsignup_activity,container,false);
Button signIn = (Button)root.findViewById(R.id.login);
signIn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startActivity(new Intent(getActivity(), LoginActivity.class));
}
});
Button signUp = (Button)root.findViewById(R.id.signup);
signUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity(),SignUpActivity.class));
}
});
return root;
}
private void onSessionStateChange(Session session, Session state, Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
}
}
and here is the layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#67AAE4">
<Button
android:id="#+id/signup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sign Up"/>
<Button
android:id="#+id/login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"/>
<com.facebook.widget.LoginButton
android:id="#+id/authButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
/>
</LinearLayout>
MANIFEST
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:name=".ParseStarter">
<activity
android:screenOrientation="portrait"
android:name=".MainActivity"
android:label="#string/app_name" >
</activity>
<activity android:name=".SignUpOrLogInActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity >
<activity android:name=".DispatchActivity"/>
<activity android:name=".LoginActivity" />
<activity android:name=".SignUpActivity" />
<activity android:name="com.facebook.LoginActivity"/>
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="#string/facebook_app_id"/>
</application>
</manifest>
"CORRECTED MANIFEST"
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sebasdeldihotmail.mediocre11" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:name=".ParseStarter">
<activity
android:screenOrientation="portrait"
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 >
<activity android:name=".DispatchActivity"/>
<activity android:name=".LoginActivity" />
<activity android:name=".SignUpActivity" />
<activity android:name="com.facebook.LoginActivity"/>
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="#string/facebook_app_id"/>
</application>
</manifest>
Can anyone figure out what is making the app crash?
Thanks very much for reading :)
Your SignUpOrLogInActivity extends Fragment. I'm assuming, based on the name, that this class is declared in the manifest as an Activity, which makes Android expect it to be a sub-class of Activity.
A Fragment must be contained in an Activity, so you need to create a class that extends Activity and contains your Fragment (which I would rename to something that doesn't contain the word Activity, since it's confusing). Your Android manifest should declare that activity class as the activity from which your app is launched.
SignUpOrLogInActivity extends Fragment
this is a fragment, and you are casting it to an activity.
You need to typecast it to a fragment for it to work
Caused by: java.lang.ClassCastException: com.sebasdeldihotmail.mediocre11.SignUpOrLogInActivity cannot be cast to android.app.Activity