Before I explain to you, I told you, I've been searching in all of questions in stackoverflow and many webistes, so don't mark it duplicate or any negative acts. I've been stuck here more than 4 days.
I wanna change a font size based on spinner clicked. Every I click dropdown list spinner, it took me to java.lang.NullPointerException. Here you go:
MyAndroidAppActivity
public class MyAndroidAppActivity extends AppCompatActivity {
private Spinner spinner1, spinnerLatin;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//this line shows back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Display data
Spinner spinnerBackgroundChange = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> spinnerArrayAdapter = ArrayAdapter.createFromResource(this, R.array.country_arrays, android.R.layout.simple_spinner_item);
spinnerArrayAdapter.setDropDownViewResource(R.layout.textview_with_background);
spinnerBackgroundChange.setAdapter(spinnerArrayAdapter);
addListenerOnSpinnerItemSelection();
addListenerOnSpinner2ItemSelection();
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new SelectedListener());
}
public void addListenerOnSpinner2ItemSelection() {
spinnerLatin = (Spinner) findViewById(R.id.spinnerLatin);
spinnerLatin.setOnItemSelectedListener(new SelectedLatin());
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
} }
SelectedListener
public class SelectedListener implements OnItemSelectedListener {
public void onItemSelected (AdapterView <?> parent, View view, int pos, long id){
((TextView) view).setTextColor(Color.RED);
switch (pos) {
case 0:
TextView dgs = (TextView) view.findViewById(R.id.sizedoa);
dgs.setTextSize(30);
break;
case 1:
TextView dgf = (TextView) view.findViewById(R.id.fontLatin);
dgf.setTextSize(30);
break;
default:
//Default image
//image.setImageResource(R.drawable.item2);
break;
}
}
#Override
public void onNothingSelected (AdapterView <?> arg0){
// TODO Auto-generated method stub
} }
main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/reldoa"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="3dp"
android:background="#android:color/white"
android:orientation="vertical">
<TextView
android:id="#+id/sizedoa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:paddingBottom="10dp"
android:paddingLeft="15dp"
android:paddingTop="5dp"
android:text="Ukuran Font"
android:textColor="#222222"
android:textSize="18sp" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true" />
</RelativeLayout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/reldoa"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="3dp"
android:background="#android:color/white"
android:orientation="vertical">
<TextView
android:id="#+id/sizelatin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:paddingBottom="10dp"
android:paddingLeft="15dp"
android:paddingTop="5dp"
android:text="Jenis Font"
android:textColor="#222222"
android:textSize="18sp" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:entries="#array/type_arrays"
android:prompt="#string/type_font"/>
</RelativeLayout>
<!-- Font latin -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relLatin"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="35dp"
android:background="#android:color/white"
android:orientation="vertical">
<TextView
android:id="#+id/fontLatin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:paddingBottom="15dp"
android:paddingLeft="15dp"
android:paddingTop="15dp"
android:text="Font Latin"
android:textColor="#226169"
android:textSize="20sp" />
</RelativeLayout>
But, the problem lays here:
Error located here
And this is the result of error:
10-05 00:20:08.848 5035-5035/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at id.or.tauhid.doadandzikir.SelectedListener.onItemSelected(SelectedListener.java:32)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:892)
at android.widget.AdapterView.access$200(AdapterView.java:49)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:860)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Can you help me to fix the problem please? I've been stuck here 4 days.
In your listener, these lines are almost certainly wrong:
TextView dgs = (TextView) view.findViewById(R.id.sizedoa);
TextView dgf = (TextView) view.findViewById(R.id.fontLatin);
The view argument passed to this method is the view inside the spinner that was clicked, which means that calling view.findViewById() will only look inside (a portion of) the spinner itself. Presumably these views are in your Fragment's or Activity's layout, and not inside the spinner.
How you fix this will depend on exactly how your app is wired together, but one potential possibility is to cast the AdapterView's context to Activity and then find the views inside that:
Activity activity = (Activity) parent.getContext();
TextView dgs = activity.findViewById(R.id.sizedoa);
Related
I have set up a RecyclerView adapter with ViewPager in an activity namely TvShowEpisodeDetails , it works well but there is one issue, the Layout of RecyclerView is fixed while scrolling up and down in the Fragment(TvShowEpisodeDetailsFragment). But I want it to scroll with them.
The RecyclerView and ViewPager are both set inside viewpager_with_toolbar_overlay.xml Layout , and both has been settup in The Activity.
TvShowEpisodeDetailsFragment is the fragment class which belongs to activity class TvShowEpisodeDetails , the fragment creates as many episodes as a TV Show season can offer.
And off course this issue will be gone if I set RecyclerView adapter inside fragment, but I will get non-fixable highlighting and scrolling issues , that is why I set it inside the activity because it does not give those issues.
I need to make it work somehow inside the activity.
My goal is that RecyclerView and ViewPager has to be in the same layout XML file and they both must either be in the activity or fragment class
Is it possible to make the RecyclerView scroll with rest of the fragment layouts?
or
Is it possible to do it programmatically?
Here is the activity
public class TvShowEpisodeDetails extends MizActivity{
#Override
protected int getLayoutResource() {
return R.layout.viewpager_with_toolbar_overlay;
}
#Override
public void onCreate(Bundle savedInstanceState) {
mBus = MizuuApplication.getBus();
super.onCreate(savedInstanceState);
// Set theme
setTheme(R.style.Mizuu_Theme_NoBackground);
// setting episodeslist
final ArrayList<PlanetModel> episodeslist = new ArrayList<>();
for(TvShowEpisode e : mEpisodes){
episodeslist.add(new PlanetModel(e.mEpisode));
}
// setting RecyclerView
mEpisodesList = (RecyclerView) findViewById(R.id.episodesLIST);
// Setting LinearLayoutManager
LinearLayoutManager layoutManager
= new LinearLayoutManager(this.getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
//mEpisodesList.setLayoutManager(new LinearLayoutManager(mContext));
mEpisodesList.setLayoutManager(layoutManager);
// Setting RecyclerView Adapter
PlanetAdapter.OnItemClickListener indicatorCallback = new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(String item) {
SharedPreferences getPref = getContext().getSharedPreferences("PlanetAdapter", Context.MODE_PRIVATE);
int pos = getPref.getInt("newPosition", 0);
mViewPager.setCurrentItem(pos,false);
}
};
final PlanetAdapter planetAdapter = new PlanetAdapter(episodeslist,indicatorCallback);
mEpisodesList.setAdapter(planetAdapter);
// Setting ViewPager
mViewPager = (ViewPager) findViewById(R.id.awesomepager);
mViewPager.setAdapter(new TvShowEpisodeDetailsAdapter(getSupportFragmentManager()));
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
planetAdapter.setSelectedIndex(position);
planetAdapter.notifyDataSetChanged();
mEpisodesList.smoothScrollToPosition(position);
//mEpisodesList.scrollToPosition(position);
for (int i=0; i<episodeslist.size(); i++)
{
episodeslist.get(i).setPlanetSelected(false);
}
episodeslist.get(position).setPlanetSelected(true);
ViewUtils.updateToolbarBackground(TvShowEpisodeDetails.this, mToolbar, 0, mEpisodes.get(position).getTitle(), Color.TRANSPARENT);
}
});
if (savedInstanceState != null) {
mViewPager.setCurrentItem(savedInstanceState.getInt("tab", 0));
} else {
for (int i = 0; i < mEpisodes.size(); i++) {
if (mEpisodes.get(i).getSeason().equals(MizLib.addIndexZero(mSeason)) && mEpisodes.get(i).getEpisode().equals(MizLib.addIndexZero(mEpisode))) {
mViewPager.setCurrentItem(i);
break;
}
}
}
}
}
viewpager_with_toolbar_overlay
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
android:id="#+id/awesomepager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#068006"
android:layout_marginTop="450dp"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/episodesLIST"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:scrollbars="horizontal" />
</LinearLayout>
<include layout="#layout/toolbar_layout" />
</FrameLayout>
Here is the XML layout of the fragment which is inflated in onCreateView of the fragment class
episode_details.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:background="#color/abc_input_method_navigation_guard">
<com.miz.views.ObservableScrollView
android:id="#+id/observableScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/episodePhoto"
android:layout_width="match_parent"
android:layout_height="#dimen/backdrop_portrait_height"
android:scaleType="centerCrop"
android:src="#drawable/bg" />
<com.melnykov.fab.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/episodePhoto"
android:layout_alignParentEnd="false"
android:layout_alignParentRight="true"
android:layout_marginTop="#dimen/content_details_fab_negative_margin"
android:layout_marginRight="#dimen/content_details_baseline_margin"
android:src="#drawable/ic_play_arrow_white_36dp"
app:fab_colorNormal="#666"
app:fab_type="mini" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/fab"
android:layout_marginLeft="#dimen/content_details_baseline_margin"
android:layout_marginTop="#dimen/content_details_title_margin_top"
android:layout_marginRight="#dimen/content_details_baseline_margin"
android:layout_toLeftOf="#+id/fab"
android:orientation="vertical">
<TextView
android:id="#+id/movieTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="3"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_title" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/content_details_very_small_margin"
android:layout_marginBottom="#dimen/content_details_baseline_margin"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_subheader"
android:textStyle="bold|italic" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:id="#+id/details_area"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#666"
android:baselineAligned="false"
android:elevation="1dp"
android:minHeight="#dimen/content_details_large_margin"
android:orientation="horizontal"
android:paddingLeft="#dimen/content_details_baseline_margin"
android:paddingTop="#dimen/content_details_small_margin"
android:paddingRight="#dimen/content_details_baseline_margin"
android:paddingBottom="#dimen/content_details_small_margin">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center_horizontal"
android:lines="1"
android:maxLines="1"
android:text="#string/detailsAirDate"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="#dimen/content_details_area_subheader" />
<TextView
android:id="#+id/textReleaseDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_area_header"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/textView61"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center_horizontal"
android:lines="1"
android:maxLines="1"
android:text="#string/detailsRating"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="#dimen/content_details_area_subheader" />
<TextView
android:id="#+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_area_header"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="#dimen/content_details_baseline_margin">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/content_details_baseline_margin"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/director"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_movie_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/writer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_edit_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/guest_stars"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_people_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_folder_open_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_body_text" />
</LinearLayout>
</LinearLayout>
</com.miz.views.ObservableScrollView>
<FrameLayout
android:id="#+id/progress_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
android:visibility="gone">
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</FrameLayout>
</FrameLayout>
Update
Fragment
#SuppressLint("InflateParams") public class TvShowEpisodeDetailsFragment extends Fragment {
public TvShowEpisodeDetailsFragment() {}
public static TvShowEpisodeDetailsFragment newInstance(String showId, int season, int episode) {
TvShowEpisodeDetailsFragment pageFragment = new TvShowEpisodeDetailsFragment();
Bundle bundle = new Bundle();
bundle.putString("showId", showId);
bundle.putInt("season", season);
bundle.putInt("episode", episode);
pageFragment.setArguments(bundle);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
mContext = getActivity();
mBus = MizuuApplication.getBus();
mShowFileLocation = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(SHOW_FILE_LOCATION, true);
mPicasso = MizuuApplication.getPicassoDetailsView(getActivity());
mMediumItalic = TypefaceUtils.getRobotoMediumItalic(mContext);
mMedium = TypefaceUtils.getRobotoMedium(mContext);
mCondensedRegular = TypefaceUtils.getRobotoCondensedRegular(mContext);
mDatabaseHelper = MizuuApplication.getTvEpisodeDbAdapter();
LocalBroadcastManager.getInstance(mContext).registerReceiver(mBroadcastReceiver,
new IntentFilter(LocalBroadcastUtils.UPDATE_TV_SHOW_EPISODE_DETAILS_OVERVIEW));
loadEpisode();
}
#Override
public void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mBroadcastReceiver);
}
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
loadEpisode();
loadData();
}
};
private void loadEpisode() {
if (!getArguments().getString("showId").isEmpty() && getArguments().getInt("season") >= 0 && getArguments().getInt("episode") >= 0) {
Cursor cursor = mDatabaseHelper.getEpisode(getArguments().getString("showId"), getArguments().getInt("season"), getArguments().getInt("episode"));
if (cursor.moveToFirst()) {
mEpisode = new TvShowEpisode(getActivity(),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SHOW_ID)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_TITLE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_PLOT)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_AIRDATE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_DIRECTOR)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_WRITER)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_GUESTSTARS)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_RATING)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_HAS_WATCHED)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_FAVOURITE))
);
mEpisode.setFilepaths(MizuuApplication.getTvShowEpisodeMappingsDbAdapter().getFilepathsForEpisode(
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SHOW_ID)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE))
));
}
cursor.close();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.episode_details, container, false);
}
#Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mBackdrop = (ImageView) view.findViewById(R.id.imageBackground);
mEpisodePhoto = (ImageView) view.findViewById(R.id.episodePhoto);
mDetailsArea = view.findViewById(R.id.details_area);
mTitle = (TextView) view.findViewById(R.id.movieTitle);
mSeasonEpisodeNumber = (TextView) view.findViewById(R.id.textView7);
mDescription = (TextView) view.findViewById(R.id.textView2);
mFileSource = (TextView) view.findViewById(R.id.textView3);
mAirDate = (TextView) view.findViewById(R.id.textReleaseDate);
mRating = (TextView) view.findViewById(R.id.textView12);
mDirector = (TextView) view.findViewById(R.id.director);
mWriter = (TextView) view.findViewById(R.id.writer);
mGuestStars = (TextView) view.findViewById(R.id.guest_stars);
mScrollView = (ObservableScrollView) view.findViewById(R.id.observableScrollView);
mFab = (FloatingActionButton) view.findViewById(R.id.fab);
mFab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ViewUtils.animateFabJump(v, new SimpleAnimatorListener() {
#Override
public void onAnimationEnd(Animator animation) {
play();
}
});
}
});
...
}
...
}
I have set up a RecyclerView adapter with ViewPager in an activity namely TvShowEpisodeDetails , it works well but there is one issue, the Layout of RecyclerView is fixed while scrolling up and down in the Fragment(TvShowEpisodeDetailsFragment). But I want it to scroll with them.
It's hard to use the RecyclerView outside of the ViewPager page fragment; because you can't synchronize and link the touch/motion events when you scroll the page up/down (or when you swipe to next/previous page) between both the page fragment and a standalone (i.e. activity) RecyclerView. Even that won't be smooth.
So, the RecyclerView should be a part of the ViewPager page.
And off course this issue will be gone if I set RecyclerView adapter inside fragment, but I will get unfixable highlighting and scrolling issues
So, now the issue of adding the RecyclerView in the ViewPager fragment is the highlighting issue of the RecyclerView item when you click on any item or when you swipe the ViewPager to right/left page.
But, the main issue is that there is a RecyclerView instance per page, i.e. if you have 5 pages, then you have 5 RecyclerViews.
So, it's a cumbersome to track highlighting only within the RecyclerView adapter class. And hence manipulating that with OnClickListeners solely will have issues of linking these RecyclerView and adapter instances together to update their highlighting item.
So, a simpler approach is to pass a parameter to the RecyclerView adapter with the selected item (which is definitely equals to the current ViewPager page position).
And then do a check in the onBindViewHolder() if the position equals to the passed-in value, then highlight the item; otherwise keep items with the original color.
So, wrapping this up into actions:
Change the adapter constructor to accept a highlighted_position parameter
public PlanetAdapter(ArrayList<PlanetModel> episodeslist,
int highlightedPosition, OnItemClickListener listener)
Whenever you create the ViewPager fragment using newInstance() pass-in the current position of the page fragment:
So, in the TvShowEpisodeDetails activity:
for (int i = 0; i < mEpisodes.size(); i++)
fragments.add(TvShowEpisodeDetailsFragment
.newInstance(mShowId,
Integer.parseInt(mEpisodes.get(i).getSeason()),
Integer.parseInt(mEpisodes.get(i).getEpisode()),
i)); // The position
And in the TvShowEpisodeDetailsFragment fragment, register this into a field in the fragment argument:
public static TvShowEpisodeDetailsFragment newInstance(String showId, int season, int episode, int position) { // adding position
TvShowEpisodeDetailsFragment pageFragment = new TvShowEpisodeDetailsFragment();
Bundle bundle = new Bundle();
// trimmed code.
bundle.putInt("position", position); // <<<< into the bundle
pageFragment.setArguments(bundle);
return pageFragment;
}
And set that in the adapter creation:
int currentPosition = getArguments().getInt("position");
planetAdapter = new PlanetAdapter(episodeslist, currentPosition, new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(final int pos) {
mCallback.sendText(pos);
}
});
And reflect that in the adapter to highlight the item:
public class PlanetAdapter extends RecyclerView.Adapter<PlanetAdapter.PlanetViewHolder> {
private final int highlightedPos;
public PlanetAdapter(ArrayList<PlanetModel> episodeslist, int highlightedPosition, OnItemClickListener listener) {
this.episodeslist = episodeslist;
this.listener = listener;
this.highlightedPos = highlightedPosition; // <<< set the position
}
#Override
public void onBindViewHolder(PlanetAdapter.PlanetViewHolder vh, final int position) {
TextView tv = (TextView) vh.itemView;
PlanetModel planetModel = episodeslist.get(position);
tv.setText(planetModel.getPlanetName());
tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.bg, 0, 0, 0);
if (highlightedPos == position) { //<<<<< Highlight the item
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryLight));
Log.d("LOG_TAG", "onClick: Highlight item: " + highlightedPos);
} else {
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryDark));
Log.d("LOG_TAG", "onClick: No highlight: " + highlightedPos);
}
}
}
I have an android app code that uses the navigation drawer layout with fragments as the main content.
So far I have had a specific fragment class for all the fragment items in my drawer. Now I do however have a different layout I want to get as an item in my drawer as well. The layout is a LiniarLayout and defined in xml characteristic.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<LinearLayout android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/label_device_address"
android:textSize="18sp"/>
<Space android:layout_width="5dp"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/device_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"/>
</LinearLayout>
<LinearLayout android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/label_state"
android:textSize="18sp"/>
<Space android:layout_width="5dp"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/connection_state"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/disconnected"
android:textSize="18sp"/>
</LinearLayout>
<LinearLayout android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/label_data"
android:textSize="18sp"/>
<Space android:layout_width="5dp"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/data_value"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/no_data"
android:textSize="18sp"/>
</LinearLayout>
<ExpandableListView android:id="#+id/gatt_services_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
in my main activity I preload the fragments in the onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//create adapters early
mAdapter = new DeviceAdapter(this, false);
mFilterAdapter = new DeviceAdapter(this, true);
setContentView(R.layout.activity_main);
mFragmentManager = getFragmentManager();
mNavigationDrawerFragment = (NavigationDrawerFragment)
mFragmentManager.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
mDevices = new HashMap<String, ScanResultContent.BtLeDeviceItem>();
mFilteredDevices = new HashMap<String, ScanResultContent.BtLeDeviceItem>();
//setup fragment 1
mScanResultFragment = new ResultListFragment();
//setup fragment 2
mFilteredScanResultFragment = new ResultListFragment();
mScanResultFragment.setListAdapter(mAdapter);
//setup fragment 3
mDeviceInfoFragment = DeviceInfoFragment.newInstance("");
// Sets up UI references for the Device Info viewer.
mConnectionState = (TextView) findViewById(R.id.connection_state);
mDataField = (TextView) findViewById(R.id.data_value);
mGattServicesList = (ExpandableListView) findViewById(R.id.gatt_services_list);
mGattServicesList.setOnChildClickListener(servicesListClickListner);
mFilteredScanResultFragment.setListAdapter(mFilterAdapter);
// setup default fragment shown
mFragmentManager.beginTransaction().add(R.id.container, mScanResultFragment).commit();
}
I have tried to get the layout loaded into a fragment using the DeviceInfoFragment class:
public class DeviceInfoFragment extends Fragment {
public DeviceInfoFragment(){
super();
}
public static DeviceInfoFragment newInstance(String text) {
DeviceInfoFragment f = new DeviceInfoFragment();
Bundle b = new Bundle();
b.putString("text", text);
f.setArguments(b);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.gatt_characteristics_layout, container, false);
return v;
}
}
I want to be able to switch between the fragments using this (which have worked fine except for the new fragment 3):
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment f = null;
switch (position+1){
case 1:
f = mScanResultFragment;
mTitle = getString(R.string.title_devicescan);
break;
case 2:
f = mFilteredScanResultFragment;
mTitle = getString(R.string.title_results);
break;
case 3:
f = mDeviceInfoFragment;
mTitle = getString(R.string.title_device_info);
break;
}
if(f != null) {
mFragmentManager.beginTransaction()
.replace(R.id.container, f)
.commit();
}
restoreActionBar();
}
It does however not seem to work as the line:
mGattServicesList.setOnChildClickListener(servicesListClickListner);
fails with
E/AndroidRuntime(30644): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ExpandableListView.setOnChildClickListener(android.widget.ExpandableListView$OnChildClickListener)' on a null object reference
Can anyone tell me what I am doing wrong here?
I'm implementing a Camera app on Android, I'd like to have a button on it which will lead the user to the developer website, or my website.
This button is placed right of the shutter button.
I was trying to call the webview activity from this button, but it's giving me errors and I'm confused on this case, because there are plenty of examples of calling an activity inside another one, but no from a camera app.
I don't know what am I doing wrong.
Here's the piece of code in MainActivity:
public class MainActivity extends Activity /**implements OnClickListener**/ {
ImageView image;
Activity context;
Preview preview;
Camera camera;
Button exitButton;
ImageView fotoButton;
Button webButton;
LinearLayout progressLayout;
String path = "/sdcard/KutCamera/cache/images/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
webButton = (Button) findViewById(R.id.imageView_world);
fotoButton = (ImageView) findViewById(R.id.imageView_foto);
exitButton = (Button) findViewById(R.id.button_exit);
image = (ImageView) findViewById(R.id.imageView_photo);
progressLayout = (LinearLayout) findViewById(R.id.progress_layout);
preview = new Preview(this,
(SurfaceView) findViewById(R.id.KutCameraFragment));
FrameLayout frame = (FrameLayout) findViewById(R.id.preview);
frame.addView(preview);
preview.setKeepScreenOn(true);
fotoButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
takeFocusedPicture();
} catch (Exception e) {
}
exitButton.setClickable(false);
fotoButton.setClickable(false);
webButton.setClickable(true);
progressLayout.setVisibility(View.VISIBLE);
}
});
webButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(MainActivity.this, WebActivity.class);
MainActivity.this.startActivity(myIntent);
}
});
}
Everytime I run it it throws me this error:
4-04 00:33:43.929 4237-4237/com.kut.kutcamera E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.kut.kutcamera/com.kut.kutcamera.MainActivity}: java.lang.ClassCastException: android.widget.ImageView cannot be cast to android.widget.Button
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2295)
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:175)
at android.app.ActivityThread.main(ActivityThread.java:5279)
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.ClassCastException: android.widget.ImageView cannot be cast to android.widget.Button
at com.kut.kutcamera.MainActivity.onCreate(MainActivity.java:56)
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:2295)
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:175)
at android.app.ActivityThread.main(ActivityThread.java:5279)
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)
The layout declaration of the world button is just Okay, I don't really think it's because of that, I guess there is something inside that camera method that doesn't allows me to properly make the call.
Can anybody shed some light on this?
Thanks in advance!
EDIT
activiy_main.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity" >
<FrameLayout
android:id="#+id/preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" >
<SurfaceView
android:id="#+id/KutCameraFragment"
android:name="com.kut.camera.KutCameraFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<RelativeLayout
android:id="#+id/rel_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:alpha="1"
android:background="#android:color/black"
android:orientation="vertical"
android:padding="10dp" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textViewReferan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Photo"
android:textColor="#android:color/white"
android:textSize="16sp" />
<Button
android:id="#+id/button_exit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#android:color/transparent"
android:text="Ok"
android:textColor="#2799CF" />
</RelativeLayout>
<LinearLayout
android:id="#+id/progress_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone" >
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/islem_value_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Loading..." />
</LinearLayout>
</LinearLayout>
<RelativeLayout
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:alpha="0.9"
android:background="#android:color/black"
android:padding="10dp" >
<ImageView
android:id="#+id/imageView_foto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/camera"
android:contentDescription="1" />
<ImageView
android:id="#+id/imageView_photo"
android:layout_width="80dp"
android:layout_height="100dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:padding="5dp"
android:scaleType="fitCenter"
android:src="#drawable/fotocekicon"
android:contentDescription="2" />
<ImageView
android:id="#+id/imageView_world"
android:layout_width="80dp"
android:layout_height="100dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:padding="5dp"
android:scaleType="fitCenter"
android:src="#drawable/world"
android:contentDescription="2" />
</RelativeLayout>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/mark3"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
</FrameLayout>
</FrameLayout>
Hi I have update your activity class, just replace with my code let me know you still face the problem.
public class MainActivity extends Activity /**implements OnClickListener**/ {
ImageView image;
Activity context;
Preview preview;
Camera camera;
Button exitButton;
ImageView fotoButton;
ImageView webButton;
LinearLayout progressLayout;
String path = "/sdcard/KutCamera/cache/images/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
webButton = (ImageView) findViewById(R.id.imageView_world);
fotoButton = (ImageView) findViewById(R.id.imageView_foto);
exitButton = (Button) findViewById(R.id.button_exit);
image = (ImageView) findViewById(R.id.imageView_photo);
progressLayout = (LinearLayout) findViewById(R.id.progress_layout);
preview = new Preview(this,
(SurfaceView) findViewById(R.id.KutCameraFragment));
FrameLayout frame = (FrameLayout) findViewById(R.id.preview);
frame.addView(preview);
preview.setKeepScreenOn(true);
fotoButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
takeFocusedPicture();
} catch (Exception e) {
}
exitButton.setClickable(false);
fotoButton.setClickable(false);
webButton.setClickable(true);
progressLayout.setVisibility(View.VISIBLE);
}
});
webButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(MainActivity.this, WebActivity.class);
MainActivity.this.startActivity(myIntent);
}
});
}
Thank you
I want that when I click on an element of GridView displayed letter, which I clicked. But initially I got here error when I wanted to take the position of the element. If I understood correctly, gridview does not see the textview, but i don't know why.
Error:
5312-5312/standandroid.ru.words E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.content.res.Resources.getText(Resources.java:240)
at android.content.res.MiuiResources.getText(MiuiResources.java:131)
at android.widget.Toast.makeText(Toast.java:273)
at standandroid.ru.words.MainActivity$1$1.onItemClick(MainActivity.java:70)
at android.widget.AdapterView.performItemClick(AdapterView.java:298)
at android.widget.AbsListView.performItemClick(AbsListView.java:1130)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2818)
at android.widget.AbsListView$1.run(AbsListView.java:3498)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5137)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:756)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:572)
at miui.dexspy.DexspyInstaller.main(DexspyInstaller.java:171)
at dalvik.system.NativeStart.main(Native Method)
MainActivity.java :
public class MainActivity extends Activity {
TextView txt, textTV;
EditText etxt;
Button btn;
ArrayAdapter<String> adapter;
GridView gridView;
String name;
char c;
ArrayList arrayList=new ArrayList();
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView) findViewById(R.id.textView);
etxt = (EditText) findViewById(R.id.editText);
btn = (Button) findViewById(R.id.button);
textTV = (TextView) findViewById(R.id.tv);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = etxt.getText().toString();
TreeSet list = new TreeSet();
for (i = 0; i < name.length(); i++) {
c = name.charAt(i);
list.add(c);
}
arrayList = new ArrayList(list);
adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.item, R.id.tv, arrayList);
gridView = (GridView) findViewById(R.id.gridmain);
gridView.setAdapter(adapter);
ViewGrid();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, position,Toast.LENGTH_LONG).show();
}
});
}
});}
private void ViewGrid(){
gridView.setNumColumns(4);
gridView.setStretchMode(GridView.STRETCH_COLUMN_WIDTH); }}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textView"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="175dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:singleLine="true"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="48dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="44dp" />
<GridView
android:id="#+id/gridmain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="44dp"
android:layout_alignTop="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"></GridView>
</RelativeLayout>
item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tv"
android:textSize="40sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
http://i.stack.imgur.com/j5S93.png
Ohh! I see, the issue is that Toast is thinking of position as a resourceID. If you see Toast specs here, you would see that you can define resourceId or a CharSequence. So make sure you are passing the position as a String. Something like:
Toast.makeText(MainActivity.this, String.valueOf(position),Toast.LENGTH_LONG).show();
There is an error occurring in an app of mine when I set an Adapter to a ListView. Upon removing the 60/61 line of code (mainListViewTip/Hour.setAdapter(tip/hourAdapter);), the application runs perfectly, except since the adapter is never set, no data appears in the ListView. The goal is for the values of the EditText fields to become new values in the String to be displayed in a ListView along with previous entries also.
The TipBookActivity code:
public class TipBookActivity extends Activity {
/** Called when the activity is first created. */
TextView textTip,textHour,textWage;
EditText editHour,editTip;
float wage;
int precision = 100;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textTip = (TextView) findViewById(R.id.tvTip);
textHour = (TextView) findViewById(R.id.tvHour);
textWage = (TextView) findViewById(R.id.tvWage);
editTip = (EditText) findViewById(R.id.etTip);
editHour = (EditText) findViewById(R.id.etHour);
}
public void myClickHandler (View v){
Button bSubmit = (Button) findViewById(R.id.bSubmit);
bSubmit.isClickable();
ListView mainListViewTip = (ListView) findViewById(R.id.mainListViewTip);
ListView mainListViewHour = (ListView) findViewById(R.id.mainListViewHour);
switch(v.getId()){
case R.id.bSubmit:
if(bSubmit.isPressed()){
wage = Float.parseFloat(editTip.getText().toString()) / Float.parseFloat(editHour.getText().toString());
String tip = String.format("$%.2f",wage);
textWage.setText(String.valueOf(tip) + " an hour");
textHour.setText(editHour.getText() + " Hour(s)");
textTip.setText("$" + editTip.getText());
String[] sTip = new String[] {editTip.getText().toString()};
String[] sHour = new String[] {editHour.getText().toString()};
ArrayAdapter<String> tipAdapter = new ArrayAdapter<String>(TipBookActivity.this,R.layout.main,R.id.rowTextView,sTip);
ArrayAdapter<String> hourAdapter = new ArrayAdapter<String>(TipBookActivity.this,R.layout.main,R.id.rowTextView,sHour);
mainListViewTip.setAdapter(tipAdapter);
mainListViewHour.setAdapter(hourAdapter);
Toast displayWage = Toast.makeText(this, "$" + editTip.getText() + " over " + editHour.getText() + " hour(s) for a wage of $" + wage + " an hour.", Toast.LENGTH_LONG);
displayWage.show();
}
}
}
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
MenuInflater mMain = getMenuInflater();
mMain.inflate(R.menu.main_menu,menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
ViewFlipper vf = (ViewFlipper) findViewById(R.id.vfMain);
switch (item.getItemId()){
case R.id.menuHistory:
vf.setAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_in_right));
vf.showNext();
return true;
case R.id.menuClear:
//set up next tutorials
Toast displayClear = Toast.makeText(this, "Clear History feature coming soon.", Toast.LENGTH_SHORT);
displayClear.show();
return true;
case R.id.menuSettings:
Toast displaySettings = Toast.makeText(this, "Settings Options coming soon.", Toast.LENGTH_SHORT);
displaySettings.show();
return true;
}
return false;
}
public void onBackPressed() {
finish();
}
}
The main xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/llMain" >
<ViewFlipper
android:id="#+id/vfMain"
android:layout_height="match_parent"
android:layout_width="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/rletbtv">
<EditText
android:id="#+id/etTip"
android:layout_height="wrap_content"
android:layout_width="140dp"
android:hint="Tips"
android:layout_margin="8dp"
android:inputType="numberDecimal"
android:layout_alignParentLeft="true"/>
<EditText
android:id="#+id/etHour"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:hint="Hours"
android:layout_margin="8dp"
android:inputType="numberDecimal"
android:layout_alignParentRight="true"
android:layout_toRightOf="#id/etTip"/>
<Button
android:id="#+id/bSubmit"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_margin="8dp"
android:ems="10"
android:text="Submit"
android:textSize="22sp"
android:layout_below="#id/etTip"
android:onClick="myClickHandler"/>
<TextView
android:id="#+id/tvTip"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Tips"
android:textSize="22sp"
android:layout_margin="8dp"
android:layout_below="#id/bSubmit"/>
<TextView
android:id="#+id/tvHour"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Hours"
android:textSize="22sp"
android:layout_margin="8dp"
android:layout_below="#id/bSubmit"
android:layout_toRightOf="#id/tvTip"/>
<TextView
android:id="#+id/tvWage"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Wage"
android:textSize="22sp"
android:layout_margin="8dp"
android:layout_below="#id/bSubmit"
android:layout_toRightOf="#id/tvHour"/>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="50"
android:id="#+id/mainListViewTip"/>
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="50"
android:id="#+id/mainListViewHour"/>
</LinearLayout>
</ViewFlipper>
</LinearLayout>
The simplerow xml file:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rowTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp" />
The logcat error report:
FATAL EXCEPTION: main
java.lang.NullPointerException
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:353)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:323)
at android.widget.AbsListView.obtainView(AbsListView.java:1315)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1198)
at android.widget.ListView.onMeasure(ListView.java:1109)
at android.view.View.measure(View.java:8171)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1012)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:381)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
at android.view.View.measure(View.java:8171)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
at android.view.View.measure(View.java:8171)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1012)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:381)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
at android.view.View.measure(View.java:8171)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
at android.view.View.measure(View.java:8171)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:526)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
at android.view.View.measure(View.java:8171)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
at android.view.View.measure(View.java:8171)
at android.view.ViewRoot.performTraversals(ViewRoot.java:801)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
at android.os.Handler.dispatchMessage(Handler.java:99)
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)
The problem is because the layout you are passing to the ArrayAdapter is R.layout.main. This is not the resource you want to pass; you want to pass the layout for each individual list item. The layout you pass must have a TextView with a certain ID in it, and obviously R.layout.main does not have this.
Try substituting R.layout.main in those two lines to be android.R.layout.simple_list_item_1, and removing your custom TextView ID. That should solve the error and allow your list to display properly.
Like so:
ArrayAdapter<String> tipAdapter = new ArrayAdapter<String>(TipBookActivity.this,android.R.layout.simple_list_item_1,sTip);
ArrayAdapter<String> hourAdapter = new ArrayAdapter<String>(TipBookActivity.this,android.R.layout.simple_list_item_1,sHour);
If you later want to use a custom layout for the list items, try this tutorial or this one.
yes eric is right change this two lines of arrayadapter as shown below if you have not make layout for row item of listview
ArrayAdapter<String> tipAdapter = new ArrayAdapter<String>(TipBookActivity.this,R.layout.main,R.id.rowTextView,sTip);
ArrayAdapter<String> hourAdapter = new ArrayAdapter<String>(TipBookActivity.this,R.layout.main,R.id.rowTextView,sHour);
by
ArrayAdapter<String> tipAdapter = new ArrayAdapter<String>(TipBookActivity.this,android.R.layout.simple_list_item_1,sTip);
ArrayAdapter<String> hourAdapter = new ArrayAdapter<String>(TipBookActivity.this,android.R.layout.simple_list_item_1,sHour);
I think adam want to use his own textview so that he can change the text size and color which is not possible with "android.R.layout.simple_list_item_1". Instead of that we can use adam's "simplerow xml" file. to get this we need to replace 2 lines of the code
ArrayAdapter<String> tipAdapter = new ArrayAdapter<String>(TipBookActivity.this,R.layout.main,R.id.rowTextView,sTip);
ArrayAdapter<String> hourAdapter = new ArrayAdapter<String>(TipBookActivity.this,R.layout.main,R.id.rowTextView,sHour);
to
ArrayAdapter<String> tipAdapter = new ArrayAdapter<String>(TipBookActivity.this,R.layout.samplerow,R.id.rowTextView,sTip);
ArrayAdapter<String> hourAdapter = new ArrayAdapter<String>(TipBookActivity.this,R.layout.samplerow,R.id.rowTextView,sHour);
Note: the change is "R.layout.main" to "R.layout.samplerow"