Android Studio Page Spitter - java

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

Related

Android app. Connecting to firebase and wanting to get data from it app crashes

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);
}
}

App stopped after first launch, but no errors

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

Implementing RecyclerView to show the contacts of the device, using ContactsContract but there is error. I've involved the gradle error code below

I have tried to show the device contacts in the recyclerview. I'm using ContactsContract to populate the list. I think the error is that the contacts are not being fetched but I don't know why.
Can you please check my mistake?
Error:
10-11 17:50:21.550 27076-27076/com.example.anubh.contactsearch D/Proxy: setHttpRequestCheckHandler
10-11 17:50:21.694 27076-27076/com.example.anubh.contactsearch D/OpenSSLLib: OpensslErr:Module:13(114:155); file:external/openssl/crypto/asn1/asn1_lib.c ;Line:142;Function:ASN1_get_object
10-11 17:50:22.532 27076-27076/com.example.anubh.contactsearch D/ActivityThread: BIND_APPLICATION handled : 0 / AppBindData{appInfo=ApplicationInfo{14eaff4b com.example.anubh.contactsearch}}
10-11 17:50:22.533 27076-27076/com.example.anubh.contactsearch V/ActivityThread: Handling launch of ActivityRecord{d9bd28 token=android.os.BinderProxy#2947ea41 {com.example.anubh.contactsearch/com.example.anubh.contactsearch.MainActivity}}
10-11 17:50:22.803 27076-27076/com.example.anubh.contactsearch V/ActivityThread: ActivityRecord{d9bd28 token=android.os.BinderProxy#2947ea41 {com.example.anubh.contactsearch/com.example.anubh.contactsearch.MainActivity}}: app=android.app.Application#4684527, appName=com.example.anubh.contactsearch, pkg=com.example.anubh.contactsearch, comp={com.example.anubh.contactsearch/com.example.anubh.contactsearch.MainActivity}, dir=/data/app/com.example.anubh.contactsearch-1/base.apk
10-11 17:50:22.941 27076-27076/com.example.anubh.contactsearch W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
10-11 17:50:23.147 27076-27076/com.example.anubh.contactsearch I/AppCompatViewInflater: app:theme is now deprecated. Please move to using android:theme instead.
10-11 17:50:23.440 27076-27076/com.example.anubh.contactsearch D/ActivityThread: hoder:android.app.IActivityManager$ContentProviderHolder#36d02546,provider,holder.Provider:android.content.ContentProviderProxy#1c1f6307
10-11 17:50:23.482 27076-27076/com.example.anubh.contactsearch I/System.out: Name: Micromax carephone: 18605008286
10-11 17:50:23.486 27076-27076/com.example.anubh.contactsearch D/AndroidRuntime: Shutting down VM
10-11 17:50:23.487 27076-27076/com.example.anubh.contactsearch E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.anubh.contactsearch, PID: 27076
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anubh.contactsearch/com.example.anubh.contactsearch.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2455)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2517)
at android.app.ActivityThread.access$800(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1412)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:189)
at android.app.ActivityThread.main(ActivityThread.java:5530)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
at com.example.anubh.contactsearch.myAdapter.<init>(myAdapter.java:71)
at com.example.anubh.contactsearch.MainActivity.onCreate(MainActivity.java:30)
at android.app.Activity.performCreate(Activity.java:5966)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2408)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2517) 
at android.app.ActivityThread.access$800(ActivityThread.java:162) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1412) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:189) 
at android.app.ActivityThread.main(ActivityThread.java:5530) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745) 
10-11 17:50:29.394 27076-27089/com.example.anubh.contactsearch W/CursorWrapperInner: Cursor finalized without prior close()
MainActivity.java
package com.example.anubh.contactsearch;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
RecyclerView recyclerView;
myAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//getSupportActionBar().setTitle("Contacts");
getSupportActionBar().setSubtitle("Search");
getSupportActionBar().setIcon(R.drawable.ic_action_toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
adapter = new myAdapter(this);
recyclerView.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
return super.onCreateOptionsMenu(menu);
}
}
myAdapter.java
package com.example.anubh.contactsearch;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.List;
public class myAdapter extends RecyclerView.Adapter<ListViewHolder>{
private List<ListItems> listItemsList;
private Context mContext;
private int focusedItem = 0;
public myAdapter(Context context){
mContext = context;
ContentResolver cr = mContext.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
String name;
String phone = null;
String image_uri = "";
ListItems listItems;
int i = 1;
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
if(i == 1){
cur.moveToFirst();
i++;
}
String id = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
image_uri = cur
.getString(cur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[]{id}, null);
if (pCur.moveToNext()) {
phone = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println("Name: "+ name + "phone: " + phone);
}
pCur.close();
listItems = new ListItems(name,phone,image_uri);
listItemsList.add(listItems);
}
cur.close();
}
}
#Override
public ListViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
Context context = viewGroup.getContext();
LayoutInflater layoutInflater = LayoutInflater.from(context);
View v = layoutInflater.inflate(R.layout.list_row,null);
//View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row,null);
ListViewHolder holder = new ListViewHolder(v);
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
return holder;
}
#Override
public void onBindViewHolder(ListViewHolder holder, int position) {
ListItems listItems = listItemsList.get(position);
TextView contact_name = holder.contactname;
TextView contact_num = holder.contactnum;
ImageView contact_image = holder.contactimage;
contact_name.setText(listItems.getContactname());
contact_num.setText(listItems.getContactnum());
Uri myuri = Uri.parse(listItems.getThumbnail());
InputStream photo_stream = ContactsContract.Contacts.openContactPhotoInputStream(mContext.getContentResolver(),myuri);
BufferedInputStream buf =new BufferedInputStream(photo_stream);
Bitmap my_btmp = BitmapFactory.decodeStream(buf);
contact_image.setImageBitmap(my_btmp);
}
#Override
public int getItemCount() {
return listItemsList.size();
}
}
ListViewHolder.java
package com.example.anubh.contactsearch;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class ListViewHolder extends RecyclerView.ViewHolder {
protected ImageView contactimage;
protected TextView contactname,contactnum;
protected RelativeLayout relativeLayout;
public ListViewHolder(View view){
super(view);
contactimage = (ImageView)view.findViewById(R.id.contactimage);
contactname = (TextView) view.findViewById(R.id.contactname);
contactnum = (TextView) view.findViewById(R.id.contactno);
relativeLayout = (RelativeLayout) view.findViewById(R.id.relativeLayout);
view.setClickable(false);
}
}
ListItems.java
package com.example.anubh.contactsearch;
public class ListItems {
private String Contactname,contactnum,thumbnail;
public ListItems(String name,String number,String imageuri){
this.Contactname = name;
this.contactnum = number;
this.thumbnail = imageuri;
}
public String getContactname() {
return Contactname;
}
public void setContactname(String contactname) {
Contactname = contactname;
}
public String getContactnum() {
return contactnum;
}
public void setContactnum(String contactnum) {
this.contactnum = contactnum;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.anubh.contactsearch">
<uses-permission android:name="android.permission.READ_CONTACTS" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.Main" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="android.app.searchable"
android:resource="#xml/searchable"/>
</activity>
</application>
</manifest>
Add this line to "myAdapter" constructor.
listItemsList = new ArrayList<>();
I know this is an old thread, but I have checked your code because I am doing something similar. I saw you had problems with RecyclerView not showing anything, and the problem might be in how you handle your ListItems object.
First of all, you've forgotten about the layout manager in MainActivity.java:
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
Second, you have no checks to determine if a user even has an image, because in case it doesn't, you will receive a null pointer exception error. When you store a null value in your thumbnail variable, later trying to access it in the adapter
Uri myuri = Uri.parse(listItems.getThumbnail());
there is a simple check missing, for example
if (listItems.getThumbnail() != null) {
Uri myuri = Uri.parse(listItems.getThumbnail());
InputStream photo_stream = ContactsContract.Contacts.openContactPhotoInputStream(mContext.getContentResolver(),myuri);
BufferedInputStream buf =new BufferedInputStream(photo_stream);
Bitmap my_btmp = BitmapFactory.decodeStream(buf);
contact_image.setImageBitmap(my_btmp);
} else {
// Find an alternative method, like displaying custom ImageView with name initials
}
Finally, I would like to point out a redundant if statement in adapter's constructor
if(i == 1){
cur.moveToFirst();
i++;
}
There is no need to make an additional check, you can simply say
cur.moveToFirst();

My android studio project works finely on lollipop but crashes while testing on kitkat devices

My android studio project works finely on lollipop but crashes while testing on kitkat devices. it has a material view pager and while opening activity that has material view pager the app just force close on kit kat device.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.production.iedc.helo, PID: 12711
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.production.iedc.helo/com.production.iedc.helo.MainActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2338)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at android.support.v7.app.AppCompatDelegateImplV7.createSubDecor(AppCompatDelegateImplV7.java:310)
at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:279)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:253)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at com.production.iedc.helo.MainActivity.onCreate(MainActivity.java:80)
at android.app.Activity.performCreate(Activity.java:5264)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2302)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) 
at android.os.Handler.dispatchMessage(Handler.java:110) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:5292) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640) 
at dalvik.system.NativeStart.main(Native Method) 
Build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.production.iedc.helo"
minSdkVersion 14
targetSdkVersion 23
versionCode 1
versionName "1.0"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile ('com.github.florent37:materialviewpager:1.0.8#aar'){
transitive=true
}
compile 'com.squareup.picasso:picasso:2.3.3'
compile 'com.github.paolorotolo:appintro:3.4.0'
compile 'com.android.support:multidex:1.0.0'
}
Main activity
package com.production.iedc.helo;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.media.Image;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toolbar;
import com.github.florent37.materialviewpager.MaterialViewPager;
import com.squareup.picasso.Picasso;
public class MainActivity extends ActionBarActivity {
MaterialViewPager materialViewPager;
View headerLogo;
ImageView headerLogoContent;
DrawerLayout mDrawer;
ActionBarDrawerToggle mDrawerToggle;
android.support.v7.widget.Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Declare a new thread to do a preference check
Thread t = new Thread(new Runnable() {
#Override
public void run() {
// Initialize SharedPreferences
SharedPreferences getPrefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
// Create a new boolean and preference and set it to true
boolean isFirstStart = getPrefs.getBoolean("firstStart", true);
// If the activity has never started before...
if (isFirstStart) {
// Launch app intro
Intent i = new Intent(MainActivity.this, DefaultIntro.class);
startActivity(i);
// Make a new preferences editor
SharedPreferences.Editor e = getPrefs.edit();
// Edit preference to make it false because we don't want this to run again
e.putBoolean("firstStart", false);
// Apply changes
e.apply();
}
}
});
// Start the thread
t.start();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//4 onglets
final int tabCount = 4;
//les vues définies dans #layout/header_logo
headerLogo = findViewById(R.id.headerLogo);
headerLogoContent = (ImageView) findViewById(R.id.headerLogoContent);
//le MaterialViewPager
this.materialViewPager = (MaterialViewPager) findViewById(R.id.materialViewPager);
toolbar = materialViewPager.getToolbar();
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (toolbar != null) {
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setHomeButtonEnabled(true);
}
}
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawer, 0, 0);
mDrawer.setDrawerListener(mDrawerToggle);
materialViewPager.getViewPager().setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
#Override
public Fragment getItem(int position) {
//je créé pour chaque onglet un RecyclerViewFragment
return RecyclerViewFragment.newInstance();
}
#Override
public int getCount() {
return 4;
}
//le titre à afficher pour chaque page
#Override
public CharSequence getPageTitle(int position) {
switch (position % 4) {
case 0:
return "ACADEMICS";
case 1:
return "NEWS FEEDS";
case 2:
return "EVENTS";
case 3:
return "MISC";
default:
return "Page " + position;
}
}
int oldItemPosition = -1;
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
//seulement si la page est différente
if (oldItemPosition != position) {
oldItemPosition = position;
//définir la nouvelle couleur et les nouvelles images
Drawable imageUrl = null;
int color = Color.BLACK;
Drawable newDrawable = null;
switch (position) {
case 0:
imageUrl = getResources().getDrawable(R.drawable.academics);
color = getResources().getColor(R.color.cyan);
newDrawable = getResources().getDrawable(R.drawable.earth);
break;
case 1:
imageUrl = getResources().getDrawable(R.drawable.newsfeeds);
color = getResources().getColor(R.color.red);
newDrawable = getResources().getDrawable(R.drawable.tennis);
break;
case 2:
imageUrl = getResources().getDrawable(R.drawable.events);
color = getResources().getColor(R.color.green);
newDrawable = getResources().getDrawable(R.drawable.evennt);
break;
case 3:
imageUrl = getResources().getDrawable(R.drawable.misc);
color = getResources().getColor(R.color.lime);
newDrawable = getResources().getDrawable(R.drawable.light);
break;
}
//puis modifier les images/couleurs
int fadeDuration = 400;
materialViewPager.setColor(color, fadeDuration);
materialViewPager.setImageDrawable(imageUrl, fadeDuration);
toggleLogo(newDrawable,color,fadeDuration);
}
}
});
//permet au viewPager de garder 4 pages en mémoire (à ne pas utiliser sur plus de 4 pages !)
this.materialViewPager.getViewPager().setOffscreenPageLimit(tabCount);
//relie les tabs au viewpager
this.materialViewPager.getPagerTitleStrip().setViewPager(this.materialViewPager.getViewPager());
}
private void toggleLogo(final Drawable newLogo, final int newColor, int duration){
//animation de disparition
final AnimatorSet animatorSetDisappear = new AnimatorSet();
animatorSetDisappear.setDuration(duration);
animatorSetDisappear.playTogether(
ObjectAnimator.ofFloat(headerLogo, "scaleX", 0),
ObjectAnimator.ofFloat(headerLogo, "scaleY", 0)
);
//animation d'apparition
final AnimatorSet animatorSetAppear = new AnimatorSet();
animatorSetAppear.setDuration(duration);
animatorSetAppear.playTogether(
ObjectAnimator.ofFloat(headerLogo, "scaleX", 1),
ObjectAnimator.ofFloat(headerLogo, "scaleY", 1)
);
//après la disparition
animatorSetDisappear.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
//modifie la couleur du cercle
((GradientDrawable) headerLogo.getBackground()).setColor(newColor);
//modifie l'image contenue dans le cercle
headerLogoContent.setImageDrawable(newLogo);
//démarre l'animation d'apparition
animatorSetAppear.start();
}
});
//démarre l'animation de disparition
animatorSetDisappear.start();
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return mDrawerToggle.onOptionsItemSelected(item) ||
super.onOptionsItemSelected(item);
}
}
Activitylayout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.github.florent37.materialviewpager.MaterialViewPager
android:id="#+id/materialViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:viewpager_logo="#layout/header_logo"
app:viewpager_pagerTitleStrip="#layout/material_view_pager_pagertitlestrip_newstand"
app:viewpager_logoMarginTop="100dp"
app:viewpager_color="#color/colorPrimary"
app:viewpager_headerHeight="200dp"
app:viewpager_headerAlpha="0.6"
app:viewpager_hideLogoWithFade="false"
app:viewpager_hideToolbarAndTitle="true"
app:viewpager_enableToolbarElevation="true"
app:viewpager_parallaxHeaderFactor="1.5"
app:viewpager_headerAdditionalHeight="20dp"
app:viewpager_displayToolbarWhenSwipe="true"
app:viewpager_transparentToolbar="true"
app:viewpager_animatedHeaderImage="true"
/>
<include layout="#layout/drawer" />
</android.support.v4.widget.DrawerLayout>
you should change the inheritance of java use
ActionBarActivity
to
Activity
and leave the dialog theme in the manifest as it is. i think you will not have the problem.

java.lang.NoSuchFieldError: android.support.v4.app.Watson.mFragments

I'm trying to implement ActionBarSherlock swipe menu as I like how this animation slides over the slide menu. Unfortunately I keep getting this error and haven't been able to solve it.
This guy is getting the same error but none of the answers on this solves my problem. Android: java.land.NoSuchFieldError after update to SDK 23
Here is my Gradle file.
buildscript {
repositories {
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
classpath 'io.fabric.tools:gradle:1.+'
}
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'com.google.gms.google-services'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.myegotest.ego_17012016"
minSdkVersion 14
targetSdkVersion 23
versionCode 1
versionName "1.0"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
mavenCentral()
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
//compile 'com.android.support:appcompat-v7:23.1.1'
//compile 'com.android.support:design:23.1.1'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.facebook.android:facebook-android-sdk:4.9.0'
compile('com.twitter.sdk.android:twitter:1.12.0#aar') {
transitive = true;
}
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
//compile 'com.android.support:multidex:1.0.1'
compile "com.android.support:support-v4:23.1.1"
compile 'com.squareup.okhttp:okhttp:2.5.0'
compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.google.android.gms:play-services-auth:8.3.0'
compile project(':SlidingMenuLib-master')
}
Here is the activity trying to implement the SlidingMenu.
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Toast;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import com.myegotest.ego_17012016.ProfileFragments.InterestsPageFragment;
import com.myegotest.ego_17012016.ProfileFragments.ProfilePageFragment;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.MalformedInputException;
import Library.LocalDataBase;
import Library.User;
public class MainActivity extends SlidingFragmentActivity {
//View item variables
ViewPager mPager;
//Other variables
private String firstName;
private String lastName;
private String username;
String profilepic;
LocalDataBase mLocalDataBase;
//The pager adapter, which provides the pages to the view pager widget.
private PagerAdapter mPagerAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get logged in user from LocalDataBase and
//Destroy Activity if user is logged out
mLocalDataBase = new LocalDataBase(this);
User user = mLocalDataBase.getLoggedInUserInfo();
if(!mLocalDataBase.userIsLoggedIn()){
MainActivity.this.finish();
}
setBehindContentView(R.layout.menu_frame);
//Get loggedIn user values from the LocalDataBase .
firstName = user.mFirstName;
lastName = user.mLastName;
username = user.mUsername;
//Capitalize 1st letter of the following variable.
firstName = capitalizeFirstCharacter(firstName);
lastName = capitalizeFirstCharacter(lastName);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.myViewPager);
mPager.setPageTransformer(true, new ZoomOutPageTransformer());
netAsync();
}
//Method to capitalize 1st letter of the String thats using this method.
private String capitalizeFirstCharacter(String textInput){
String input = textInput.toLowerCase();
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
return output;
}
/**
* A simple pager adapter that represents 2 ScreenSlidePageFragment objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position){
case 1:
return new InterestsPageFragment();
default: break;
}
return ProfilePageFragment.newInstance(firstName, lastName, profilepic);
}
#Override
public int getCount() {
return 2;
}
}
//Animation for swiping between page views
public class ZoomOutPageTransformer implements ViewPager.PageTransformer {
private static final float MIN_SCALE = 0.85f;
private static final float MIN_ALPHA = 0.5f;
public void transformPage(View view, float position) {
int pageWidth = view.getWidth();
int pageHeight = view.getHeight();
if (position < -1) { // [-Infinity,-1)
// This page is way off-screen to the left.
view.setAlpha(0);
} else if (position <= 1) { // [-1,1]
// Modify the default slide transition to shrink the page as well
float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
float vertMargin = pageHeight * (1 - scaleFactor) / 2;
float horzMargin = pageWidth * (1 - scaleFactor) / 2;
if (position < 0) {
view.setTranslationX(horzMargin - vertMargin / 2);
} else {
view.setTranslationX(-horzMargin + vertMargin / 2);
}
// Scale the page down (between MIN_SCALE and 1)
view.setScaleX(scaleFactor);
view.setScaleY(scaleFactor);
// Fade the page relative to its size.
view.setAlpha(MIN_ALPHA +
(scaleFactor - MIN_SCALE) /
(1 - MIN_SCALE) * (1 - MIN_ALPHA));
} else { // (1,+Infinity]
// This page is way off-screen to the right.
view.setAlpha(0);
}
}
}
}
Finally, here is the error I am getting.
E/AndroidRuntime: FATAL EXCEPTION: main
E/AndroidRuntime: Process: com.myegotest.ego_17012016, PID: 8545
E/AndroidRuntime: java.lang.NoSuchFieldError: android.support.v4.app.Watson.mFragments
E/AndroidRuntime: at android.support.v4.app.Watson.onCreatePanelMenu(Watson.java:50)
E/AndroidRuntime: at com.actionbarsherlock.ActionBarSherlock.callbackCreateOptionsMenu(ActionBarSherlock.java:560)
E/AndroidRuntime: at com.actionbarsherlock.internal.ActionBarSherlockNative.dispatchCreateOptionsMenu(ActionBarSherlockNative.java:64)
E/AndroidRuntime: at com.actionbarsherlock.app.SherlockFragmentActivity.onCreatePanelMenu(SherlockFragmentActivity.java:164)
E/AndroidRuntime: at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:486)
E/AndroidRuntime: at com.android.internal.policy.impl.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:855)
E/AndroidRuntime: at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:271)
E/AndroidRuntime: at android.view.Choreographer$CallbackRecord.run(Choreographer.java:803)
E/AndroidRuntime: at android.view.Choreographer.doCallbacks(Choreographer.java:603)
E/AndroidRuntime: at android.view.Choreographer.doFrame(Choreographer.java:572)
E/AndroidRuntime: at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:789)
E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:733)
E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
E/AndroidRuntime: at android.os.Looper.loop(Looper.java:157)
E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5293)
E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
I/Process: Sending signal. PID: 8545 SIG: 9
I was able to solve the problem by removing the facebook sdk from my gradle file. Since i need the facebook sdk, i was able to get around this by making MainActivity just extend FragmentActivity instead of SlidingFragmentActivty. I made this inner class inside of MainActivty to extend SlidingActivity, that way i can still use the methods i need.
private class SlidingMenuClass extends SlidingActivity {
private SlidingMenu sm;
public SlidingMenuClass(Context ctx){
sm = new SlidingMenu(ctx);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setBehindContentView(R.layout.menu_frame);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
sm = getSlidingMenu();
sm.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
sm.setShadowWidthRes(R.dimen.shadow_width);
//sm.setShadowDrawable(R.drawable.shadow);
sm.setFadeDegree(1f);
sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
sm.setBehindOffsetRes(R.dimen.behindoffsetRes);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggle();
return true;
}
return super.onOptionsItemSelected(item);
}
}

Categories

Resources