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.
Related
I am trying to have a grid layout in a recyclerview to show and image text and a double variable. The goal is to add a search bar that will display the results to the recycleView. I am new to kotlin so forgive me if the problem is obvious. I am not sure exactly what is causing my app to crash, but I narrowed it down to 1 line of code in my
MainActivity.kt
dataList.add(mealData("mealTitle.toString()",
Restaurant.toString(),R.drawable.food1,"mealCat.toString()",
"mealDescription.toString()"))
I suspected it was my mealCost variable so I took it out but it is still crashing, here is my code
MainActivity.kt
package com.example.foodme2
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.GridLayoutManager
import com.smarteist.autoimageslider.SliderView
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.food_search_list.*
class MainActivity : AppCompatActivity() {
private lateinit var showImage: ArrayList<Int>
lateinit var sliderView: SliderView
lateinit var sliderAdapter: SliderAdapter
private lateinit var photoAdapter: PhotoAdapter
private var dataList = mutableListOf<mealData>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
sliderView = findViewById(R.id.slider)
showImage = ArrayList()
showImage.add(R.drawable.food1)
showImage.add(R.drawable.food3)
showImage.add(R.drawable.food4)
sliderAdapter =SliderAdapter(showImage)
sliderView.autoCycleDirection = SliderView.LAYOUT_DIRECTION_LTR
sliderView.setSliderAdapter(sliderAdapter)
sliderView.scrollTimeInSec = 3
sliderView.isAutoCycle = true
sliderView.startAutoCycle()
recyclerView.layoutManager = GridLayoutManager(applicationContext,2)
photoAdapter = PhotoAdapter()
recyclerView.adapter = photoAdapter
dataList.add(mealData("mealTitle.toString()",
Restaurant.toString(),R.drawable.food1,"mealCat.toString()",
"mealDescription.toString()"))
photoAdapter.setDataList(dataList)
}
}
activityMain.xml
<?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"
android:background="#color/Background"
android:layout_margin="2dp"
android:outlineAmbientShadowColor="#color/BorderColor"
tools:context=".MainActivity">
<com.smarteist.autoimageslider.SliderView
android:id="#+id/slider"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_centerInParent="true"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:sliderAnimationDuration="600"
app:sliderAutoCycleDirection="back_and_forth"
app:sliderIndicatorAnimationDuration="600"
app:sliderIndicatorEnabled="true"
app:sliderIndicatorGravity="center_horizontal|bottom"
app:sliderIndicatorMargin="15dp"
app:sliderIndicatorOrientation="horizontal"
app:sliderIndicatorPadding="3dp"
app:sliderIndicatorRadius="2dp"
app:sliderIndicatorSelectedColor="#5A5A5A"
app:sliderIndicatorUnselectedColor="#FFF"
app:sliderScrollTimeInSec="1" />
<SearchView
android:id="#+id/searchView"
android:layout_width="match_parent"
android:layout_height="50dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/slider" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="406dp"
android:layout_height="400dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/searchView" />
</androidx.constraintlayout.widget.ConstraintLayout>
The layout for the recyclerView food_search_list.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
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:background="#color/cadetGrey"
android:layout_margin="2dp"
android:layout_height="match_parent">
<ImageView
android:id="#+id/MealImage"
android:contentDescription="#string/Description"
android:layout_width="match_parent"
android:layout_height="130dp"
android:layout_marginTop="75dp"
android:background="#color/white"
android:padding="2dp" />
<TextView
android:id="#+id/Restaurant"
android:layout_width="156dp"
android:layout_height="29dp"
android:layout_marginStart="115dp"
android:textAlignment="center"
android:layout_marginTop="8dp"
android:padding="2dp"
android:background="#color/white"
/>
<TextView
android:id="#+id/mealTite"
android:layout_width="100dp"
android:layout_height="20dp"
android:layout_marginStart="140dp"
android:layout_marginTop="44dp"
android:background="#color/white"
android:padding="2dp" />
<TextView
android:id="#+id/mealDescription"
android:layout_width="168dp"
android:layout_height="95dp"
android:layout_marginStart="110dp"
android:layout_marginTop="210dp"
android:background="#color/white"
android:padding="2dp"
android:scaleX="45" />
<TextView
android:id="#+id/mealCost"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginStart="24dp"
android:layout_marginTop="10dp"
android:padding="2dp"
android:background="#color/white"
/>
<TextView
android:id="#+id/mealCat"
android:layout_width="50dp"
android:layout_height="20dp"
android:layout_marginStart="24dp"
android:layout_marginTop="10dp"/>
</androidx.cardview.widget.CardView>
data class mealData.kt
package com.example.foodme2
import android.widget.TextView
data class mealData(
// var mealId:Int = 0;
var mealName: String,
var restaurant: String,
var mealImage: Int,
var mealCat: String,
var mealDescription: String,
//var mealCost: Double,
)
The adapter for recyclerView mRecycleViewAdapter.kt
package com.example.foodme2
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
//import kotlinx.android.synthetic.main.food_search_list.view.*
class PhotoAdapter :RecyclerView.Adapter<PhotoAdapter.ViewHolder>() {
private var dataList = emptyList<mealData>()
internal fun setDataList(dataList: List<mealData>) {
this.dataList = dataList
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var mealImage: ImageView = itemView.findViewById(R.id.MealImage)
var mealName: TextView = itemView.findViewById(R.id.mealTite)
var mealCat: TextView = itemView.findViewById(R.id.mealCat)
var restaurant: TextView = itemView.findViewById(R.id.Restaurant)
var mealDescription: TextView = itemView.findViewById(R.id.mealDescription)
//var mealCost: TextView = itemView.findViewById(R.id.mealCost)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.food_search_list, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val data = dataList[position]
holder.mealImage.setImageResource(data.mealImage)
holder.mealName.text = data.mealName
holder.mealDescription.text = data.mealDescription
holder.mealCat.text = data.mealCat
holder.restaurant.text = data.restaurant
//holder.mealCost.text = data.mealCost.toString()
}
override fun getItemCount() = dataList.size
}
And The Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.foodme2">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.FoodMe2">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
and the s from the debugger. I am trying to understand what was going on here all I got is the the Issue was in my MainActivity.kt and it was the line of code i first started.
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.foodme2, PID: 1784
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.foodme2/com.example.foodme2.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.widget.TextView.toString()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.widget.TextView.toString()' on a null object reference
at com.example.foodme2.MainActivity.onCreate(MainActivity.kt:43)
at android.app.Activity.performCreate(Activity.java:7994)
at android.app.Activity.performCreate(Activity.java:7978)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
I/Process: Sending signal. PID: 1784 SIG: 9
Disconnected from the target VM, address: 'localhost:62990', transport: 'socket'
Start by deleting:
import kotlinx.android.synthetic.main.food_search_list.*
(and consider moving away from Kotlin synthetic accessors, as they are deprecated)
That is not the activity's layout; do not attempt to reference widgets using those accessors.
Then, modify:
dataList.add(mealData("mealTitle.toString()",
Restaurant.toString(),R.drawable.food1,"mealCat.toString()",
"mealDescription.toString()"))
to get rid of references to widgets that are not in this activity and to populate your dataList from actual data. For example, you could start with:
dataList.add(mealData("Sample Title",
Restaurant.toString(),R.drawable.food1,"Sample Category",
"Sample Description"))
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
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I tried to add data to sqlite, but when I clicked Add Button error appear and my app closed. I don't understand, so many wasted hours for looking the solution by myself..
here is my java code, AddSampleActivity.java
package com.example.mangan;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddSampleActivity extends AppCompatActivity {
DatabaseHelper myDb;
EditText editNama, editJarak, editRating , editHarga;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_sample);
editNama = (EditText) findViewById(R.id.nama);
editJarak = (EditText) findViewById(R.id.jarak);
editRating = (EditText) findViewById(R.id.rating);
editHarga = (EditText) findViewById(R.id.harga);
myDb = new DatabaseHelper(this);
}
public void addData(View view) {
boolean isInserted = myDb.insertData(editNama.getText().toString(),
editJarak.getText().toString(),
editRating.getText().toString(),
editHarga.getText().toString() );
if(isInserted)
Toast.makeText(AddSampleActivity.this,"Data Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(AddSampleActivity.this,"Data not Inserted",Toast.LENGTH_LONG).show();
}
}
my layout, activity_add_sample.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
tools:context="com.example.mangan.AddSampleActivity">
<EditText
android:id="#+id/jarak_editText"
android:hint="Jarak"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/rating_editText"
android:hint="Rating"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/harga_editText"
android:hint="Harga"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/add_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="addData"
android:text="Add"/>
</LinearLayout>
This is fullstack trace
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5675)
at android.view.View$PerformClick.run(View.java:22651)
at android.os.Handler.handleCallback(Handler.java:836)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:208)
at android.app.ActivityThread.main(ActivityThread.java:6267)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5675)
at android.view.View$PerformClick.run(View.java:22651)
at android.os.Handler.handleCallback(Handler.java:836)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:208)
at android.app.ActivityThread.main(ActivityThread.java:6267)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.mangan.AddSampleActivity.addData(AddSampleActivity.java:30)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5675)
at android.view.View$PerformClick.run(View.java:22651)
at android.os.Handler.handleCallback(Handler.java:836)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:208)
at android.app.ActivityThread.main(ActivityThread.java:6267)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
It seem that some content on addData method is the problem. I read another question, Getting IllegalStateException on button click, but the problem is little bit different..
Your edittext ids aren't correct. change them like below
editJarak = (EditText) findViewById(R.id.jarak_editText);
editRating = (EditText) findViewById(R.id.rating_editText);
editHarga = (EditText) findViewById(R.id.harga_editText);
Your edit text ids are wrong. Try this,
editNama = (EditText) findViewById(R.id.nama_editText);
editJarak = (EditText) findViewById(R.id.jarak_editText);
editRating = (EditText) findViewById(R.id.rating_editText);
editHarga = (EditText) findViewById(R.id.harga_editText);
I created a simple app that the only thing that does is to print "Hello world".
When i try to launch it on my device in some point it stops and says "Unfortunately ,(the name of my app) has stopped. " I searched everywhere, but I couldn't find a solution to this problem.
Here 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"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:textSize="36sp"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold"
android:layout_marginLeft="12dp"
android:layout_marginTop="12dp"
/>
</RelativeLayout>
AndroidManifest.xml(if this is helpful.) :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.test">
<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:
Process: com.example.android.test, PID: 6266
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.test/com.example.android.test.MainActivity}: 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:3319)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7325)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.android.test.MainActivity.onCreate(MainActivity.java:21)
at android.app.Activity.performCreate(Activity.java:6904)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7325)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
I hope this is what is required to help me solve this problem. If you need some more declerations please let me know.
EDIT
here is my Main.Activity.java code:
package com.example.android.test;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Example of a call to a native method
//TextView tv = (TextView) findViewById(R.id.sample_text);
//tv.setText(stringFromJNI());
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
public native String stringFromJNI();
public class SampleActivity extends AppCompatActivity {
// Create the variable
TextView mTextView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Other view stuff
// Get the reference
mTextView = (TextView) findViewById(R.id.text_view);
// Now you can do things to the Textview like change its text
mTextView.setText("Hello world!");
}
}
}
According to the Logcat output it looks like you are trying to set the text of your TextView before getting your reference to it, try this.
First make sure you add the ID field to your xml.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:textSize="36sp"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold"
android:layout_marginLeft="12dp"
android:layout_marginTop="12dp"
android:"#+id/text_view"
/>
Then open your MainActivity class and add the following to your class
public class SampleActivity extends AppCompatActivity {
// Create the variable
TextView mTextView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Other view stuff
// Get the reference
mTextView = (TextView) findViewById(R.id.text_view);
// Now you can do things to the Textview like change its text
mTextView.setText("Hello World!");
}
}
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!!