hello, thanks a lot for the time you re according to my issue.
I am trying to run an app in android studio and it builds fine with 0 errors, the app icon is showing on the device(i tried on different devices and emulators btw) but when it launches, it crashes after a few seconds, saying "my app" has stopped. I tried to view the logcat errors and i didnt understand the problem.
here is the logcat error file, and tell me if you need any other information about the problem please.
03-28 19:20:23.382 13915-13921/? E/jdwp: Failed sending reply to debugger: Broken pipe
03-28 19:20:23.532 13915-13929/? E/dalvikvm: Could not find class 'android.app.AppOpsManager', referenced from method com.google.android.gms.internal.zzadf.zzg
03-28 19:20:23.762 13915-13915/? E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
03-28 19:20:23.782 13915-13915/? E/OneSignal: OneSignal AppId format is invalid.
Example: 'b2f7f966-d8cc-11e4-bed1-df8f05be55ba'
java.lang.NumberFormatException: Invalid long: "xxxxxxxx"
at java.lang.Long.invalidLong(Long.java:125)
at java.lang.Long.parse(Long.java:362)
at java.lang.Long.parseLong(Long.java:353)
at java.util.UUID.fromString(UUID.java:201)
at com.onesignal.OSUtils.initializationChecker(OSUtils.java:52)
at com.onesignal.OneSignal.init(OneSignal.java:238)
at com.onesignal.OneSignal.init(OneSignal.java:215)
at com.onesignal.OneSignal.access$000(OneSignal.java:68)
at com.onesignal.OneSignal$Builder.init(OneSignal.java:142)
at com.mp3player.searchonline.MainActivity.onCreate(MainActivity.java:65)
at android.app.Activity.performCreate(Activity.java:5326)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2218)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2309)
at android.app.ActivityThread.access$700(ActivityThread.java:157)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1289)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5317)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
03-28 19:20:27.816 13915-13915/com.usmans.songscloud E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NoClassDefFoundError: android.support.v7.internal.widget.TintManager
at android.support.design.widget.TabLayout$TabView.<init>(TabLayout.java:1041)
at android.support.design.widget.TabLayout.createTabView(TabLayout.java:582)
at android.support.design.widget.TabLayout.addTabView(TabLayout.java:616)
at android.support.design.widget.TabLayout.addTab(TabLayout.java:334)
at android.support.design.widget.TabLayout.addTab(TabLayout.java:309)
at android.support.design.widget.TabLayout.setTabsFromPagerAdapter(TabLayout.java:571)
at android.support.design.widget.TabLayout.setupWithViewPager(TabLayout.java:550)
at com.mp3player.searchonline.MainActivity.setView(MainActivity.java:93)
at com.mp3player.searchonline.MainActivity.onCreate(MainActivity.java:86)
at android.app.Activity.performCreate(Activity.java:5326)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2218)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2309)
at android.app.ActivityThread.access$700(ActivityThread.java:157)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1289)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5317)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mp3player.searchonline" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/MyMaterialTheme"
android:name="com.mp3player.searchonline.App" >
<!--This meta-data tag is required to use Google Play Services.-->
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
<activity
android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
<activity
android:name="com.mp3player.searchonline.MainActivity"
android:label="#string/app_name"
android:windowSoftInputMode="adjustNothing" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.mp3player.searchonline.PlayerActivity"
android:label="#string/app_name"
android:theme="#style/MyDialogTheme" >
</activity>
</application>
</manifest>
MainActivity.java
package com.mp3player.searchonline;
/**
* Created by Usman Jamil on 02/02/2017.
* Usmans.net
* Skype usman.jamil78
* email usmanjamil547#gmail.com
*/
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.Snackbar;
import com.onesignal.OneSignal;
import java.util.ArrayList;
import java.util.List;
import android.support.design.widget.CoordinatorLayout;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity implements constants {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private CoordinatorLayout coordinatorLayout;
private SearchView mSearchView;
private MenuItem searchMenuItem;
String[] Final_Suggestions=null;
private SimpleCursorAdapter mAdapter;
String SearchText=null;
SongFragment fragment;
ProgressDialog pDialog;
String TabFragmentB;
Boolean Is = false;
FloatingActionButton Sharebutton;
String urs;
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id
.coordinatorLayout);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
int id = viewPager.getCurrentItem();
OneSignal.startInit(this).init();
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
Sharebutton = (FloatingActionButton) findViewById(R.id.fav);
Sharebutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onshare();
}
});
final String[] from = new String[] {"cityName"};
final int[] to = new int[] {android.R.id.text1};
mAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
null,
from,
to,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
Snackbar snackbar = Snackbar .make(coordinatorLayout, getString(R.string.WelcomeMsg), Snackbar.LENGTH_LONG);
SongFragment toy1 = (SongFragment) getSupportFragmentManager().findFragmentByTag(
"android:switcher:" + viewPager.getId() + ":" + 0);
setView();
snackbar.show();
}
public void setView(){
Sharebutton.setVisibility(View.VISIBLE);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new SongFragment(), "Search");
adapter.addFragment(new DownloadFragment(), "Downloaded");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public Fragment getActiveFragment() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
return null;
}
String tag = getSupportFragmentManager().getBackStackEntryAt(getSupportFragmentManager().getBackStackEntryCount() - 1).getName();
return getSupportFragmentManager().findFragmentByTag(tag);
}
#Override
public boolean onKeyDown(int paramInt, KeyEvent paramKeyEvent) {
if ((paramInt == 4) && (paramKeyEvent.getRepeatCount() == 0)) {
onexit();
}
return super.onKeyDown(paramInt, paramKeyEvent);
}
public void onexit() {
AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
localBuilder.setTitle("Rate Us");
localBuilder
.setMessage(getString(R.string.rating)).setNeutralButton("Rate",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface paramAnonymousDialogInterface,
int paramAnonymousInt) {
MainActivity.this.ratee(MainActivity.this
.getApplicationContext()
.getPackageName());
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface paramAnonymousDialogInterface,
int paramAnonymousInt) {
paramAnonymousDialogInterface.dismiss();
MainActivity.this.finish();
}
});
localBuilder.show();
}
public void onshare() {
AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
localBuilder.setTitle("Share");
localBuilder
.setMessage(getString(R.string.share)).setNeutralButton("Share",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface paramAnonymousDialogInterface,
int paramAnonymousInt) {
MainActivity.this.share(getString(R.string.ShareMsg)+MainActivity.this
.getApplicationContext()
.getPackageName());
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface paramAnonymousDialogInterface,
int paramAnonymousInt) {
paramAnonymousDialogInterface.dismiss();
}
});
localBuilder.show();
}
public void ratee(String paramString) {
try {
Intent localIntent = new Intent("android.intent.action.VIEW");
localIntent
.setData(Uri.parse("market://details?id=" + paramString));
startActivity(localIntent);
return;
} catch (Exception localException) {
}
}
public void share(String paramString) {
try {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT,paramString);
sendIntent.setType("text/plain");
startActivity(sendIntent);
return;
} catch (Exception localException) {
}
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
Build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion '25.0.0'
defaultConfig {
applicationId "com.usmans.songscloud"
minSdkVersion 14
targetSdkVersion 25
versionCode 1
versionName "1.0"
manifestPlaceholders = [onesignal_app_id: "xxxxxxxx-e269-4dfb-8b48-357b707acdae",
// Project number pulled from dashboard, local value is ignored.
onesignal_google_project_number: "108880509xxxx"]
useLibrary 'org.apache.http.legacy'
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
maven {
url 'https://dl.bintray.com/ayz4sci/maven/'
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:25.0.0'
compile 'com.android.support:design:22.2.0'
compile 'com.cjj.materialrefeshlayout:library:1.3.0'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.ayz4sci.androidfactory:downloadprogress:1.0.1'
compile 'com.android.support:support-v4:25.0.0'
// Required for OneSignal, even if you have added FCM.
compile 'com.google.android.gms:play-services-gcm:+'
// Required for geotagging
compile 'com.google.android.gms:play-services-location:+'
compile 'com.google.android.gms:play-services-analytics:+'
// play-services-analytics is only needed when using 8.1.0 or older.
// compile 'com.google.android.gms:play-services-analytics:+'
compile 'com.google.android.gms:play-services-ads:10.2.1'
compile 'com.onesignal:OneSignal:3.4.3'
}
Seems like the "app id" you're passing to the OneSignal framework should be of type Long but you're passing an invalid value.
See this error discussion: OneSignal AppId format is invalid
Related
Regards to all.
I am a beginner in Android Studio. I'm trying to make a simple application that converts long text into multiple pages. I found an old example of the "PageSplitter" project, but the new version of Android Studio reported a lot of errors. I managed to debug it but when I start the project in the emulator it starts to open and then a message appears that the application has been terminated. Can anyone help me find the error. Thanks in advance. Here is the code:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="ru.appheads.pagesplitterapp">
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Pagesplitterapp"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
package ru.appheads.pagesplitterapp;
import android.os.Bundle;
import android.text.TextPaint;
import android.view.ViewTreeObserver;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager.widget.ViewPager;
public class MainActivity extends FragmentActivity {
private ViewPager pagesView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pagesView = (ViewPager) findViewById(R.id.pages);
// to get ViewPager width and height we have to wait global layout
pagesView.getViewTreeObserver().addOnGlobalLayoutListener(new
ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
PageSplitter pageSplitter = new PageSplitter(pagesView.getWidth(),
pagesView.getHeight(), 1, 0);
TextPaint textPaint = new TextPaint();
textPaint.setTextSize(getResources().getDimension(R.dimen.text_size));
for (int i = 0; i < 1000; i++) {
pageSplitter.append("Hello, ", textPaint);
textPaint.setFakeBoldText(true);
pageSplitter.append("world", textPaint);
textPaint.setFakeBoldText(false);
pageSplitter.append("! ", textPaint);
if ((i + 1) % 100 == 0) {
pageSplitter.append("\n", textPaint);
}
}
pagesView.setAdapter(new TextPagerAdapter(getSupportFragmentManager(),
pageSplitter.getPages()));
pagesView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
}
}
PageFragment.java
package ru.appheads.pagesplitterapp;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
public class PageFragment extends Fragment {
private final static String PAGE_TEXT = "PAGE_TEXT";
public static PageFragment newInstance(CharSequence pageText) {
PageFragment frag = new PageFragment();
Bundle args = new Bundle();
args.putCharSequence(PAGE_TEXT, pageText);
frag.setArguments(args);
return frag;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
CharSequence text = getArguments().getCharSequence(PAGE_TEXT);
TextView pageView = (TextView) inflater.inflate(R.layout.page, container, false);
pageView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
getResources().getDimension(R.dimen.text_size));
pageView.setText(text);
return pageView;
}
}
PageSpitter.java
package ru.appheads.pagesplitterapp;
import android.graphics.Typeface;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.style.StyleSpan;
import java.util.ArrayList;
import java.util.List;
public class PageSplitter {
private final int pageWidth;
private final int pageHeight;
private final float lineSpacingMultiplier;
private final int lineSpacingExtra;
private final List<CharSequence> pages = new ArrayList<CharSequence>();
private SpannableStringBuilder currentLine = new SpannableStringBuilder();
private SpannableStringBuilder currentPage = new SpannableStringBuilder();
private int currentLineHeight;
private int pageContentHeight;
private int currentLineWidth;
private int textLineHeight;
public PageSplitter(int pageWidth, int pageHeight, float lineSpacingMultiplier, int
lineSpacingExtra) {
this.pageWidth = pageWidth;
this.pageHeight = pageHeight;
this.lineSpacingMultiplier = lineSpacingMultiplier;
this.lineSpacingExtra = lineSpacingExtra;
}
public void append(String text, TextPaint textPaint) {
textLineHeight = (int) Math.ceil(textPaint.getFontMetrics(null) * lineSpacingMultiplier +
lineSpacingExtra);
String[] paragraphs = text.split("\n", -1);
int i;
for (i = 0; i < paragraphs.length - 1; i++) {
appendText(paragraphs[i], textPaint);
appendNewLine();
}
appendText(paragraphs[i], textPaint);
}
private void appendText(String text, TextPaint textPaint) {
String[] words = text.split(" ", -1);
int i;
for (i = 0; i < words.length - 1; i++) {
appendWord(words[i] + " ", textPaint);
}
appendWord(words[i], textPaint);
}
private void appendNewLine() {
currentLine.append("\n");
checkForPageEnd();
appendLineToPage(textLineHeight);
}
private void checkForPageEnd() {
if (pageContentHeight + currentLineHeight > pageHeight) {
pages.add(currentPage);
currentPage = new SpannableStringBuilder();
pageContentHeight = 0;
}
}
private void appendWord(String appendedText, TextPaint textPaint) {
int textWidth = (int) Math.ceil(textPaint.measureText(appendedText));
if (currentLineWidth + textWidth >= pageWidth) {
checkForPageEnd();
appendLineToPage(textLineHeight);
}
appendTextToLine(appendedText, textPaint, textWidth);
}
private void appendLineToPage(int textLineHeight) {
currentPage.append(currentLine);
pageContentHeight += currentLineHeight;
currentLine = new SpannableStringBuilder();
currentLineHeight = textLineHeight;
currentLineWidth = 0;
}
private void appendTextToLine(String appendedText, TextPaint textPaint, int textWidth) {
currentLineHeight = Math.max(currentLineHeight, textLineHeight);
currentLine.append(renderToSpannable(appendedText, textPaint));
currentLineWidth += textWidth;
}
public List<CharSequence> getPages() {
List<CharSequence> copyPages = new ArrayList<CharSequence>(pages);
SpannableStringBuilder lastPage = new SpannableStringBuilder(currentPage);
if (pageContentHeight + currentLineHeight > pageHeight) {
copyPages.add(lastPage);
lastPage = new SpannableStringBuilder();
}
lastPage.append(currentLine);
copyPages.add(lastPage);
return copyPages;
}
private SpannableString renderToSpannable(String text, TextPaint textPaint) {
SpannableString spannable = new SpannableString(text);
if (textPaint.isFakeBoldText()) {
spannable.setSpan(new StyleSpan(Typeface.BOLD), 0, spannable.length(), 0);
}
return spannable;
}
}
TextAdapter.java
package ru.appheads.pagesplitterapp;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import java.util.List;
public class TextPagerAdapter extends FragmentPagerAdapter {
private final List<CharSequence> pageTexts;
public TextPagerAdapter(FragmentManager fm, List<CharSequence> pageTexts) {
super(fm);
this.pageTexts = pageTexts;
}
#Override
public Fragment getItem(int i) {
return PageFragment.newInstance(pageTexts.get(i));
}
#Override
public int getCount() {
return pageTexts.size();
}
}
activity_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="ru.appheads.pagesplitterapp.MainActivity">
<androidx.viewpager2.widget.ViewPager2 xmlns:android="http://schemas.android.com/apk/res
/android"
android:id="#+id/pages"
android:overScrollMode="never"
android:layout_height="match_parent"
android:layout_width="match_parent">
</androidx.viewpager2.widget.ViewPager2>
</RelativeLayout>
Page.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:lineSpacingMultiplier="1"
android:lineSpacingExtra="0sp">
</TextView>
styles.xml
<resources>
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
</style>
</resources>
build.gradle.app
plugins {
id 'com.android.application'
}
android {
compileSdk 32
defaultConfig {
applicationId "ru.appheads.pagesplitterapp"
minSdk 21
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-
rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.0'
implementation 'com.google.android.material:material:1.6.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'androidx.viewpager2:viewpager2:1.0.0'
//implementation 'androidx.fragment:fragment-ktx:1.2.0-beta02'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
you are using Viewpager2 in xml and imported and declared Viewpager in MainActivity, that's why you are getting ClassCastException. Both xml and activity viewPager type should be same
This is a 1/4 of logcat content.
This is second logcat - after clear logcat.
2022-09-08 23:03:25.664 6760-6760/? I/pagesplitterap: Late-enabling
-Xcheck:jni
2022-09-08 23:03:25.731 6760-6760/? I/pagesplitterap: Unquickening 12
vdex files!
2022-09-08 23:03:25.737 6760-6760/? W/pagesplitterap: Unexpected CPU
variant for X86 using defaults: x86
2022-09-08 23:03:26.651 6760-6760/ru.appheads.pagesplitterapp
D/NetworkSecurityConfig: No Network Security Config specified, using
platform default
2022-09-08 23:03:26.651 6760-6760/ru.appheads.pagesplitterapp
D/NetworkSecurityConfig: No Network Security Config specified, using
platform default
2022-09-08 23:03:26.739 6760-6783/ru.appheads.pagesplitterapp
D/libEGL:
loaded /vendor/lib/egl/libEGL_emulation.so
2022-09-08 23:03:26.743 6760-6783/ru.appheads.pagesplitterapp
D/libEGL:
loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
2022-09-08 23:03:26.753 6760-6783/ru.appheads.pagesplitterapp
D/libEGL:
loaded /vendor/lib/egl/libGLESv2_emulation.so
2022-09-08 23:03:27.182 6760-6760/ru.appheads.pagesplitterapp
D/AndroidRuntime: Shutting down VM
--------- beginning of crash
2022-09-08 23:03:27.184 6760-6760/ru.appheads.pagesplitterapp
E/AndroidRuntime: FATAL EXCEPTION: main
Process: ru.appheads.pagesplitterapp, PID: 6760
java.lang.RuntimeException: Unable to start activity
ComponentInfo {ru.appheads.pagesplitterapp
/ru.appheads.pagesplitterapp.MainActivity}:
java.lang.ClassCastException: androidx.viewpager2.widget.ViewPager2
cannot be cast to androidx.viewpager.widget.ViewPager
at
android.app.ActivityThread.performLaunchActivity
(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity
(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute
(LaunchActivityItem.java:85)
at
android.app.servertransaction.TransactionExecutor.executeCallbacks
(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute
(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage
(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run
(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.ClassCastException:
androidx.viewpager2.widget.ViewPager2 cannot be cast to
androidx.viewpager.widget.ViewPager
at ru.appheads.pagesplitterapp.MainActivity.onCreate
(MainActivity.java:19)
at android.app.Activity.performCreate(Activity.java:7994)
at android.app.Activity.performCreate(Activity.java:7978)
at android.app.Instrumentation.callActivityOnCreate
(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity
(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity
(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute
(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.
executeCallbacks (TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute
(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage
(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run
(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
2022-09-08 23:03:27.217 6760-6760/ru.appheads.pagesplitterapp
I/Process: Sending signal. PID: 6760 SIG: 9
I'm trying to build an app which fetches data from firebase and displays info in cardholders when searched by word but when I try to open the window where the code is implemented I get the app crashed. Any advice and help will do.
More in detail.
Basically, I created buttons on the first page(MainActivity.java) and made a button to toggle a new window where you can search foods from firebase in real time (datasearch.java).
As soon as I press the button to the search window the app crashes without any error messages.
MainActivity:
package com.example.kursinis;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.ImageView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class MainActivity extends AppCompatActivity {
ImageView logo;
Button mKmi_btn,mDatasearch_btn,mLogdata_btn;
CalendarView mCalendar;
DatabaseReference ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
logo = findViewById(R.id.logo);
mKmi_btn = findViewById(R.id.kmi_btn);
mDatasearch_btn = findViewById(R.id.datasearch_btn);
mLogdata_btn = findViewById(R.id.logdata_btn);
mCalendar = findViewById(R.id.calendarView3);
mDatasearch_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(),datasearch.class));
}
});
mLogdata_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(),logdata.class));
}
});
mKmi_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(),kmi.class));
}
});
/* Insert calendar clicks for every day to see logged results */
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id==R.id.action_logout) {
logout();
return true;
}
return super.onOptionsItemSelected(item);
}
private void logout() {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(),login.class));
finish();
}
}
datasearch java
package com.example.kursinis;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.widget.SearchView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Locale;
public class datasearch extends AppCompatActivity {
DatabaseReference ref;
ArrayList<produktas> list;
RecyclerView recyclerView;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_datasearch);
ref = FirebaseDatabase.getInstance().getReference().child("https://link_to_ref/");
recyclerView = findViewById(R.id.rec_view);
searchView = findViewById(R.id.search_data);
}
#Override
protected void onStart() {
super.onStart();
if (ref!=null){
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
list = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()){
list.add(ds.getValue(produktas.class));
}
AdapterClass adapterClass = new AdapterClass(list);
recyclerView.setAdapter(adapterClass);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(datasearch.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
if (searchView != null){
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
search(s);
return true;
}
});
}
}
private void search(String str){
ArrayList<produktas> sList = new ArrayList<>();
for (produktas object : list){
if (object.getKalorijos().toLowerCase().contains(str.toLowerCase())){
sList.add(object);
}
if (object.getAngliavandianiai().toLowerCase().contains(str.toLowerCase())){
sList.add(object);
}
if (object.getBaltymai().toLowerCase().contains(str.toLowerCase())){
sList.add(object);
}
if (object.getRiebalai().toLowerCase().contains(str.toLowerCase())){
sList.add(object);
}
}
AdapterClass adapterClass = new AdapterClass(sList);
recyclerView.setAdapter(adapterClass);
}
}
Adapterclass
package com.example.kursinis;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder>{
ArrayList<produktas> list;
public AdapterClass(ArrayList<produktas> list){
this.list = list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cardholder,viewGroup,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.id.setText(list.get(i).getMaisto_prod());
myViewHolder.desc1.setText(list.get(i).getKalorijos());
myViewHolder.desc2.setText(list.get(i).getAngliavandianiai());
myViewHolder.desc3.setText(list.get(i).getBaltymai());
myViewHolder.desc4.setText(list.get(i).getRiebalai());
}
#Override
public int getItemCount() {
return list.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView id,desc1,desc2,desc3,desc4;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
id = itemView.findViewById(R.id.prod_name);
desc1 = itemView.findViewById(R.id.prod_desc1);
desc2 = itemView.findViewById(R.id.prod_desc2);
desc3 = itemView.findViewById(R.id.prod_desc3);
desc4 = itemView.findViewById(R.id.prod_desc4);
}
}
}
product.java
package com.example.kursinis;
public class produktas {
private String angliavandianiai;
private String baltymai;
private String kalorijos;
private String maisto_prod;
private String riebalai;
public produktas(String angliavandianiai, String baltymai, String kalorijos, String maisto_prod, String riebalai) {
this.angliavandianiai = angliavandianiai;
this.baltymai = baltymai;
this.kalorijos = kalorijos;
this.maisto_prod = maisto_prod;
this.riebalai = riebalai;
}
public String getAngliavandianiai() {
return angliavandianiai;
}
public void setAngliavandianiai(String angliavandianiai) {
this.angliavandianiai = angliavandianiai;
}
public String getBaltymai() {
return baltymai;
}
public void setBaltymai(String baltymai) {
this.baltymai = baltymai;
}
public String getKalorijos() {
return kalorijos;
}
public void setKalorijos(String kalorijos) {
this.kalorijos = kalorijos;
}
public String getMaisto_prod() {
return maisto_prod;
}
public void setMaisto_prod(String maisto_prod) {
this.maisto_prod = maisto_prod;
}
public String getRiebalai() {
return riebalai;
}
public void setRiebalai(String riebalai) {
this.riebalai = riebalai;
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.kursinis">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Kursinis">
<activity
android:name=".calendar"
android:exported="false" />
<activity
android:name=".kmi"
android:exported="false" />
<activity
android:name=".logdata"
android:exported="false" />
<activity
android:name=".datasearch"
android:exported="false" />
<activity
android:name=".login"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".registration"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Gradel
plugins {
id 'com.android.application'
id 'com.google.gms.google-services'
}
android {
compileSdk 31
defaultConfig {
applicationId "com.example.kursinis"
minSdk 26
targetSdk 31
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildFeatures {
viewBinding true
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.6.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'androidx.navigation:navigation-fragment:2.4.2'
implementation 'androidx.navigation:navigation-ui:2.4.2'
implementation 'com.google.firebase:firebase-database:20.0.5'
implementation 'com.google.firebase:firebase-firestore:24.1.2'
implementation 'com.google.firebase:firebase-auth:21.0.5'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation platform('com.google.firebase:firebase-bom:30.1.0')
implementation 'com.google.firebase:firebase-analytics'
implementation 'com.google.firebase:firebase-core:21.0.0'
}
As well I don't get any error upon app crash, but the only thing I found in Database Inspector that the google_app_measurement_local.db (closed).
Any help and answers are welcome and I will be very thankful.
EDITED:
I changed the ref link in datasearch.java to a name which I created "food" from firebase realtime database, but the only thing that got fixed it that now the window opens up with the search bar but when I try to enter at least one letter it crashes again.
EDITED added logcat
2022-06-19 22:11:45.729 2067-2072/com.example.kursinis I/zygote: After code cache collection, code=469KB, data=239KB
2022-06-19 22:11:45.767 2067-2067/com.example.kursinis E/RecyclerView: No adapter attached; skipping layout
2022-06-19 22:11:45.807 2067-2124/com.example.kursinis D/EGL_emulation: eglMakeCurrent: 0xa10061a0: ver 2 0 (tinfo 0xa10032f0)
2022-06-19 22:11:45.845 2067-2124/com.example.kursinis I/chatty: uid=10089(u0_a89) RenderThread identical 1 line
2022-06-19 22:11:45.857 2067-2124/com.example.kursinis D/EGL_emulation: eglMakeCurrent: 0xa10061a0: ver 2 0 (tinfo 0xa10032f0)
2022-06-19 22:11:45.906 2067-2124/com.example.kursinis D/OpenGLRenderer: endAllActiveAnimators on 0x84068c80 (RippleDrawable) with handle 0xa10030d0
2022-06-19 22:11:46.456 2067-2165/com.example.kursinis W/PersistentConnection: pc_0 - Firebase Database connection was forcefully killed by the server. Will not attempt reconnect. Reason: Database lives in a different region. Please change your database URL to https://kursinis-kcal......
2022-06-19 22:11:50.760 2067-2103/com.example.kursinis V/FA: Inactivity, disconnecting from the service
2022-06-19 22:11:50.991 2067-2067/com.example.kursinis W/View: dispatchProvideAutofillStructure(): not laid out, ignoring
2022-06-19 22:11:50.993 2067-2067/com.example.kursinis W/View: dispatchProvideAutofillStructure(): not laid out, ignoring
2022-06-19 22:11:50.997 2067-2067/com.example.kursinis I/AssistStructure: Flattened final assist data: 2208 bytes, containing 1 windows, 9 views
2022-06-19 22:11:50.997 2067-2072/com.example.kursinis I/zygote: Do partial code cache collection, code=478KB, data=260KB
2022-06-19 22:11:50.998 2067-2072/com.example.kursinis I/zygote: After code cache collection, code=478KB, data=260KB
2022-06-19 22:11:50.998 2067-2072/com.example.kursinis I/zygote: Increasing code cache capacity to 2MB
2022-06-19 22:11:51.252 2067-2067/com.example.kursinis E/RecyclerView: No adapter attached; skipping layout
2022-06-19 22:11:51.467 2067-2067/com.example.kursinis E/InputEventSender: Exception dispatching finished signal.
2022-06-19 22:11:51.467 2067-2067/com.example.kursinis E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
2022-06-19 22:11:51.469 2067-2067/com.example.kursinis E/MessageQueue-JNI: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Iterator java.util.ArrayList.iterator()' on a null object reference
at com.example.kursinis.datasearch.search(datasearch.java:79)
at com.example.kursinis.datasearch.access$000(datasearch.java:20)
at com.example.kursinis.datasearch$2.onQueryTextChange(datasearch.java:71)
at android.widget.SearchView.onTextChanged(SearchView.java:1250)
at android.widget.SearchView.-wrap9(Unknown Source:0)
at android.widget.SearchView$8.onTextChanged(SearchView.java:1776)
at android.widget.TextView.sendOnTextChanged(TextView.java:9359)
at android.widget.TextView.handleTextChanged(TextView.java:9446)
at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:11904)
at android.text.SpannableStringBuilder.sendTextChanged(SpannableStringBuilder.java:1252)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:573)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:504)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:502)
at android.text.method.QwertyKeyListener.onKeyDown(QwertyKeyListener.java:228)
at android.text.method.TextKeyListener.onKeyDown(TextKeyListener.java:141)
at android.widget.TextView.doKeyDown(TextView.java:7316)
at android.widget.TextView.onKeyDown(TextView.java:7093)
at android.widget.AutoCompleteTextView.onKeyDown(AutoCompleteTextView.java:831)
at android.view.KeyEvent.dispatch(KeyEvent.java:2688)
at android.view.View.dispatchKeyEvent(View.java:11662)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at com.android.internal.policy.DecorView.superDispatchKeyEvent(DecorView.java:437)
at com.android.internal.policy.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1818)
at androidx.core.view.KeyEventDispatcher.activitySuperDispatchKeyEventPre28(KeyEventDispatcher.java:130)
at androidx.core.view.KeyEventDispatcher.dispatchKeyEvent(KeyEventDispatcher.java:87)
at androidx.core.app.ComponentActivity.dispatchKeyEvent(ComponentActivity.java:140)
at androidx.appcompat.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:569)
at androidx.appcompat.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:59)
at androidx.appcompat.app.AppCompatDelegateImpl$AppCompatWindowCallback.dispatchKeyEvent(AppCompatDelegateImpl.java:3054)
at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:351)
at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:4714)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4586)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4128)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4181)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4147)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4274)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4155)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4331)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4128)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4181)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4147)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4155)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4128)
at android.
2022-06-19 22:11:51.469 2067-2067/com.example.kursinis D/AndroidRuntime: Shutting down VM
2022-06-19 22:11:51.471 2067-2067/com.example.kursinis E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kursinis, PID: 2067
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Iterator java.util.ArrayList.iterator()' on a null object reference
at com.example.kursinis.datasearch.search(datasearch.java:79)
at com.example.kursinis.datasearch.access$000(datasearch.java:20)
at com.example.kursinis.datasearch$2.onQueryTextChange(datasearch.java:71)
at android.widget.SearchView.onTextChanged(SearchView.java:1250)
at android.widget.SearchView.-wrap9(Unknown Source:0)
at android.widget.SearchView$8.onTextChanged(SearchView.java:1776)
at android.widget.TextView.sendOnTextChanged(TextView.java:9359)
at android.widget.TextView.handleTextChanged(TextView.java:9446)
at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:11904)
at android.text.SpannableStringBuilder.sendTextChanged(SpannableStringBuilder.java:1252)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:573)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:504)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:502)
at android.text.method.QwertyKeyListener.onKeyDown(QwertyKeyListener.java:228)
at android.text.method.TextKeyListener.onKeyDown(TextKeyListener.java:141)
at android.widget.TextView.doKeyDown(TextView.java:7316)
at android.widget.TextView.onKeyDown(TextView.java:7093)
at android.widget.AutoCompleteTextView.onKeyDown(AutoCompleteTextView.java:831)
at android.view.KeyEvent.dispatch(KeyEvent.java:2688)
at android.view.View.dispatchKeyEvent(View.java:11662)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at com.android.internal.policy.DecorView.superDispatchKeyEvent(DecorView.java:437)
at com.android.internal.policy.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1818)
at androidx.core.view.KeyEventDispatcher.activitySuperDispatchKeyEventPre28(KeyEventDispatcher.java:130)
at androidx.core.view.KeyEventDispatcher.dispatchKeyEvent(KeyEventDispatcher.java:87)
at androidx.core.app.ComponentActivity.dispatchKeyEvent(ComponentActivity.java:140)
at androidx.appcompat.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:569)
at androidx.appcompat.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:59)
at androidx.appcompat.app.AppCompatDelegateImpl$AppCompatWindowCallback.dispatchKeyEvent(AppCompatDelegateImpl.java:3054)
at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:351)
at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:4714)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4586)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4128)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4181)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4147)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4274)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4155)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4331)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4128)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4181)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4147)
2022-06-19 22:11:51.471 2067-2067/com.example.kursinis E/AndroidRuntime: at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4155)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4128)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4181)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4147)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4307)
at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:4468)
at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:2435)
at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:1998)
at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:1989)
at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:2412)
at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:141)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:325)
at android.os.Looper.loop(Looper.java:142)
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)
At your search function, the value list is null. To solve this problem, you need to check if the list is null or not.
private void search(String str){
ArrayList<produktas> sList = new ArrayList<>();
//At here you need to check list is null or not and if got any list or not.
if (list != null && list.size() > 0) {
for (produktas object : list){
if (object.getKalorijos().toLowerCase().contains(str.toLowerCase())){
sList.add(object);
}
if (object.getAngliavandianiai().toLowerCase().contains(str.toLowerCase())){
sList.add(object);
}
if (object.getBaltymai().toLowerCase().contains(str.toLowerCase())){
sList.add(object);
}
if (object.getRiebalai().toLowerCase().contains(str.toLowerCase())){
sList.add(object);
}
}
dapterClass adapterClass = new AdapterClass(sList);
recyclerView.setAdapter(adapterClass);
}
}
There is no error when gradle. When it is install on the virtual machine, the program cannot run and the following error is displayed. This is the code. This is Android development.
MainActivity.java
package com.example.app;
import java.util.List;
import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.esri.arcgisruntime.data.ArcGISFeature;
import com.esri.arcgisruntime.data.FeatureEditResult;
import com.esri.arcgisruntime.loadable.LoadStatus;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.layers.ArcGISTiledLayer;
import com.esri.arcgisruntime.data.ServiceFeatureTable;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.GeoElement;
import com.esri.arcgisruntime.mapping.Viewpoint;
import com.esri.arcgisruntime.mapping.view.Callout;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.IdentifyLayerResult;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.google.android.material.snackbar.Snackbar;
import android.app.ProgressDialog;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private MapView mMapView;
private Callout mCallout;
private ArcGISFeature mSelectedArcGISFeature;
private static final String TAG = MainActivity.class.getSimpleName();
private android.graphics.Point mClickPoint;
private Snackbar mSnackbarSuccess;
private Snackbar mSnackbarFailure;
private String mSelectedArcGISFeatureAttributeValue;
private boolean mFeatureUpdated;
private View mCoordinatorLayout;
private ProgressDialog mProgressDialog;
private ServiceFeatureTable mServiceFeatureTable;
private FeatureLayer mFeatureLayer;
#SuppressLint("ClickableViewAccessibility")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMapView = findViewById(R.id.mapView);
String url = "http://map.geoq.cn/arcgis/rest/services/ChinaOnlineCommunity/MapServer";
ArcGISTiledLayer arcGISTiledLayer = new ArcGISTiledLayer(url);
Basemap basemap = new Basemap(arcGISTiledLayer);
ArcGISMap arcGISMap = new ArcGISMap(basemap);
mCallout = mMapView.getCallout();
ServiceFeatureTable mServiceFeatureTable = new ServiceFeatureTable("http://192.168.1.103:6080/arcgis/rest/services/huda1/MapServer/0");
FeatureLayer featureLayer = new FeatureLayer(mServiceFeatureTable);
arcGISMap.getOperationalLayers().add(featureLayer);
mFeatureLayer.setOpacity(0.8f);*/
mMapView.setMap(arcGISMap);
mMapView.setViewpoint(new Viewpoint(30.577421, 114.331955, 10000));
//set an on touch listener to listen for click events
// set an on touch listener to listen for click events
mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, mMapView) {
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
// get the point that was clicked and convert it to a point in map coordinates
mClickPoint = new android.graphics.Point((int) e.getX(), (int) e.getY());
// clear any previous selection
mFeatureLayer.clearSelection();
mSelectedArcGISFeature = null;
mCallout.dismiss();
// identify the GeoElements in the given layer
final ListenableFuture<IdentifyLayerResult> identifyFuture = mMapView
.identifyLayerAsync(mFeatureLayer, mClickPoint, 5, false, 1);
// add done loading listener to fire when the selection returns
identifyFuture.addDoneListener(() -> {
try {
// call get on the future to get the result
IdentifyLayerResult layerResult = identifyFuture.get();
List<GeoElement> resultGeoElements = layerResult.getElements();
if (!resultGeoElements.isEmpty()) {
if (resultGeoElements.get(0) instanceof ArcGISFeature) {
mSelectedArcGISFeature = (ArcGISFeature) resultGeoElements.get(0);
// highlight the selected feature
mFeatureLayer.selectFeature(mSelectedArcGISFeature);
// show callout with the value for the attribute "typdamage" of the selected feature
mSelectedArcGISFeatureAttributeValue = (String) mSelectedArcGISFeature.getAttributes()
.get("typdamage");
showCallout(mSelectedArcGISFeatureAttributeValue);
Toast.makeText(MainActivity.this, "Tap on the info button to change attribute value",
Toast.LENGTH_SHORT).show();
}
} else {
// none of the features on the map were selected
mCallout.dismiss();
}
} catch (Exception e1) {
Log.e(TAG, "Select feature failed: " + e1.getMessage());
}
});
return super.onSingleTapConfirmed(e);
}
});
mSnackbarSuccess = Snackbar
.make(mCoordinatorLayout, "Feature successfully updated", Snackbar.LENGTH_LONG)
.setAction("UNDO", view -> {
String snackBarText = updateAttributes(mSelectedArcGISFeatureAttributeValue) ?
"Feature is restored!" :
"Feature restore failed!";
Snackbar snackbar1 = Snackbar.make(mCoordinatorLayout, snackBarText, Snackbar.LENGTH_SHORT);
snackbar1.show();
});
mSnackbarFailure = Snackbar.make(mCoordinatorLayout, "Feature update failed", Snackbar.LENGTH_LONG);
}
/**
* Function to read the result from newly created activity
*/
#Override
protected void onActivityResult(int requestCode,
int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
// display progress dialog while updating attribute callout
mProgressDialog.show();
updateAttributes(data.getStringExtra("typdamage"));
}
}
/**
* Applies changes to the feature, Service Feature Table, and server.
*/
private boolean updateAttributes(final String typeDamage) {
// load the selected feature
mSelectedArcGISFeature.loadAsync();
// update the selected feature
mSelectedArcGISFeature.addDoneLoadingListener(() -> {
if (mSelectedArcGISFeature.getLoadStatus() == LoadStatus.FAILED_TO_LOAD) {
Log.e(TAG, "Error while loading feature");
}
// update the Attributes map with the new selected value for "typdamage"
mSelectedArcGISFeature.getAttributes().put("typdamage", typeDamage);
try {
// update feature in the feature table
ListenableFuture<Void> mapViewResult = mServiceFeatureTable.updateFeatureAsync(mSelectedArcGISFeature);
/*mServiceFeatureTable.updateFeatureAsync(mSelectedArcGISFeature).addDoneListener(new Runnable() {*/
mapViewResult.addDoneListener(() -> {
// apply change to the server
final ListenableFuture<List<FeatureEditResult>> serverResult = mServiceFeatureTable.applyEditsAsync();
serverResult.addDoneListener(() -> {
try {
// check if server result successful
List<FeatureEditResult> edits = serverResult.get();
if (!edits.isEmpty()) {
if (!edits.get(0).hasCompletedWithErrors()) {
Log.e(TAG, "Feature successfully updated");
mSnackbarSuccess.show();
mFeatureUpdated = true;
}
} else {
Log.e(TAG, "The attribute type was not changed");
mSnackbarFailure.show();
mFeatureUpdated = false;
}
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
// display the callout with the updated value
showCallout((String) mSelectedArcGISFeature.getAttributes().get("typdamage"));
}
} catch (Exception e) {
Log.e(TAG, "applying changes to the server failed: " + e.getMessage());
}
});
});
} catch (Exception e) {
Log.e(TAG, "updating feature in the feature table failed: " + e.getMessage());
}
});
return mFeatureUpdated;
}
/**
* Displays Callout
*
* #param title the text to show in the Callout
*/
private void showCallout(String title) {
// create a text view for the callout
RelativeLayout calloutLayout = new RelativeLayout(getApplicationContext());
TextView calloutContent = new TextView(getApplicationContext());
calloutContent.setId(R.id.textview);
calloutContent.setTextColor(Color.BLACK);
calloutContent.setTextSize(18);
calloutContent.setPadding(0, 10, 10, 0);
calloutContent.setText(title);
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
relativeParams.addRule(RelativeLayout.RIGHT_OF, calloutContent.getId());
// create image view for the callout
ImageView imageView = new ImageView(getApplicationContext());
imageView
.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_info_outline_black_18dp));
imageView.setLayoutParams(relativeParams);
imageView.setOnClickListener(new ImageViewOnclickListener());
calloutLayout.addView(calloutContent);
calloutLayout.addView(imageView);
mCallout.setGeoElement(mSelectedArcGISFeature, null);
mCallout.setContent(calloutLayout);
mCallout.show();
}
#Override
protected void onPause() {
mMapView.pause();
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
mMapView.resume();
}
#Override
protected void onDestroy() {
mMapView.dispose();
super.onDestroy();
}
/**
* Defines the listener for the ImageView clicks
*/
private class ImageViewOnclickListener implements View.OnClickListener {
#Override public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this, DamageTypesListActivity.class);
startActivityForResult(myIntent, 100);
}
}
}
DamageTypesListActivity.java
package com.example.app;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* Displays the Damage type options in a ListView.
*/
public class DamageTypesListActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.damage_types_listview);
final String[] damageTypes = getResources().getStringArray(R.array.damage_types);
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(new ArrayAdapter<>(this, R.layout.damage_types, damageTypes));
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent myIntent = new Intent();
myIntent.putExtra("typdamage", damageTypes[position]); //Optional parameters
setResult(100, myIntent);
finish();
}
});
}
#Override
public void onBackPressed() {
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app">
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:glEsVersion="0x00020000" android:required="true" />
<application
android:allowBackup="false"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.DisplayAMapJava">
<activity
android:name=".MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DamageTypesListActivity"
android:label="#string/select_damage_Type">
</activity>
</application>
</manifest>
strings.xml
<resources>
<string name="app_name">Display a map java</string>
<string name="select_damage_Type">"Select new damage type"</string>
<!-- Progress dialog messages -->
<string name="progress_title">Updating attribute type</string>
<string name="progress_message">Please wait…</string>
<!-- Sample Strings -->
<string name="sample_service_url">https://sampleserver6.arcgisonline.com/arcgis/rest/services/DamageAssessment/FeatureServer/0</string>
<string-array name="damage_types">
<item>Destroyed</item>
<item>Major</item>
<item>Minor</item>
<item>Affected</item>
<item>Inaccessible</item>
</string-array>
</resources>
below is logcat message
AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.app, PID: 21571
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.app/com.example.app.MainActivity}: java.lang.IllegalArgumentException: No suitable parent found from the given view. Please provide a valid view.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.IllegalArgumentException: No suitable parent found from the given view. Please provide a valid view.
at com.google.android.material.snackbar.Snackbar.make(Snackbar.java:158)
at com.example.app.MainActivity.onCreate(MainActivity.java:137)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Initialize the CoordinatorLayout (mCoordinatorLayout) before using it in Snackbar.make()
Use findViewById to initialize mCoordinatorLayout
mCoordinatorLayout = findViewById(layout_id)
I have an issue with my Android App. I am asking for permissions to the user to access the READ_EXTERNAL_STORAGE but the bug "permission denial" still makes my app crash.
I have spent hours on it and I have no clue how to fix it.
Here's my logcat:
03-07 15:02:12.387 6800-8893/? E/DatabaseUtils: Writing exception to parcel
java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=8108, uid=10089 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
at android.content.ContentProvider.enforceReadPermissionInner(ContentProvider.java:605)
at android.content.ContentProvider$Transport.enforceReadPermission(ContentProvider.java:480)
at android.content.ContentProvider$Transport.query(ContentProvider.java:211)
at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:112)
at android.os.Binder.execTransact(Binder.java:453)
03-07 15:02:12.391 8108-11729/? E/iu.UploadsManager: Insufficient permissions to process media
java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=8108, uid=10089 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
at android.os.Parcel.readException(Parcel.java:1602)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
at android.content.ContentProviderProxy.query(ContentProviderNative.java:421)
at android.content.ContentResolver.query(ContentResolver.java:502)
at android.content.ContentResolver.query(ContentResolver.java:438)
at lqt.a(PG:14)
at com.google.android.libraries.social.autobackup.FingerprintScannerIntentService.onHandleIntent(PG:15)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:66)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:150)
at android.os.HandlerThread.run(HandlerThread.java:61)
My Main activity is:
package com.example.arjufy;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.Manifest;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
public class MainActivity extends AppCompatActivity implements MarketPlaceFragment.OnListFragmentInteractionListener {
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
private DatabaseReference mDatabaseReference;
private String mUsername;
private String mPhotoUrl;
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (checkPermissionREAD_EXTERNAL_STORAGE(this)) {
// do your stuff..
// Initialize Firebase Auth
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
if (mFirebaseUser == null) {
// Not signed in, launch the Sign In activity
startActivity(new Intent(this, SplashScreenActivity.class));
finish();
return;
} else {
mUsername = mFirebaseUser.getEmail();
}
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
setContentView(R.layout.activity_main);
Fragment fragment = new MarketPlaceFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.theFragmentFrame, fragment).addToBackStack("MarketPlaceFragment").commit();
}
}
public boolean checkPermissionREAD_EXTERNAL_STORAGE(
final Context context) {
int currentAPIVersion = Build.VERSION.SDK_INT;
if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(
(Activity) context,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
showDialog("External storage", context,
Manifest.permission.READ_EXTERNAL_STORAGE);
} else {
ActivityCompat
.requestPermissions(
(Activity) context,
new String[] { Manifest.permission.READ_EXTERNAL_STORAGE },
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
public void showDialog(final String msg, final Context context,
final String permission) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage(msg + " permission is necessary");
alertBuilder.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) context,
new String[] { permission },
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
}
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// do your stuff
} else {
Toast.makeText(MainActivity.this, "GET_ACCOUNTS Denied",
Toast.LENGTH_SHORT).show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.logoff:
FirebaseAuth.getInstance().signOut();
Intent intent1 = new Intent(this, LoginActivity.class);
startActivity(intent1);
return true;
case R.id.profile:
Intent intent2 = new Intent(this, MyProfileActivity.class);
startActivity(intent2);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onListFragmentInteraction(DatabaseReference reference) {
Intent intent = new Intent(this, ProductDetailViewActivity.class);
intent.putExtra("Product reference", reference.toString());
startActivity(intent);
}
}
My manifest is:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.arjufy">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>``
<activity android:name=".LoginActivity" />
<activity android:name=".SplashScr
eenActivity" />
<activity android:name=".AddProductActivity" />
<activity android:name=".SignUpActivity" />
<activity android:name=".MyProfileActivity" />
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.arjufy"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/path_files" />
</provider>
<activity android:name=".ProductDetailViewActivity" />
</application>
</manifest>
and my gradle is:
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.arjufy"
minSdkVersion 23
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.google.firebase:firebase-auth:16.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.google.android.gms:play-services-auth:16.0.1'
implementation 'com.google.firebase:firebase-storage:16.1.0'
implementation 'com.google.firebase:firebase-database:16.1.0'
implementation 'com.firebaseui:firebase-ui:0.5.3'
implementation 'me.relex:circleindicator:2.1.0#aar'
implementation 'com.getbase:floatingactionbutton:1.10.1'
implementation 'de.hdodenhof:circleimageview:2.2.0'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'com.google.firebase:firebase-core:16.0.7'
}
Do you have any idea where it might come from?
Thanks a lot for your help.
Very much appreciated.
From Android Developer Documentation
If your app needs a dangerous permission, you must check whether you have that permission every time you perform an operation that requires that permission. Beginning with Android 6.0 (API level 23), users can revoke permissions from any app at any time, even if the app targets a lower API level.
So you need to request permission like this
#TargetApi(23)
public void enableRunTimePermisstion() {
if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) &&
(getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED))
if (getActivity().shouldShowRequestPermissionRationale
(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(getActivity(), "Write storage permission is need for app"
, Toast.LENGTH_LONG).show();
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
} else {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
Toast.makeText(getActivity(), "request permission"
, Toast.LENGTH_LONG).show();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE) &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, "Write external storage granted", Toast.LENGTH_LONG).show();
// >> here you call the method that need the permission
}
} else {
Toast.makeText(getActivity(), "Write external permission denied", Toast.LENGTH_SHORT).show();
enableRunTimePermisstion(); // >> When user request the permission we calling the previous method again.
}
}
Runtime permission has actually taken a new shape in the recent times ... like you need to use a fileprovider, provide Uri and the likes but here is a good library that i have used in the recent times. It works well and hassle free. You can check it out on codepath.
https://guides.codepath.com/android/Managing-Runtime-Permissions-with-PermissionsDispatcher
Cheers.
Good evening. I am taking a course in android and having issues compiling the app.
I am currently following this tutorial. I have earlier set up a requestQueue for GET requests.
This is my MainActivity.java file:
package com.ticketapp.emailaddresss.ticketapp;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.facebook.AccessToken;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.facebook.login.LoginManager;
import com.facebook.share.model.ShareHashtag;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.widget.ShareDialog;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button button;
TextView textView;
String server_url = "https://www.idg.se/";
RequestQueue requestQueue;
private ShareDialog shareDialog;
private String name, surname, imageUrl;
private String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.bm);
textView = (TextView) findViewById(R.id.txt);
Bundle inBundle = getIntent().getExtras();
name = inBundle.getString("name");
surname = inBundle.getString("surname");
imageUrl = inBundle.getString("imageUrl");
TextView nameView = (TextView) findViewById(R.id.nameAndSurname);
nameView.setText("" + name + " " + surname);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, server_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
textView.setText(response);
//requestQueue.stop();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
textView.setText("Something went wrong");
error.printStackTrace();
//requestQueue.stop();
}
});
//requestQueue.add(stringRequest);
SingletonRequestQueue.getmInstance(getApplicationContext()).addRequestQueue(stringRequest);
}
});
}
private void share() {
shareDialog = new ShareDialog(this);
List<String> taggedUserIds = new ArrayList<String>();
taggedUserIds.add("{USER_ID}");
taggedUserIds.add("{USER_ID}");
taggedUserIds.add("{USER_ID}");
ShareLinkContent content = new ShareLinkContent.Builder()
.setContentUrl(Uri.parse("http://www.sitepoint.com"))
.setContentTitle("This is a content title")
.setContentDescription("This is a description")
.setShareHashtag(new ShareHashtag.Builder().setHashtag("#sitepoint").build())
.setPeopleIds(taggedUserIds)
.setPlaceId("{PLACE_ID}")
.build();
shareDialog.show(content);
}
private void getPosts() {
new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/posts", null, HttpMethod.GET, new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Log.e(TAG, response.toString());
}
}).executeAsync();
}
private void logout() {
LoginManager.getInstance().logOut();
Intent login = new Intent(MainActivity.this, LoginActivity.class);
startActivity(login);
finish();
}
//#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.share:
share();
break;
case R.id.getPosts:
getPosts();
break;
case R.id.logout:
logout();
break;
}
}
}
LoginActivity.java
package com.ticketapp.emailaddress.ticketapp;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.MalformedURLException;
import java.net.URL;
public class LoginActivity extends AppCompatActivity {
private CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
private LoginButton loginButton;
private String firstName,lastName, email,birthday,gender;
private URL profilePicture;
private String userId;
private String TAG = "LoginActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// FacebookSdk.sdkInitialize(this);
//FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_login);
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setHeight(100);
loginButton.setTextColor(Color.WHITE);
loginButton.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
loginButton.setCompoundDrawablePadding(0);
loginButton.setReadPermissions("email", "user_birthday","user_posts");
loginButton.registerCallback(callbackManager, callback);
}
FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.e(TAG,object.toString());
Log.e(TAG,response.toString());
try {
userId = object.getString("id");
profilePicture = new URL("https://graph.facebook.com/" + userId + "/picture?width=500&height=500");
if(object.has("first_name"))
firstName = object.getString("first_name");
if(object.has("last_name"))
lastName = object.getString("last_name");
if (object.has("email"))
email = object.getString("email");
if (object.has("birthday"))
birthday = object.getString("birthday");
if (object.has("gender"))
gender = object.getString("gender");
Intent main = new Intent(LoginActivity.this,MainActivity.class);
main.putExtra("name",firstName);
main.putExtra("surname",lastName);
main.putExtra("imageUrl",profilePicture.toString());
startActivity(main);
finish();
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
//Here we put the requested fields to be returned from the JSONObject
Bundle parameters = new Bundle();
parameters.putString("fields", "id, first_name, last_name, email, birthday, gender");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
e.printStackTrace();
}
};
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
super.onActivityResult(requestCode, responseCode, intent);
callbackManager.onActivityResult(requestCode, responseCode, intent);
}
}
SingletonRequestQueue.java
package com.ticketapp.emailaddress.ticketapp;
import android.content.Context;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import java.lang.ref.ReferenceQueue;
/**
* Created by Adde on 2017-09-11.
*/
public class SingletonRequestQueue {
private
static SingletonRequestQueue mInstance;
private RequestQueue requestQueue;
private static Context mCtx;
private SingletonRequestQueue(Context context){
mCtx = context;
requestQueue = getRequestQueue();
}
public RequestQueue getRequestQueue(){
if(requestQueue == null){
requestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return requestQueue;
}
public static synchronized SingletonRequestQueue getmInstance(Context context) {
if(mInstance == null){
mInstance = new SingletonRequestQueue(context);
}
return mInstance;
}
public<T> void addRequestQueue(Request<T> request){
requestQueue.add(request);
}
}
build.gradle (module)
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
applicationId "com.ticketapp.myName.ticketapp"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
//FB SDK
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.+'
// compile 'com.android.support:design:26.0.1'
// compile 'com.android.support:appcompat-v7:26.0.1'
// compile 'com.android.support:multidex:1.0.1'
// Firebase
// Volley
// compile 'com.android.volley:volley:1.0.0'
compile 'com.facebook.android:facebook-android-sdk:[4,5)'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.firebase:firebase-auth:11.2.2'
compile 'com.mcxiaoke.volley:library:1.0.19'
//compile "com.google.android.gms:play-services-location:11.2.2"
testCompile 'junit:junit:4.12'
}
// Add to the bottom of the file
apply plugin: 'com.google.gms.google-services'
build.gradle (app)
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
//FB SDK
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
// Add this line
classpath 'com.google.gms:google-services:3.1.0'
}
}
allprojects {
repositories {
jcenter()
//FB SDK
maven {
url "https://maven.google.com" // Google's Maven repository
}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
logcat message
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ticketapp.myname.ticketapp, PID: 9650
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.ticketapp.myname.ticketapp/com.ticketapp.myname.ticketapp.MainActivity}: android.view.InflateException: Binary XML file line #14: Binary XML file line #14: Error inflating class com.facebook.login.widget.LoginButton
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
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)
Caused by: android.view.InflateException: Binary XML file line #14: Binary XML file line #14: Error inflating class com.facebook.login.widget.LoginButton
Caused by: android.view.InflateException: Binary XML file line #14: Error inflating class com.facebook.login.widget.LoginButton
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
at android.view.LayoutInflater.createView(LayoutInflater.java:647)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.ticketapp.myname.ticketapp.MainActivity.onCreate(MainActivity.java:49)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
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)
Caused by: The SDK has not been initialized, make sure to call FacebookSdk.sdkInitialize() first.
at com.facebook.internal.Validate.sdkInitialized(Validate.java:145)
at com.facebook.AccessTokenTracker.<init>(AccessTokenTracker.java:55)
at com.facebook.login.widget.LoginButton$2.<init>(LoginButton.java:581)
at com.facebook.login.widget.LoginButton.configureButton(LoginButton.java:581)
at com.facebook.FacebookButtonBase.<init>(FacebookButtonBase.java:64)
at com.facebook.login.widget.LoginButton.<init>(LoginButton.java:210)
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
at android.view.LayoutInflater.createView(LayoutInflater.java:647)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.ticketapp.myname.ticketapp.MainActivity.onCreate(MainActivity.java:49)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
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)
Manifest
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="#string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="Secretokrn" />
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name"
android:screenOrientation="portrait" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="com.facebook.FacebookContentProvider"
android:authorities="com.facebook.app.FacebookContentProviderSecretToken"
android:exported="true" />
<activity android:name=".LoginActivity"></activity>
</application>
strings.xml
<resources>
<string name="app_name">TicketApp</string>
<string name="facebook_app_id">SecretToken</string>
<string name="fb_login_protocol_scheme">fbSecretToken</string>
<string name="app_id">$app_id_here</string>
<string name="ShareContent">Share Content</string>
<string name="Posts">Posts</string>
<string name="Logout">Logout</string>
<string name="Hello">Hello</string>
</resources>
I hope I have included enough for a replicating this or solving it without testing.
Updated catlog.
09-12 15:13:21.988 5675-5675/com.ticketapp.myname.ticketapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ticketapp.myname.ticketapp, PID: 5675
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.ticketapp.myname.ticketapp/com.ticketapp.myname.ticketapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at com.ticketapp.myname.ticketapp.MainActivity.onCreate(MainActivity.java:76)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
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)
Ok guys! New update! Apparently there was an issue in the code so I put a try and catch and the application worked. Unfortunately when u log in nothing displays at the moment. This is what I changed in the MainActivity.java
try {
name = inBundle.getString("name");
surname = inBundle.getString("surname");
imageUrl = inBundle.getString("imageUrl");
TextView nameView = (TextView) findViewById(R.id.nameAndSurname);
nameView.setText("" + name + " " + surname);
} catch (Exception e){
Log.e("Error on setContent", e.getMessage());
}
In your MainActivity, you have this:
Bundle inBundle = getIntent().getExtras();
name = inBundle.getString("name");
surname = inBundle.getString("surname");
imageUrl = inBundle.getString("imageUrl");
But the first time you load it, inBundle will be null. You should check if it is null before running getString on it:
Bundle inBundle = getIntent().getExtras();
if(inBundle!=null){
name = inBundle.getString("name");
surname = inBundle.getString("surname");
imageUrl = inBundle.getString("imageUrl");
}