I created a 2x2 grid where the first 3 grids has three(Thingspeak) charts imported from GitHub(https://github.com/MacroYau/ThingSpeakAndroid)and the fourth grid will be implemented later so for the time being I just added a blank chart in it.
I have checked out all similar questions on stackoverflow and read their answers and I have understood the error in the logcat at line 60(chartView = (LineChartView) findViewById(R.id.chart);) means that this id is pointing to null but I don't know how to solve it as chart is present as an id in my activity_main.xml layout.
I have used the following files: activity_main.xml, main.xml, TempHumidity.java and GridViewAdapter.java
Code snippet from TempHumidity.java
public class TempHumidity extends AppCompatActivity {
private ThingSpeakChannel tsChannel, tsChannel1, tsChannel2;
private ThingSpeakLineChart tsChart, tsChart1, tsChart2;
private LineChartView chartView, chartView1, chartView2;
GridView simpleGrid;
int charts[] = {R.id.chart, R.id.chart1, R.id.chart2};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
simpleGrid = (GridView) findViewById(R.id.simpleGridView); // init GridView
// Create an object of CustomAdapter and set Adapter to GirdView
GridViewAdapter customAdapter = new GridViewAdapter(getApplicationContext(), charts);
simpleGrid.setAdapter(customAdapter);
// Connect to ThinkSpeak Channels
tsChannel = new ThingSpeakChannel(377467);
tsChannel1 = new ThingSpeakChannel(357670);
tsChannel2 = new ThingSpeakChannel(377509);
// Set listener for Channel feed update events
tsChannel.setChannelFeedUpdateListener(new ThingSpeakChannel.ChannelFeedUpdateListener() {
#Override
public void onChannelFeedUpdated(long channelId, String channelName, ChannelFeed channelFeed) {
// Show Channel ID and name on the Action Bar
getSupportActionBar().setTitle(channelName);
getSupportActionBar().setSubtitle("Channel " + channelId);
// Notify last update time of the Channel feed through a Toast message
Date lastUpdate = channelFeed.getChannel().getUpdatedAt();
Toast.makeText(TempHumidity.this, lastUpdate.toString(), Toast.LENGTH_LONG).show();
}
});
// Fetch the specific Channel feed
tsChannel.loadChannelFeed();
// Create a Calendar object dated 1 minutes ago
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, -1);
// Configure LineChartView
chartView = (LineChartView) findViewById(R.id.chart); //Logcat error points here
chartView.setZoomEnabled(false);
chartView.setValueSelectionEnabled(true);
GridViewAdapter.java
public class GridViewAdapter extends BaseAdapter {
private Context context;
private final int[] charts;
LayoutInflater inflter;
public GridViewAdapter(Context Appcontext, int[] charts) {
this.context = Appcontext;
this.charts = charts;
inflter = (LayoutInflater.from(Appcontext));
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.activity_main, null); // inflate the layout
LineChartView cv = (LineChartView) view.findViewById(R.id.chart); // get the reference of ImageView
return view;
}
#Override
public int getCount() {
return charts.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
main.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">
<!--
-->
<GridView
android:id="#+id/simpleGridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:footerDividersEnabled="false"
android:padding="1dp"
android:numColumns="2" />
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Container LinearLayout -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- Row 1 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<lecho.lib.hellocharts.view.LineChartView
android:id="#+id/chart"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
/>
<lecho.lib.hellocharts.view.LineChartView
android:id="#+id/chart1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
/>
</LinearLayout>
<!-- Row 2 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<lecho.lib.hellocharts.view.LineChartView
android:id="#+id/chart2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
/>
<lecho.lib.hellocharts.view.LineChartView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
/>
</LinearLayout>
</LinearLayout>
Logcat:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.macroyau.thingspeakandroid.demo/com.macroyau.thingspeakandroid.demo.TempHumidity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2299)
at android.app.ActivityThread.access$700(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5283)
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)
Caused by: java.lang.NullPointerException
at com.macroyau.thingspeakandroid.demo.TempHumidity.onCreate(TempHumidity.java:60)
at android.app.Activity.performCreate(Activity.java:5283)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2299)
at android.app.ActivityThread.access$700(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5283)
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)
01-14 17:11:28.007 23142-23146/com.macroyau.thingspeakandroid.demo
D/dalvikvm: GC_CONCURRENT freed 587K, 19% free 8887K/10932K, paused 4ms+22ms, total 114ms
When I run the codes(as it is in GitHub) without adding two similar charts in a GridView:
Currently my activity_main.xml layout looks like this:
As Mike M. in the comments pointed out that the chart id is not present in the main.xml file which is the reason why it pointing to null.
All I had to do is remove the main.xml file and set the layout to activity_main.xml in the onCreate method like this:
setContentView(R.layout.activity_main) (as I have already made a 2x2 layout in it activity_main.xml)
and remove the GridViewAdapter.java.
Related
I have an app in which a main fragment contains a tab layout tied to a ViewPager2 in order to navigate between three different fragments. When I rotate my phone's screen, the app crashes with this error:
Fragment no longer exists for key f#0: unique id c4576c9c-4bbd-4dc0-a304-b86653ed2820
(complete error stack at the end of the post)
This is my setup:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="#+id/main_activity_coordinator"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical">
<com.google.android.material.appbar.AppBarLayout
app:layout_constraintTop_toTopOf="parent"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:id="#+id/app_bar"
android:theme="#style/Theme.VirtualGymBuddy.AppBarOverlay"
>
<com.google.android.material.appbar.MaterialToolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:title="#string/app_name" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.fragment.app.FragmentContainerView
android:tag="MAIN-FRAG"
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="#navigation/nav_graph"
/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
main_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:tag="MAIN-FRAG"
android:id="#+id/main_relative_layout"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:paddingTop="?attr/actionBarSize"
xmlns:tools="http://schemas.android.com/tools">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabTextAppearance="#style/MyTabLayoutStyle"
>
<com.google.android.material.tabs.TabItem
android:id="#+id/tab1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab1" />
<com.google.android.material.tabs.TabItem
android:id="#+id/tab2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab2" />
<com.google.android.material.tabs.TabItem
android:id="#+id/tab3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab3" />
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager2.widget.ViewPager2
android:layout_below="#id/tabBar"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
/>
</RelativeLayout>
content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/content_main_constraint"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<fragment
android:id="#+id/nav_host_fragment_content_main"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/nav_graph"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
ActivityMain.java
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration appBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(null);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
return NavigationUI.navigateUp(navController, appBarConfiguration)
|| super.onSupportNavigateUp();
}
}
MainFragment.java
public class MainFragment extends Fragment {
private ViewPager2 viewPager;
private NavigationAdapter navigationAdapter;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().setContentView(R.layout.main_fragment);
TabLayout tabLayout = getActivity().findViewById(R.id.tabBar);
int[] tabTexts = {
R.string.tab_1,
R.string.tab_2,
R.string.tab_3
};
// set up view pager and attach mediator to tab layout
this.viewPager = getActivity().findViewById(R.id.pager);
this.navigationAdapter = new NavigationAdapter(this);
viewPager.setAdapter(this.navigationAdapter);
new TabLayoutMediator(tabLayout, viewPager,
(tab, position) -> tab.setText(
tabTexts[position]
)
).attach();
}
}
NavigationAdapter.java
public class NavigationAdapter extends FragmentStateAdapter {
public NavigationAdapter(#NonNull FragmentActivity fragmentActivity) {
super(fragmentActivity);
}
public NavigationAdapter(#NonNull Fragment fragment) {
super(fragment);
}
public NavigationAdapter(#NonNull FragmentManager fragmentManager, #NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
#NonNull
#Override
public Fragment createFragment(int position) {
switch (position) {
case 0:
return new Fragment1();
case 1:
return new Fragment2();
case 2:
return new Fragment3();
}
throw new AssertionError();
}
#Override
public int getItemCount() {
return 3;
}
}
nav_graph.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/nav_graph"
app:startDestination="#id/MainFragment">
<fragment
android:id="#+id/MainFragment"
android:name="com.myapp.fragments.MainFragment"
android:label="#string/first_fragment_label"
tools:layout="#layout/main_fragment" />
</navigation>
Everything works fine and I can navigate through the fragments handled by ViewPager2.
However, as soon as I rotate the screen inside of one of those fragments, I get this:
2022-05-08 00:08:12.339 12343-12343/com.myapp E/FragmentManager: Fragment no longer exists for key f#0: unique id c4576c9c-4bbd-4dc0-a304-b86653ed2820
2022-05-08 00:08:12.339 12343-12343/com.myapp E/FragmentManager: Activity state:
2022-05-08 00:08:12.358 12343-12343/com.myapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.myapp, PID: 12343
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp/com.myapp.MainActivity}: java.lang.IllegalStateException: Fragment no longer exists for key f#0: unique id c4576c9c-4bbd-4dc0-a304-b86653ed2820
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2827)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2902)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4784)
at android.app.ActivityThread.-wrap18(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1609)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:169)
at android.app.ActivityThread.main(ActivityThread.java:6578)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.IllegalStateException: Fragment no longer exists for key f#0: unique id c4576c9c-4bbd-4dc0-a304-b86653ed2820
at androidx.fragment.app.FragmentManager.getFragment(FragmentManager.java:975)
at androidx.viewpager2.adapter.FragmentStateAdapter.restoreState(FragmentStateAdapter.java:549)
at androidx.viewpager2.widget.ViewPager2.restorePendingState(ViewPager2.java:350)
at androidx.viewpager2.widget.ViewPager2.dispatchRestoreInstanceState(ViewPager2.java:375)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3729)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3729)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3729)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3729)
at android.view.View.restoreHierarchyState(View.java:17620)
at com.android.internal.policy.PhoneWindow.restoreHierarchyState(PhoneWindow.java:2130)
at android.app.Activity.onRestoreInstanceState(Activity.java:1122)
at android.app.Activity.performRestoreInstanceState(Activity.java:1077)
at android.app.Instrumentation.callActivityOnRestoreInstanceState(Instrumentation.java:1260)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2800)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2902)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4784)
at android.app.ActivityThread.-wrap18(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1609)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:169)
at android.app.ActivityThread.main(ActivityThread.java:6578)
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)
What's wrong with my setup?
There is an issue with viewpager2 detach from recyclerview
https://issuetracker.google.com/issues/154751401
As per my knowledge two fixes are there:
add this line in your xml viewpager2 component.
<androidx.viewpager2.widget.ViewPager2
android:layout_below="#id/tabBar"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:saveEnabled="false">
But the above one don't save the current instance, which the fragment will recreate each time it pops back.
The recommended solution is add the below line on your mainfragment
override fun onDestroyView() {
super.onDestroyView()
viewPager.adapter = null
}
I have a view pager and cardview in my activity
and define lottie animation for my favorite btn
but the code of setOnClickListener didnt work and app did crash when i go to this activity
when i comment the setOnClickListener code, it will ok
and also the code is working well in another activity
this is my java activity code
public class MainActivity3 extends AppCompatActivity {
ImageView imageView;
String[] money;
boolean switchIsOn = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
//favorite animation button
final LottieAnimationView animatedSwitchButton =(LottieAnimationView) findViewById(R.id.fav_lot);
animatedSwitchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (switchIsOn){
animatedSwitchButton.setSpeed(-1);
animatedSwitchButton.playAnimation();
switchIsOn = false;
}else {
animatedSwitchButton.setSpeed(1);
animatedSwitchButton.playAnimation();
switchIsOn = true;
}
}
});
money = getResources().getStringArray(R.array.money);
ViewPager mViewPager = findViewById(R.id.viewPager);
CardPagerAdapters mCardAdapter = new CardPagerAdapters();
for (String s : money) {
mCardAdapter.addCardItem(new CardItemString(s));
}
mViewPager.setAdapter(mCardAdapter);
mViewPager.setOffscreenPageLimit(3);
}
}
and the adapter.xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/cardView"
android:layout_width="250dp"
android:layout_height="320dp"
app:cardCornerRadius="20dp"
android:layout_gravity="center"
android:backgroundTint="#00FFFFFF">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#6FCDDC39"
android:padding="15dp">
<TextView
android:id="#+id/titleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_gravity="center_horizontal"
android:fontFamily="sans-serif-black"
android:gravity="center_horizontal"
android:text="#string/app_name"
android:textColor="#075AFF"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.airbnb.lottie.LottieAnimationView
android:id="#+id/fav_lot"
android:layout_width="100dp"
android:layout_height="100dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.533"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/titleTextView"
app:lottie_rawRes="#raw/fav" />
</androidx.constraintlayout.widget.ConstraintLayout>
</com.google.android.material.card.MaterialCardView>
the logcat error is
2020-11-24 16:47:40.817 11330-11330/com.paradise.myapplication4 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.paradise.myapplication4, PID: 11330
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.paradise.myapplication4/com.paradise.myapplication4.MainActivity3}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.airbnb.lottie.LottieAnimationView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.airbnb.lottie.LottieAnimationView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.paradise.myapplication4.MainActivity3.onCreate(MainActivity3.java:26)
at android.app.Activity.performCreate(Activity.java:7009)
at android.app.Activity.performCreate(Activity.java:7000)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
mainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:overScrollMode="never"
android:paddingVertical="100dp"
android:paddingHorizontal="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"/>
</RelativeLayout>
cardIPagerAdapter java code
public class CardPagerAdapters extends PagerAdapter {
private final List<CardView> mViews;
private final List<CardItemString> mData;
private float mBaseElevation;
public CardPagerAdapters() {
mData = new ArrayList<>();
mViews = new ArrayList<>();
}
public void addCardItem(CardItemString item) {
mViews.add(null);
mData.add(item);
}
public int getCount() {
return mData.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#NonNull
#Override
public Object instantiateItem(ViewGroup container, int position) {
View view = LayoutInflater.from(container.getContext())
.inflate(R.layout.adapter, container, false);
container.addView(view);
bind(mData.get(position), view);
CardView cardView = view.findViewById(R.id.cardView);
if (mBaseElevation == 0) {
mBaseElevation = cardView.getCardElevation();
}
cardView.setMaxCardElevation(mBaseElevation * 1);
mViews.set(position, cardView);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
mViews.set(position, null);
}
private void bind(CardItemString item, View view) {
TextView titleTextView = view.findViewById(R.id.titleTextView);
titleTextView.setText(item.getTitle());
}
}
Your animatedSwitchButton is null because you use findViewById() on your current object, which is your MainActivity3. This Activity doesn't contain the View with the ID fav_lot in adapter.xml though, since its layout-file is set to activity_main3.xml.
So you need to use findViewById() on the object you attached your adapter.xml to. This could be mViewPager.findViewById(R.id.fav_lot) for example, although I am not sure what your adapter.xml is actually attached to.
I am trying to open an activity which has recyclerView in it on the click of recyclerView of first activity. But now when I'm clicking the recyclerView app is crashing with the following message.
10-18 09:30:49.912 13018-13018/in.mumbaitravellers.mtleaders
E/AndroidRuntime: FATAL EXCEPTION: main
Process: in.mumbaitravellers.mtleaders, PID: 13018
java.lang.RuntimeException: Unable to start activity
ComponentInfo{in.mumbaitravellers.mtleaders/in.mumbaitravellers.mtleaders.activity.DetailActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a
null object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void
android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a
null object reference
at
in.mumbaitravellers.mtleaders.activity.DetailActivity.setupRecycler(DetailActivity.java:120)
at
in.mumbaitravellers.mtleaders.activity.DetailActivity.onCreate(DetailActivity.java:52)
at android.app.Activity.performCreate(Activity.java:6245)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
10-18 09:31:13.376 1801-2412/? E/native: do suspend false
The java code is as follows:
public class DetailActivity extends AppCompatActivity {
private ExpenseAdapter adapter;
private Realm realm;
private LayoutInflater inflater;
private FloatingActionButton fab;
private RecyclerView recycler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
fab = (FloatingActionButton) findViewById(R.id.fab);
recycler = (RecyclerView) findViewById(R.id.recycler);
//get realm instance
this.realm = RealmController.with(this).getRealm();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*String event = getIntent().getStringExtra("eventName");
TextView tv = (TextView) findViewById(R.id.txt_EventName);
tv.setText(event);*/
setupRecycler();
if (!Prefs.with(this).getPreLoad()) {
setRealmData();
}
// refresh the realm instance
RealmController.with(this).refresh();
// get all persisted objects
// create the helper adapter and notify data set changes
// changes will be reflected automatically
setRealmAdapter(RealmController.with(this).getExpenses());
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
inflater = DetailActivity.this.getLayoutInflater();
View content = inflater.inflate(R.layout.activity_add_new_expense, null);
final EditText editExpense = (EditText) content.findViewById(R.id.edtxt_expense);
final EditText editDescription = (EditText) content.findViewById(R.id.edtxt_description);
AlertDialog.Builder builder = new AlertDialog.Builder(DetailActivity.this);
builder.setView(content)
.setTitle("Add Expense")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Expense expense = new Expense();
expense.setId((int) (RealmController.getInstance().getExpenses().size() + System.currentTimeMillis()));
expense.setAmount(editExpense.getText().toString());
expense.setDescription(editDescription.getText().toString());
realm.beginTransaction();
realm.copyToRealm(expense);
realm.commitTransaction();
adapter.notifyDataSetChanged();
// scroll the recycler view to bottom
recycler.scrollToPosition(RealmController.getInstance().getExpenses().size() - 1);
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
public void setRealmAdapter(RealmResults<Expense> expenses) {
RealmExpenseAdapter realmExpenseAdapter = new RealmExpenseAdapter(this.getApplicationContext(), expenses, true);
adapter.setRealmAdapter(realmExpenseAdapter);
adapter.notifyDataSetChanged();
}
private void setupRecycler() {
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
recycler.setHasFixedSize(true);
// use a linear layout manager since the cards are vertically scrollable
final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recycler.setLayoutManager(layoutManager);
// create an empty adapter and add it to the recycler view
adapter = new ExpenseAdapter(this);
recycler.setAdapter(adapter);
}
private void setRealmData() {
ArrayList<Expense> expenses = new ArrayList<>();
for (Expense e : expenses) {
// Persist your data easily
realm.beginTransaction();
realm.copyToRealm(e);
realm.commitTransaction();
}
Prefs.with(this).setPreLoad(true);
}
}
And the xml file is as follows:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="in.mumbaitravellers.mtleaders.activity.DetailActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_detail" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#drawable/ic_action_add" />
</android.support.design.widget.CoordinatorLayout>
Recycler View Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/card_expense"
style="#style/AppTheme.Card.Margins"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/text_amount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/margin_small"
android:paddingBottom="#dimen/margin_normal"
android:paddingLeft="#dimen/margin_large"
android:paddingRight="#dimen/margin_large"
android:paddingTop="#dimen/margin_large"
android:textColor="#555555"
android:text="\u20B9"
android:textSize="40dp"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="25dp"
android:id="#+id/text_description"
android:textSize="20dp"/>
</LinearLayout>
</android.support.v7.widget.CardView>
Content Detail.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/recyclerExpense"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:showIn="#layout/activity_detail"
tools:context="in.mumbaitravellers.mtleaders.activity.DetailActivity"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
What is wrong in code, please help.
Thanks in advance!
Your problem lies in incorrect search of RecyclerView
Change your code:
recycler = (RecyclerView) findViewById(R.id.recycler);
to
recycler = (RecyclerView) findViewById(R.id.recyclerExpense);
I am creating list view which contain text view,image and google map.
Code for list view layout:-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="45dp"
android:orientation="horizontal"
android:background="#ffffff"
android:paddingLeft="3dp"
android:paddingRight="3dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginLeft="3dp"
android:layout_marginTop="3dp"
android:scaleType="fitXY"
android:src="#drawable/profile_pic_bg" />
<TextView
android:id="#+id/textView_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView_time"
android:layout_alignRight="#+id/textView_time"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#0A7692"
android:textSize="15dp"
android:textStyle="bold" />
<TextView
android:id="#+id/textView_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView_username"
android:layout_toRightOf="#+id/imageView1"
android:gravity="left|center"
android:layout_marginLeft="15dp"
android:layout_marginTop="4dp"
android:textColor="#BBB9BC"
android:text=""
android:textSize="13dp"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceLarge"
/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingLeft="3dp"
android:background="#ffffff"
android:paddingRight="3dp" >
<TextView
android:id="#+id/customtxtmessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:ellipsize="end"
android:maxLines="5"
android:autoLink="web"
android:linksClickable="true"
android:text=""
android:textColor="#000000" />
<cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager
android:id="#+id/view_pager"
android:layout_marginLeft="10dp"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:layout_marginTop="5dp"
android:background="#ffffff"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:visibility="visible" >
</cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager>
</LinearLayout>
<LinearLayout
android:id="#+id/customwall_lin_setwatchlist"
android:layout_width="match_parent"
android:layout_height="30dp"
android:background="#eef7fa"
android:gravity="center_vertical" >
<TextView
android:id="#+id/customtxtlike"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#D56438" />
<ImageView
android:id="#+id/customimgdot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:src="#drawable/dot_sep" />
<TextView
android:id="#+id/customtxtcomment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Comment"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#D56438" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center|right" >
<TextView
android:id="#+id/customtxttotallikes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="15dp"
android:drawableLeft="#drawable/heart_icon"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#D56438" />
<TextView
android:id="#+id/customtxttotalcomments"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:drawableLeft="#drawable/comment_icon"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#D56438" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/customlayoutgray"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#a3a8aa"
android:orientation="vertical" >
<TextView
android:id="#+id/textView_temp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#a3a8aa"
android:textSize="6sp" />
</LinearLayout>
</LinearLayout>
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="160dp"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
Code for List view adapter is:-
/********* Adapter class extends with BaseAdapter and implements with OnClickListener ************/
public class CustomAdapter extends BaseAdapter {
/*********** Declare Used Variables *********/
private FragmentActivity activity;
private ArrayList data;
public ArrayList CommentData;
private static LayoutInflater inflater=null;
public Resources res;
CommonWallBean tempValues=null;
ViewHolder holder;
int i=0;
public static String id="";
String TextOfLike="";
SupportMapFragment mapFragment;
GoogleMap map;
HashMap<String, String> mMarkerPlaceLink = new HashMap<String, String>();
Context con;
/************* CustomAdapter Constructor *****************/
public CustomAdapter(Context c,FragmentActivity a, ArrayList d,ArrayList CommentData,Resources resLocal) {
/********** Take passed values **********/
activity = a;
data=d;
res = resLocal;
con=c;
CommentData=CommentData;
/*********** Layout inflator to call external xml layout () ***********/
inflater = ( LayoutInflater )activity.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if(data.size()<=0)
return 1;
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder{
public TextView customtxtmessage, customtxttime,customtxttotallikes,textView_time,textView_username
,text_likes;
public ViewPager view_pager;
public ImageView user_image,customimguseravtar;
public TextView textViewLike,customtxtcomment,customtxttotalcomments;
public MapView mapView;
}
/****** Depends upon data size called for each row , Create each ListView row *****/
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
final PagerAdapter adapter;
if(convertView==null){
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = inflater.inflate(R.layout.wall, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
// holder.customtxttime = (TextView) vi.findViewById(R.id.customtxttime);
holder.textView_username=(TextView)vi.findViewById(R.id.textView_username);
holder.customimguseravtar=(ImageView)vi.findViewById(R.id.imageView1);
holder.textView_time=(TextView)vi.findViewById(R.id.textView_time);
holder.view_pager=(ViewPager)vi.findViewById(R.id.view_pager);
holder.textViewLike=(TextView)vi.findViewById(R.id.customtxtlike);
holder.customtxtmessage=(TextView)vi.findViewById(R.id.customtxtmessage);
holder.customtxttotallikes=(TextView)vi.findViewById(R.id.customtxttotallikes);
holder.customtxtcomment=(TextView)vi.findViewById(R.id.customtxtcomment);
holder.customtxttotalcomments=(TextView)vi.findViewById(R.id.customtxttotalcomments);
mapFragment = (SupportMapFragment) activity.getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
map = mapFragment.getMap();
// Getting reference to the SupportMapFragment
// SupportMapFragment fragment = ( SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
/************ Set holder with LayoutInflater ************/
vi.setTag( holder );
}
else{
holder=(ViewHolder)vi.getTag();
}
if(position<data.size()){
/***** Get each Model object from Arraylist ********/
// tempValues=null;
tempValues = ( CommonWallBean ) data.get( position );
/************ Set Model values in Holder elements ***********/
holder.textView_time.setText( tempValues.getDate());
holder.textView_username.setText( tempValues.getEmployeeName());
holder.textViewLike.setText(tempValues.getValueOfLike());
holder.customtxtmessage.setText(Html.fromHtml(tempValues.getPostMessage()));
holder.customtxttotallikes.setText(tempValues.getPostLikeCount());
holder.customtxttotalcomments.setText(tempValues.getPostCommentCount());
try {
String url = Const.NewbaseurlPhoto + tempValues.getPhotographFileName();
System.out.println("Thumbnil Url "+url);
Picasso.with(activity).load(url).into(holder.customimguseravtar);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String wallPhotos = tempValues.getWallPhotograph();
String latitude = tempValues.getLatitude();
String longitude = tempValues.getLongitude();
if (latitude != null && !latitude.isEmpty() && !latitude.equals("null")){
holder.view_pager.setVisibility(View.GONE);
String Latitude = tempValues.getLatitude();
String Longitude = tempValues.getLongitude();
//map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Showing / hiding your current location
map.setMyLocationEnabled(false);
// Enable / Disable zooming controls
map.getUiSettings().setZoomControlsEnabled(false);
// Enable / Disable my location button
map.getUiSettings().setMyLocationButtonEnabled(false);
// Enable / Disable Compass icon
map.getUiSettings().setCompassEnabled(false);
// Enable / Disable Rotate gesture
map.getUiSettings().setRotateGesturesEnabled(false);
// Enable / Disable zooming functionality
map.getUiSettings().setZoomGesturesEnabled(false);
MapsInitializer.initialize(con);
// Updates the location and zoom of the MapView
double lat = Double.valueOf("23.012034");
double longi = Double.valueOf("72.510754");
MarkerOptions marker = new MarkerOptions().position(
new LatLng(lat, longi))
.title("Hello Maps");
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED));
map.addMarker(marker);
//Zoom Particular position
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(lat,
longi)).zoom(12).build();
map.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}else {
holder.view_pager.setVisibility(View.GONE);
}
}
return vi;
}
}
}
}
The Log Cat is :
FATAL EXCEPTION: main
Process: com.vervesys.konnect, PID: 26705
android.view.InflateException: Binary XML file line #178: 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.vervesys.konnect.adapter.CustomAdapter.getView(CustomAdapter.java:130)
at android.widget.AbsListView.obtainView(AbsListView.java:2255)
at android.widget.ListView.makeAndAddView(ListView.java:1790)
at android.widget.ListView.fillDown(ListView.java:691)
at android.widget.ListView.fillFromTop(ListView.java:752)
at android.widget.ListView.layoutChildren(ListView.java:1630)
at android.widget.AbsListView.onLayout(AbsListView.java:2087)
at android.view.View.layout(View.java:14860)
at android.view.ViewGroup.layout(ViewGroup.java:4643)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
at android.view.View.layout(View.java:14860)
at android.view.ViewGroup.layout(ViewGroup.java:4643)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
at android.view.View.layout(View.java:14860)
at android.view.ViewGroup.layout(ViewGroup.java:4643)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
at android.view.View.layout(View.java:14860)
at android.view.ViewGroup.layout(ViewGroup.java:4643)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
at android.view.View.layout(View.java:14860)
at android.view.ViewGroup.layout(ViewGroup.java:4643)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
at android.view.View.layout(View.java:14860)
at android.view.ViewGroup.layout(ViewGroup.java:4643)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2013)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1770)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1019)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5725)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:544)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
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:5086)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: Binary XML file line #178: Duplicate id 0x7f0d00c0, tag null, or parent id 0xffffffff with another fragment for com.google.android.gms.maps.SupportMapFragment
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2293)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:357)
at android.support.v4.app.BaseFragmentActivityHoneycomb.o
03-18 16:56:08.410 26705-27435/com.vervesys.konnect D/dalvikvm: GC_FOR_ALLOC freed 3139K, 28% free 8554K/11772K, paused 46ms, total 46ms
Please help me to solve this issue, i am not able to figure out what is wrong with this code.
Please help for the same.
Just remove xmlns:android="http://schemas.android.com/apk/res/android"
in this line
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
AND
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
You need have at the end :
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
After struggle a lot for this issue, finally i found that google provides static map in URL.
By using Mapview or fragmentManager will be heavy and app will be slow. so for this better option is to use google static map api.
More details are provided in Android - MapView contained within a Listview and
https://developers.google.com/maps/documentation/staticmaps/
I posted this answer as it may help other.
you can try this line of code in your adapter class for inflating layout
vi = inflater.inflate(R.layout.wall, parent,false);
I have an app that needs to capture a customer's signature and then present it in an ImageView. For proof-of-concept, I've written a small app that has a layout with a GestureOverlayView at the top, then a "Save Signature" button, then an ImageView below. When I press the Save Signature button, it should create an image from the GestureOverlayView and display it in the ImageView. Below is the code/layout and then a list of issues:
Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<android.gesture.GestureOverlayView android:id="#+id/GestureView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#FFFFFF"
android:fadeEnabled="false"
android:gestureStrokeType="multiple"
android:gestureStrokeWidth="1.5"
android:gestureColor="#000000"
android:fadeOffset="600000"
android:eventsInterceptionEnabled="false"
android:alwaysDrawnWithCache="true">
</android.gesture.GestureOverlayView>
<Button android:id="#+id/SubmitButton"
android:text="Save Signature"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<ImageView android:id="#+id/ImageView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#FFFFFF">
</ImageView>
</LinearLayout>
Code:
public class TestActivity extends Activity {
ImageView iv;
GestureOverlayView gv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
iv = (ImageView)findViewById(R.id.ImageView);
gv = (GestureOverlayView)findViewById(R.id.GestureView);
Button submitButton = (Button)findViewById(R.id.SubmitButton);
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Bitmap b = Bitmap.createBitmap(gv.getDrawingCache());
iv.setImageBitmap(b);
}
});
}
}
I get a Null Pointer exception every time on the createBitmap() method. I believe it is because gv.getDrawingCaches() is returning null. As you can see, drawing cache IS enabled so it should return SOMETHING!
Here's the logcat:
FATAL EXCEPTION: main
java.lang.NullPointerException
at android.graphics.Bitmap.createBitmap(Bitmap.java:358)
at com.pgov.barcode.TestActivity$2.onClick(TestActivity.java:42)
at android.view.View.performClick(View.java:2408)
at android.view.View$PerformClick.run(View.java:8816)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
Any and all help would be greatly appreciated!
Apparently I answered my own question. Even though I used:
android:alwaysDrawnWithCache="true"
I changed the code to:
gv.setDrawingCacheEnabled(true);
Bitmap b = Bitmap.createBitmap(gv.getDrawingCache());
iv.setImageBitmap(b);
gv.setDrawingCacheEnabled(false);
And it works! Not sure why the XML flag doesn't affect it though...