NullPointerException with setImageDrawable method in android studio [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I just started an app for a project which I wanted to have an into slider for. I got everything working except for the page dots, which do not display when the IntroSlider activity, the activity which displays all of the slides, is launched, and crashes the application when trying to go to the next slide. I don't understand what is causing the error, I would appreciate any help. Look for the comment in IntroSlider.java which specifies the line number that Android Studio says is causing the error. Thank you
IntoSlider.java:
package com.businessbrains.businessbrains.Activities;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.businessbrains.businessbrains.Adapters.SlidesAdapter;
import com.businessbrains.businessbrains.Internals.PreferenceManager;
import com.businessbrains.businessbrains.R;
public class IntroSlider extends AppCompatActivity implements View.OnClickListener{
private ViewPager mPager;
private int[] layouts = {R.layout.slide_welcome, R.layout.slide_account, R.layout.slide_selftest, R.layout.slide_mutliplayer};
private SlidesAdapter slidesAdapter;
private LinearLayout Dots_Layout;
private ImageView[] dots;
private Button skipBtn, nextBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(new PreferenceManager(this).isSlidesEnabled()){
loadLogin();
}
if(Build.VERSION.SDK_INT >= 19){
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
} else{
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
setContentView(R.layout.activity_intro_slider);
mPager= (ViewPager) findViewById(R.id.viewPager);
slidesAdapter = new SlidesAdapter(layouts, this);
mPager.setAdapter(slidesAdapter);
Dots_Layout = findViewById(R.id.dotsLayout);
nextBtn = (Button) findViewById(R.id.nextBtn);
nextBtn.setOnClickListener(this);
skipBtn = (Button) findViewById(R.id.skipBtn);
skipBtn.setOnClickListener(this);
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i1) {
}
#Override
public void onPageSelected(int i) {
createDots(i);
if(i==layouts.length-1){
nextBtn.setText("Start");
skipBtn.setVisibility(View.INVISIBLE);
}
else{
nextBtn.setText("Next");
skipBtn.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
}
private void createDots(int current_position){
if(Dots_Layout!=null){
Dots_Layout.removeAllViews();
}
dots = new ImageView[layouts.length];
for(int i = 0; i < layouts.length; i++){
if(i==current_position){
dots[i].setImageDrawable((Drawable)ContextCompat.getDrawable(getApplicationContext(), R.drawable.accessory_active_dots));
}
else{
dots[i].setImageDrawable((Drawable)(ContextCompat.getDrawable(getApplicationContext(), R.drawable.accessory_inactive_dots)));
//line which is causing the error
}
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(4,0,4,0);
Dots_Layout.addView(dots[i], params);
}
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.nextBtn:
loadNextSlide();
break;
case R.id.skipBtn:
loadLogin();
new PreferenceManager(this).writeDisableSlides();
break;
}
}
private void loadLogin(){
startActivity(new Intent(this, LoginOptionsActivity.class));
finish();
}
private void loadNextSlide(){
int nextslide = mPager.getCurrentItem() + 1;
if(nextslide < layouts.length){
mPager.setCurrentItem(nextslide);
}
else{
loadLogin();
new PreferenceManager(this).writeDisableSlides();
}
}
}
the corresponding .xml, activity_into_slider.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activities.IntroSlider">
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewPager"
/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:alpha=".5"
android:layout_above="#+id/dotsLayout"
android:background="#android:color/white"
android:layout_marginBottom="15dp"
></View>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/dotsLayout"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:gravity="center"
android:layout_marginBottom="55sp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Skip"
android:textSize="16sp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#android:color/transparent"
android:id="#+id/skipBtn"
android:layout_marginBottom="8dp"
android:textColor="#android:color/white"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:textSize="16sp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#android:color/transparent"
android:id="#+id/nextBtn"
android:layout_marginBottom="8dp"
android:textColor="#android:color/white"
/>
</RelativeLayout>
One of the slides:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorSlide_welcome">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/ic_welcome"
android:layout_centerHorizontal="true"
android:scaleType="centerCrop"
android:layout_marginTop="150dp"
android:id="#+id/img"
android:tint="#android:color/black"
/>
<TextView
android:layout_width="132dp"
android:layout_height="100dp"
android:text="#string/slide1title"
android:textColor="#android:color/white"
android:textSize="30sp"
android:textStyle="bold"
android:layout_centerHorizontal="true"
android:layout_below="#+id/img"
android:layout_marginTop="12dp"
android:id="#+id/slidetitle"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/slide1desc"
android:textColor="#android:color/white"
android:textSize="18sp"
android:gravity="center_horizontal"
android:layout_below="#+id/slidetitle"
android:layout_marginTop="10dp"
android:id="#+id/slide_desc"
android:layout_marginRight="40sp"
android:layout_marginLeft="40sp"
/>
</RelativeLayout>
The error which is being thrown:
07-11 00:30:30.253 6010-6010/com.businessbrains.businessbrains E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.businessbrains.businessbrains, PID: 6010
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageDrawable(android.graphics.drawable.Drawable)' on a null object reference
at com.businessbrains.businessbrains.Activities.IntroSlider.createDots(IntroSlider.java:89)
at com.businessbrains.businessbrains.Activities.IntroSlider.access$000(IntroSlider.java:21)
at com.businessbrains.businessbrains.Activities.IntroSlider$1.onPageSelected(IntroSlider.java:62)
at android.support.v4.view.ViewPager.dispatchOnPageSelected(ViewPager.java:1947)
at android.support.v4.view.ViewPager.scrollToItem(ViewPager.java:686)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:670)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:631)
at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:612)
at com.businessbrains.businessbrains.Activities.IntroSlider.loadNextSlide(IntroSlider.java:118)
at com.businessbrains.businessbrains.Activities.IntroSlider.onClick(IntroSlider.java:101)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
accessory_active_dots.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"
android:useLevel="true"
android:dither="true">
<size android:height="8dp" android:width="8dp"/>
<solid android:color="#color/active_dots"/>
</shape>
accessory_inactive_dots.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"
android:useLevel="true"
android:dither="true">
<size android:height="8dp" android:width="8dp"/>
<solid android:color="#color/inactive_dots"/>
</shape>

dots = new ImageView[layouts.length]; creates an array of size layouts.length but all the elements of the array are null.
So when you invoke setImageDrawable(..) on dots[i], you are actually invoking the method setImageDrawable(..) on a null object.
Fix: initialize dots[i] (i.e., dots[i] =) with a non-null value before use. For example, do dots[i] = new ImageView() before you invoke setImageDrawable(..) on dots[i].

Related

Why does findViewById() returns "null"?

I have an important issue with java
I have this code :
package fr.christian.lbcde;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;
import fr.christian.lbcde.ui.main.PageViewModel;
import fr.christian.lbcde.ui.main.SectionsPagerAdapter;
public class MainActivity extends AppCompatActivity {
PageViewModel pageViewModel;
View activity_main, tab_create, tab_connect;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pageViewModel = new ViewModelProvider(this).get(PageViewModel.class);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
FloatingActionButton fab = findViewById(R.id.fab);
tab_connect = findViewById(R.id.tab_connect);
tab_create = findViewById(R.id.tab_create);
System.out.print("Result of tab_connect : ");
System.out.print(findViewById(R.id.tab_connect));
System.out.print(" ");
System.out.println(tab_connect==null);
System.out.print("Result of tab_create : ");
System.out.print(findViewById(R.id.tab_create));
System.out.print(" ");
System.out.println(tab_create==null);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addNew();
}
});
// hideAll();
// tab_connect.setVisibility(View.VISIBLE);
pageViewModel.addTabListener(new PageViewModel.tabChangeListener() {
#Override
public void onChangeTab(View view, int tab) {
switch (tab) {
case 1:
hideAll();
tab_connect.setVisibility(View.VISIBLE);
break;
case 2:
hideAll();
tab_create.setVisibility(View.VISIBLE);
break;
default:
new Toast(getApplicationContext())
.makeText(getApplicationContext(), "Rien a afficher pour cet onglet", Toast.LENGTH_SHORT)
.show();
}
}
});
}
public void addNew() {
new Toast(getApplicationContext())
.makeText(getApplicationContext(), "Cette option n'est pas encore disponible", Toast.LENGTH_SHORT)
.show();
}
public void hideAll() {
View[] views = {
tab_create,
tab_connect
};
for (int i = 0; i < views.length; i++) {
views[i].setVisibility(View.INVISIBLE);
}
;
}
}
and four files for my layouts :
activity main.xml :
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.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"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/Theme.LeBonCoinDeLÉvangile.AppBarOverlay">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:minHeight="?actionBarSize"
android:padding="#dimen/appbar_padding"
android:text="#string/app_name"
android:textAppearance="#style/TextAppearance.Widget.AppCompat.Toolbar.Title" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:tabSelectedTextColor="?attr/colorPrimaryVariant"/>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<com.google.android.material.floatingactionbutton.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:background="?attr/colorPrimary"
app:srcCompat="#android:drawable/ic_menu_info_details" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
fragment_main.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:id="#+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.main.PlaceholderFragment">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginStart="#dimen/activity_horizontal_margin"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:layout_marginEnd="#dimen/activity_horizontal_margin"
android:layout_marginBottom="#dimen/activity_vertical_margin">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<include layout="#layout/login_main"/>
<include layout="#layout/create_main"/>
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
create_main.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="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/tab_create"
android:orientation="vertical"
android:layout_marginStart="#dimen/activity_horizontal_margin"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:layout_marginEnd="#dimen/activity_horizontal_margin"
android:layout_marginBottom="#dimen/activity_vertical_margin"
android:visibility="invisible">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="TAB_CREATE"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BONJOUR LES ÉLËPHANTS"/>
</LinearLayout>
and login_main.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="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/tab_connect"
android:orientation="vertical"
android:layout_marginStart="#dimen/activity_horizontal_margin"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:layout_marginEnd="#dimen/activity_horizontal_margin"
android:layout_marginBottom="#dimen/activity_vertical_margin">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="TAB_CONNECT"/>
<TextView
style="#style/h2textStyle"
android:text="#string/titleConnect_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/loginConnect_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Name" />
</LinearLayout>
The problem is that at the lines :
System.out.print(findViewById(R.id.tab_connect));
and
System.out.print(findViewById(R.id.tab_create));
I have this result (for the both) :
null
So I can't remove the error "java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setVisibility(int)' on a null object reference" in hideAll(), tab_create.setVisibility(View.VISIBLE), etc... because when I initialize my layouts, they are initialized with a null object (and not my layouts).
I add some lines like
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="TAB_CREATE"/>
in my file to see if those tabs are really those I see on my screen and its appear that I really see them (when I cancel the lines with the layouts visibility).
Thanks for your help!
Your tab_connect etc. are included in fragment_main layout and not in activity_main layout that is inflated when you call findViewById() for those ids. The code you posted does not show where you're using fragment_main but what is certain is that it is not in your activity's view hierarchy at the time when you try to look up those views.
Either move the findViewById() calls and whatever you're doing with the views to the fragment, or move the views from the fragment to your main activity.

android java Null point exeption at view.setonclicklistener at the secend init why they do not match

I have this problem and it shows me following error
please help me:
I get a NullPointerException in init2(). Apperently sms is null.
I don't understand the problem
Process: com.example.android.projectdestage, PID: 11049
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.android.projectdestage/com.example.android.projectdestage.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.view.View.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.view.View.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at
com.example.android.projectdestage.MainActivity.init2(MainActivity.java:60)
at
com.example.android.projectdestage.MainActivity.onCreate(MainActivity.java:38)
at android.app.Activity.performCreate(Activity.java:6956)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045) 
at android.app.ActivityThread.-wrap14(ActivityThread.java) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6776) 
at java.lang.reflect.Method.invoke(Native Method) 
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
****this is my main activity****
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
public class MainActivity extends AppCompatActivity
{
private Button sms;
private Button btnMap;
private static final String TAG = "MainActivity";
private static final int ERROR_DIALOG_REQUEST = 9001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
if(isServicesOK()){
init();
init2();
}
}
private void init(){
Button btnMap = (Button) findViewById(R.id.btnMap);
btnMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MapActivity.class);
startActivity(intent);
}
});
}
private void init2()
{
Button sms = (Button) findViewById(R.id.sms);
sms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent message = new Intent(MainActivity.this, MainActivity2.class);
startActivity(message);
}
});
}
public boolean isServicesOK()
{
Log.d(TAG, "isServicesOK: checking google services version");
int available = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(MainActivity.this);
if(available == ConnectionResult.SUCCESS)
{
// koulchi mli7 map request
Log.d(TAG, "isServicesOK: Google Play Services is working");
return true;
}
else if(GoogleApiAvailability.getInstance().isUserResolvableError(available))
{
//test d erreur
Log.d(TAG, "isServicesOK: an error occured but we can fix it");
Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(MainActivity.this, available, ERROR_DIALOG_REQUEST);
dialog.show();
}else
{
Toast.makeText(this, "You can't make map requests", Toast.LENGTH_SHORT).show();
}
return false;
}
}
`**this is my mainactivity 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="com.example.android.projectdestage.MainActivity">
<Button
android:id="#+id/btnMap"
android:layout_width="87dp"
android:layout_height="45dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="244dp"
android:text="#string/map"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.43"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/smsbtn"
android:layout_width="wrap_content"
android:layout_height="43dp"
android:layout_marginBottom="136dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="#string/enter_your_message"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.43"
app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>
**and the main2activity 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:gravity="center"
android:orientation="vertical"
tools:context="com.example.android.projectdestage.MainActivity2">
<TextView
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/enter_your_message"
android:textSize="30sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="519dp"
android:orientation="vertical">
<TextView
android:id="#+id/editText2"
android:layout_width="385dp"
android:layout_height="410dp"
android:layout_marginTop="50dp"
android:layout_weight="1"
android:text="#string/textview" />
<Button
android:id="#+id/btnSendSMSendSms"
android:layout_width="wrap_content"
android:layout_height="250dp"
android:layout_marginLeft="150dp"
android:layout_marginStart="150dp"
android:layout_marginVertical="110dp"
android:layout_weight="1"
android:text="#string/sendsms"
tools:targetApi="o" />
</LinearLayout>
</LinearLayout>
and the the mapactivity xml
i think the main problem is here
<?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">
<fragment 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:id="#+id/map"
tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:elevation="10dp"
android:background="#drawable/white_border"
android:id="#+id/relLayout1" tools:targetApi="lollipop">
<ImageView
android:layout_width="15dp"
android:layout_height="15dp"
android:id="#+id/ic_magnify"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:src="#drawable/ic_magnify" android:contentDescription="#string/todoo" android:layout_marginStart="10dp" />
<AutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toRightOf="#+id/ic_magnify"
android:layout_centerVertical="true"
android:textSize="15sp"
android:textColor="#000"
android:id="#+id/input_search"
android:background="#null"
android:hint="#string/enter_address_city_or_zip_code"
android:imeOptions="actionSearch" android:layout_toEndOf="#+id/ic_magnify" />
</RelativeLayout>
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_below="#id/relLayout1"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:scaleType="centerCrop"
android:id="#+id/ic_gps"
android:src="#drawable/ic_gps" android:contentDescription="#string/todo" android:layout_alignParentEnd="true" android:layout_marginEnd="10dp" />
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:id="#+id/place_picker"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
android:scaleType="centerCrop"
android:layout_below="#+id/relLayout1"
android:src="#drawable/ic_map" android:contentDescription="#string/todoml" android:layout_marginStart="10dp" />
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_below="#+id/place_picker"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
android:scaleType="centerCrop"
android:id="#+id/place_info"
android:src="#drawable/ic_info" android:layout_marginStart="10dp" android:contentDescription="#string/todoop" />
</RelativeLayout>
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
Button sms = (Button) findViewById(R.id.sms); returns null
This means he can not find R.id.sms in your activity_main.xml layout.
Maybe a typo or copy paste error? Check if this button's ID in this file really is sms.
Also if you have multiple layouts for different screen sizes, etc. Check all of them.
You have smsBtn as an id for sms Button in your activity_main.xml, whereas you've passed sms as id. So id with sms is not found and so button is null and throws null pointer exception.
There is better approach that can accomplish this using Butterknife library:
public class MainActivity extends AppCompatActivity
{
#BindView(R.id.smsBtn)
private Button sms;
#BindView(R.id.btnMap)
private Button btnMap;
private static final String TAG = "MainActivity";
private static final int ERROR_DIALOG_REQUEST = 9001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
#OnClick({R.id.btnMap, R.id.smsBtn})
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnMap:
//Your functionality
break;
case R.id.smsBtn:
//Your functionality
break;
}
}
}
//Dependency for ButterKnife library
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
//Butterknife link
https://github.com/JakeWharton/butterknife

Android ID not found, when it is there

Android Studio is giving me errors in the Main Activity Java over unresolved symbols or id's. As far as I can see the id's refrenced in the java code exist.
In another app which used these same principles, it worked, I cross refrenced the two apps and could not find anything that stood out.
Here is my java code:
package com.example.android.quizapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
public class QuizMainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_main);
}
public void display(int value) {
TextView quantityTextView = findViewById(R.id.value_text);
quantityTextView.setText(value);
}
public void slider(View view){
SeekBar seekBar = (SeekBar)findViewById(R.id.i);
int Value = seekBar.getProgress();
EditText text = (EditText)findViewById(R.id.valueText);
String name = text.getText().toString();
text.setText(Value);
}
}
Here is my XML: (The id's are there)
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.quizapplication.QuizMainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Quiz"
android:textAlignment="center"/>
<TextView
android:id="#+id/question"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="What is you favorite color?"
android:textAlignment="center"
android:paddingTop="20dp"
android:textSize="20dp"
android:textStyle="bold"
android:textColor="#000000"
android:layout_below="#+id/title"
/>
<TextView
android:id="#+id/value_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Test"
android:textAlignment="center"
android:layout_alignParentBottom="true"
android:layout_marginBottom="300dp"/>
<SeekBar
android:id="#+id/i"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="146dp"
android:onClick="slider"/>
</RelativeLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
/>
Try adding this:
import com.example.android.quizapplication.R;

attempt to invoke a virtual method on null object with onclicklistener

I'm sure this question has been asked a few times; however, after searching for a while, all I find is "to declare the variable before calling the clicklistner" I've done that already. But still getting the same error. If someone can let me know why the clicklistener called on the getQuoteBotton is giving the following error.
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
mainActivity
package com.example.george.radonquote;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import static com.example.george.radonquote.R.layout.activity_main;
public class MainActivity extends AppCompatActivity {
TextView titleTextView;
ImageView mainImageView;
Button getQuoteBotton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
titleTextView = (TextView) findViewById(R.id.main_title);
mainImageView = (ImageView) findViewById(R.id.main_image);
getQuoteBotton = (Button) findViewById(R.id.get_quote_btn);
getQuoteBotton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent quoteActivityIntent = new Intent(getApplicationContext(), QuotesActivity.class);
startActivity(quoteActivityIntent);
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#154350"
tools:context="com.example.george.radonquote.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Random Quotes"
android:textColor="#fff"
android:textSize="27dp"
android:textAlignment="center"
android:id="#+id/main_title"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="55dp" />
<ImageView
android:layout_width="match_parent"
android:layout_height="200dp"
android:src="#drawable/vector_socrates"
android:id="#+id/main_image"
android:layout_below="#+id/main_title"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="84dp" />
<Button
android:id="#+id/get_quote_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/main_image"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:text="get quote" />
</RelativeLayout>

Android: EditText in CustomView not behaving as expected when touched

I have a CustomView which contains a LinearLayout that holds an EditText & another custom view element. However, when I run my app and touch the EditText it does not behave as expected (doesn't appear to receive focus & the soft keyboard doesn't open). I've tried setting duplicateParentState="true" on both the EditText & the LinearLayout. I also attached an onTouchEventListener to the EditText that calls a simple toast & the toast did show up.
Here's the code for my CustomView.
form_field.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_marginBottom="15dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/grey_rounded_borders">
<EditText
android:id="#+id/edit_text"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:inputType="text"
android:padding="10dp"
android:textColor="#2d6169"
android:textSize="18sp"
android:background="#color/transparent" />
<RelativeLayout
android:layout_marginStart="5dp"
android:layout_marginEnd="10dp"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<com.example.app.ValidationIcon
android:id="#+id/validation_icon"
android:layout_width="wrap_content"
android:layout_height="match_parent"
tools:ignore="ContentDescription" />
</RelativeLayout>
</LinearLayout>
FormField.java
package com.example.app;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import java.util.ArrayList;
public class FormField extends LinearLayout {
private EditText editText;
private ValidationIcon validationIcon;
private Integer fieldInputType;
private String fieldInputHint;
public FormField(Context context)
{
super(context);
}
public FormField(Context context, AttributeSet attributeSet)
{
super(context, attributeSet);
TypedArray attrs = context.obtainStyledAttributes(attributeSet, R.styleable.FormField, 0, 0);
fieldInputType = attrs.getInt(
R.styleable.FormField_fieldInputType,
InputType.TYPE_TEXT_VARIATION_NORMAL
);
fieldInputHint = attrs.getString(
R.styleable.FormField_fieldInputHint
);
attrs.recycle();
inflate(getContext(), R.layout.form_field, this);
this.setFocusable(true);
this.setFocusableInTouchMode(true);
editText = (EditText)findViewById(R.id.edit_text);
editText.setInputType(fieldInputType);
editText.setHint(fieldInputHint);
editText.setFocusableInTouchMode(true);
validationIcon = (ValidationIcon)findViewById(R.id.validation_icon);
validationIcon.setValid(true);
ArrayList<View> touchables = new ArrayList<View>();
touchables.add(this);
touchables.add(editText);
addTouchables(touchables);
}
public FormField(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
}
registration_layout.xml
<RelativeLayout android:id="#+id/container"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp">
<RelativeLayout android:id="#+id/account_details"
android:layout_marginBottom="15dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.example.app.FormField
android:id="#+id/name_field"
android:layout_width="match_parent"
android:layout_height="wrap_content"
custom:fieldInputHint="#string/name_field_hint" />
<com.example.app.FormField
android:id="#+id/email_field"
android:layout_width="match_parent"
android:layout_height="wrap_content"
custom:fieldInputHint="#string/email_field_hint" />
<com.example.app.FormField
android:id="#+id/password_field"
android:layout_width="match_parent"
android:layout_height="wrap_content"
custom:fieldInputHint="#string/password_field_hint" />
<com.example.app.FormField
android:id="#+id/re_password_field"
android:layout_width="match_parent"
android:layout_height="wrap_content"
custom:fieldInputHint="#string/re_password_field_hint" />
</RelativeLayout>
</RelativeLayout>
Min SDK Version is set at 14, target is set at 20. Any help would be greatly appreciated!
EDIT:
I got this logcat message today while testing long presses on my FormFields.
W/TextView﹕ TextView does not support text selection. Action mode cancelled.
I double checked my code and the EditText element is only ever cast as an EditText. If the EditText is being cast to a TextView that would explain my original issues but now I'm confused as to why or how it was cast as a TextView.
It looks like you are extending LinearLayout but never using it in your layout. From what you've posted, you aren't using the FormField at all and the only custom View I see is the ValidationIcon view. So hooking the touch events into EditText and ValidationIcon aren't occurring because you aren't using FormField in your layout.xml.
Rather than extending LinearLayout, why not just use the predefined methods and attributes to handle the behaviour you are trying to achieve. For example, displaying keyboard, requesting focus, and displaying hint:
<EditText
android:id="#+id/edit_text"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
**android:inputType="text"**
**android:hint="#styleable/FormField_fieldInputHint"**
android:padding="10dp"
android:textColor="#2d6169"
android:textSize="18sp"
android:background="#color/transparent" />
The keyboard should display when the edit text receives focus, if not you could programmatically do this by requesting focus and handling the IME manager call. For example, from the Activity/Fragment:
//call this from onViewCreated to grab focus and begin the flow
editText.requestFocus();
//set focus listener to handle keyboard display
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
InputMethodManager imm = (InputMethodManager)getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
} else {
InputMethodManager imm = (InputMethodManager)getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.showSoftInputFromWindow(myEditText.getWindowToken(), 0);
}
});
Make sure have not been setting inputType:'none' or '0X000000'
use this code for custom Edittext with title
custom_view.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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="wrap_content"
android:layout_gravity="right"
android:foregroundGravity="right"
app:layout_anchorGravity="right">
<LinearLayout
android:orientation="vertical"
android:id="#+id/search_closed_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center|right"
android:background="#color/white"
android:foregroundGravity="center"
android:gravity="right">
<TextView
android:id="#+id/txt_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|left"
android:layout_marginStart="16dp"
android:layout_marginTop="14dp"
android:fontFamily="#font/intel"
android:foregroundGravity="center"
android:text="textview"
android:textColor="#color/title_color"
android:textSize="14dp"
android:textStyle="bold" />
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/lay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:clickable="true"
android:orientation="horizontal">
<androidx.appcompat.widget.AppCompatEditText
android:id="#+id/edt_text"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#drawable/edit_txtbg"
android:fontFamily="#font/intel"
android:gravity="center|start"
android:paddingStart="24dp"
android:textColor="#color/text_color"
android:textColorHint="#color/txt_hint"
android:textSize="#dimen/text_nev"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/img_add_patient"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
</FrameLayout>
CustomEditText.kt
package com.mdppractice.custom
import android.content.Context
import android.text.InputType
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.TextView
import com.mdppractice.R
class CustomEditText(
context: Context,
attrs: AttributeSet,
) : FrameLayout(context, attrs) {
private var txt_title: TextView
private var edt_text: EditText
init {
LayoutInflater.from(context)
.inflate(R.layout.custom_view, this, true)
txt_title = findViewById(R.id.txt_title)
edt_text = findViewById(R.id.edt_text)
val a = context.obtainStyledAttributes(attrs, R.styleable.CustomEditText)
txt_title.text = a.getString(R.styleable.CustomEditText_title)
edt_text.hint = a.getString(R.styleable.CustomEditText_hint)
when(a.getString(R.styleable.CustomEditText_inputType)) {
"number" -> edt_text.inputType = InputType.TYPE_CLASS_PHONE
"textCapSentences" -> edt_text.inputType = InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
"text" -> edt_text.inputType = InputType.TYPE_CLASS_TEXT
}
a.recycle()
}
fun setmInputType(type: Int) {
edt_text.setRawInputType(InputType.TYPE_CLASS_TEXT)
setmInputType(type)
}
fun setTitle(title: Int) {
txt_title.setText(title)
}
fun set_Text(title: Int) {
edt_text.setText(title)
}
fun getTitle(): String {
return txt_title.text.toString()
}
fun get_Text(): String {
return edt_text.text.toString()
}
}
main/../attr.xml
<declare-styleable name="CustomEditText">
<attr name="title" format="string"/>
<attr name="onCenter" format="boolean"/>
<attr name="hint" format="string"/>
<attr name="maxLength" format="integer"/>
<attr name="inputType" format="string"/>
</declare-styleable>
#drawable/edit_txtbg
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:id="#+id/listview_background_shape">
<stroke android:width="1dp" android:color="#color/button_bg_border" />
<padding android:left="0dp"
android:top="0dp"
android:right="0dp"
android:bottom="0dp" />
<corners android:radius="6dp"/>
<solid android:color="#color/button_bg" />
</shape>
use in layout
<com.mdppractice.custom.CustomEditText
android:id="#+id/edt_custom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:title="Patient ID/Phone"
android:autofillHints="#string/verified"
android:foregroundGravity="center"
android:hint="Please enter name"
app:inputType="textCapSentences"
android:textColor="#color/title_color"
android:textSize="14dp"
android:textStyle="bold" />
thanks you

Categories