Error inflating class <unknown> - app crashes - java

In an Android app that I developed, the app crashes when I move to a certain activity. I saw that many people encountered a similar problem before, but none of the former answers solve my problem.
Here's the relevant code:
StillsActivity.java
the code crashes on the last line of this snippet
public class StillsActivity extends SpatialFilteringActivity {
private static final int SELECT_PICTURE = 1;
private static final String TAG = "Stills";
private Uri mURI;
private Bitmap mBitmap;
private ImageView mImageView;
private Mat mImToProcess = new Mat();
private Mat mImGray = new Mat();
private Mat mFilteredImage = new Mat();
private SeekBar mSeekBarSpatial;
private SeekBar mSeekBarIntensity;
private SeekBar mSeekBarAlpha;
private SeekBar mSeekBarBeta;
private TextView mTextViewSpatial;
private TextView mTextViewIntensity;
private TextView mTextViewAlpha;
private TextView mTextViewBeta;
private MenuItem mSelectedItem;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_PICTURE) {
if (resultCode == RESULT_OK) {
mURI = data.getData();
if (mURI != null) {
try {
mBitmap = Util.getBitmap(this, mURI);
mImageView.setImageBitmap(Util.getResizedBitmap(mBitmap,
1000));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stills);
// APP CRASHES HERE
mImageView = (ImageView) findViewById(R.id.imageView1);
Button loadButton = (Button) findViewById(R.id.loadButton);
loadButton.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SimpleDateFormat")
#Override
public void onClick(View v) {
Log.i(TAG, "onClick event");
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select an image"), SELECT_PICTURE);
}
});
mSeekBarSpatial = (SeekBar) findViewById(R.id.seekBarSpatial);
mTextViewSpatial = (TextView) findViewById(R.id.sigmaSpatialTextView);
setSeekBar(mSeekBarSpatial, mTextViewSpatial, getResources().getString(R.string.stringSpatial), MyImageProc.SIGMA_SPATIAL_MAX);
mSeekBarIntensity = (SeekBar) findViewById(R.id.seekBarIntensity);
mTextViewIntensity = (TextView) findViewById(R.id.sigmaIntensityTextView);
setSeekBar(mSeekBarIntensity, mTextViewIntensity, getResources().getString(R.string.stringIntensity), MyImageProc.SIGMA_INTENSITY_MAX);
mSeekBarAlpha = (SeekBar) findViewById(R.id.seekBarAlpha);
mTextViewAlpha = (TextView) findViewById(R.id.alphaTextView);
setSeekBar(mSeekBarAlpha, mTextViewAlpha, getResources().getString(R.string.stringAlpha), MyImageProc.ALPHA_MAX);
mSeekBarBeta = (SeekBar) findViewById(R.id.seekBarBeta);
mTextViewBeta = (TextView) findViewById(R.id.betaTextView);
setSeekBar(mSeekBarBeta, mTextViewBeta, getResources().getString(R.string.stringBeta), MyImageProc.BETA_MAX);
}
// etc.
SpatialFilteringActivity.java
public class SpatialFilteringActivity extends AppCompatActivity {
private static final String TAG = "SpatialFiltering";
//menu members
private SubMenu mResolutionSubMenu;
private SubMenu mCameraSubMenu;
//flags
private Boolean mSettingsMenuAvailable =false;
protected static final int SETTINGS_GROUP_ID = 1;
protected static final int RESOLUTION_GROUP_ID = 2;
protected static final int CAMERA_GROUP_ID = 3;
protected static final int DEFAULT_GROUP_ID = 4;
protected static final int COLOR_GROUP_ID = 5;
protected static final int FILTER_GROUP_ID = 6;
protected static final int STILL_GROUP_ID = 7;
private MyJavaCameraView mOpenCvCameraView;
private CameraListener mCameraListener = new CameraListener();
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
Log.i(TAG, "OpenCV loaded successfully");
mOpenCvCameraView.enableView();
break;
default:
super.onManagerConnected(status);
break;
}
}
};
private String[] mCameraNames = {"Front", "Rear"};
private int[] mCameraIDarray = {CameraBridgeViewBase.CAMERA_ID_FRONT, CameraBridgeViewBase.CAMERA_ID_BACK};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spatial_filtering);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mOpenCvCameraView = (MyJavaCameraView) findViewById(R.id.Java_Camera_View);
mOpenCvCameraView.setCameraIndex(CameraBridgeViewBase.CAMERA_ID_ANY);
mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
mOpenCvCameraView.setCvCameraViewListener(mCameraListener);
Button saveButton = (Button) findViewById(R.id.saveButton);
saveButton.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SimpleDateFormat")
#Override
public void onClick(View v) {
Log.i(TAG, "onClick event");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
String currentDateandTime = sdf.format(new Date());
String fileName = Environment.getExternalStorageDirectory().getPath() +
"/sample_picture_" + currentDateandTime + ".jpg";
mOpenCvCameraView.takePicture(fileName);
addImageToGallery(fileName, SpatialFilteringActivity.this);
Toast.makeText(SpatialFilteringActivity.this, fileName + " saved",
Toast.LENGTH_SHORT).show();
}
});
}
//etc.
activity_stills.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android: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="il.ac.tau.adviplab.iplab2_hn.StillsActivity">
<ImageView
android:contentDescription="#string/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView1"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:src="#drawable/loadimage"
android:adjustViewBounds="true"
android:layout_centerVertical="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/load_button"
android:id="#+id/loadButton"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/seekBarSpatial"
android:layout_marginTop="13dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignLeft="#+id/sigmaSpatialTextView"
android:layout_alignStart="#+id/sigmaSpatialTextView"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:id="#+id/sigmaSpatialTextView"
android:text="#string/stringSpatial"
android:layout_below="#+id/seekBarSpatial"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/seekBarIntensity"
android:layout_marginTop="15dp"
android:layout_below="#+id/sigmaSpatialTextView"
android:layout_alignLeft="#+id/sigmaSpatialTextView"
android:layout_alignStart="#+id/sigmaSpatialTextView"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:id="#+id/sigmaIntensityTextView"
android:text="#string/stringIntensity"
android:layout_below="#+id/seekBarIntensity"
android:layout_alignLeft="#+id/seekBarIntensity"
android:layout_alignStart="#+id/seekBarIntensity"/>
<SeekBar
android:id="#+id/seekBarAlpha"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_below="#+id/sigmaIntensityTextView"
android:layout_alignLeft="#+id/alphaTextView"
android:layout_alignStart="#+id/alphaTextView"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/alphaTextView"
android:text="#string/stringAlpha"
android:layout_marginTop="12dp"
android:layout_below="#+id/seekBarAlpha"
android:layout_alignLeft="#+id/sigmaIntensityTextView"
android:layout_alignStart="#+id/sigmaIntensityTextView"/>
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/seekBarBeta"
android:layout_marginTop="8dp"
android:layout_below="#+id/alphaTextView"
android:layout_alignLeft="#+id/alphaTextView"
android:layout_alignStart="#+id/alphaTextView"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/betaTextView"
android:text="#string/stringBeta"
android:layout_below="#+id/seekBarBeta"
android:layout_alignLeft="#+id/seekBarBeta"
android:layout_alignStart="#+id/seekBarBeta"/>
</RelativeLayout>
note: the #drawable/loadimage is 1000*978 pixels, if that matters
Logs
java.lang.RuntimeException: Unable to start activity ComponentInfo{il.ac.tau.adviplab.iplab2_hn/il.ac.tau.adviplab.iplab2_hn.StillsActivity}: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class <unknown>
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2450)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2520)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5466)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class <unknown>
at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at il.ac.tau.adviplab.iplab2_hn.StillsActivity.onCreate(StillsActivity.java:73)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2520) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5466) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>
at android.view.LayoutInflater.createView(LayoutInflater.java:645)
at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:694)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:762)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:374) 
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292) 
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) 
at il.ac.tau.adviplab.iplab2_hn.StillsActivity.onCreate(StillsActivity.java:73) 
at android.app.Activity.performCreate(Activity.java:6251) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2403) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2520) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5466) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance(Native Method)
at android.view.LayoutInflater.createView(LayoutInflater.java:619)
at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58) 
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:694) 
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:762) 
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:492) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:423) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:374) 
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292) 
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) 
at il.ac.tau.adviplab.iplab2_hn.StillsActivity.onCreate(StillsActivity.java:73) 
at android.app.Activity.performCreate(Activity.java:6251) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2403) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2520) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5466) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Caused by: java.lang.UnsupportedOperationException: Can't convert to dimension: type=0x1
at android.content.res.TypedArray.getDimensionPixelSize(TypedArray.java:666)
at android.view.View.<init>(View.java:3969)
at android.view.ViewGroup.<init>(ViewGroup.java:573)
at android.widget.RelativeLayout.<init>(RelativeLayout.java:248)
at android.widget.RelativeLayout.<init>(RelativeLayout.java:244)
at android.widget.RelativeLayout.<init>(RelativeLayout.java:240)
at java.lang.reflect.Constructor.newInstance(Native Method) 
at android.view.LayoutInflater.createView(LayoutInflater.java:619) 
at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58) 
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:694) 
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:762) 
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:492) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:423) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:374) 
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292) 
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) 
at il.ac.tau.adviplab.iplab2_hn.StillsActivity.onCreate(StillsActivity.java:73) 
at android.app.Activity.performCreate(Activity.java:6251) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2403) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2520) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5466) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
I'd appreciate any help.
Thanks!

Please follow background image size
For Supported device
LDPI:
Portrait: 200x320px
Landscape: 320x200px
MDPI:
Portrait: 320x480px
Landscape: 480x320px
HDPI:
Portrait: 480x800px
Landscape: 800x480px
XHDPI:
Portrait: 720px1280px
Landscape: 1280x720px

Related

How to correctly use a snackbar in Android

I have created a simple counter application for Android. I have just started using support libraries and just to test it out, I wanted to show a snackbar which says Hello. Here is my code in the MainActivity.java file :
package com.mapsup.counter;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.google.android.material.snackbar.Snackbar;
public class MainActivity extends Activity {
long count=0;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
SharedPreferences sp=getApplicationContext().getSharedPreferences("preferences",Context.MODE_PRIVATE);
count=sp.getLong("count",0);
tv=findViewById(R.id.counter);
tv.setText(String.valueOf(count));
//Create and display a snackbar
Snackbar snackbar = Snackbar.make(tv,"Hello",Snackbar.LENGTH_LONG);
snackbar.show();
}
public void increase(View view) {
++count;
tv.setText(String.valueOf(count));
}
public void decrease(View view) {
if(count>0) {
--count;
tv.setText(String.valueOf(count));
}
}
public void reset(View view) {
count=0;
tv.setText("0");
}
#Override
public void onStop() {
super.onStop();
Context ctx=getApplicationContext();
SharedPreferences sp=ctx.getSharedPreferences("preferences",Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sp.edit();
editor.putLong("count",count);
editor.apply();
}
}
Here is the layout main_layout.xml file :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#0031A0"
android:orientation="vertical"
android:padding="20dp"
android:id="#+id/root">
<TextView
android:id="#+id/counter"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginBottom="20dp"
android:layout_weight="1"
android:background="#B2FFFFFF"
android:gravity="center"
android:textSize="36sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="increase"
android:text="#string/add"
android:textSize="30sp" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="decrease"
android:text="#string/subt"
android:textSize="30sp" />
</LinearLayout>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="reset"
android:text="#string/reset"
android:textAllCaps="false"
android:textSize="30sp" />
</LinearLayout>
When I am running the app, the app crashes. The logcat shows this as the error message :
2020-02-03 00:20:10.015 12849-12849/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mapsup.counter, PID: 12849
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mapsup.counter/com.mapsup.counter.MainActivity}: android.view.InflateException: Binary XML file line #26: Binary XML file line #26: Error inflating class <unknown>
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
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: android.view.InflateException: Binary XML file line #26: Binary XML file line #26: Error inflating class <unknown>
Caused by: android.view.InflateException: Binary XML file line #26: Error inflating class <unknown>
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
at android.view.LayoutInflater.createView(LayoutInflater.java:645)
at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:717)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:785)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
at com.google.android.material.snackbar.Snackbar.make(Snackbar.java:164)
at com.mapsup.counter.MainActivity.onCreate(MainActivity.java:23)
at android.app.Activity.performCreate(Activity.java:6712)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2677)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
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.UnsupportedOperationException: Failed to resolve attribute at index 6: TypedValue{t=0x2/d=0x101009b a=1}
at android.content.res.TypedArray.getColorStateList(TypedArray.java:531)
at android.widget.TextView.<init>(TextView.java:805)
at android.widget.TextView.<init>(TextView.java:727)
at android.widget.TextView.<init>(TextView.java:723)
at java.lang.reflect.Constructor.newInstance0(Native Method) 
at java.lang.reflect.Constructor.newInstance(Constructor.java:430) 
at android.view.LayoutInflater.createView(LayoutInflater.java:645) 
at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58) 
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:717) 
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:785) 
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:858) 
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:518) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:426) 
at com.google.android.material.snackbar.Snackbar.make(Snackbar.java:164) 
at com.mapsup.counter.MainActivity.onCreate(MainActivity.java:23) 
at android.app.Activity.performCreate(Activity.java:6712) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2677) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527) 
at android.os.Handler.dispatchMessage(Handler.java:110) 
at android.os.Looper.loop(Looper.java:203) 
at android.app.ActivityThread.main(ActivityThread.java:6251) 
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) 
The app runs all fine if I remove the snackbar code.
According to my thinking, creating a snackbar is the same as creating a toast, we just need to replace Toast with Snackbar. Is this correct?
What is my mistake and how to properly use a snackbar?
Please replace tv to rootLayout in Snackbar.make(llRootLayout,"Hello",Snackbar.LENGTH_LONG); as below.
public class MainActivity extends Activity {
long count=0;
TextView tv;|
LinearLayout llRootLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
SharedPreferences sp=getApplicationContext().getSharedPreferences("preferences",Context.MODE_PRIVATE);
count=sp.getLong("count",0);
tv=findViewById(R.id.counter);
llRootLayout=findViewById(R.id.root);
tv.setText(String.valueOf(count));
//Create and display a snackbar
Snackbar snackbar=Snackbar.make(llRootLayout,"Hello",Snackbar.LENGTH_LONG);
snackbar.show();
}
public void increase(View view) {
++count;
tv.setText(String.valueOf(count));
}
public void decrease(View view) {
if(count>0) {
--count;
tv.setText(String.valueOf(count));
}
}
public void reset(View view) {
count=0;
tv.setText("0");
}
#Override
public void onStop() {
super.onStop();
Context ctx=getApplicationContext();
SharedPreferences sp=ctx.getSharedPreferences("preferences",Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sp.edit();
editor.putLong("count",count);
editor.apply();
}
}

Getting IllegalStateException on button click and Application is stopped

I am creating an application using Android Studio and Genymotion as an emulator, in which i am entering the data in 3 EditTexts, when i click the button to store it in sqlite database then it is not working.. and this is what i see in LOGCAT
FATAL EXCEPTION: main
Process: com.example.aadeshmishra.com.sdk18, PID: 1551
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:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4438) 
at android.view.View$PerformClick.run(View.java:18422) 
at android.os.Handler.handleCallback(Handler.java:733) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5001) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: java.lang.NullPointerException
at com.example.aadeshmishra.com.sdk18.ThirdActitvity.addData(ThirdActitvity.java:64)
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:4438) 
at android.view.View$PerformClick.run(View.java:18422) 
at android.os.Handler.handleCallback(Handler.java:733) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5001) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 
at dalvik.system.NativeStart.main(Native Method) 
The button will call a method named addData() which is in ThirdActivity.
here the code for ThirdActivity.java
public class ThirdActitvity extends AppCompatActivity {
EditText ed1,ed2,ed3;
Button B1;
UserDBHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
ed1 = (EditText)findViewById(R.id.E1);
ed2 = (EditText)findViewById(R.id.E2);
ed3 = (EditText)findViewById(R.id.E3);
B1 = (Button) findViewById(R.id.addB);
}
public void addData(View view)
{
String name = ed1.getText().toString();
String desc = ed2.getText().toString();
String contact = ed3.getText().toString();
Boolean r1 = mydb.insertDataClient(name,desc,contact);
if(r1 == true)
{
Toast.makeText(this,"Data inserted",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this,"Data not inserted",Toast.LENGTH_LONG).show();
}
}
}
Here the Code for activity_third.xml
<EditText
android:id="#+id/E1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/client"
android:textSize="20sp"
android:layout_marginEnd="20dp"/>
<EditText
android:id="#+id/E2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/destail"
android:textSize="20sp"
android:layout_alignEnd="#+id/E1" />
<EditText
android:id="#+id/E3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="#string/EN"
android:textSize="20sp"
android:layout_marginBottom="18dp"
android:layout_above="#+id/addB"
/>
<Button
android:id="#+id/addB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="49dp"
android:text="#string/add"
android:textSize="20sp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="addData"
/>
And at Last the UserDbHelper.java
public class UserDBHelper extends SQLiteOpenHelper {
// Database Details
private static final int DB_VER = 1;
private static final String DB_NAME = "DIARY_DB";
// Table Name
private static final String table_clientinfo = "Client_Info";
// columns
private static final String name = "Name";
private static final String desc = "Desc";
private static final String cont = "Contact";
// Create table -- ClientInfo
private String Create_ClientInfo = "Create table "+ table_clientinfo +"(" + id + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ name + " TEXT ," + desc + " TEXT,"
+ cont + " INTEGER)";
public UserDBHelper(Context context)
{
super(context,DB_NAME,null,DB_VER);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(Create_ClientInfo);
db.close();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
public Boolean insertDataClient(String Name, String Desc, String Contact)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues con = new ContentValues();
con.put(name,Name);
con.put(desc,Desc);
con.put(cont,Contact);
long r = db.insert(table_clientinfo,null,con);
db.close();
if(r == -1)
{
return false;
}
else
{
return true;
}
}}
Can anyone tell what's the problem..?
thanks in advance..!
You need to initialize mydb in onCreate (or before using it anywhere though oncreate executed only once so better to do it inside onCreate) as
UserDBHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
mydb = new UserDBHelper(this);
//^^^^^^^^^^^^^^^^^^^^^
ed1 = (EditText)findViewById(R.id.E1);
ed2 = (EditText)findViewById(R.id.E2);
ed3 = (EditText)findViewById(R.id.E3);
B1 = (Button) findViewById(R.id.addB);
}

currency convertor app not working

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: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="edu.uncc.sbagursu.currencyconvertor.MainActivity">
<EditText
android:hint="Input Amount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:id="#+id/inputAmount" />
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/inputAmount"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:id="#+id/radioGroup2">
<RadioButton
android:id="#+id/aud"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/aud"
android:onClick="onRadioButtonClicked1"/>
<RadioButton
android:id="#+id/cad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/cad"
android:onClick="onRadioButtonClicked1"/>
<RadioButton
android:id="#+id/inr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/inr"
android:onClick="onRadioButtonClicked1"/>
</RadioGroup>
<TextView
android:text="#string/convertTo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:id="#+id/textView2"
android:layout_below="#+id/radioGroup2"
android:layout_alignRight="#+id/radioGroup2"
android:layout_alignEnd="#+id/radioGroup2" />
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/inputAmount"
android:layout_centerHorizontal="true"
android:layout_marginTop="170dp"
android:id="#+id/radioGroup3">
<RadioButton
android:id="#+id/usd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/usd"
android:onClick="onRadioButtonClicked2"/>
<RadioButton
android:id="#+id/gbp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/gbp"
android:onClick="onRadioButtonClicked2"/>
</RadioGroup>
<Button
android:text="#string/convert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/radioGroup3"
android:layout_centerHorizontal="true"
android:layout_marginTop="13dp"
android:id="#+id/convertButton"
android:onClick="onClickConvert"/>
<TextView
android:text="#string/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/convertButton"
android:layout_alignLeft="#+id/radioGroup3"
android:layout_alignStart="#+id/radioGroup3"
android:layout_marginTop="28dp"
android:id="#+id/textView3" />
<Button
android:text="Clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView3"
android:layout_alignLeft="#+id/convertButton"
android:layout_alignStart="#+id/convertButton"
android:layout_marginTop="23dp"
android:id="#+id/clearButton" />
</RelativeLayout>
MainActivity.java :
package com.example.shara.currencyconvertor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private TextView txt = (TextView) findViewById(R.id.textView3);
private RadioGroup grp1 = (RadioGroup) findViewById(R.id.radioGroup2);
private RadioGroup grp2 = (RadioGroup) findViewById(R.id.radioGroup3);
private EditText inputAmt = (EditText) findViewById(R.id.inputAmount);
private final String inputText = inputAmt.getText().toString();
private double inputAmount = Integer.parseInt(inputText);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.convertButton).setOnClickListener(this);
findViewById(R.id.clearButton).setOnClickListener(this);
grp1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton btn = (RadioButton) findViewById(checkedId);
}
});
grp2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton btn2 = (RadioButton) findViewById(checkedId);
}
});
}
#Override
public void onClick(View v) {
int radioId1 = grp1.getCheckedRadioButtonId();
int radioId2 = grp2.getCheckedRadioButtonId();
double result = 0;
if(v.getId()==R.id.convertButton){
if(radioId1 == R.id.aud){
if(radioId2 == R.id.usd){
result = inputAmount*1.34;
Log.d("test", "Result is" +result);
txt.setText(""+result);
}
else if(radioId2 == R.id.gbp){
result = inputAmount*(0.83/1.34);
Log.d("test", "Result is" +result);
txt.setText(""+result);
}
else {
Log.d("test", "nothing here");
}
}
if(radioId1 == R.id.cad){
if(radioId2 == R.id.usd){
result = inputAmount*1.32;
Log.d("test", "Result is" +result);
txt.setText(""+result);
}
else if (radioId2 == R.id.gbp) {
result = inputAmount * (0.83 / 1.32);
Log.d("test", "Result is" + result);
txt.setText(""+result);
}
}
else {
Log.d("test", "nothing here");
}
if(radioId1 == R.id.inr){
if(radioId2 == R.id.usd){
result = inputAmount*68.14;
Log.d("test", "Result is" +result);
txt.setText(""+result);
}
else if(radioId2 == R.id.gbp){
result = inputAmount*(0.83/68.14);
Log.d("test", "Result is" +result);
txt.setText(""+result);
}
else {
Log.d("test", "nothing here");
}
}
}
else if(v.getId()== R.id.clearButton){
txt.setText("");
}
}
}
Unfortunately though everything seems right I am unable to get the app to run and the app crashes. Any help in resolving this is appreciated. I am a novice in android.
Updated with Logcat file:
01-21 17:42:56.229 6017-6017/? I/art: Late-enabling -Xcheck:jni
01-21 17:42:56.244 6017-6023/? E/art: Failed sending reply to debugger: Broken pipe
01-21 17:42:56.244 6017-6023/? I/art: Debugger is no longer active
01-21 17:42:56.278 6017-6017/? W/System: ClassLoader referenced unknown path: /data/app/com.example.shara.currencyconvertor-1/lib/x86
01-21 17:42:56.278 6017-6017/? I/InstantRun: Instant Run Runtime started. Android package is com.example.shara.currencyconvertor, real application class is null.
01-21 17:42:56.526 6017-6017/? W/System: ClassLoader referenced unknown path: /data/app/com.example.shara.currencyconvertor-1/lib/x86
01-21 17:42:56.556 6017-6017/? D/AndroidRuntime: Shutting down VM
01-21 17:42:56.556 6017-6017/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.shara.currencyconvertor, PID: 6017
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.shara.currencyconvertor/com.example.shara.currencyconvertor.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:120)
at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:151)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:31)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:55)
at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:33)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:203)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:185)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:525)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:193)
at com.example.shara.currencyconvertor.MainActivity.<init>(MainActivity.java:15)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
01-21 17:47:56.701 6017-6017/com.example.shara.currencyconvertor I/Process: Sending signal. PID: 6017 SIG: 9
LogCat after making changes:
01-21 18:33:57.523 11590-11590/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.shara.currencyconvertor, PID: 11590
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.shara.currencyconvertor/com.example.shara.currencyconvertor.MainActivity}: java.lang.NumberFormatException: Invalid double: ""
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NumberFormatException: Invalid double: ""
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseDouble(StringToReal.java:267)
at java.lang.Double.parseDouble(Double.java:301)
at com.example.shara.currencyconvertor.MainActivity.onCreate(MainActivity.java:37)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
You're initializing the views before the onCreate has loaded. It makes sense you're getting a NullPointerException.
Try the changes here. Notice that all the views are being declared at the top but initialized in the OnCreate. The "inputText" can't be final, Unless you declare it inside the onCreate.
package com.example.shara.currencyconvertor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private TextView txt;
private RadioGroup grp1;
private RadioGroup grp2;
private EditText inputAmt;
private String inputText;
private double inputAmount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.convertButton).setOnClickListener(this);
findViewById(R.id.clearButton).setOnClickListener(this);
txt = (TextView) findViewById(R.id.textView3);
grp1 = (RadioGroup) findViewById(R.id.radioGroup2);
grp2 = (RadioGroup) findViewById(R.id.radioGroup3);
inputAmt = (EditText) findViewById(R.id.inputAmount);
inputText = inputAmt.getText().toString();
inputAmount = Integer.parseInt(inputText);
grp1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton btn = (RadioButton) findViewById(checkedId);
}
});
grp2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton btn2 = (RadioButton) findViewById(checkedId);
}
});
}
#Override
public void onClick(View v) {
int radioId1 = grp1.getCheckedRadioButtonId();
int radioId2 = grp2.getCheckedRadioButtonId();
double result = 0;
if(v.getId()==R.id.convertButton){
if(radioId1 == R.id.aud){
if(radioId2 == R.id.usd){
result = inputAmount*1.34;
Log.d("test", "Result is" +result);
txt.setText(""+result);
}
else if(radioId2 == R.id.gbp){
result = inputAmount*(0.83/1.34);
Log.d("test", "Result is" +result);
txt.setText(""+result);
}
else {
Log.d("test", "nothing here");
}
}
if(radioId1 == R.id.cad){
if(radioId2 == R.id.usd){
result = inputAmount*1.32;
Log.d("test", "Result is" +result);
txt.setText(""+result);
}
else if (radioId2 == R.id.gbp) {
result = inputAmount * (0.83 / 1.32);
Log.d("test", "Result is" + result);
txt.setText(""+result);
}
}
else {
Log.d("test", "nothing here");
}
if(radioId1 == R.id.inr){
if(radioId2 == R.id.usd){
result = inputAmount*68.14;
Log.d("test", "Result is" +result);
txt.setText(""+result);
}
else if(radioId2 == R.id.gbp){
result = inputAmount*(0.83/68.14);
Log.d("test", "Result is" +result);
txt.setText(""+result);
}
else {
Log.d("test", "nothing here");
}
}
}
else if(v.getId()== R.id.clearButton){
txt.setText("");
}
}
}
UPDATE:
Sorry I just now noticed the XML.
You are tring to parse the content of the EditText when it's empty. You need to parse it after the use wrote something. If you dont wanna add a button, you can use:
inputAmt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
inputText = inputAmt.getText().toString();
inputAmount = Integer.parseInt(inputText);
}
#Override
public void afterTextChanged(Editable s) {
}
});

java android crash setOnClickListener

i am new in android and i was trying to make my app works in all phones
it works in 23 API and don't work in 19 API kitkat it crashes each time i open the application
Is there a way to fix this problem ?
and could you tell me what was my problem and explain it to me,
public class MainActivity extends AppCompatActivity {
private Button ButtonStart,ButtonReset ;
private TextView Number ;
private CountDownTimer myTimer ;
private MediaPlayer TimePassesSound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButtonStart = (Button)findViewById (R.id.button); //initialize view
Number = (TextView)findViewById (R.id.textView); //initialize view
ButtonReset = (Button)findViewById (R.id.button2);
MediaPlayer TimePassesSound;
TimePassesSound = new MediaPlayer();
TimePassesSound = MediaPlayer.create(getApplicationContext(), R.raw.time_passing);
addListerOnButton (); //call method of the view
addListerOnButton2 (); //call method of the view
}
public void addListerOnButton () {
ButtonStart.setOnClickListener (
new View.OnClickListener () {
public void onClick(View v) {
if (ButtonStart.getText ().toString () != "Stop") {
int StartTime = Integer.parseInt (Number.getText ().toString ());
myTimer = new CountDownTimer (StartTime*1000, 1000) {
public void onTick(long millisUntilFinished) {
ButtonStart.setText ("Stop");
Number.setText (""+millisUntilFinished / 1000);
}
public void onFinish() {
Number.setText("60");
ButtonStart.setText ("Start");
TimePassesSound.setLooping(false);
TimePassesSound.start();
}
}.start();
} else {
ButtonStart.setText ("Start");
myTimer.cancel ();
}
}
}
);
}
public void addListerOnButton2 () {
ButtonReset.setOnClickListener (
new View.OnClickListener () {
public void onClick(View v) {
if ("Start".equals (ButtonStart.getText ().toString())) {
Number.setText ("60");
myTimer.cancel ();
}else{
Toast.makeText (MainActivity.this,"You must stop the countdown first",Toast.LENGTH_LONG).show();
}
}
}
);
}
}
public void addListerOnButton2 () {
ButtonReset.setOnClickListener (
new View.OnClickListener () {
public void onClick(View v) {
if ("Start".equals (ButtonStart.getText ().toString())) {
Number.setText ("60");
myTimer.cancel ();
}else{
Toast.makeText (MainActivity.this,"You must stop the countdown first",Toast.LENGTH_LONG).show();
}
}
}
);
}
}
-- Error messages
Process: com.aabdelrahman730yahoo.mydesign, PID: 3627
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.aabdelrahman730yahoo.mydesign/com.aabdelrahman730yahoo.mydesign.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.aabdelrahman730yahoo.mydesign.MainActivity.addListerOnButton(MainActivity.java:51)
at com.aabdelrahman730yahoo.mydesign.MainActivity.onCreate(MainActivity.java:43)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5017) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
at dalvik.system.NativeStart.main(Native Method) 
Main Activity :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_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.aabdelrahman730yahoo.mydesign.MainActivity"
android:touchscreenBlocksFocus="false"
android:background="#34416a">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset"
android:id="#+id/button2"
android:layout_above="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="60"
android:id="#+id/textView"
android:singleLine="true"
android:textSize="80dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
That's was my full problem i hope someone could help me with
You are calling the method of the view without initializing it.
You need to initialize the view first and then call the method
ButtonStart = (Button)findViewById (R.id.button); //initialize view
Number = (TextView)findViewById (R.id.textView); //initialize view
addListerOnButton (); //call method of the view
addListerOnButton2 (); //call method of the view
Check this,
As #Rod_ mentioned and from error log, it clearly states that view is not initialized.
java.lang.NullPointerException
at
com.aabdelrahman730yahoo.mydesign.MainActivity.addListerOnButton(MainActivity.java:51)
at
com.aabdelrahman730yahoo.mydesign.MainActivity.onCreate(MainActivity.java:43)
Make sure following buttons were initialized in your java code.
ButtonStart and ButtonReset -- Buttonreset is not initialized here it seems.
Change your code like below.
under oncreate
ButtonStart = (Button)findViewById (R.id.button);
ButtonReset = (Button)findViewById (R.id.button_); --> You missed it ..
Number = (TextView)findViewById (R.id.textView);
addListerOnButton ();
addListerOnButton2 ();
Hope it seems clear..!!
UPDATE:
You may not initialized the media player.
The problem may be also due to usage of media player. Kindly check the code below.
MediaPlayer mediaPlayer;
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.time_passing);
in your case
MediaPlayer TimePassesSound;
TimePassesSound = new MediaPlayer();
TimePassesSound = MediaPlayer.create(getApplicationContext(), R.raw.time_passing);
Add the above lines befor calling the functions.

Android: RNG error and button theme

I have my Random Number generator and it crashes when I I type in 0 in the 'numberTo' string and gives me int: "0". With this I cannot make remove the editText and show the hint because of the TextWatcher. Please help me with that! And guys how do I add a button with a different color, can you please explain?
This is my code:
activity_main.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="bedi.gursimran.materialtest.MainActivity">
<include
android:id="#+id/app_bar"
layout="#layout/app_bar" />
<TextView
android:textSize="68dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/random_text"
android:text="Number"
android:layout_marginTop="12dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="false"
android:layout_marginLeft="50dp"
/>
<EditText
android:layout_width="140dp"
android:layout_height="wrap_content"
android:inputType="number"
android:padding="12dp"
android:ems="10"
android:id="#+id/text_from"
android:maxLength="6"
android:hint="From"
android:layout_below="#+id/app_bar"
android:layout_alignParentStart="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="24dp"
android:backgroundTint="#color/primaryColorDark"
android:textSize="#dimen/edit_text_size"/>
<EditText
android:layout_width="140dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:padding="12dp"
android:id="#+id/text_to"
android:layout_below="#+id/text_from"
android:layout_alignParentStart="true"
android:maxLength="8"
android:hint="To"
android:backgroundTint="#color/primaryColorDark"
android:layout_marginTop="8dp"
android:layout_marginLeft="10dp"
android:textSize="#dimen/edit_text_size"/>
<Button
android:layout_width="140dp"
android:layout_height="70dp"
android:text="Generate"
android:id="#+id/generate_button"
android:onClick="generate"
android:layout_below="#+id/app_bar"
android:layout_marginLeft="190dp"
android:layout_marginTop="51dp"
android:textColor="#fffafafa"
android:textSize="22dp"
android:backgroundTint="#color/accentColor"
/>
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="AppTheme.Base">
<!-- Customize your theme here. -->
</style>
<!--Base theme-->
<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar" >
<item name="colorPrimary">#color/primaryColor</item>
<item name="colorPrimaryDark">#color/primaryColorDark</item>
<item name="colorAccent">#color/accentColor</item>
<!-- Generate Button Color -->
<item name="android:colorButtonNormal">#color/primaryColor</item>
</style>
<!--Action Bar theme-->
<style name="MyCustomToolBarTheme" parent="ThemeOverlay.AppCompat.Light">
<!--The title-->
<item name="android:textColorPrimary">#FFFFFF</item>
<item name="android:textColor">#FFFFFF</item>
<!--The 'overflow icon-->
<item name="android:textColorSecondary">#FFFFFF</item>
</style>
<style name="ActionBarPopupThemeOverlay" parent="ThemeOverlay.AppCompat.Light" >
<item name="android:background">#android:color/white</item>
<item name="android:textColor">#de000000</item>
</style>
</resources>
app_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
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="56dp"
android:background="#color/primaryColor"
app:theme="#style/MyCustomToolBarTheme"
android:paddingTop="#dimen/app_bar_top_padding"
android:elevation="#dimen/action_bar_elevation"
app:popupTheme="#style/ActionBarPopupThemeOverlay"
>
</android.support.v7.widget.Toolbar>
And most importantly... MainActivity.java
public class MainActivity extends ActionBarActivity implements TextWatcher {
private Toolbar toolbar;
TextView randomText;
EditText editTextFrom;
EditText editTextTo;
Button generate_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//toolbar= (Toolbar) findViewById(R.id.app_bar);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
//Generated Number
randomText = (TextView) findViewById(R.id.random_text);
Typeface myCustomFontTextView = Typeface.createFromAsset(getAssets(), "fonts/RobotoCondensed-Light.ttf");
randomText.setTypeface(myCustomFontTextView);
//From Text
editTextFrom = (EditText) findViewById(R.id.text_from);
Typeface myCustomFontEditViewFrom = Typeface.createFromAsset(getAssets(), "fonts/RobotoCondensed-Regular.ttf");
editTextFrom.setTypeface(myCustomFontEditViewFrom);
editTextFrom.addTextChangedListener(this);
//To Text
editTextTo = (EditText) findViewById(R.id.text_to);
Typeface myCustomFontEditViewTo = Typeface.createFromAsset(getAssets(), "fonts/RobotoCondensed-Regular.ttf");
editTextTo.setTypeface(myCustomFontEditViewTo);
editTextTo.addTextChangedListener(this);
//Generate Button
generate_button = (Button) findViewById(R.id.generate_button);
Typeface myCustomFontButton = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Bold.ttf");
generate_button.setTypeface(myCustomFontButton);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
// if (id == R.id.navigate) {
// startActivity(new Intent(this, SubActivity.class));
// }
return super.onOptionsItemSelected(item);
}
public void generate(View view) {
//text
EditText from = (EditText) findViewById(R.id.text_from);
EditText to = (EditText) findViewById(R.id.text_to);
String stringFrom, stringTo;
stringFrom = from.getText().toString();
stringTo = to.getText().toString();
int numberFrom, numberTo;
if (stringFrom.equals("")) {
stringFrom = "0";
}
if (stringTo.equals("")) {
stringTo = "0";
}
numberFrom = Integer.parseInt(stringFrom);
numberTo = Integer.parseInt(stringTo);
Random random = new Random();
int number = random.nextInt(numberTo + 1);
if(numberFrom != numberTo) {
while (number < numberFrom || number > numberTo) {
number = random.nextInt(numberTo + 1);
}
} else {
numberFrom = numberTo = number;
}
// } catch (NumberFormatException e) {}
try {
TextView myText = (TextView) findViewById(R.id.random_text);
String myString = String.valueOf(number);
myText.setText(myString);
} catch (NumberFormatException e) {
TextView myText = (TextView) findViewById(R.id.random_text);
myText.setText("Enter a number greater than zero");
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable editable) {
int numberto;
try {
numberto = Integer.parseInt(editable.toString());
} catch (NumberFormatException e) {
numberto = 0;
}
if (numberto == 0) {
editable.replace(0, editable.length(), "1");
}
}
}
edit
The errors went away as I took the implements TextWatcher out. Please help me with the button colors, I still don't know how to have 2 different colored buttons. Thanks!
edit 2 Gives me this log when I put both as null. Please help!!
2414-2414/bedi.gursimran.materialtest E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: bedi.gursimran.materialtest, PID: 2414
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4007)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.IllegalArgumentException: n <= 0: 0
at java.util.Random.nextInt(Random.java:182)
at bedi.gursimran.materialtest.MainActivity.generate(MainActivity.java:120)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at android.view.View$1.onClick(View.java:4002)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Categories