I want to select the button element by ID, but when I run the program, I get the app keeps stopping error.
I ran the program in debug mode and the error Caused by:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.Button.findViewById(int)' on a null object reference
Even when I click on R.id.button, the button element is displayed in the xml file.
mainActivityFile :
package com.example.app;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity6 extends AppCompatActivity {
private Button btn;
private TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main6);
btn.findViewById(R.id.button);
txt.findViewById(R.id.txt);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
txt.setText("This is a new text.");
}
});
// Toast.makeText(this, "str", Toast.LENGTH_LONG).show();
}
}
xml file :
<?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"
tools:context=".MainActivity6">
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:autoSizeTextType="uniform"
android:autoSizeMinTextSize="25sp"
android:autoSizeMaxTextSize="100dp"
android:autoSizeStepGranularity="2sp"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
btn.findViewById(R.id.button);
You're not supposed to use it this way because btn is null at this point.
You have to do the following:
btn = (Button)findViewById(R.id.button);
I'm new at coding so I might be not very good at explaining. I'm trying to build chat app with Firebase.
Here is my code for Main activity:
Mpackage com.example.otto.myfirstapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.text.format.DateFormat;
import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.database.FirebaseListAdapter;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
public class MainActivity extends AppCompatActivity {
private static int SIGN_IN_REQUEST_CODE = 1;
private FirebaseListAdapter<ChatClass> adapter;
RelativeLayout activity_main;
FloatingActionButton fab;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.menu_sign_out)
{
AuthUI.getInstance().signOut(this).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Snackbar.make(activity_main,"You have been signed out.", Snackbar.LENGTH_SHORT).show();
finish();
}
});
}
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == SIGN_IN_REQUEST_CODE)
{
if(resultCode == RESULT_OK)
{
Snackbar.make(activity_main,"Successfully sighned in.Welcome!", Snackbar.LENGTH_SHORT).show();
displayChatMessage();
}
else{
Snackbar.make(activity_main,"Error 1", Snackbar.LENGTH_SHORT).show();
finish();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fab = (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText input = (EditText)findViewById(R.id.input);
FirebaseDatabase.getInstance().getReference().push().setValue(new ChatClass(input.getText().toString(),FirebaseAuth.getInstance().getCurrentUser().getEmail()));
input.setText("");
}
});
if(FirebaseAuth.getInstance().getCurrentUser() == null)
{
startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(),SIGN_IN_REQUEST_CODE);
}
else
{
Snackbar.make(activity_main,"Welcome " +FirebaseAuth.getInstance().getCurrentUser().getEmail(),Snackbar.LENGTH_SHORT).show();
}
displayChatMessage();
}
private void displayChatMessage() {
ListView listOfMessage = (ListView)findViewById(R.id.list_of_message);
adapter = new FirebaseListAdapter<ChatClass>(this,ChatClass.class,R.layout.list_item,FirebaseDatabase.getInstance().getReference()) {
#Override
protected void populateView(View v, ChatClass model, int position) {
TextView messageText,messageUser,messageTime;
messageText = (TextView)findViewById(R.id.message_text);
messageUser = (TextView)findViewById(R.id.message_user);
messageTime = (TextView)findViewById(R.id.message_time);
messageText.setText(model.getMessageText());
messageUser.setText(model.getMessageUser());
messageTime.setText(DateFormat.format("dd-mm-yy (HH:mm:ss)",model.getMessageTime()));
}
};
listOfMessage.setAdapter(adapter);
}
}
And code for acitivty_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:src="#drawable/c_send"
android:id="#+id/fab"
android:tint="#android:color/white"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
app:fabSize="mini"
/>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/fab"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Message..."
android:id="#+id/input"
/>
</android.support.design.widget.TextInputLayout>
<ListView
android:id="#+id/list_of_message"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/fab"
android:dividerHeight="16dp"
android:divider="#android:color/transparent"
android:layout_marginBottom="16dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
Error code from the logcat while app says that it keeps stopping tells me that problem is in the snackbar:
Caused by: java.lang.IllegalArgumentException: No suitable parent found from the given view. Please provide a valid view.
at android.support.design.widget.Snackbar.make(Snackbar.java:181)
at com.example.otto.myfirstapplication.MainActivity.onCreate(MainActivity.java:97)
at android.app.Activity.performCreate(Activity.java:7009)
at android.app.Activity.performCreate(Activity.java:7000)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
I updated all dependencies to the latest versions. I was thinking maybe I have to downgrade to solve a problem but I'm not sure.
Anyway I'm super stuck and hope you can help me. Thanks in advance.
Change at all places,
Snackbar.make(activity_main,...
to
Snackbar.make(findViewById(android.R.id.content),...
Cause
You did not initialize activity_main. So it is null when you use it. findViewById(android.R.id.content) gives you root view of current Activity.
First of All you have to create coordinator layout to appear your snackbar. so change your main relativelayout to coordinator layout .
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
//YOUR CURRENT CODE
</android.support.design.widget.CoordinatorLayout>
after that in your activity .
coordinatorLayout = (CoordinatorLayout) findViewById(R.id
.coordinatorLayout);
and make your Snackbar layout like this
Snackbar snackbar = Snackbar.make(coordinatorLayout, "Welcome to AndroidHive", Snackbar.LENGTH_LONG);
snackbar.show();
As in your code,
RelativeLayout activity_main;
you haven't initialized the activity_main, use findviewbyid in onCreate of activity
In xml change the below code, add the id in xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/container"
tools:context=".MainActivity">
and in the code fetch the id in onCreate method of Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity_main=findViewById(R.id.container);
}
and now use this view(activity_main) in snack bar.
I'm making an app, now i want to make a button with an image and some text on it.
But every time I click the button my app crashes, android studio does compile however.
This is how i my xml code to make the layout of the screen.
<?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">
<RelativeLayout
android:id="#+id/buttonStartTest"
style="#android:style/Widget.Button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="MissingConstraints">
<ImageView... />
<TextView.../>
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
java code:
package com.example.user.ballbounceapp;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout StartTest = findViewById(R.id.buttonStartTest);
StartTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TestActivity();
}
});
}
public void TestActivity(){
Intent intent = new Intent(MainActivity.this,TestActivity.class);
startActivity(intent);
}
};
You may have forgot to declare your TestActivity inside your manifest.
More about activities in manifest here : https://developer.android.com/guide/topics/manifest/activity-element
So you will need something like this :
<activity android:name="TestActivity">
If the crash persists, the problem might be in your TestActivity 's OnCreate method.
Qr code scanner not running in android 6.0.1 ie redmi note 4 (showing white screen and camera is not opening). Also, The app is running perfectly fine on my kit-kat(4.4) and lolipop device (5.1). please explain what was causing the issue.
package com.example.android.qrking;
import android.app.Activity;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.google.zxing.Result;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class MainActivity extends Activity implements ZXingScannerView.ResultHandler{
private ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mScannerView = new ZXingScannerView(this);
}
public void onClick(View v){
setContentView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
#Override
protected void onPause() {
super.onPause();
mScannerView.stopCamera();
}
#Override
public void handleResult(Result result){
Log.v("handler result", result.getText());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("scan results");
builder.setMessage(result.getText());
AlertDialog alertDialog = builder.create();
alertDialog.show();
//uncomment to scan again
mScannerView.resumeCameraPreview(this);
}
}
my layout file
<?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_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.example.android.qrking.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Scan qr code"
android:layout_centerInParent="true"
android:onClick="onClick"/>
</RelativeLayout>
The correct way to use zxing is by sending an Intent that it will handle. See http://github.com/zxing/zxing/wiki/Scanning-Via-Intent for details about how to do this.
I have 2 activities:
the first - is just an opening page and it has a button that goes to the second activity
the second activity - will open up the contact list and will allow the user to pick contacts and retrieve their numbers - they will be saved for later use.
My problem is I can not figure out how to get it to work in the second activity. All the examples only have the contact list in the Main/first activity and I am really new to this and don't understand how to get it to move to the second.
my code I have right now
Main.java
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) this.findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View v){
Intent i = new Intent(MainActivity.this, Contacts.class);
startActivity(i);
}
});
}
}
Main XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView android:text="#string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Settings"
android:id="#+id/button1"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="93dp"/>
</RelativeLayout>
Contacts java
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class Contacts extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
}
}
Contacts XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context="akh.seniorproj.Contacts">
</RelativeLayout>
Check this solution: How to call Android contacts list?
Its pretty much what you need to do but instead name you should search the number with the cursor.