I am using a tabbed layout, created using the wizard, and have a fragment ready to go. I have added some EditTexts to my fragment, and am all ready to go, however, when running the app, I get a NullPointerException at my EditText declaration.
Fragment Code:
package com.boreas.snowdaycalculatorsp2;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class AdvancedFragment extends Fragment {
EditText inSnow, durnStorm, pSnow, pTime, fSnow, wSpeed, sGround;
public double inchSnow, durationStorm, peakSnow, peakTime, finalSnow, windSpeed, snowGround, result;
TextView results;
Button calc;
String resInt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
inSnow = (EditText) getView().findViewById(R.id.inchesSnow);
durnStorm = (EditText)getView().findViewById(R.id.durationStorm);
pSnow = (EditText) getView().findViewById(R.id.peakRate);
pTime = (EditText)getView().findViewById(R.id.peakRateTime);
fSnow = (EditText) getView().findViewById(R.id.finalRate);
wSpeed = (EditText) getView().findViewById(R.id.windSpeed);
sGround = (EditText) getView().findViewById(R.id.snowGround);
results = (TextView) getView().findViewById(R.id.resultView);
calc = (Button) getView().findViewById(R.id.button);
return inflater.inflate(R.layout.advfrag_layout, container, false);
}
}
Fragment XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="#000000"
android:layout_height="match_parent">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/inchesSnow"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:hint="Inches of Snow"
android:singleLine="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/durationStorm"
android:layout_below="#+id/inchesSnow"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:hint="Duration of Storm"
android:singleLine="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/peakRate"
android:layout_below="#+id/durationStorm"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:hint="Peak Snow Rate"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:layout_alignParentStart="false"
android:singleLine="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/peakRateTime"
android:layout_below="#+id/peakRate"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:hint="Time of Peak Snow Rate"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:singleLine="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberSigned"
android:ems="10"
android:id="#+id/finalRate"
android:layout_below="#+id/peakRateTime"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:hint="Final Snow Rate"
android:singleLine="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberSigned"
android:ems="10"
android:id="#+id/windSpeed"
android:layout_below="#+id/finalRate"
android:layout_alignParentLeft="true"
android:hint="Wind Speed"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:layout_alignParentRight="true"
android:singleLine="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/snowGround"
android:layout_below="#+id/windSpeed"
android:layout_alignParentLeft="true"
android:hint="Snow Already on Ground"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:layout_alignParentRight="true"
android:singleLine="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate"
android:id="#+id/button"
android:layout_below="#+id/snowGround"
android:layout_centerHorizontal="true"
android:layout_marginTop="39dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/resultView"
android:layout_below="#+id/button"
android:layout_alignRight="#+id/button"
android:layout_marginTop="41dp"
android:layout_alignLeft="#+id/button" />
</RelativeLayout>
Main Activity:
package com.boreas.snowdaycalculatorsp2;
import java.util.Locale;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
Fragment fragment;
switch (position){
case 0:
fragment = new BasicFragment();
break;
case 1:
fragment = new AdvancedFragment();
break;
default:
throw new IllegalArgumentException("Invalid Section Number");
}
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return "Basic";
case 1:
return "Advanced";
}
return null;
}
}
}
Any ideas on what is causing the NullPointerException?
Either you should initialize your view using view object using inflater
like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.advfrag_layout, container, false);
inSnow = (EditText) view.getView().findViewById(R.id.inchesSnow);
durnStorm = (EditText)view.getView().findViewById(R.id.durationStorm);
pSnow = (EditText)view. getView().findViewById(R.id.peakRate);
pTime = (EditText)view.getView().findViewById(R.id.peakRateTime);
fSnow = (EditText)view. getView().findViewById(R.id.finalRate);
wSpeed = (EditText)view. getView().findViewById(R.id.windSpeed);
sGround = (EditText) view.getView().findViewById(R.id.snowGround);
results = (TextView)view. getView().findViewById(R.id.resultView);
calc = (Button)view. getView().findViewById(R.id.button);
return view;
}
Or you should initialize it in OnActivityCreated like this
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
nSnow = (EditText) getView().findViewById(R.id.inchesSnow);
durnStorm = (EditText)getView().findViewById(R.id.durationStorm);
pSnow = (EditText) getView().findViewById(R.id.peakRate);
pTime = (EditText)getView().findViewById(R.id.peakRateTime);
fSnow = (EditText) getView().findViewById(R.id.finalRate);
wSpeed = (EditText) getView().findViewById(R.id.windSpeed);
sGround = (EditText) getView().findViewById(R.id.snowGround);
results = (TextView) getView().findViewById(R.id.resultView);
calc = (Button) getView().findViewById(R.id.button);
}
Note: You are getting error because OnCreateView is trying to execute before OnCreate of Activity has finished .
Change onCreateView to
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.advfrag_layout, container, false);
// inflate the layout
inSnow = (EditText) view.findViewById(R.id.inchesSnow);
// use the inflated view object to initialize edittext
durnStorm = (EditText)view.findViewById(R.id.durationStorm);
pSnow = (EditText) view.findViewById(R.id.peakRate);
pTime = (EditText)view.findViewById(R.id.peakRateTime);
fSnow = (EditText)view.findViewById(R.id.finalRate);
wSpeed = (EditText) view.findViewById(R.id.windSpeed);
sGround = (EditText) view.findViewById(R.id.snowGround);
results = (TextView) view.findViewById(R.id.resultView);
calc = (Button) view.findViewById(R.id.button);
return view; // return view
}
You have to inflate the View in onCreateView
View rootView = inflater.inflate(R.layout.advfrag_layout,
container, false);
inSnow = (EditText) rootView.findViewById(R.id.inchesSnow);
This should fix the problem
You need to initialize the view you are using so it knows where to find your editText.
Related
I would like to know how to implement a tabbed activity( 4 fragments) with recycler and cardview that connect to a firebase DB to pull data.
-Do I have to create an adapter for each fragment or same adapter but each fragment will filter what data it requires?
-Do I have to call getInstance and reference Firebase DB from main Activity?
I'm completely new to recyclerView, please give me every possible details.
-For the cardview, an object will be created called "property", 2 textview and 1 imageview. How this will fit into the whole code, I mean the property class and its instance.
-Can I store the image that will be used in the cardview on Firebase Storage? If so how to query them?
Here's the code
package com.realty.drake.kunuk;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("debugg", "OnCreate started");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Log.d("DEBUGG","getItem called" );
//Returning the current tab
switch (position) {
case 0:
Tab1Buy tab1 = new Tab1Buy();
return tab1;
case 1:
Tab2Rent tab2 = new Tab2Rent();
return tab2;
case 2:
Tab3Lot tab3 = new Tab3Lot();
return tab3;
case 3:
Tab4Saved tab4 = new Tab4Saved();
return tab4;
default:
return null;
}
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position){
Log.d("Debugg", "getPageTitle: Executed");
switch (position) {
case 0:
return "BUY";
case 1:
return "RENT";
case 2:
return "LOT";
case 3:
return "SAVED";
}
return null;
}
}
}
package com.realty.drake.kunuk;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by drake on 4/11/18.
*/
public class Tab1Buy extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1buy, container, false);
return rootView;
}
}
package com.realty.drake.kunuk;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by drake on 4/11/18.
*/
public class Tab2Rent extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab2rent, container, false);
return rootView;
}
}
<?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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.realty.drake.kunuk.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
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:layout_weight="1"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:title="#string/app_name">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
app:tabMode="fixed">
<android.support.design.widget.TabItem
android:id="#+id/tabItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_1" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_2" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_3" />
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:background="#dfdfdf"
android:orientation="vertical">
<!-- TODO Add white icon -->
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/tools"
android:id="#+id/property"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:cardUseCompatPadding="true"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="290dp"
android:orientation="vertical">
<ImageView
android:id="#+id/post_image"
android:contentDescription="#string/property"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="71dp"
android:scaleType="centerCrop"
android:src="#drawable/house1"
app:layout_constraintBottom_toTopOf="#+id/number_bedroom"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/post_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginStart="5dp"
android:layout_marginTop="8dp"
android:text="55,000$"
android:textColor="#color/colorPrimary"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.79" />
<TextView
android:id="#+id/post_desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginStart="5dp"
android:layout_marginTop="1dp"
android:text="23,Rue Duvivier-hall, Les Cayes, "
android:textColor="#737373"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/post_title"
app:layout_constraintVertical_bias="0.0" />
<ImageView
android:id="#+id/bathroom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginStart="100dp"
android:layout_marginTop="2dp"
android:background="#ff9100"
android:src="#drawable/bathtub"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.976" />
<ImageView
android:id="#+id/bedroom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginStart="25dp"
android:layout_marginTop="2dp"
android:background="#ff9100"
android:src="#drawable/bedroom"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.976" />
<TextView
android:id="#+id/number_bathroom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:text="2"
android:textColor="#ff9100"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="#+id/bathroom"
app:layout_constraintEnd_toStartOf="#+id/bathroom" />
<TextView
android:id="#+id/number_bedroom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:text="3"
android:textColor="#ff9100"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="#+id/bedroom"
app:layout_constraintEnd_toStartOf="#+id/bedroom" />
<TextView
android:id="#+id/number_garage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:text="1"
android:textColor="#ff9100"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="#+id/garage"
app:layout_constraintEnd_toStartOf="#+id/garage" />
<ImageView
android:id="#+id/garage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginStart="175dp"
android:layout_marginTop="2dp"
android:background="#ff9100"
android:src="#drawable/garage"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.976" />
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<!--TODO add recyclerView layout-->
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rv_items">
</android.support.v7.widget.RecyclerView>
</FrameLayout>
Thanks for your help
-Do I have to create an adapter for each fragment or same adapter but each fragment will filter what data it requires?
A: I have each fragment get their own reference to the firebase database, each one querying a child. In the firebase database, look at image, each Fragment call one child: Buy, Lot, Rent..
-Do I have to call getInstance and reference Firebase DB from main Activity? I'm completely new to recyclerView, please give me every possible details.
A: I call the getIntance in each fragment instead,
public class Tab1Buy extends Fragment {
private DatabaseReference propertyRef;
private RecyclerView mPropertyRecyclerView;
FirebaseRecyclerAdapter<Property, PropertyViewHolder> mPropertyAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.property_tab, container, false);
mPropertyRecyclerView = rootView.findViewById(R.id.property_recyclerView);
return rootView;
}
//TODO Check internet and display error msg if internet down
#Override
public void onViewCreated(final View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mPropertyRecyclerView.hasFixedSize();
mPropertyRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
final ProgressBar progressBar = view.findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
propertyRef = FirebaseDatabase.getInstance()
.getReference()
.child("Buy");
propertyRef.keepSynced(true);
// keyQuery - the Firebase location containing the list of keys to be found in dataRef
//Query personQuery = propertyRef.orderByKey();
FirebaseRecyclerOptions<Property> options =
new FirebaseRecyclerOptions.Builder<Property>()
.setQuery(propertyRef, Property.class)
.build();
mPropertyAdapter = new FirebaseRecyclerAdapter<Property, PropertyViewHolder>(options) {
#Override
// Bind the Property object to the ViewHolder PropertyHolder
public void onBindViewHolder(#NonNull PropertyViewHolder holder,
final int position, #NonNull final Property model) {
holder.setPrice(model.getPrice());
holder.setAddress(model.getAddress());
holder.setNumberOfBed(model.getNumberOfBed());
holder.setNumberOfBath(model.getNumberOfBath());
holder.setNumberOfCar(model.getNumberOfCar());
holder.setPropertyImage(model.getPropertyImage());
//This Intent send Parcelable from Property to PropertyDetail
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().startActivity(new Intent(getActivity(), PropertyDetail.class)
.putExtra("Property", model));
}
});
}
#Override
public PropertyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a new instance of the ViewHolder, in this case we are using a custom
// layout called R.layout.property_card for each item
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.property_card, parent, false);
return new PropertyViewHolder(view);
}
#Override
public void onDataChanged() {
// Called each time there is a new data snapshot. You may want to use this method
// to hide a loading spinner or check for the "no documents" state and update your UI.
// ...
progressBar.setVisibility(View.GONE);
}
//TODO Implement onError
#Override
public void onError(#NonNull DatabaseError e) {
// Called when there is an error getting data. You may want to update
// your UI to display an error message to the user.
// ...
progressBar.setVisibility(View.GONE);
Toast.makeText(getActivity(), "DatabaseError", Toast.LENGTH_SHORT).show();
}
};
mPropertyRecyclerView.setAdapter(mPropertyAdapter);
}
#Override
public void onStart() {
super.onStart();
mPropertyAdapter.startListening();
}
#Override
public void onStop() {
super.onStop();
mPropertyAdapter.stopListening();
}
public class PropertyViewHolder extends RecyclerView.ViewHolder {
View mView;
public PropertyViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setPrice(int price) {
String currencyPrice = NumberFormat //Format the price variable in currency form
.getCurrencyInstance(Locale.US)
.format(price);
TextView Price = mView.findViewById(R.id.post_price);
Price.setText(currencyPrice);
}
public void setAddress(String address){
TextView Address = mView.findViewById(R.id.post_address);
Address.setText(String.valueOf(address));
}
public void setNumberOfBed(int numberOfBed){
TextView NumberOfBed = mView.findViewById(R.id.post_bedroom);
NumberOfBed.setText(String.valueOf(numberOfBed));
}
public void setNumberOfBath(int numberOfBath){
TextView NumberOfBath = mView.findViewById(R.id.post_bathroom);
NumberOfBath.setText(String.valueOf(numberOfBath));
}
public void setNumberOfCar(int numberOfCar) {
TextView NumberOfCar = mView.findViewById(R.id.post_garage);
NumberOfCar.setText(String.valueOf(numberOfCar));
}
public void setPropertyImage(String propertyImage){
ImageView imageView = mView.findViewById(R.id.post_propertyImage);
//take one long string containing multiple url in and parse it
String propertyImageArray[] = propertyImage.split(",");
//Loading circle for placeholder, ColorAccent has been used
CircularProgressDrawable progressDrawable =
new CircularProgressDrawable(getContext());
progressDrawable.setStrokeWidth(5f);
progressDrawable.setCenterRadius(30f);
progressDrawable.setColorSchemeColors(Color.argb(1,255,145,0));
progressDrawable.start();
// Download directly from StorageReference using Glide
// (See MyAppGlideModule for Loader registration)
GlideApp.with(getContext())
.load(propertyImageArray[0])
.placeholder(progressDrawable)
.fitCenter()
.into(imageView);
}
}
}
-For the cardview, an object will be created called "property", 2 textview and 1 imageview. How this will fit into the whole code, I mean the property class and its instance.
A: Create a new instance of the ViewHolder, in this case we are using a custom layout called R.layout.property_card for each item. Look at the code above, specifically at that line public PropertyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
-Can I store the image that will be used in the cardview on Firebase Storage? If so how to query them?
A: yes I stored image in Firebase Storage,then I use their generated url to pass in Glide method. look at the code above.
I only show for the first fragment because they all look similar, except the child reference in the firebase differ.
I am developing my first Android application as part of a college project. I am relatively new to java. My application consists of a bottom navigation, which contains 4 separate pages. Within these pages I have a head section, containing a title, contact button and logout button.
Underneath the head section I wish to have a midsection which will in itself contain 3 swipe panels containing information. Essentially there should be 3 panels for each page, with there being 4 pages (So 4 sets of 3 swipe panels).
This is where I'm having difficulty.. I'm unsure of how to nest the fragments so that only that midsection will be swipe-able. Here is a screenshot of what I have so far:
Screenshot of app
Here is my Code for my MainActivity.java class:
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
private static final String SELECTED_ITEM = "arg_selected_item";
private BottomNavigationView mBottomNav;
private int mSelectedItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBottomNav = (BottomNavigationView) findViewById(R.id.navigation);
mBottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
selectFragment(item);
return true;
}
});
MenuItem selectedItem;
if (savedInstanceState != null) {
mSelectedItem = savedInstanceState.getInt(SELECTED_ITEM, 0);
selectedItem = mBottomNav.getMenu().findItem(mSelectedItem);
} else {
selectedItem = mBottomNav.getMenu().getItem(0);
}
selectFragment(selectedItem);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(SELECTED_ITEM, mSelectedItem);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
MenuItem homeItem = mBottomNav.getMenu().getItem(0);
if (mSelectedItem != homeItem.getItemId()) {
// select home item
selectFragment(homeItem);
} else {
super.onBackPressed();
}
}
private void selectFragment(MenuItem item) {
Fragment frag = null;
// init corresponding fragment
switch (item.getItemId()) {
case R.id.menu_home:
frag = MenuFragment.newInstance(getString(R.string.text_home),
getString(R.string.test_home));
break;
case R.id.menu_notifications:
//Call to a function that does the stuff here
frag = MenuFragment.newInstance(getString(R.string.text_notifications),
getString(R.string.test_notifications));
break;
case R.id.menu_search:
frag = MenuFragment.newInstance(getString(R.string.text_search),
getString(R.string.test_search));
break;
case R.id.menu_followed:
frag = MenuFragment.newInstance(getString(R.string.text_follow),
getString(R.string.test_follow));
}
// update selected item
mSelectedItem = item.getItemId();
// uncheck the other items.
for (int i = 0; i< mBottomNav.getMenu().size(); i++) {
MenuItem menuItem = mBottomNav.getMenu().getItem(i);
menuItem.setChecked(menuItem.getItemId() == item.getItemId());
}
if (frag != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.container, frag, frag.getTag());
ft.commit();
}
}
}
Here is the acitivity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:design="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.socialivemusic.socialivetestproject.MainActivity">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#ff292929">
</FrameLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_weight="0.06"
android:background="#ff000000"
android:textAlignment="center"
design:menu="#menu/bottom_nav_items" />
</LinearLayout>
And here is my MenuFragment.java class:
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
public class MenuFragment extends Fragment {
private static final String ARG_TEXT = "arg_text";
private static final String ARG_TESTSTRING = "arg_testString";
private String mText;
private String mTest;
private View mContent;
private TextView mTextView;
private TextView mTestView;
private Button contactButton;
private Button logoutButton;
public static Fragment newInstance(String text, String testString) {
Fragment frag = new MenuFragment();
Bundle args = new Bundle();
args.putString(ARG_TEXT, text);
args.putString(ARG_TESTSTRING, testString);
frag.setArguments(args);
return frag;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_menu, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// retrieve text and color from bundle or savedInstanceState
if (savedInstanceState == null) {
Bundle args = getArguments();
mText = args.getString(ARG_TEXT);
mTest = args.getString(ARG_TESTSTRING);
} else {
mText = savedInstanceState.getString(ARG_TEXT);
mTest = savedInstanceState.getString(ARG_TESTSTRING);
}
// initialize views
mContent = view.findViewById(R.id.fragment_content);
mTextView = (TextView) view.findViewById(R.id.text);
mTestView = (TextView) view.findViewById(R.id.test);
contactButton = (Button) view.findViewById(R.id.contactButton);
logoutButton = (Button) view.findViewById(R.id.logoutbutton);
// set text and background color
mTextView.setText(mText);
mTestView.setText(mTest);
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(ARG_TEXT, mText);
outState.putString(ARG_TESTSTRING, mTest);
super.onSaveInstanceState(outState);
}
}
Here is the fragments_menu.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.socialivemusic.socialivetestproject.MenuFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_marginLeft="17dp"
android:layout_marginRight="17dp"
android:layout_height="150dp"
android:layout_marginTop="15dp"
android:background="#ff434343"
android:weightSum="1">
<Button
android:text="CONTACT"
android:textColor="#ffffff"
android:layout_width="420dp"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_height="90dp"
android:layout_gravity="center"
android:id="#+id/contactButton"
android:layout_weight="0.33"
android:background="#drawable/round_button"
android:textSize="20sp"/>
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_gravity="center"
android:textColor="#969696"
android:textSize="40sp"
android:textStyle="bold"
android:layout_weight="0.355"
/>
<Button
android:text="LOGOUT"
android:textColor="#ffffff"
android:layout_width="420dp"
android:layout_height="90dp"
android:layout_gravity="center"
android:id="#+id/logoutbutton"
android:layout_weight="0.33"
android:background="#drawable/logout_button"
android:textSize="20sp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_marginLeft="17dp"
android:layout_marginRight="17dp"
android:layout_height="match_parent"
android:layout_marginBottom="15dp"
android:layout_marginTop="185dp"
android:background="#ff434343">
<TextView
android:id="#+id/test"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</RelativeLayout>
The second LinearLayout in the above file is the one which should be the swipe-panel. The only other files on the project are xml files dealing with layout of the bottom navigation bar itself, so not relevant to the trouble I'm having.
Does anyone have any recommendations on how to approach this? A helping hand on how to start this part of the project would be amazing! Thanks in advance!
I have used this for android image swipe. It's working fine. But I need some customization in it. I need text and button bellow image and text should be change according to image swipe. And the text and button should not swipe.
What I did i put two text view and button on fragment_page.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center_horizontal"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:background="#drawable/background"
android:weightSum="1">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="wrap_content"
android:layout_height="217dp"
android:layout_weight="0.71">
</android.support.v4.view.ViewPager>
<TextView
style="#style/bigFont"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textBold"
android:layout_marginTop="20dp"
android:textColor="#color/text_color"
android:layout_centerHorizontal="true"/>
<TextView
style="#style/smallFont"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/textsmall"
android:layout_marginTop="20dp"
android:layout_below="#+id/textBold"
android:textColor="#color/text_color"
android:layout_centerHorizontal="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="REGISTER NOW"
android:id="#+id/button2"
android:background="#drawable/button_design"
android:textColor="#color/text_color"
android:padding="#dimen/abc_action_bar_content_inset_material"
android:layout_below="#+id/textsmall"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp" />
</LinearLayout>
here is my class.
package com.example.rocku28.mdt;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class Slider extends FragmentActivity {
static final int NUM_ITEMS = 4;
ImageFragmentPagerAdapter imageFragmentPagerAdapter;
ViewPager viewPager;
TextView boldTxt,smallTxt;
Button regButton;
public static final String[] IMAGE_NAME = {"one", "two", "three", "four"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
boldTxt = (TextView) findViewById(R.id.textBold);
smallTxt = (TextView) findViewById(R.id.textsmall);
imageFragmentPagerAdapter = new ImageFragmentPagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(imageFragmentPagerAdapter);
}
public static class ImageFragmentPagerAdapter extends FragmentPagerAdapter {
public ImageFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position) {
SwipeFragment fragment = new SwipeFragment();
return SwipeFragment.newInstance(position);
}
}
public static class SwipeFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View swipeView = inflater.inflate(R.layout.swipe_fragment, container, false);
ImageView imageView = (ImageView) swipeView.findViewById(R.id.imageView);
Bundle bundle = getArguments();
int position = bundle.getInt("position");
String imageFileName = IMAGE_NAME[position];
int imgResId = getResources().getIdentifier(imageFileName, "drawable", "com.example.rocku28.mdt");
imageView.setImageResource(imgResId);
setText(position);
return swipeView;
}
public void setText(int position){
// here I tried to change text on text view
switch (position){
case 0:
new Slider().boldTxt.setText(R.string.verify_licence);
new Slider().smallTxt.setText(R.string.take_back_picture);
break;
case 1:
// boldTxt.setText(R.string.verify_licence);
// smallTxt.setText(R.string.take_front_picture);
break;
case 2:
// boldTxt.setText(R.string.dashboard);
// smallTxt.setText(R.string.choose_option_to_call);
break;
case 3:
// boldTxt.setText(R.string.helpline);
// smallTxt.setText(R.string.call_call_center);
break;
}
}
static SwipeFragment newInstance(int position) {
SwipeFragment swipeFragment = new SwipeFragment();
Bundle bundle = new Bundle();
bundle.putInt("position", position);
swipeFragment.setArguments(bundle);
return swipeFragment;
}
}
}
check settext method. Here I tried to change text but problem is this context is in another class and it's static so I couldn't able to change it. How could I make it working?
Hi i am beginner and i want to write simple on click event so i come up with these code in Android SDK and Eclipse :
package com.example.aplic;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView tx = (TextView) findViewById(R.id.textView1);
tx.setText("yourtext");
}
});
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
and :
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.aplic.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_marginTop="110dp"
android:layout_toRightOf="#+id/textView1" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button1"
android:layout_below="#+id/button1"
android:layout_marginTop="96dp"
android:contentDescription="#string/abc_action_mode_done"
android:src="#drawable/abc_ab_bottom_solid_dark_holo" />
</RelativeLayout>
The problem is when i launch the code on emulator it hang and reset and when i launch it in the real device , it close the program, I dont know what is wrong with it , do i use wrong event ?
PS: When i delete the onclick event part, it works fine but it don't react on the click.
activity_main.xml :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.deomanapp.MainActivity"
tools:ignore="MergeRootFrame" />
It looks like the button belongs to fragment_main.xml.
From your comment
The name is fragment_main.xml
Its not hanging. Its a crash. You are probably getting NullPointerException.
Change to
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button b = (Button) rootView.findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView tx = (TextView) rootview.findViewById(R.id.textView1);
tx.setText("yourtext");
}
});
return rootView;
}
was testing som things in Android Studios and ran in to this error:
FATAL EXCEPTION: main
Process: com.meisolsson.app, PID: 25610
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.meisolsson.app/com.meisolsson.app.LoginActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f070053 (com.meisolsson.app:id/container) for fragment PlaceholderFragment{4284e750 #0 id=0x7f070053}
Here is my LoginActivity.java
package com.meisolsson.app;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.view.Window;
import android.widget.Button;
public class LoginActivity extends ActionBarActivity {
private Button loginButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_login);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
this.setContentView(R.layout.fragment_login);
this.loginButton = (Button)this.findViewById(R.id.button);
this.loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_login, container, false);
return rootView;
}
}
}
And my fragment_login.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=".LoginActivity$PlaceholderFragment"
android:focusable="true"
android:background="#fcff00">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:hint="#string/user"
android:padding="10dp"
android:background="#ffffff"
android:layout_above="#+id/editText2"
android:layout_alignLeft="#+id/editText2"
android:layout_alignRight="#+id/editText2" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/editText2"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:hint="#string/pass"
android:background="#ffffff"
android:padding="10dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/login"
android:id="#+id/button"
style="#style/AppTheme"
android:background="#ff5900"
android:shadowColor="#000000"
android:layout_below="#+id/editText2"
android:layout_alignLeft="#+id/editText"
android:layout_alignRight="#+id/editText2"
android:clickable="true"/>
</RelativeLayout>
The problem is the way you're doing this. For the Activity, you don't set the Fragment's view, you set a separate view that has a spot to put a Fragment. Depending on how you did your PlaceHolderFragment, the following ought to get a working app.
First add this file:
activity_main.xml
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Then change this stuff in your Activity:
LoginActivity.java
/* Same stuff*/
#Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
//This is the important change right here!
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
//The stuff that you had handling buttons should go in your
//PlaceHolderFragment class's onCreateView() method
}
I hope this helps. Good Luck!