I am following slidenerd Material design tutorial(Android RecyclerView Example part1,2,3,4) & I am using real device to test my android application.I have successfully build navigation drawer & when I try to add RecylerView into it by adding adapter (ThalakazAdapter.java) , app unfortunately get stopped.
This is my NavigationDrawerFragment.java
package com.thaalakaz.nadeesha.materialdesignapp1;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
//import android.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.app.Fragment;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class NavigationDrawerFragment extends Fragment {
private RecyclerView recyclerView;
public static final String PREF_FILE_NAME = "testpref";
public static final String KAY_USER_LEARNED_DRAWER ="user_learned_drawer";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ThalakazAdapter adapter;
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
private View containerView;
public NavigationDrawerFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUserLearnedDrawer=Boolean.valueOf(readFromPreferences(getActivity(),KAY_USER_LEARNED_DRAWER,"false"));
if (savedInstanceState != null){
mFromSavedInstanceState = true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawer_layout);
adapter = new ThalakazAdapter(getActivity(),getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return layout;
}
public static List<Information> getData(){
List<Information> data = new ArrayList<>();
int[] icons ={R.drawable.ic_m,R.drawable.ic_m1,R.drawable.ic_m2,R.drawable.ic_m3};
String[] titles = {"Nadeesha","Thilakarathne","Semini","Roshani"};
for (int i=0;i<titles.length && i<icons.length;i++){
Information current = new Information();
current.iconId = icons[i];
current.titlel = titles[i];
data.add(current);
}
return data;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(),drawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if(!mUserLearnedDrawer){
mUserLearnedDrawer = true;
saveToPreferences(getActivity(),KAY_USER_LEARNED_DRAWER,mUserLearnedDrawer+"");
}
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
if (slideOffset<0.6){
toolbar.setAlpha(1-slideOffset);
}
}
};
if (!mUserLearnedDrawer && mFromSavedInstanceState){
mDrawerLayout.openDrawer(containerView);
}
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static void saveToPreferences(Context context,String prferenceName,String preferenceValue){
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(prferenceName,preferenceValue);
editor.apply();
}
public static String readFromPreferences(Context context,String prferenceName,String defaultValue){
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME,Context.MODE_PRIVATE);
return sharedPreferences.getString(prferenceName,defaultValue);
}
}
This is my Adapter (ThalakazAdapter.java)
package com.thaalakaz.nadeesha.materialdesignapp1;
import android.content.Context;
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.ListView;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
/**
* Created by hp on 7/22/2015.
*/
public class ThalakazAdapter extends RecyclerView.Adapter <ThalakazAdapter.myViewHolder>{
private LayoutInflater inflater;
List<Information> data = Collections.emptyList();
public ThalakazAdapter(Context context, List<Information> data){
inflater=LayoutInflater.from(context);
this.data = data;
}
#Override
public myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.custom_row, parent, false);
myViewHolder holder = new myViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(myViewHolder holder, int position) {
Information current = data.get(position);
holder.title.setText(current.titlel);
holder.icon.setImageResource(current.iconId);
}
#Override
public int getItemCount() {
return 0;
}
class myViewHolder extends RecyclerView.ViewHolder{
ImageView icon;
TextView title;
public myViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.listText);
icon = (ImageView) itemView.findViewById(R.id.listIcon);
}
}
}
My information.java class
package com.thaalakaz.nadeesha.materialdesignapp1;
/**
* Created by hp on 7/22/2015.
*/
public class Information {
int iconId;
String titlel;
}
You can view my entire project from here
Logcat
07-21 22:32:07.101 7099-7099/com.thaalakaz.nadeesha.materialdesignapp1 D/dalvikvm﹕ Late-enabling CheckJNI
07-21 22:32:07.111 7099-7099/com.thaalakaz.nadeesha.materialdesignapp1 I/SystemProperties﹕ get key=ro.kernel.android.tracing
07-21 22:32:07.281 7099-7099/com.thaalakaz.nadeesha.materialdesignapp1 I/dalvikvm﹕ Could not find method android.view.ViewGroup.onRtlPropertiesChanged, referenced from method android.support.v7.widget.Toolbar.onRtlPropertiesChanged
07-21 22:32:07.281 7099-7099/com.thaalakaz.nadeesha.materialdesignapp1 W/dalvikvm﹕ VFY: unable to resolve virtual method 14685: Landroid/view/ViewGroup;.onRtlPropertiesChanged (I)V
07-21 22:32:07.281 7099-7099/com.thaalakaz.nadeesha.materialdesignapp1 D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0007
07-21 22:32:07.301 7099-7099/com.thaalakaz.nadeesha.materialdesignapp1 I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
07-21 22:32:07.301 7099-7099/com.thaalakaz.nadeesha.materialdesignapp1 W/dalvikvm﹕ VFY: unable to resolve virtual method 414: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
07-21 22:32:07.301 7099-7099/com.thaalakaz.nadeesha.materialdesignapp1 D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
07-21 22:32:07.311 7099-7099/com.thaalakaz.nadeesha.materialdesignapp1 I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
07-21 22:32:07.311 7099-7099/com.thaalakaz.nadeesha.materialdesignapp1 W/dalvikvm﹕ VFY: unable to resolve virtual method 436: Landroid/content/res/TypedArray;.getType (I)I
07-21 22:32:07.311 7099-7099/com.thaalakaz.nadeesha.materialdesignapp1 D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
07-21 22:32:07.381 7099-7099/com.thaalakaz.nadeesha.materialdesignapp1 D/AndroidRuntime﹕ Shutting down VM
07-21 22:32:07.381 7099-7099/com.thaalakaz.nadeesha.materialdesignapp1 W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41027208)
07-21 22:32:07.391 7099-7099/com.thaalakaz.nadeesha.materialdesignapp1 E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.thaalakaz.nadeesha.materialdesignapp1/com.thaalakaz.nadeesha.materialdesignapp1.MainActivity}: android.view.InflateException: Binary XML file line #24: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:787)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #24: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:697)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:739)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:742)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:249)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:106)
at com.thaalakaz.nadeesha.materialdesignapp1.MainActivity.onCreate(MainActivity.java:20)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:787)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.thaalakaz.nadeesha.materialdesignapp1.NavigationDrawerFragment.onCreateView(NavigationDrawerFragment.java:63)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:924)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1116)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1218)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2170)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:300)
at android.support.v7.app.AppCompatDelegateImplV7.callActivityOnCreateView(AppCompatDelegateImplV7.java:838)
at android.support.v7.app.AppCompatDelegateImplV11.callActivityOnCreateView(AppCompatDelegateImplV11.java:34)
at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(AppCompatDelegateImplV7.java:826)
at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:668)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:739)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:742)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:249)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:106)
at com.thaalakaz.nadeesha.materialdesignapp1.MainActivity.onCreate(MainActivity.java:20)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:787)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
at dalvik.system.NativeStart.main(Native Method)
fragment_navigation_drawer.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:background="#DADADA"
tools:context="com.thaalakaz.nadeesha.materialdesignapp1.NavigationDrawerFragment">
<LinearLayout
android:id="#+id/containerDrawerImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FF6F00">
<ImageView
android:layout_width="280dp"
android:layout_height="140dp"
android:src = "#drawable/dog"
android:layout_margin="16dp"/>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/drawerList"
android:layout_height="match_parent"
android:layout_width="wrap_content">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
in your onCreateView your are looking for the wrong id. Change
recyclerView = (RecyclerView) layout.findViewById(R.id.drawer_layout);
with
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
I also noticed that in your Adapter's constructor, you are assingn this.data to itself. Change
this.data = this.data;
to
this.data = data
and getItemCount shouldn't return 0, but the size of data (if it is not null)
Related
I am trying to create an Image Slider containing 4 images for my application and i've been running into the following errors. I've tried searching and have found similiar titles but the problems are different.
This is the logcat:
example.prgguru.com.wallit E/AndroidRuntime: FATAL EXCEPTION: main
Process: example.prgguru.com.wallit, PID: 32048
java.lang.RuntimeException: Unable to start activity ComponentInfo{example.prgguru.com.wallit/example.prgguru.com.wallit.MainActivity}: android.view.InflateException: Binary XML file line #3: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2404)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2464)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5653)
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:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #3: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:719)
at android.view.LayoutInflater.inflate(LayoutInflater.java:470)
at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:350)
at android.app.Activity.setContentView(Activity.java:2059)
at example.prgguru.com.wallit.MainActivity.onCreate(MainActivity.java:13)
at android.app.Activity.performCreate(Activity.java:5541)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2368)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2464)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5653)
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:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.app.Fragment$InstantiationException: Trying to instantiate a class example.prgguru.com.wallit.MainActivityFragment that is not a Fragment
at android.app.Fragment.instantiate(Fragment.java:585)
at android.app.Fragment.instantiate(Fragment.java:561)
at android.app.Activity.onCreateView(Activity.java:5066)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:695)
at android.view.LayoutInflater.inflate(LayoutInflater.java:470)
at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:350)
at android.app.Activity.setContentView(Activity.java:2059)
at example.prgguru.com.wallit.MainActivity.onCreate(MainActivity.java:13)
at android.app.Activity.performCreate(Activity.java:5541)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2368)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2464)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5653)
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:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException
at android.app.Fragment.instantiate(Fragment.java:585)
at android.app.Fragment.instantiate(Fragment.java:561)
at android.app.Activity.onCreateView(Activity.java:5066)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:695)
at android.view.LayoutInflater.inflate(LayoutInflater.java:470)
at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:350)
at android.app.Activity.setContentView(Activity.java:2059)
at example.prgguru.com.wallit.MainActivity.onCreate(MainActivity.java:13)
at android.app.Activity.performCreate(Activity.java:5541)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2368)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2464)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5653)
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:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
This is my Main Activity.java:
package example.prgguru.com.wallit;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
This is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:name="example.prgguru.com.wallit.MainActivityFragment"
android:id="#+id/fragment"
tools:layout="#layout/fragment_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#32383d">
<!-- ViewPager -->
<!-- Footer -->
<android.support.v4.view.ViewPager
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/imageviewPager" />
<include layout="#layout/footer"/>
</FrameLayout>
MainActivityFragment.java
package example.prgguru.com.wallit;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivityFragment extends Fragment {
private ViewPager _mViewPager;
private ImageViewPagerAdapter _adapter;
private ImageView _btn1, _btn2, _btn3,_btn4;
public MainActivityFragment() {
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setUpView();
setTab();
onCircleButtonClick();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
private void onCircleButtonClick() {
_btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
_btn1.setImageResource(R.drawable.fill_circle);
_mViewPager.setCurrentItem(0);
}
});
_btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
_btn2.setImageResource(R.drawable.fill_circle);
_mViewPager.setCurrentItem(1);
}
});
_btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
_btn3.setImageResource(R.drawable.fill_circle);
_mViewPager.setCurrentItem(2);
}
});
_btn4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
_btn4.setImageResource(R.drawable.fill_circle);
_mViewPager.setCurrentItem(3);
}
});
}
private void setUpView() {
_mViewPager = (ViewPager) getView().findViewById(R.id.imageviewPager);
_adapter = new ImageViewPagerAdapter(getActivity(), getFragmentManager());
_mViewPager.setAdapter(_adapter);
_mViewPager.setCurrentItem(0);
initButton();
}
private void setTab() {
_mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int position) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
_btn1.setImageResource(R.drawable.holo_circle);
_btn2.setImageResource(R.drawable.holo_circle);
_btn3.setImageResource(R.drawable.holo_circle);
_btn4.setImageResource(R.drawable.holo_circle);
btnAction(position);
}
});
}
private void btnAction(int action) {
switch (action) {
case 0:
_btn1.setImageResource(R.drawable.fill_circle);
break;
case 1:
_btn2.setImageResource(R.drawable.fill_circle);
break;
case 2:
_btn3.setImageResource(R.drawable.fill_circle);
break;
case 3:
_btn4.setImageResource(R.drawable.fill_circle);
break;
}
}
private void initButton() {
_btn1 = (ImageView) getView().findViewById(R.id.btn1);
_btn1.setImageResource(R.drawable.fill_circle);
_btn2 = (ImageView) getView().findViewById(R.id.btn2);
_btn3 = (ImageView) getView().findViewById(R.id.btn3);
_btn4 = (ImageView) getView().findViewById(R.id.btn4);
}
private void setButton(Button btn, String text, int h, int w) {
btn.setWidth(w);
btn.setHeight(h);
btn.setText(text);
}
}
Your Activity extends from Activity and not AppCompatActivity. But your fragment extends from android.support.v4.app.Fragment. You must use one type of fragment: from support library or normal one.
Try to change extends Fragment from android.app.Fragment in your fragment class.
so I am having trouble locating where in my code I have gone wrong. I am building an audio player. The function cannot find all audio files in my device except 2 of them. I am thinking the problem may lie somewhere in my song locating algorithm, findSongs.
Here is my log cat:
03-17 15:29:24.492 20066-20066/? I/SELinux﹕ Function: selinux_android_load_priority , priority [3] , priority version is VE=SEPF_SGH-M919_4.4.4_0048
03-17 15:29:24.492 20066-20066/? E/dalvikvm﹕ >>>>> Normal User
03-17 15:29:24.492 20066-20066/? E/dalvikvm﹕ >>>>> com.example.joe.audiodomain [ userId:0 | appId:10237 ]
03-17 15:29:24.492 20066-20066/? D/dalvikvm﹕ Late-enabling CheckJNI
03-17 15:29:24.632 20066-20066/? W/dalvikvm﹕ VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
03-17 15:29:24.632 20066-20066/? I/dalvikvm﹕ Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.view.WindowCallbackWrapper.onSearchRequested
03-17 15:29:24.632 20066-20066/? W/dalvikvm﹕ VFY: unable to resolve interface method 15027: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
03-17 15:29:24.632 20066-20066/? D/dalvikvm﹕ VFY: replacing opcode 0x72 at 0x0002
03-17 15:29:24.632 20066-20066/? I/dalvikvm﹕ Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.view.WindowCallbackWrapper.onWindowStartingActionMode
03-17 15:29:24.632 20066-20066/? W/dalvikvm﹕ VFY: unable to resolve interface method 15031: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
03-17 15:29:24.632 20066-20066/? D/dalvikvm﹕ VFY: replacing opcode 0x72 at 0x0002
03-17 15:29:24.702 20066-20066/? I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.widget.TintTypedArray.getChangingConfigurations
03-17 15:29:24.702 20066-20066/? W/dalvikvm﹕ VFY: unable to resolve virtual method 396: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
03-17 15:29:24.702 20066-20066/? D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
03-17 15:29:24.702 20066-20066/? I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.widget.TintTypedArray.getType
03-17 15:29:24.702 20066-20066/? W/dalvikvm﹕ VFY: unable to resolve virtual method 418: Landroid/content/res/TypedArray;.getType (I)I
03-17 15:29:24.702 20066-20066/? D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
03-17 15:29:24.712 20066-20066/? E/VdcInflateDelegate﹕ Exception while inflating <vector>
org.xmlpull.v1.XmlPullParserException: Binary XML file line #17<vector> tag requires viewportWidth > 0
at android.support.graphics.drawable.VectorDrawableCompat.updateStateFromTypedArray(VectorDrawableCompat.java:535)
at android.support.graphics.drawable.VectorDrawableCompat.inflate(VectorDrawableCompat.java:472)
at android.support.graphics.drawable.VectorDrawableCompat.createFromXmlInner(VectorDrawableCompat.java:436)
at android.support.v7.widget.AppCompatDrawableManager$VdcInflateDelegate.createFromXmlInner(AppCompatDrawableManager.java:829)
at android.support.v7.widget.AppCompatDrawableManager.loadDrawableFromDelegates(AppCompatDrawableManager.java:303)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:178)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:173)
at android.support.v7.widget.TintTypedArray.getDrawable(TintTypedArray.java:60)
at android.support.v7.widget.Toolbar.<init>(Toolbar.java:254)
at android.support.v7.widget.Toolbar.<init>(Toolbar.java:196)
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at android.view.LayoutInflater.createView(LayoutInflater.java:600)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:702)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)
at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
at android.support.v7.app.AppCompatDelegateImplV7.createSubDecor(AppCompatDelegateImplV7.java:379)
at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:300)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:264)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:129)
at com.example.joe.audiodomain.MainActivity.onCreate(MainActivity.java:25)
at android.app.Activity.performCreate(Activity.java:5585)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2400)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2495)
at android.app.ActivityThread.access$900(ActivityThread.java:170)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5635)
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:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
03-17 15:29:24.712 20066-20066/? D/AndroidRuntime﹕ Shutting down VM
03-17 15:29:24.712 20066-20066/? W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41845da0)
03-17 15:29:24.712 20066-20066/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.joe.audiodomain, PID: 20066
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.joe.audiodomain/com.example.joe.audiodomain.MainActivity}: android.view.InflateException: Binary XML file line #36: Error inflating class android.support.v7.widget.Toolbar
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2436)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2495)
at android.app.ActivityThread.access$900(ActivityThread.java:170)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5635)
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:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #36: Error inflating class android.support.v7.widget.Toolbar
at android.view.LayoutInflater.createView(LayoutInflater.java:626)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:702)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)
at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
at android.support.v7.app.AppCompatDelegateImplV7.createSubDecor(AppCompatDelegateImplV7.java:379)
at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:300)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:264)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:129)
at com.example.joe.audiodomain.MainActivity.onCreate(MainActivity.java:25)
at android.app.Activity.performCreate(Activity.java:5585)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2400)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2495)
at android.app.ActivityThread.access$900(ActivityThread.java:170)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5635)
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:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at android.view.LayoutInflater.createView(LayoutInflater.java:600)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:702)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)
at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
at android.support.v7.app.AppCompatDelegateImplV7.createSubDecor(AppCompatDelegateImplV7.java:379)
at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:300)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:264)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:129)
at com.example.joe.audiodomain.MainActivity.onCreate(MainActivity.java:25)
at android.app.Activity.performCreate(Activity.java:5585)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2400)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2495)
at android.app.ActivityThread.access$900(ActivityThread.java:170)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5635)
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:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: File res/drawable-v19/abc_ic_ab_back_material.xml from drawable resource ID #0x7f020016
at android.content.res.Resources.loadDrawable(Resources.java:3439)
at android.content.res.Resources.getDrawable(Resources.java:1893)
at android.support.v7.widget.TintResources.superGetDrawable(TintResources.java:48)
at android.support.v7.widget.AppCompatDrawableManager.onDrawableLoadedFromResources(AppCompatDrawableManager.java:374)
at android.support.v7.widget.TintResources.getDrawable(TintResources.java:44)
at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:323)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:180)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:173)
at android.support.v7.widget.TintTypedArray.getDrawable(TintTypedArray.java:60)
at android.support.v7.widget.Toolbar.<init>(Toolbar.java:254)
at android.support.v7.widget.Toolbar.<init>(Toolbar.java:196)
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at android.view.LayoutInflater.createView(LayoutInflater.java:600)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:702)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)
at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
at android.support.v7.app.AppCompatDelegateImplV7.createSubDecor(AppCompatDelegateImplV7.java:379)
at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:300)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:264)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:129)
at com.example.joe.audiodomain.MainActivity.onCreate(MainActivity.java:25)
at android.app.Activity.performCreate(Activity.java:5585)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2400)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2495)
at android.app.ActivityThread.access$900(ActivityThread.java:170)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5635)
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:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #17: invalid drawable tag vector
at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:986)
at android.graphics.drawable.Drawable.createFromXml(Drawable.java:930)
at android.content.res.Resources.loadDrawable(Resources.java:3435)
at android.content.res.Resources.getDrawable(Resources.java:1893)
at android.support.v7.widget.TintResources.superGetDrawable(TintResources.java:48)
at android.support.v7.widget.AppCompatDrawableManager.onDrawableLoadedFromResources(AppCompatDrawableManager.java:374)
at android.support.v7.widget.TintResources.getDrawable(TintResources.java:44)
at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:323)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:180)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:173)
at android.support.v7.widget.TintTypedArray.getDrawable(TintTypedArray.java:60)
at android.support.v7.widget.Toolbar.<init>(Toolbar.java:254)
at android.support.v7.widget.Toolbar.<init>(Toolbar.java:196)
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at android.view.LayoutInflater.createView(LayoutInflater.java:600)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:702)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)
at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
at android.support.v7.app.AppCompatDelegateImplV7.createSubDecor(AppCompatDelegateImplV7.java:379)
at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:300)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:264)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:129)
at com.example.joe.audiodomain.MainActivity.onCreate(MainActivity.java:25)
at android.app.Activity.performCreate(Activity.java:5585)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2400)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2495)
at android.app.ActivityThread.access$900(ActivityThread.java:170)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5635)
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:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
03-17 15:29:31.839 20066-20066/? I/Process﹕ Sending signal. PID: 20066 SIG: 9
Here is my code:
`
package com.example.joe.mp3demo;
import android.app.Activity;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class ListActivity extends Activity {
ListView lv;
ArrayAdapter<String> adapter;
String songs[];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
//Creating a List view instance
lv= (ListView) findViewById(R.id.listView);
//Array list to hold all songs, using findSongs method passing the SD card directory
ArrayList<File> allSongs= findSongs(Environment.getExternalStorageDirectory());
songs= new String[allSongs.size()];
for(int c=0; c< allSongs.size(); c++){
songs[c]=allSongs.get(c).getName().toString();
}
adapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, songs);
lv.setAdapter(adapter);
}
//function to find all songs in SD card. Storing them in a temp ArrayList and returning
public ArrayList<File> findSongs(File root){
ArrayList<File> al= new ArrayList<File>();
File[] files=root.listFiles();
for(File singleFile: files){
if(singleFile.isDirectory() && !singleFile.isHidden()) {
al.addAll(findSongs(singleFile));
}
else{
if(singleFile.getName().endsWith(".mp3") || singleFile.getName().endsWith(".wav") || singleFile.getName().endsWith(".wma") ){
al.add(singleFile);
}
}
}
return al;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_list, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Try this code:-
public class FindMp3Files extends AppCompatActivity {
ListView mp3List;
String title, artist, path, displayName, songDuration;
ArrayList<Mp3Model> songs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_mp3_files);
mp3List = (ListView) findViewById(R.id.mp3List);
songs = new ArrayList<>();
scanSdcard();
SongAdapter adapter = new SongAdapter(this, songs);
mp3List.setAdapter(adapter);
}
private void scanSdcard() {
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
String[] projection = {
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DURATION
};
final String sortOrder = MediaStore.Audio.AudioColumns.TITLE + " COLLATE LOCALIZED ASC";
Cursor cursor = null;
try {
Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
cursor = this.getContentResolver().query(uri, projection, selection, null, sortOrder);
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Mp3Model mp3Model = new Mp3Model();
title = cursor.getString(0);
artist = cursor.getString(1);
path = cursor.getString(2);
displayName = cursor.getString(3);
songDuration = cursor.getString(4);
mp3Model.setTitle(title);
mp3Model.setArtist(artist);
mp3Model.setPath(path);
mp3Model.setDisplayName(displayName);
mp3Model.setSongDuration(songDuration);
songs.add(mp3Model);
cursor.moveToNext();
}
}
} catch (Exception e) {
Log.e("Tag", e.toString());
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}
Here is the Mp3Model class :-
public class Mp3Model {
String title, artist, path, displayName, songDuration;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getSongDuration() {
return songDuration;
}
public void setSongDuration(String songDuration) {
this.songDuration = songDuration;
}
}
SongAdapter.java
public class SongAdapter extends BaseAdapter {
Context context;
ArrayList<Mp3Model> mp3Models;
LayoutInflater inflater;
Typeface captureFont;
public SongAdapter(Context context, ArrayList<Mp3Model> mp3Models) {
this.context = context;
this.mp3Models = mp3Models;
inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
captureFont = Typeface.createFromAsset(this.context.getAssets(), "fonts/Montserrat.ttf");
}
#Override
public int getCount() {
return mp3Models.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class ViewHolder {
TextView songName;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh;
if (convertView == null) {
vh = new ViewHolder();
convertView = inflater.inflate(R.layout.song_row, parent, false);
vh.songName = (TextView) convertView.findViewById(R.id.songName);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
vh.songName.setText(mp3Models.get(position).getTitle());
vh.songName.setTypeface(captureFont);
vh.songName.setPadding(10, 10, 10, 10);
vh.songName.setTextColor(Color.WHITE);
vh.songName.setBackgroundColor(Color.parseColor("#333333"));
vh.songName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
return convertView;
}
}
I am learning android programming and created a basic project using android studio.
My application crashes when I click on the getdata button.
The MainActivity.java:
package com.cs_infotech.newpathshala;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new ExampleFragment();
break;
case 1:
fragment = new Example1Fragment();
break;
case 2:
fragment = new Example2Fragment();
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment).commit();
} }
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = "ePathshala";
break;
case 2:
mTitle = "Daily Collection";
break;
case 3:
mTitle = "New Enrolled";
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
test1.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/getdata"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="23dp"
android:text="Get Data" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/getdata" />
<TextView
android:id="#+id/vers"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/api"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
Example1Fragment.java:
package com.cs_infotech.newpathshala;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.cs_infotech.newpathshala.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class Example1Fragment extends Fragment {
ListView list;
TextView ver;
TextView name;
TextView api;
Button btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://api.learn2crack.com/android/jsonos/";
//JSON Node Names
private static final String TAG_OS = "android";
private static final String TAG_VER = "ver";
private static final String TAG_NAME = "name";
private static final String TAG_API = "api";
JSONArray android = null;
private View v;
public Example1Fragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.test1, container, false);
oslist = new ArrayList<HashMap<String, String>>();
btngetdata = (Button) rootView.findViewById(R.id.getdata);
v=rootView;
btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
//Toast.makeText(getActivity(), "You Clicked at " , Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
name = (TextView) v.findViewById(R.id.name);
ver = (TextView) v.findViewById(R.id.vers);
api = (TextView) v.findViewById(R.id.api);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl("http://api.learn2crack.com/android/jsonos/");
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
list=(ListView) v.findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(getActivity(), oslist,
R.layout.list_v,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity(), "You Clicked at " + oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Logcat:
04-10 10:12:52.253 30126-30126/com.cs_infotech.newpathshala D/ActivityThread﹕ handleBindApplication:com.cs_infotech.newpathshala
04-10 10:12:52.343 30126-30126/com.cs_infotech.newpathshala W/ApplicationPackageManager﹕ getCSCPackageItemText()
04-10 10:12:52.343 30126-30126/com.cs_infotech.newpathshala D/DisplayManager﹕ DisplayManager()
04-10 10:12:52.423 30126-30126/com.cs_infotech.newpathshala I/dalvikvm﹕ Could not find method android.view.ViewGroup.onNestedScrollAccepted, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.onNestedScrollAccepted
04-10 10:12:52.423 30126-30126/com.cs_infotech.newpathshala W/dalvikvm﹕ VFY: unable to resolve virtual method 11359: Landroid/view/ViewGroup;.onNestedScrollAccepted (Landroid/view/View;Landroid/view/View;I)V
04-10 10:12:52.423 30126-30126/com.cs_infotech.newpathshala D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0000
04-10 10:12:52.423 30126-30126/com.cs_infotech.newpathshala I/dalvikvm﹕ Could not find method android.view.ViewGroup.onStopNestedScroll, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.onStopNestedScroll
04-10 10:12:52.423 30126-30126/com.cs_infotech.newpathshala W/dalvikvm﹕ VFY: unable to resolve virtual method 11365: Landroid/view/ViewGroup;.onStopNestedScroll (Landroid/view/View;)V
04-10 10:12:52.423 30126-30126/com.cs_infotech.newpathshala D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0000
04-10 10:12:52.433 30126-30126/com.cs_infotech.newpathshala I/dalvikvm﹕ Could not find method android.support.v7.internal.widget.ActionBarOverlayLayout.stopNestedScroll, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.setHideOnContentScrollEnabled
04-10 10:12:52.433 30126-30126/com.cs_infotech.newpathshala W/dalvikvm﹕ VFY: unable to resolve virtual method 9053: Landroid/support/v7/internal/widget/ActionBarOverlayLayout;.stopNestedScroll ()V
04-10 10:12:52.433 30126-30126/com.cs_infotech.newpathshala D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x000e
04-10 10:12:52.443 30126-30126/com.cs_infotech.newpathshala I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
04-10 10:12:52.443 30126-30126/com.cs_infotech.newpathshala W/dalvikvm﹕ VFY: unable to resolve virtual method 374: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
04-10 10:12:52.443 30126-30126/com.cs_infotech.newpathshala D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
04-10 10:12:52.443 30126-30126/com.cs_infotech.newpathshala I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
04-10 10:12:52.443 30126-30126/com.cs_infotech.newpathshala W/dalvikvm﹕ VFY: unable to resolve virtual method 396: Landroid/content/res/TypedArray;.getType (I)I
04-10 10:12:52.443 30126-30126/com.cs_infotech.newpathshala D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
04-10 10:12:52.834 30126-30126/com.cs_infotech.newpathshala D/OpenGLRenderer﹕ Enabling debug mode 0
04-10 10:12:52.934 30126-30126/com.cs_infotech.newpathshala I/Timeline﹕ Timeline: Activity_idle id: android.os.BinderProxy#41e049e0 time:9101016
04-10 10:15:04.772 30126-30126/com.cs_infotech.newpathshala I/Timeline﹕ Timeline: Activity_idle id: android.os.BinderProxy#41e049e0 time:9232856
04-10 10:15:11.359 30126-30656/com.cs_infotech.newpathshala W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x416c8bc0)
04-10 10:15:11.379 30126-30656/com.cs_infotech.newpathshala E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.cs_infotech.newpathshala, PID: 30126
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at com.cs_infotech.newpathshala.JSONParser.getJSONFromUrl(JSONParser.java:44)
at com.cs_infotech.newpathshala.Example1Fragment$JSONParse.doInBackground(Example1Fragment.java:80)
at com.cs_infotech.newpathshala.Example1Fragment$JSONParse.doInBackground(Example1Fragment.java:62)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
at libcore.io.Posix.getaddrinfo(Native Method)
at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at com.cs_infotech.newpathshala.JSONParser.getJSONFromUrl(JSONParser.java:44)
at com.cs_infotech.newpathshala.Example1Fragment$JSONParse.doInBackground(Example1Fragment.java:80)
at com.cs_infotech.newpathshala.Example1Fragment$JSONParse.doInBackground(Example1Fragment.java:62)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: libcore.io.ErrnoException: getaddrinfo failed: EACCES (Permission denied)
at libcore.io.Posix.getaddrinfo(Native Method)
at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at com.cs_infotech.newpathshala.JSONParser.getJSONFromUrl(JSONParser.java:44)
at com.cs_infotech.newpathshala.Example1Fragment$JSONParse.doInBackground(Example1Fragment.java:80)
at com.cs_infotech.newpathshala.Example1Fragment$JSONParse.doInBackground(Example1Fragment.java:62)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
04-10 10:15:12.330 30126-30126/com.cs_infotech.newpathshala E/OpenGLRenderer﹕ SFEffectCache:clear(), mSize = 0
04-10 10:15:12.360 30126-30126/com.cs_infotech.newpathshala E/WindowManager﹕ android.view.WindowLeaked: Activity com.cs_infotech.newpathshala.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41e91890 V.E..... R......D 0,0-471,144} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:388)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at com.cs_infotech.newpathshala.Example1Fragment$JSONParse.onPreExecute(Example1Fragment.java:74)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.cs_infotech.newpathshala.Example1Fragment$1.onClick(Example1Fragment.java:56)
at android.view.View.performClick(View.java:4508)
at android.view.View$PerformClick.run(View.java:18675)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
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:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
04-10 10:15:14.992 30126-30656/com.cs_infotech.newpathshala I/Process﹕ Sending signal. PID: 30126 SIG: 9
How can I resolve this?
I am trying to add the abmob ads to an activity in my android app but the the fragment will not load. When the application load it crash and say's Unable to start activity ComponentInfo{catchmedia.jamaica.dictionary/catchmedia.jamaica.dictionary.HomeActivity}: android.view.InflateException: Binary XML file line #15: Error inflating class fragment. what is that i have done wrong?
stacktrace
01-06 22:28:02.335 1356-1356/catchmedia.jamaica.dictionary E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: catchmedia.jamaica.dictionary, PID: 1356
java.lang.RuntimeException: Unable to start activity ComponentInfo{catchmedia.jamaica.dictionary/catchmedia.jamaica.dictionary.HomeActivity}: android.view.InflateException: Binary XML file line #15: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #15: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:290)
at android.app.Activity.setContentView(Activity.java:1929)
at catchmedia.jamaica.dictionary.HomeActivity.onCreate(HomeActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f030004
at android.content.res.Resources.getValue(Resources.java:1123)
at android.content.res.Resources.loadXmlResourceParser(Resources.java:2309)
at android.content.res.Resources.getLayout(Resources.java:939)
at android.view.LayoutInflater.inflate(LayoutInflater.java:395)
at catchmedia.jamaica.dictionary.HomeActivity$AdFragment.onCreateView(HomeActivity.java:156)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:920)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1206)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2159)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:297)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:290)
at android.app.Activity.setContentView(Activity.java:1929)
at catchmedia.jamaica.dictionary.HomeActivity.onCreate(HomeActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
01-06 22:28:04.183 1356-1356/catchmedia.jamaica.dictionary I/Process﹕ Sending signal. PID: 1356 SIG: 9
AdFragment
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--ads:adUnitId sets the ad unit ID, which is defined in values/strings.xml -->
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
ads:adSize="BANNER"
ads:adUnitId="#string/banner_ad_unit_id" />
</RelativeLayout>
Xml Code
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</android.support.v4.view.ViewPager>
<fragment
android:id="#+id/adFragment"
android:name="catchmedia.jamaica.dictionary.HomeActivity$AdFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" />
Class
package catchmedia.jamaica.dictionary;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import java.util.List;
import catchmedia.jamaica.dictionary.adapter.TabsPagerAdapter;
import database.DatabaseHandler;
import database.DatabaseInfo;
import database.Word;
public class HomeActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter tabsPagerAdapter;
private ActionBar actionBar;
DatabaseHandler db = new DatabaseHandler(this);
private String[] tabsTitles = {"Lesson", "Word"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
initializeDatabase();
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
tabsPagerAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(tabsPagerAdapter);
actionBar.setHomeButtonEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabsTitles) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
public void initializeDatabase() {
List<Word> words = db.getAllWords();
if (words.size() == 0) {
DatabaseInfo info = new DatabaseInfo(db);
info.insertWords();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return super.onCreateOptionsMenu(menu);
}
#Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
default:
return super.onOptionsItemSelected(item);
}
}
public static class AdFragment extends Fragment {
private AdView mAdView;
public AdFragment() {
}
#Override
public void onActivityCreated(Bundle bundle) {
super.onActivityCreated(bundle);
mAdView = (AdView) getView().findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
mAdView.loadAd(adRequest);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_ad, container, false);
}
/** Called when leaving the activity */
#Override
public void onPause() {
if (mAdView != null) {
mAdView.pause();
}
super.onPause();
}
/** Called when returning to the activity */
#Override
public void onResume() {
super.onResume();
if (mAdView != null) {
mAdView.resume();
}
}
/** Called before the activity is destroyed */
#Override
public void onDestroy() {
if (mAdView != null) {
mAdView.destroy();
}
super.onDestroy();
}
}
}
In your HomeActivity class, you've imported android.support.v4.app.Fragment, android.support.v4.app.FragmentActivity, etc. There is a conflict here.
In your XML, you're using <fragment>. You need to either change your imports to android.app.Fragment, or change XML to:
<android.support.v4.app.fragment
android:id="#+id/adFragment"
android:name="catchmedia.jamaica.dictionary.HomeActivity$AdFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" />
If you're using fragments, and want to target devices before API 11, you should be using use android.support.v4.app.Fragment. However, if you're only targeting devices running API 11 or above, you can use android.app.Fragment.
Otherwise, there is a conflict between you using Fragment and Fragment from the Android support library.
You should change fragment to android.support.v4.Fragment in your xml file as your AdFragment extends from android.support.v4.Fragment.
I am getting a NullPointerException. Below you can find my Logcat and the relevant code.
Logcat:
12-23 00:17:35.330: E/AndroidRuntime(2019): FATAL EXCEPTION: main
12-23 00:17:35.330: E/AndroidRuntime(2019): Process: com.android.timesheet, PID: 2019
12-23 00:17:35.330: E/AndroidRuntime(2019): java.lang.NullPointerException
12-23 00:17:35.330: E/AndroidRuntime(2019): at com.android.timesheet.adapter.CustomCursorAdapter$1.onClick(CustomCursorAdapter.java:54)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.view.View.performClick(View.java:4438)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.view.View$PerformClick.run(View.java:18422)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.os.Handler.handleCallback(Handler.java:733)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.os.Handler.dispatchMessage(Handler.java:95)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.os.Looper.loop(Looper.java:136)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.app.ActivityThread.main(ActivityThread.java:5017)
12-23 00:17:35.330: E/AndroidRuntime(2019): at java.lang.reflect.Method.invokeNative(Native Method)
12-23 00:17:35.330: E/AndroidRuntime(2019): at java.lang.reflect.Method.invoke(Method.java:515)
12-23 00:17:35.330: E/AndroidRuntime(2019): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
12-23 00:17:35.330: E/AndroidRuntime(2019): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
12-23 00:17:35.330: E/AndroidRuntime(2019): at dalvik.system.NativeStart.main(Native Method)
CustomCursorAdapter.java:
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.TextView;
import com.android.timesheet.ModifyMember;
import com.android.timesheet.R;
public class CustomCursorAdapter extends CursorAdapter {
Button delete_btn;
TextView memID_tv, memName_tv;
#SuppressWarnings("deprecation")
public CustomCursorAdapter(Activity context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.single_row_item, parent, false);
return retView;
}
#Override
public void bindView(View view, final Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
TextView textViewPersonName = (TextView) view.findViewById(R.id.tv_person_name);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
delete_btn=(Button)view.findViewById(R.id.delete_btn);
delete_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
memID_tv = (TextView)v.findViewById(R.id.member_id);
memName_tv = (TextView)v.findViewById(R.id.member_name);
String memberID_val = memID_tv.getText().toString();; ---->54th Line
String memberName_val = memName_tv.getText().toString();
Intent i = new Intent(context,
ModifyMember.class);
i.putExtra("memberName", memberName_val);
i.putExtra("memberID", memberID_val);
((Activity)context).startActivity(i);
}
});
}
}
I am using a delete button to delete all the listview row items. At that point I am getting the NullPointerException.
Use view(view of row) instead of v parameter of onClick method which is view of Button :
delete_btn=(Button)view.findViewById(R.id.delete_btn);
delete_btn.setTag(view);
delete_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View rowview=(View)v.getTag();
memID_tv = (TextView)rowview.findViewById(R.id.member_id);
memName_tv = (TextView)rowview.findViewById(R.id.member_name);
}
});
Use view instead of v
memID_tv = (TextView)view.findViewById(R.id.member_id);
In bindview try this-
if (view == null) {
view = inflater.inflate(R.layout.single_row_item, parent, null);
}
TextView textViewPersonName = (TextView) view.findViewById(R.id.tv_person_name);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
delete_btn=(Button)view.findViewById(R.id.delete_btn);
.
.
.
you are getting the view from clicked view, but you have to get the views from the root view.
memID_tv = (TextView)v. findViewById(R.id.member_id);
memName_tv = (TextView)v.findViewById(R.id.member_name);
change these lines into this:
memID_tv = (TextView)view. findViewById(R.id.member_id);
memName_tv = (TextView)view.findViewById(R.id.member_name);