I'm receiving an InflateException from ChatActivity when it is not the LAUNCHER activity but when I change the manifest such that ChatActivity is the LAUNCHER, the app work properly.
I'm probably missing something, is there something missing in the code?
Update 18:15 16.10 -
I've found that if I delete
implements View.OnClickListener
from LoginActivity the app working (but now I don't have buttons).
What is the cause of this problem and how can it be fixed?
Part of the MANIFEST when the error accrue -
<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=".Activities.LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Activities.ChatMainActivity"></activity>
<activity android:name=".Activities.RegisterActivity" />
And if I'm changing the file to this (below) the chat work properly -
<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=".Activities.LoginActivity"></activity>
<activity android:name=".Activities.ChatMainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Activities.RegisterActivity" />
The dependencies -
implementation 'androidx.appcompat:appcompat:1.0.0'
implementation 'com.google.android.material:material:1.0.0'
XML file of ChatActivity -
<?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=".Activities.ChatMainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/appBarLayout">
<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
</androidx.appcompat.widget.Toolbar>
<com.google.android.material.tabs.TabLayout
android:id="#+id/main_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"></com.google.android.material.tabs.TabLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/main_tabPager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/appBarLayout">
</androidx.viewpager.widget.ViewPager>
</RelativeLayout>
The activity -
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import androidx.appcompat.widget.Toolbar;
import com.google.android.material.tabs.TabLayout;
import com.nirkov.hive.Fragments.ChatFragment;
import com.nirkov.hive.Fragments.ChatOffersFragment;
import com.nirkov.hive.Fragments.ChatRequestsFragment;
import com.nirkov.hive.R;
public class ChatMainActivity extends AppCompatActivity {
private ViewPager mViewPager;
private SectionsPagerAdapter mSectionsPagerAdapter;
private TabLayout mTabLayout;
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_main);
mToolbar = (Toolbar) findViewById(R.id.main_app_bar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Chat");
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.main_tabPager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mTabLayout = (TabLayout) findViewById(R.id.main_tabs);
mTabLayout.setupWithViewPager(mViewPager);
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.chat_bar_layout, menu);
return true;
}
#Override
public void onStart() {
super.onStart();
}
private class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(final int position) {
switch (position){
case 0:
return new ChatRequestsFragment();
case 1:
return new ChatFragment();
case 2:
return new ChatOffersFragment();
}
return null;
}
#Override
public int getCount() {
return 3;
}
public CharSequence getPageTitle(final int position){
switch(position){
case 0:
return "REQUESTS";
case 1:
return "CHATS";
case 2:
return "OFFERS";
}
return null;
}
}
}
The appTheme style -
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
The LoginActivity -
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.nirkov.hive.R;
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "LoginActivity";
private Button loginButton;
private EditText emailBox, passwordBox;
private TextView registerHereLink;
private FirebaseAuth mAuth;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginButton = (Button) findViewById(R.id.loginButton);
emailBox = (EditText)findViewById(R.id.emailBox);
passwordBox = (EditText)findViewById(R.id.passwordBox);
registerHereLink = (TextView)findViewById(R.id.registerHereLink);
progressBar = (ProgressBar) findViewById(R.id.loginProgressBar);
mAuth = FirebaseAuth.getInstance();
loginButton.setOnClickListener(this);
registerHereLink.setOnClickListener(this);
}
#Override
public void onStart() {
super.onStart();
if(mAuth.getCurrentUser() != null){
startActivity(new Intent(this, ChatMainActivity.class));
}
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.loginButton:
String email = emailBox.getText().toString();
String password = passwordBox.getText().toString();
loginButton.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
signIn(email, password);
break;
case R.id.registerHereLink:
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
break;
}
}
private void signIn(String email, final String password){
mAuth.signInWithEmailAndPassword(email, password).
addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Log.d(TAG, "signIn : success");
startActivity(new Intent(LoginActivity.this, MainActivity.class));
}else{
Log.w(TAG, "signIn:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
loginButton.setVisibility(View.VISIBLE);
}
});
}
}
The Login XML file -
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".Activities.LoginActivity">
<TextView
android:id="#+id/email"
android:layout_width="255dp"
android:layout_height="34dp"
android:layout_marginStart="20dp"
android:layout_marginTop="32dp"
android:text="Email:"
android:textSize="24sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/emailBox"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:ems="10"
android:inputType="textPersonName"
android:text=""
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/email" />
<!--Password : text view and text box-->
<TextView
android:id="#+id/password"
android:layout_width="133dp"
android:layout_height="31dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="Password:"
android:textSize="24sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/emailBox" />
<EditText
android:id="#+id/passwordBox"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:ems="10"
android:inputType="textPersonName"
android:text=""
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/password" />
<Button
android:id="#+id/loginButton"
android:layout_width="115dp"
android:layout_height="37dp"
android:layout_marginStart="8dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="8dp"
android:text="Login"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/passwordBox" />
<ProgressBar
android:id="#+id/loginProgressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="38dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:visibility="invisible"
app:layout_constraintBottom_toTopOf="#+id/spaceInBottom"
app:layout_constraintEnd_toEndOf="#+id/loginButton"
app:layout_constraintStart_toStartOf="#+id/loginButton"
app:layout_constraintTop_toTopOf="#+id/loginButton" />
<TextView
android:id="#+id/registerHereLink"
android:layout_width="63dp"
android:layout_height="12dp"
android:layout_gravity="center_horizontal"
android:layout_marginStart="8dp"
android:layout_marginTop="3dp"
android:layout_marginEnd="8dp"
android:text="Register Here"
android:textSize="10sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/loginButton" />
</androidx.constraintlayout.widget.ConstraintLayout>
The full error -
2019-10-16 01:07:43.323 6109-6109/com.nirkov.hive E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.nirkov.hive, PID: 6109
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nirkov.hive/com.nirkov.hive.Activities.ChatMainActivity}: android.view.InflateException: Binary XML file line #9: Binary XML file line #9: Error inflating class android.support.design.widget.AppBarLayout
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
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)
Caused by: android.view.InflateException: Binary XML file line #9: Binary XML file line #9: Error inflating class android.support.design.widget.AppBarLayout
Caused by: android.view.InflateException: Binary XML file line #9: Error inflating class android.support.design.widget.AppBarLayout
Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.design.widget.AppBarLayout" on path: DexPathList[[zip file "/system/framework/org.apache.http.legacy.boot.jar", zip file "/data/app/com.nirkov.hive-8a2GYMMALuvTn0Up_KEgfw==/base.apk"],nativeLibraryDirectories=[/data/app/com.nirkov.hive-8a2GYMMALuvTn0Up_KEgfw==/lib/x86, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.view.LayoutInflater.createView(LayoutInflater.java:606)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
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)
at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:555)
at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:161)
at com.nirkov.hive.Activities.ChatMainActivity.onCreate(ChatMainActivity.java:38)
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)
upload login Activity code as well , and tell me which is your parent class
Can you try adding
<item name="windowNoTitle">true</item>
to your main style and see if that works?
Didn't find class "android.support.design.widget.AppBarLayout" on path
Comes from your activity where you set the toolbar wrongly:
mToolbar = (Toolbar) findViewById(R.id.main_app_bar);
setSupportActionBar(mToolbar);
Your toolbar is wrapped by com.google.android.material.appbar.AppBarLayout.
So there's no need to add it into the supportActionBar.
Just define your activity theme as NoActionBar (in your styles.xml) and delete setSupportActionBar(mToolbar); in your activity
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I know this has been asked numerous times but since I'am a beginner I couldn't understand any of the solutions.
I wrote a simple app to count up and down from 0 but the app kept crashing.
After reading through StackOverFlow I learnt about Stack trace and found what the problem was but was not able to fix.
Here is my code
MainActivity.java:
package com.example.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int counter;
{
counter = 0;
}
Button add,sub;
TextView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
display.setText("Count: " +counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter--;
display.setText("Count: " +counter);
}
});
}
}
activity_main.xml:
<?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=".MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="107dp"
android:layout_marginBottom="8dp"
android:text="#string/Title"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.133" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="217dp"
android:text="#string/add"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.754" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:text="#string/sub"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.511"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/button"
app:layout_constraintVertical_bias="0.005" />
</android.support.constraint.ConstraintLayout>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication">
<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>
Logcat:
2019-02-17 20:36:55.107 3748-3748/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 3748
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.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:2926)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3061)
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:1821)
at android.os.Handler.dispatchMessage(Handler.java:114)
at android.os.Looper.loop(Looper.java:198)
at android.app.ActivityThread.main(ActivityThread.java:6716)
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)
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 com.example.myapplication.MainActivity.onCreate(MainActivity.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:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2906)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3061)
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:1821)
at android.os.Handler.dispatchMessage(Handler.java:114)
at android.os.Looper.loop(Looper.java:198)
at android.app.ActivityThread.main(ActivityThread.java:6716)
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)
You have declared the button variables (add and sub) and the textview variable (display), but you never assigned the respective Button and TextView objects to them.
You have to create two buttons objects:
add = (Button)findViewById(R.id.button);
sub = (Button)findViewById(R.id.button2);
And also a TextView object:
display = (TextView)findViewById(R.id.textView);
After the assignment you proceed with adding the listeners to the button objects.
I am new to android programming.
I made an app having 2 activities(one being the launcher other being seek). the second activity is started by a button in the main activity.
while i do this the app crashes.
The Mainfest.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.a1.starklabs.myapplication">
<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=".Seek">
<intent-filter>
<action android:name="com.a1.starklabs.myapplication.Seek" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
**Main_activity.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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.a1.starklabs.myapplication.MainActivity">
<ImageView
android:layout_height="100dp"
app:srcCompat="#mipmap/game"
android:id="#+id/imageView3"
android:scaleType="centerCrop"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
android:layout_width="100dp" />
<Button
android:text="Image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
style="#android:style/Widget.Button"
android:elevation="24dp"
android:textAppearance="#style/TextAppearance.AppCompat.Body2"
android:layout_marginTop="27dp"
android:layout_below="#+id/imageView3"
android:layout_centerHorizontal="true" />
<TextView
android:text="Other Activities:"
android:layout_width="150dp"
android:layout_height="20dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="18dp"
android:layout_marginStart="18dp"
android:id="#+id/textView"
android:elevation="5dp"
android:fontFamily="cursive"
android:textColorLink="?attr/actionMenuTextColor"
android:textColor="#android:color/holo_green_dark" />
<Button
android:text="SEEK"
android:layout_below="#+id/textView"
android:layout_alignLeft="#+id/textView"
android:layout_alignStart="#+id/textView"
android:layout_marginTop="12dp"
android:id="#+id/button2"
android:layout_height="33dp"
android:layout_width="60dp" />
</RelativeLayout>
Main_activity.java
package com.a1.starklabs.myapplication;
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.ImageView;
public class MainActivity extends AppCompatActivity {
public static ImageView i1;
public static Button b1;
private int img_index;
int[] images={R.mipmap.game,R.mipmap.mustang};
private static Button b_seek;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonClick();
seek_button();
}
public void seek_button()
{
b_seek=(Button)findViewById(R.id.button2);
b_seek.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent i=new Intent("com.a1.starklabs.myapplication.Seek");
startActivity(i);
}
}
);
}
public void buttonClick()
{
i1=(ImageView)findViewById(R.id.imageView3);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
img_index++;
img_index=img_index%images.length;
i1.setImageResource(images[img_index]);
}
});
}
}
activity_seek.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:id="#+id/activity_seek"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.a1.starklabs.myapplication.Seek">
<SeekBar
android:layout_marginTop="86dp"
android:id="#+id/seekBar"
android:layout_height="50dp"
android:layout_width="300dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:text="TextView"
android:layout_width="100dp"
android:layout_below="#+id/seekBar"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
android:id="#+id/textView2"
android:textSize="20dp"
android:layout_height="30dp"
android:textAppearance="#style/TextAppearance.AppCompat"
style="#android:style/Widget.Material.TextView" />
</RelativeLayout>
seek.java
package com.a1.starklabs.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;
public class Seek extends AppCompatActivity {
private static SeekBar s1;
private static TextView t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seek);
seekbar();
}
public void seekbar(){
s1=(SeekBar)findViewById(R.id.seekBar);
t1=(TextView)findViewById(R.id.textView2);
t1.setText(s1.getProgress());
s1.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener() {
int prog_ress;
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
prog_ress=i;
t1.setText(s1.getProgress());
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
t1.setText(s1.getProgress());
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
t1.setText(s1.getProgress());
}
}
);
}
}
error log
$ adb shell am start -n "com.a1.starklabs.myapplication/com.a1.starklabs.myapplication.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Client not ready yet..Connected to process 2913 on device emulator-5554
W/System: ClassLoader referenced unknown path: /data/app/com.a1.starklabs.myapplication-2/lib/x86
I/InstantRun: Instant Run Runtime started. Android package is com.a1.starklabs.myapplication, real application class is null.
W/System: ClassLoader referenced unknown path: /data/app/com.a1.starklabs.myapplication-2/lib/x86
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
W/ResourceType: No package identifier when getting value for resource number 0x00000000
D/AndroidRuntime: Shutting down VM
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.a1.starklabs.myapplication, PID: 2913
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.a1.starklabs.myapplication/com.a1.starklabs.myapplication.Seek}: android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.content.res.Resources.getText(Resources.java:335)
at android.widget.TextView.setText(TextView.java:4555)
at com.a1.starklabs.myapplication.Seek.seekbar(Seek.java:36)
at com.a1.starklabs.myapplication.Seek.onCreate(Seek.java:27)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Application terminated.
t1.setText(s1.getProgress()); is probably the cause of your problems.
I guess you want to set the current progress as text, but it calls TextView.setText(int) which tries to load a string resource with the id equal to the given progress. Since this is 0 at the start it tries to load resource 0, which does not exist.
To fix it, explicitly turn the progress into a string: t1.setText(Integer.toString(s1.getProgress()));.
Try this:
Intent i=new Intent(MainActivity.this, Seek.class);
startActivity(i);
Hope it helps!!
I know this has been asked a lot, already have done search on this particular topic. and all of them returns the same answer but doesn't solve my problem, I have a button created on separate xml, used as a fragment. TabbedActivity just wont fire up, App is crashing when button is clicked, even throws NPE on first code used. just don't know what to do.
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set HomeFragment as user starts the app.
if (savedInstanceState == null){
InitStartFrag();
}
//-----BUG!-----//
1st:Code Used
android.support.v7.widget.AppCompatButton myButton = (android.support.v7.widget.AppCompatButton)findViewById(R.id.myButton);
myButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent intent = new Intent(MainActivity.this, TabbedActivity.class);
startActivity(intent);
}
});
2nd Code:
public void doThis(View view){
Intent intent = new Intent(this, TabbedActivity.class);
MainActivity.this.startActivity(intent);
}
3rd Code:
public void doThis(View view){
setContentView(R.layout.activity_tabbed);
}
//-----Bug Ends-----//
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
private void InitStartFrag() {
android.app.FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
.....
.....
}
The Log Cat:
Process: com.my_app.app_one, PID: 3799
java.lang.IllegalStateException: Could not find a method doThis(View) in the activity class android.support.v7.widget.TintContextWrapper for onClick handler on view class android.support.v7.widget.AppCompatButton with id 'myButton'
at android.view.View$1.onClick(View.java:3843)
at android.view.View.performClick(View.java:4471)
at android.view.View$PerformClick.run(View.java:18778)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5324)
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:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NoSuchMethodException: doThis [class android.view.View]
at java.lang.Class.getConstructorOrMethod(Class.java:472)
at java.lang.Class.getMethod(Class.java:864)
at android.view.View$1.onClick(View.java:3836)
at android.view.View.performClick(View.java:4471)
at android.view.View$PerformClick.run(View.java:18778)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5324)
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:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
The Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.my_app.app_one">
<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"
android:configChanges="keyboardHidden|orientation"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".TabbedActivity"
android:label="#string/title_activity_tabbed"
android:parentActivityName=".MainActivity"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.my_app.app_one.MainActivity" />
</activity>
</application>
</manifest>
The XML, used as Fragment : buttons_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.percent.PercentRelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--Upper Buttons-->
<android.support.v7.widget.AppCompatButton
android:id="#+id/myButton"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:text="Fire"
android:textSize="15sp"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%"
app:backgroundTint="#color/colorBtn1"
android:textColor="#color/colorBtnText1"
android:drawableStart="#drawable/fire_icon"
android:drawablePadding="-62dip"
android:paddingLeft="30dip"
android:paddingRight="26dip"
android:singleLine="true"
android:gravity="center"
android:onClick="doThis"/>
<android.support.v7.widget.AppCompatButton
android:id="#+id/myButton1"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:layout_below="#id/myButton"
android:text="Flood"
android:textSize="15sp"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%"
app:backgroundTint="#color/colorBtn3"
android:textColor="#color/colorBtnText3"/>
<!-- Divider -->
<android.support.v7.widget.AppCompatButton
android:id="#+id/myButton2"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:layout_toEndOf="#id/myButton1"
android:text="Thunder"
android:textSize="15sp"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%"
app:backgroundTint="#color/colorBtn2"
android:textColor="#color/colorBtnText2"/>
<android.support.v7.widget.AppCompatButton
android:id="#+id/myButton4"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_below="#id/myButton2"
android:layout_gravity="center_horizontal"
android:layout_toEndOf="#id/myButton1"
android:text="Civil Defense Operation Center"
android:textSize="15sp"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%"
app:backgroundTint="#color/colorBtn4"
android:textColor="#color/colorBtnText4"/>
<!--Lower Buttons-->
<android.support.v7.widget.AppCompatButton
android:id="#+id/myButton5"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:layout_below="#id/myButton3"
android:text="Landslide"
android:textSize="15sp"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%"
app:backgroundTint="#color/colorBtn5"
android:textColor="#color/colorBtnText5"/>
<android.support.v7.widget.AppCompatButton
android:id="#+id/myButton7"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:layout_below="#id/myButton5"
android:text="Women and Children Protection Center"
android:textSize="15sp"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%"
app:backgroundTint="#color/colorBtn7"
android:textColor="#color/colorBtnText7"/>
<!-- Divider -->
<android.support.v7.widget.AppCompatButton
android:id="#+id/myButton6"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:layout_below="#id/myButton4"
android:layout_toEndOf="#id/myButton3"
android:text="Storm"
android:textSize="15sp"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%"
app:backgroundTint="#color/colorBtn6"
android:textColor="#color/colorBtnText6"/>
<android.support.v7.widget.AppCompatButton
android:id="#+id/myButton8"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_below="#id/myButton6"
android:layout_gravity="center_horizontal"
android:layout_toEndOf="#id/myButton5"
android:text="Earthquake"
android:textSize="15sp"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%"
app:backgroundTint="#color/colorBtn8"
android:textColor="#color/colorBtnText8"/>
</android.support.percent.PercentRelativeLayout>
</LinearLayout>
New Code Used:
private void InitBtnListener(){
LayoutInflater layoutInflater = this.getLayoutInflater();
View view = layoutInflater.inflate(R.layout.buttons_layout,null);
android.support.v7.widget.AppCompatButton myButton = (android.support.v7.widget.AppCompatButton)view.findViewById(R.id.myButton);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, TabbedActivity.class);
startActivity(intent);
}
});
}
TabbedFragment.java Code
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
public class TabbedFragment extends Fragment implements OnClickListener {
View myView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.survival_tips_layout,container,false);
android.support.v7.widget.AppCompatButton myButton = (android.support.v7.widget.AppCompatButton)myView.findViewById(R.id.myButton);
myButton.setOnClickListener(this);
return myView;
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.myButton:
//--Missing Code:--//
After Btn Click Fire up that TabbedActivity.
//--Ends--//
// Can I do intents Here?
Intent intent = new Intent(MainActivity.this,TabbedActivity.class);
startActivity(intent);
break;
}
}
}
This line needs to be above any findViewById
setContentView(R.layout.activity_main);
If the android:onClick is defined from the XML, you need a public method that accepts a View parameter with that name.
For example, android:onClick="doThis" means you need this method
public void doThis(View view) {
// TODO: Handle click
}
i have a button created on separate xml, used as a fragment
Then you need to find that button from the Fragment class. You can't find it from the Activity.
For example
public class MyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
// Inflate the layout
View rootView = inflater.inflate(R.layoutbuttons_layout, parentViewGroup, false);
Button button = (Button) rootView.findViewById(R.id.button);
// TODO: button.setOnClickListener();
return rootView;
}
// OR... if you have android:onclick="doThis"
public void doThis(View view) {
// TODO: Handle click
}
}
I'm new to Android & was trying out the Bluetooth APIs of Google. Whenever I run my app on my phone, it crashes for some reason. I'm following the Google Developer's tutorial for the APIs & have made changes to my MainActivity.java & content.xml accordingly, but no use. Please have a look.
Here's my MainActivity.java
import android.content.Intent;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.*;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button btn;
private BluetoothAdapter BA = BluetoothAdapter.getDefaultAdapter();
private int REQUEST_ENABLE_BT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/* FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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);
}
public void bluetoothDiscovery()
{
if(BA == null)
{
System.out.println("System Doesn't Support Bluetooth");
}
if(!BA.isEnabled())
{
Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBTIntent,REQUEST_ENABLE_BT);
Toast.makeText(MainActivity.this,"Turned On!!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(MainActivity.this, "ALREADY ON", Toast.LENGTH_LONG).show();
}
}
}
Here's my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="vertex2016.mvjce.edu.bluetoothapptry">
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<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"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here's my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
tools:context="vertex2016.mvjce.edu.bluetoothapptry.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<!-- <android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email"
android:onClick="bluetoothDiscovery"/> -->
</android.support.design.widget.CoordinatorLayout>
Here's my content.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="vertex2016.mvjce.edu.bluetoothapptry.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BTButton"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="bluetoothDiscovery"/>
</RelativeLayout>
And here's my logcat
03-13 02:06:34.719 18759-18759/vertex2016.mvjce.edu.bluetoothapptry E/AndroidRuntime: FATAL EXCEPTION: main
Process: vertex2016.mvjce.edu.bluetoothapptry, PID: 18759
java.lang.IllegalStateException: Could not find method bluetoothDiscovery(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'button'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:307)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:266)
at android.view.View.performClick(View.java:4789)
at android.view.View$PerformClick.run(View.java:19881)
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:5292)
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)
Thank you for your time
Your method bluetoothDiscovery must accept a parameter of type View, see View.onClick for reference.
public void bluetoothDiscovery(View v) {}
When this method is called, v will be the View object that was clicked.
i.e.
switch ( v.getId() ) {
case R.id.button:
// do something
break;
case R.id.other_button
// do something else
break;
}
Where r.id.button comes from your definition in XML,
android:id="#+id/button"
It is using this, you could have a single onClick method that is called by multiple buttons, each one with their own action.
You need a View parameter in your onClick method
public void bluetoothDiscovery(View v)
Personally, I try not to add onClick in the XML because they are hard to find as you add more classes and layouts. You can just set the OnClickListener from the Java code for clearer visibility.
I'm new to Android developing. This is an assignment which was given to me. I have to convert the value and the converted value must be shown in the next activity. But when I press the submit button its crashes.I don;t know what is the problem. Is there a problem with my RadioButtons. Please help me...
This is the second activity(ConvertActivity)
package com.gihan.temperatureconverter;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
public class ConvertActivity extends ActionBarActivity {
//RadioButton cel=(RadioButton) findViewById(R.id.rCel);
//RadioButton fah=(RadioButton) findViewById(R.id.rFah);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_convert);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_convert, 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);
}
public void calculation(View view) {
EditText val=(EditText) findViewById(R.id.editText);
int value = Integer.valueOf(val.getText().toString()).intValue();
int ans=0;
int fahval=0;
int celval=0;
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.rCel:
if (checked){
ans=((value-32)*5/9);
fahval=value;
celval=ans;}
break;
case R.id.rFah:
if (checked){
ans=((value*9)/5)+32;
celval=value;
fahval=ans;}
break;
}
/*if (cel.isChecked()){
ans=((value-32)*5/9);
fahval=value;
celval=ans;
}
if (fah.isChecked()){
ans=((value*9)/5)+32;
celval=value;
fahval=ans;
}*/
Intent intent = new Intent(ConvertActivity.this, LastActivity.class);
intent.putExtra("celval", getText(celval));
intent.putExtra("fahval", getText(fahval));
ConvertActivity.this.startActivity(intent);
}
}
This is the 2nd XML(activity_convert)
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.gihan.temperatureconverter.ConvertActivity"
android:background="#drawable/ic_background">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/editText"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="50dp"
android:hint="Enter Value"
android:textSize="20dp"/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radioGroup"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true">
<RadioButton
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="To Celsius"
android:id="#+id/rCel"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:checked="false"
android:gravity="fill_horizontal"
android:textColor="#ffc80301"
android:textSize="25sp"/>
<RadioButton
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="To Fahrenheit"
android:id="#+id/rFah"
android:checked="false"
android:gravity="fill_horizontal"
android:textColor="#ffc80301"
android:textSize="25sp"
android:layout_below="#+id/rCel"
android:layout_alignLeft="#+id/rCel"
android:layout_alignStart="#+id/rCel" />
</RadioGroup>
<Button
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Submit"
android:id="#+id/sub"
android:onClick="calculation"
android:layout_below="#+id/radioGroup"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp" />
</RelativeLayout>
This is the 3rd activity(LastActivity)
package com.gihan.temperatureconverter;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class LastActivity extends ActionBarActivity {
TextView vFah=(TextView)findViewById(R.id.vFah);
TextView vCel=(TextView)findViewById(R.id.vCel);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_last);//use whatever layout you want.
Bundle extras = getIntent().getExtras();
int celval=extras.getInt("celval");
int fahval=extras.getInt("fahval");
//String cel=String.valueOf(celval);
//String fah=String.valueOf(fahval);
vCel.setText(Integer.toString(celval));
vFah.setText(Integer.toString(fahval));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_convert, 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);
}
public void again(View view) {
Intent intent = new Intent(LastActivity.this, ConvertActivity.class);
LastActivity.this.startActivity(intent);
}
public void home(View view) {
Intent intent = new Intent(LastActivity.this, MainActivity.class);
LastActivity.this.startActivity(intent);
}
}
This is the 3rd XML(activity_last)
<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:background="#drawable/ic_background"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.gihan.temperatureconverter.LastActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Successfully Converted"
android:id="#+id/textView2"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:textColor="#ffff0004"
android:textSize="30sp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Home"
android:id="#+id/button2"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="70dp"
android:gravity="center_horizontal"
android:textSize="25sp"
android:onClick="home"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Calculate again"
android:id="#+id/button3"
android:layout_marginBottom="45dp"
android:gravity="center_horizontal"
android:layout_above="#+id/button2"
android:layout_centerHorizontal="true"
android:textSize="25sp"
android:onClick="again"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Fahrenheit"
android:id="#+id/textView3"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:textColor="#ff0010ff" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Celsius"
android:id="#+id/textView4"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp"
android:textColor="#ff0010ff" />
<TextView
android:layout_width="wrap_content"
android:layout_height="20sp"
android:id="#+id/vFah"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true"
android:textColor="#ff9300ff"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="20sp"
android:id="#+id/vCel"
android:layout_below="#+id/textView4"
android:layout_centerHorizontal="true"
android:textColor="#ff9300ff"/>
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.gihan.temperatureconverter" >
<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=".ConvertActivity"
android:label="#string/app_name">
</activity>
<activity
android:name=".LastActivity"
android:label="#string/app_name">
</activity>
</application>
</manifest>
Logcat
--------- beginning of crash
06-09 21:05:58.413 2381-2381/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.gihan.temperatureconverter, PID: 2381
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4020)
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)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4015)
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)
Caused by: java.lang.ClassCastException: android.support.v7.widget.AppCompatButton cannot be cast to android.widget.RadioButton
at com.gihan.temperatureconverter.ConvertActivity.calculation(ConvertActivity.java:56)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4015)
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)
Some Comments were some ways I tried. It's also failed.
And also this is Android Studio Project.
Your Error Solved Check this code
mainactivity.java
public class MainActivity extends ActionBarActivity {
EditText val;
public static int ans;
public static String fahval="";
public static String celval="";
RadioButton Box1,Box2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
val =(EditText) findViewById(R.id.editText);
}
public void calculation(View v)
{
//get value from edit text box and convert into double
double a=Double.parseDouble(String.valueOf(val.getText()));
Box1 = (RadioButton) findViewById(R.id.rCel);
Box2 = (RadioButton) findViewById(R.id.rFah);
//check which radio button is checked
if(Box1.isChecked())
{
//display conversion
celval = String.valueOf(f2c(a));
// Toast.makeText(getApplicationContext(), celval,Toast.LENGTH_LONG).show();
Box1.setChecked(true);
}
else
{
fahval = String.valueOf(c2f(a));
// Toast.makeText(getApplicationContext(), fahval,Toast.LENGTH_LONG).show();
Box2.setChecked(true);
}
Intent intent = new Intent(this, LastActivity.class);
intent.putExtra("celval", celval);
intent.putExtra("fahval", fahval);
startActivity(intent);
}
//Celcius to Fahrenhiet method
private double c2f(double c)
{
return (c*9)/5+32;
}
//Fahrenhiet to Celcius method
private double f2c(double f)
{
return (f-32)*5/9;
}
}
LastActivity.java
public class LastActivity extends ActionBarActivity {
TextView vFah;
TextView vCel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.last);//use whatever layout you want.
vFah=(TextView)findViewById(R.id.vFah);
vCel=(TextView)findViewById(R.id.vCel);
Bundle extras = getIntent().getExtras();
String celval=extras.getString("celval");
String fahval=extras.getString("fahval");
//String cel=String.valueOf(celval);
//String fah=String.valueOf(fahval);
vCel.setText(celval);
vFah.setText(fahval);
}
public void again(View view) {
Intent intent = new Intent(LastActivity.this, MainActivity.class);
LastActivity.this.startActivity(intent);
}
public void home(View view) {
Intent intent = new Intent(LastActivity.this, MainActivity.class);
LastActivity.this.startActivity(intent);
}
}
I was building some apps this week, and couldn't figure out why I couldn't navigate from the Main Activity to a second activity and from there to a 3rd level activity (that would pop to 2nd activity), and app kept crashing when I added the 3rd. Finally looked in the Logcat to figure out what's wrong, and then read "Cannot Navigate from 'second activity'.... This View will not accept Navigation". Searched through code to find errors, but Never thought to look there before.