I want to pass some List from fragment into 2 other fragment. When i pass data to fragment two it is going well. But it is error when pass to the fragment three
Error code
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.yehezkiel.eclassapp, PID: 15267
java.lang.IllegalArgumentException: No view found for id 0x7f0d00c4 (com.example.yehezkiel.eclassapp:id/fragment3) for
fragment ThreeFragment{e045027 #3 id=0x7f0d00c4}
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1415)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1752)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1821)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2595)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2382)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2337)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2244)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:702)
at android.os.Handler.handleCallback(Handler.java:742)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5555)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:745)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:635)
Pass Code in OneFragment.java
Bundle bundle=new Bundle();
bundle.putStringArrayList("keys", keys);
//set Fragmentclass Arguments
Fragment fragobj=new TwoFragment();
fragobj.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frag2, fragobj).commitAllowingStateLoss();
Bundle bundle2=new Bundle();
bundle2.putStringArrayList("keys", keys);
//set Fragmentclass Arguments
Fragment fragobj2=new ThreeFragment();
fragobj2.setArguments(bundle2);
FragmentManager fragmentManager2 = getFragmentManager();
fragmentManager2.beginTransaction().replace(R.id.fragment3, fragobj2).commitAllowingStateLoss();
the first pass into TwoFragment did well. But the second pass gave me error like that. Please help me. I have been check all of the id in the ThreeFragment.xml and all correct.
ThreeFragment.java
package com.example.yehezkiel.eclassapp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
public class ThreeFragment extends Fragment {
View v;
private List<DaftarPengumuman> listPengumuman = new ArrayList<>();
private ArrayList<String> obj3 = new ArrayList<>();
public ThreeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_three, container, false);
Bundle bundle = this.getArguments();
if(getArguments()!=null)
{
obj3 = bundle.getStringArrayList("keys");
Log.e("nba",obj3.toString());
}
// Inflate the layout for this fragment
return v;
}
}
fragment_three.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment3"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.yehezkiel.eclassapp.ThreeFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Three"
android:textSize="40dp"
android:textStyle="bold"
android:layout_centerInParent="true"/>
</FrameLayout>
This is my MainActivity.java that is stored the viewpager
package com.example.yehezkiel.eclassapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private List<MataKuliah> listMatkul = new ArrayList<>();
private ArrayList<String> keys = new ArrayList<>();
private myAdapter myAdapter;
private Button logoutBtn;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener authListener;
private RecyclerView mRecycleView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private Toolbar mToolbar;
private NavigationView mNavigationView;
private TextView mTextName;
private TextView mTextNim;
private ProgressBar mProgressBar;
static {
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
}
DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("users");
FirebaseUser users = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference mataKuliahRef = FirebaseDatabase.getInstance().getReference("courses");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mAuth = FirebaseAuth.getInstance();
//Navbar menu
mToolbar = (Toolbar) findViewById(R.id.navbaraction);
setSupportActionBar(mToolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawabel_main);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mNavigationView = (NavigationView) findViewById(R.id.nav_menu);
View header = mNavigationView.getHeaderView(0);
mTextName = (TextView) header.findViewById(R.id.header_name);
mTextNim = (TextView) header.findViewById(R.id.header_nim);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar2);
mProgressBar.setVisibility(View.VISIBLE);
//Tab Layout
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case (R.id.tugas):
break;
case (R.id.logout_menu):
signOut();
break;
}
return true;
}
});
userRef.child(users.getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = (String) dataSnapshot.child("name").getValue().toString();
String nim = (String) dataSnapshot.child("nim").getValue().toString();
mTextNim.setText(nim);
mTextName.setText(name);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user == null) {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}
};
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "Beranda");
adapter.addFragment(new TwoFragment(), "Tugas");
adapter.addFragment(new ThreeFragment(), "Pengumuman");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
private void signOut() {
mAuth.signOut();
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(authListener);
}
}
MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawabel_main"
tools:context="com.example.yehezkiel.eclassapp.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<include
layout="#layout/navbar_action"
android:layout_width="match_parent"
android:layout_height="wrap_content"></include>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:tabGravity="fill"
app:tabMode="fixed" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<ProgressBar
android:id="#+id/progressBar2"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:visibility="visible"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="304dp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/MainRView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="2dp"
android:layout_marginEnd="6dp"
android:layout_marginStart="6dp"
android:layout_marginTop="2dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</android.support.v7.widget.RecyclerView>
<Button
android:id="#+id/logoutBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="444dp"
android:background="#color/colorPrimary"
android:text="LOGOUT"
android:textColor="#color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.945"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="#menu/navbar_main"
android:layout_gravity="start"
app:headerLayout="#layout/navbar_header"
android:id="#+id/nav_menu">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
Related
I created a new fragment which is ProfileFragment.java and also created fragment_profile.xml.
The program does not give any error but my layout doesnt show. What is wrong?
My ProfileFragment.java :
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
public class ProfileFragment extends Fragment {
//firebase auth
FirebaseAuth firebaseAuth;
FirebaseUser user;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
//layout views
ImageView avatar;
TextView nameTxt, emailTxt, phoneTxt;
public ProfileFragment() {
//boş public constructor gerekli
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_profile, container, false);
//init firebase
firebaseAuth = FirebaseAuth.getInstance();
user = firebaseAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
//init layout views
avatar = view.findViewById(R.id.avatar);
nameTxt = view.findViewById(R.id.nameTxt);
emailTxt = view.findViewById(R.id.emailTxt);
phoneTxt = view.findViewById(R.id.phoneTxt);
/* giriş yapan kullanıcıların bilgilerini email yada uid kullanarak çekmek zorundayız
Kullanıcı detaylarını email adreslerini kullanarak çekicez
orderbyChild query kullanarak giriş yapılan email ile email key ini eşleştirerek kullanıcı detaylarına ulaşılıyor
*/
Query query = databaseReference.orderByChild("email").equalTo(user.getEmail());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
//gerekli veriler gelene kadar kontrol et
for (DataSnapshot ds: snapshot.getChildren()){
//verileri almak için
String name = ""+ ds.child("name").getValue();
String email = ""+ ds.child("email").getValue();
String phone = ""+ ds.child("phone").getValue();
String image = ""+ ds.child("image").getValue();
//set data
nameTxt.setText(name);
emailTxt.setText(email);
phoneTxt.setText(phone);
try {
// resim alınırsa ayarla
Picasso.get().load(image).into(avatar);
} catch (Exception e){
// resim alınırken herangi bir sıkıntı varsa varsayılan olarak ayarla
Picasso.get().load(R.drawable.add_photo_foreground).into(avatar);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
return view;
}
}
and my fragment_profile.xml :
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F1EDED"
tools:context=".ProfileFragment">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="180dp"
android:background="#2ECC71">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="120dp"
android:orientation="horizontal"
android:layout_marginTop="100dp">
<ImageView
android:id="#+id/avatar"
android:layout_width="120dp"
android:layout_height="120dp"
android:src="#drawable/add_photo_foreground"
android:layout_marginStart="20dp"
android:background="#6AE493"
android:padding="5dp">
</ImageView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/nameTxt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:textSize="25dp"
android:textColor="#FFFFFF"></TextView>
<TextView
android:id="#+id/emailTxt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:textColor="#FFFFFF"></TextView>
<TextView
android:id="#+id/phoneTxt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:textColor="#FFFFFF"></TextView>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
</ScrollView>
I want to create a user profile page using firebase realtime database. The user details come from using email for current signed user. But my profile layout file does not work. How can I fix this problem? Whats wrong in my code?
My DasboardAvtivity.java -> For fragment transaction.
package com.gamze.pawsbook;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class DashboardActivity extends AppCompatActivity {
//FirebaseAuth
FirebaseAuth firebaseAuth;
//Actionbar
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
//ActionBar ve başlığı
actionBar = getSupportActionBar();
actionBar.setTitle("Profile");
//profileTxt = findViewById(R.id.profileTxt);
firebaseAuth = FirebaseAuth.getInstance();
//Bottom navigation
BottomNavigationView navigationView = findViewById(R.id.navigation);
navigationView.setOnNavigationItemSelectedListener(selectedListener);
//Home Fragment'ı boş default fragment olarak ayarlanması
actionBar.setTitle("Home"); //ActionBar başlığını değiştirme
HomeFragment homeFragment = new HomeFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content, homeFragment, "");
ft.commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener selectedListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
//itemlere tıklanma özelliği ekleme
switch (item.getItemId()){
case R.id.action_home:
//home fragment değişimi
actionBar.setTitle("Home"); //ActionBar başlığını değiştirme
HomeFragment homeFragment = new HomeFragment();
FragmentTransaction ftHome = getSupportFragmentManager().beginTransaction();
ftHome.replace(R.id.content, homeFragment, "");
ftHome.commit();
return true;
case R.id.action_map:
//map fragment değişimi
actionBar.setTitle("Map"); //ActionBar başlığını değiştirme
MapFragment mapFragment = new MapFragment();
FragmentTransaction ftMap = getSupportFragmentManager().beginTransaction();
ftMap.replace(R.id.content, mapFragment, "");
ftMap.commit();
return true;
case R.id.action_users:
//users fragment değişimi
actionBar.setTitle("Users"); //ActionBar başlığını değiştirme
UsersFragment usersFragment = new UsersFragment();
FragmentTransaction ftUsers = getSupportFragmentManager().beginTransaction();
ftUsers.replace(R.id.content, usersFragment, "");
ftUsers.commit();
return true;
case R.id.action_profile:
//profile fragment değişimi
actionBar.setTitle("Profile"); //ActionBar başlığını değiştirme
ProfileFragment profileFragment = new ProfileFragment();
FragmentTransaction ftProfile = getSupportFragmentManager().beginTransaction();
ftProfile.replace(R.id.content, profileFragment, "");
ftProfile.commit();
return true;
}
return false;
}
};
private void checkUserStatus() {
//mevcut kullanıcıyı al
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null){
//kullanıcı giriş yapmışsa burada kal
//giriş yapan kullanıcının email i
//profileTxt.setText(user.getEmail());
}
else{
//kullanıcı giriş yapmamışsa main activity'e git
Intent intent = new Intent(DashboardActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
protected void onStart() {
//uygulamanın başlangıcını konrtol et
checkUserStatus();
super.onStart();
}
//options menu dahil etme
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//menuyu dahil etme
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
//menu itemlerine onClick özelliği aktifleştirme
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
//itemlerin id'lerini al
int id = item.getItemId();
if (id == R.id.action_logout){
//hesaptan çıkış yap
firebaseAuth.signOut();
checkUserStatus();
}
return super.onOptionsItemSelected(item);
}
}
activity_dashboard.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DashboardActivity">
//FrameLayout fragmentlerin üstüste gelebilmesi için daha kullanışlıdır
<FrameLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="0dp">
</FrameLayout>
//BottomNavigationBar
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentEnd="false"
android:layout_alignParentBottom="true"
android:background="?android:attr/windowBackground"
app:menu="#menu/bottombar_menu">
</com.google.android.material.bottomnavigation.BottomNavigationView>
</RelativeLayout>
This is what is showing from fragment_profile.xml.
Your question doesn't give information whether you are getting an empty view like above or you are not getting any view. I will try to answer on two ansumption.
Empty View
No View at all
Empty View
If you are getting empty view then you must put some Logs statement in your database responce, check if that database is returning some value.
public class ProfileFragment extends Fragment {
//Log Statment
private static final String TAG = "ProfileFragment";
......
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
//gerekli veriler gelene kadar kontrol et
for (DataSnapshot ds: snapshot.getChildren()){
//verileri almak için
String name = ""+ ds.child("name").getValue();
String email = ""+ ds.child("email").getValue();
String phone = ""+ ds.child("phone").getValue();
String image = ""+ ds.child("image").getValue();
//set data
nameTxt.setText(name);
emailTxt.setText(email);
phoneTxt.setText(phone);
Log.d(TAG, "onDataChange: \nName: "+name+" email: "+ email);
try {
// resim alınırsa ayarla
Picasso.get().load(image).into(avatar);
} catch (Exception e){
// resim alınırken herangi bir sıkıntı varsa varsayılan olarak ayarla
Picasso.get().load(R.drawable.add_photo_foreground).into(avatar);
}
}
Log.d(TAG, "onDataChange: Data is empty");
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d(TAG, "onCancelled: "+error);
}
}
}
.........
You can use breakpoints as well to further investigation.
No View at all
If view is not changing on ProileFragment then you must check how you are starting ProfileFragment.
getSupportFragmentManager().beginTransaction().replace(R.id.frgment_container, new ProfileFragment()).commit();
If you are using Navigation Component then make sure you are navigating to correct destination.
I will also suggest you to strcture the code in following format under Profile Fragment -
public class ProfileFragment extends Fragment {
//firebase auth
............
//layout views
..............
public ProfileFragment() {
//boş public constructor gerekli
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_profile, container, false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//init firebase
.................
//init layout views
.......................
/* giriş yapan kullanıcıların bilgilerini email yada uid kullanarak çekmek zorundayız
Kullanıcı detaylarını email adreslerini kullanarak çekicez
orderbyChild query kullanarak giriş yapılan email ile email key ini eşleştirerek kullanıcı detaylarına ulaşılıyor
*/
Query query = databaseReference.orderByChild("email").equalTo(user.getEmail());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
.................
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
...............
}
});
}
}
Edit (activity_dashboard.xml)
Try following layout file for activity_dashboard.xml -
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".DashboardActivity">
<FrameLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="?attr/actionBarSize"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_alignParentEnd="false"
android:layout_alignParentBottom="true"
android:background="?android:attr/windowBackground"
app:menu="#menu/bottombar_menu"/>
</RelativeLayout>
I am using ?attr/actionBarSize, which is the standard action bar size for android.
Happy Coding !
I am trying to set a tab layout inside a fragment and call it by an option inside navigation drawer but I am getting a null object reference error.
I am setting my navigation drawer inside Main2Activity
Main2Activity
import android.content.Intent;
import android.os.Bundle;
import com.bumptech.glide.Glide;
import com.example.fireapp.model.Users;
import com.firebase.ui.auth.AuthUI;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.tabs.TabLayout;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.text.Layout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import com.example.fireapp.ui.main.SectionsPagerAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import de.hdodenhof.circleimageview.CircleImageView;
public class Main2Activity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private View headerView;
private TextView usernameText;
private TextView emailText;
private CircleImageView userImage;
private FirebaseUser firebaseUser;
private DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("fireApp");
//navigation drawer
drawerLayout = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
//user details
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
headerView = navigationView.getHeaderView(0);
usernameText = headerView.findViewById(R.id.usernameText);
userImage = headerView.findViewById(R.id.userImage);
emailText = headerView.findViewById(R.id.userEmail);
setUserDetails();
// if(savedInstanceState==null) {
// getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
// new chatFragment()).commit();
// navigationView.setCheckedItem(R.id.nav_chat);
// }
}
private void setUserDetails() {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("User").child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Users user = dataSnapshot.getValue(Users.class);
usernameText.setText(user.getUsername());
emailText.setText(firebaseUser.getEmail());
if (user.getImageUrl().equals("default")) {
userImage.setImageResource(R.mipmap.ic_launcher);
} else {
Glide.with(getApplicationContext()).load(user.getImageUrl()).into(userImage);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch(menuItem.getItemId()){
case R.id.nav_chat:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new chatFragment()).commit();
break;
case R.id.nav_share:
Toast.makeText(this, "Share!", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_feedback:
Toast.makeText(this, "Feedback!", Toast.LENGTH_SHORT).show();
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
//3 dots menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.logout) {
AuthUI.getInstance()
.signOut(Main2Activity.this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
startActivity(new Intent(Main2Activity.this, MainActivity.class));
finish();
}
});
return true;
} else
return false;
}
}
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout 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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".Main2Activity"
tools:openDrawer="end">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:id="#+id/nav_view"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/drawer_menu"></com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
chatFragment
package com.example.fireapp;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.fireapp.ui.main.SectionsPagerAdapter;
import com.google.android.material.tabs.TabLayout;
public class chatFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_chat,container,false);
tabLayout=view.findViewById(R.id.tabs);
viewPager=view.findViewById(R.id.view_pager);
viewPager.setAdapter(new SectionsPagerAdapter(getChildFragmentManager()));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return view;
}
}
fragment_chat.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".chatFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary" />
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</FrameLayout>
SectionPagerAdapter
package com.example.fireapp.ui.main;
import android.content.Context;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import com.example.fireapp.R;
import com.example.fireapp.tab1;
import com.example.fireapp.tab2;
import com.example.fireapp.tab3;
import java.util.List;
/**
* A [FragmentPagerAdapter] that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
#StringRes
private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2,R.string.tab_text_3};
private Context mContext ;
public SectionsPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
public SectionsPagerAdapter(FragmentManager childFragmentManager) {
super(childFragmentManager);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0 :
tab1 tab1 = new tab1();
return tab1;
case 1:
tab2 tab2 = new tab2();
return tab2;
case 2:
tab3 tab3 = new tab3();
return tab3;
}
return null;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
I am getting the following error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.fireapp, PID: 6785
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at com.example.fireapp.ui.main.SectionsPagerAdapter.getPageTitle(SectionsPagerAdapter.java:61)
at com.google.android.material.tabs.TabLayout.populateFromPagerAdapter(TabLayout.java:1323)
at com.google.android.material.tabs.TabLayout.setPagerAdapter(TabLayout.java:1314)
at com.google.android.material.tabs.TabLayout.setupWithViewPager(TabLayout.java:1227)
at com.google.android.material.tabs.TabLayout.setupWithViewPager(TabLayout.java:1188)
at com.google.android.material.tabs.TabLayout.setupWithViewPager(TabLayout.java:1168)
at com.example.fireapp.chatFragment$1.run(chatFragment.java:32)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
I am new to android development please help.
java.lang.NullPointerException: Attempt to invoke virtual method
'android.content.res.Resources android.content.Context.getResources()'
on a null object reference
NullPointerException is thrown when an application attempts to use an object reference that has the null value.
You can try with this
private String TAB_TITLES[] = new String[]{"Tab1", "Tab2", "Tab3"};
Then
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return TAB_TITLES[position];
}
getPageTitle() - This method may be called by the ViewPager to obtain a title string to describe the specified page.
Problem Statement:
I have an activity on which I have used a view pager and inflated two fragments inside it.
The second fragment inside the view pager must also contain a view pager which has another fragment inside it(If you're wondering why this is a view pager if only a single fragment is required, because that is a configurable component and more fragments might be required inside it).
First Fragment
Second Fragment and the sub fragment inside it
Now, when we click a button I have to refresh the first and second fragments as well as the sub fragment( in the ViewPager) inside the second fragment.
The issue is that the first and the second fragments are getting updated but the sub fragment that is inside the view pager in the second fragment is not getting refreshed.
This happens after the click of the button:
First Fragment refreshed
Second fragment refreshed but the sub fragment did not
Tried solutions:
We tried to debug the code, tried clearing the adapters and the lists. Nothing worked.
Any pointers or suggestions welcome !
Code :
MainActivity.java
package com.example.admin.myapplication;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private GuestListPagerAdapter adapter;
private ViewPager viewPager;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = findViewById(R.id.view_pager);
button = findViewById(R.id.button);
setUpViewPager();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
adapter.clearFragmentList();
adapter.addFragment(FirstFragment.newInstance("55"));
adapter.addFragment(SecondFragment.newInstance("88"));
adapter.notifyDataSetChanged();
}
});
}
private void setUpViewPager() {
if (null == adapter)
adapter = new GuestListPagerAdapter(getSupportFragmentManager());
adapter.addFragment(FirstFragment.newInstance("1"));
adapter.addFragment(SecondFragment.newInstance("2"));
viewPager.setAdapter(adapter);
}
public class GuestListPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> mFragments = new ArrayList<>();
GuestListPagerAdapter(FragmentManager fm) {
super(fm);
}
void addFragment(Fragment fragment) {
mFragments.add(fragment);
}
void clearFragmentList(){
mFragments.clear();
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
}
activity_main.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="10"
tools:context=".MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="8"/>
<Button
android:text="Refresh View Pager"
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_gravity="center"/>
</LinearLayout>
SecondFragment.java
package com.example.admin.myapplication;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class SecondFragment extends Fragment {
private static final String TAG = SecondFragment.class.getSimpleName();
private static final String ARG_PARAM1 = "param1";
private String mParam1;
public SecondFragment() {
// Required empty public constructor
}
public static SecondFragment newInstance(String param1) {
SecondFragment fragment = new SecondFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
fragment.setArguments(args);
Log.d(TAG, "newInstance: 2F");
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
}
Log.d(TAG, "onCreate: 2F");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_second, container, false);
TextView tv = (TextView) view.findViewById(R.id.tv2);
tv.setText(mParam1);
ViewPager pager = (ViewPager) view.findViewById(R.id.sub_view_pager);
SubListPagerAdapter adapter = new SubListPagerAdapter(getChildFragmentManager());
adapter.clearFragmentList();
adapter.addFragment(SubFragment.newInstance(mParam1));
pager.setAdapter(adapter);
Log.d(TAG, "onCreateView: 2F");
return view;
}
public class SubListPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> mFragments = new ArrayList<>();
SubListPagerAdapter(FragmentManager fm) {
super(fm);
}
void addFragment(Fragment fragment) {
mFragments.add(fragment);
}
void clearFragmentList(){
mFragments.clear();
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
}
fragment_second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:weightSum="4"
tools:context=".SecondFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/tv2"
android:textSize="60sp"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="#string/hello_blank_fragment" />
<android.support.v4.view.ViewPager
android:background="#color/colorAccent"
android:id="#+id/sub_view_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3"/>
</LinearLayout>
SubFragment.java
package com.example.admin.myapplication;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A simple {#link Fragment} subclass.
*/
public class SubFragment extends Fragment {
private static final String TAG = SubFragment.class.getSimpleName();
private static final String ARG_PARAM1 = "param1";
private String mParam1;
public SubFragment() {
// Required empty public constructor
}
public static SubFragment newInstance(String param1) {
SubFragment fragment = new SubFragment();
Bundle args = new Bundle();
if(fragment.getArguments()!=null)
fragment.getArguments().clear();
args.putString(ARG_PARAM1, param1);
fragment.setArguments(args);
Log.d(TAG, "newInstance: sub");
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate: sub");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_sub, container, false);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
}
TextView tv = (TextView) view.findViewById(R.id.sub_tv);
tv.setText(mParam1);
Log.d(TAG, "onCreateView: sub");
return view;
}
}
fragment_sub.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
tools:context=".SubFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/sub_tv"
android:textSize="60dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_blank_fragment" />
</LinearLayout>
FirstFragment.java
package com.example.admin.myapplication;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A simple {#link Fragment} subclass.
*/
public class FirstFragment extends Fragment {
private static final String TAG = FirstFragment.class.getSimpleName();
private static final String ARG_PARAM1 = "param1";
private String mParam1;
public FirstFragment() {
// Required empty public constructor
}
public static FirstFragment newInstance(String param1) {
FirstFragment fragment = new FirstFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
fragment.setArguments(args);
Log.d(TAG, "newInstance: 1F");
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
}
Log.d(TAG, "onCreate: 1F");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_first, container, false);
TextView tv = (TextView) view.findViewById(R.id.tv);
tv.setText(mParam1);
Log.d(TAG, "onCreateView: 1F");
return view;
}
}
fragment_first.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
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"
tools:context=".FirstFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/tv"
android:textSize="60sp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</FrameLayout>
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
Okay I have spent hours trying to fix this, and no matter what I try I always get the same error, I assume I'm missing something stupidly easy so sorry if the question has already been answered I tried using their responses and it didn't help. All help is greatly appreciated.
I'm trying to add rows to a table programmatically, here is the code:
MainActivity.java:
package com.coreclue.random5;
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.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TableRow;
public class MainActivity extends AppCompatActivity{
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
public static Button b;
public static TableRow tr;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tr = new TableRow(this);
b = new Button(this);
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);
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, "test test test 123", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(id == R.id.action_settings){
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment{
private static final String ARG_SECTION_NUMBER = "section_number";
//public PlaceholderFragment(){
//}
public static PlaceholderFragment newInstance(int sectionNumber){
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View tabView1 = inflater.inflate(R.layout.tab1, container, false);
View tabView2 = inflater.inflate(R.layout.tab2, container, false);
View tabView3 = inflater.inflate(R.layout.tab3, container, false);
if(getArguments().getInt(ARG_SECTION_NUMBER) == 1){
tab1 obj = new tab1();
obj.main(tabView1);
return tabView1;
} else if(getArguments().getInt(ARG_SECTION_NUMBER) == 2){
tab2 obj = new tab2();
obj.main(tabView2);
return tabView2;
} else if(getArguments().getInt(ARG_SECTION_NUMBER) == 3){
return tabView3;
} else{
return tabView1;
}
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter{
public SectionsPagerAdapter(FragmentManager fm){
super(fm);
}
#Override
public Fragment getItem(int position){
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount(){
return 3;
}
}
}
tab2.java where I want to code to lie that adds rows to table:
package com.coreclue.random5;
import android.view.View;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import static com.coreclue.random5.MainActivity.b;
public class tab2{
public static TableRow tr;
public void main(View rootView){
final TextView line1 = rootView.findViewById(R.id.line1);
line1.setText("aa");
TableLayout tl = (TableLayout) rootView.findViewById(R.id.table123);
tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
b.setText("Dynamic Button");
b.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
tr.addView(b);
tl.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
}
}
tab2.xml: where the table lies
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/table123"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="1">
<TableRow>
<TextView
android:id="#+id/line1"
android:padding="3dip"
android:text="text 1" />
<TextView
android:gravity="right"
android:padding="3dip"
android:text="text 2" />
</TableRow>
<TableRow>
<TextView
android:padding="3dip"
android:text="text 3" />
<TextView
android:gravity="right"
android:padding="3dip"
android:text="text 4" />
</TableRow>
</TableLayout>
</LinearLayout>
</ScrollView>
and the error I get is:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.coreclue.random5, PID: 21474
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TableRow.setLayoutParams(android.view.ViewGroup$LayoutParams)' on a null object reference
at com.coreclue.random5.tab2.main(tab2.java:31)
at com.coreclue.random5.MainActivity$PlaceholderFragment.onCreateView(MainActivity.java:106)
all I'm trying to get is a simple function where I can add as many rows to the table as needed, but just trying to add one row and it fails.
Finally solved it! in tab2.java line 10:
public static TableRow tr;
when I needed it to be:
import static com.coreclue.random5.MainActivity.tr;
I assume the var wasn't instantiated which is why I had the error.
iam new to android and iam trying to create an app with a lot of websites linked on to the apps like facebook, twitter , mail etc
MainActivity.java
package com.shortshop.app;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new OneFragment(), "ONE");
adapter.addFrag(new TwoFragment(), "TWO");
adapter.addFrag(new ThreeFragment(), "THREE");
adapter.addFrag(new FourFragment(), "FOUR");
adapter.addFrag(new FiveFragment(), "FIVE");
adapter.addFrag(new SixFragment(), "SIX");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
OneFragment.java
package com.shortshop.app;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class OneFragment extends Fragment{
public OneFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_one, container, false);
}
}
fragment_one.xml
<ScrollView xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TableRow>
<ImageButton
android:id="#+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_weight="2"
android:onClick="facebook"
android:src="#drawable/facebook_icon" />
</TableRow>
</TableLayout>
</ScrollView>
Iam not able to add this code in the OneFragment.java where i endup with error
public class OneFragment extends Fragment {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_one);
}
public void facebook(View v){
Intent intent = new Intent(this, WebActivity.class);
startActivity(intent);
}
}
It would be great full if some comes out with a solution i have been trying to figure out the solution for so long
WebActivity.java
package com.shortshop.app;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class WebActivity extends Activity {
private WebView mWebview ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWebview = new WebView(this);
mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
final Activity activity = this;
mWebview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
}
});
mWebview .loadUrl("http://www.facebook.com");
setContentView(mWebview );
}
}
activity_web.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.shortshop.app.WebActivity">
<WebView
android:layout_width="368dp"
android:layout_height="495dp"
android:id="#+id/webView"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp" />
</android.support.constraint.ConstraintLayout>
In your OneFragment.java. post this code.
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_one, container, false);
ImageButton imageButton= (ImageButton ) view.findViewById(R.id.imageButton);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(this, WebActivity.class);
startActivity(intent);
}
});
return view;
}
}