I've followed different links and forums to solve this problem, but I couldn't solve it. So I think I am missing something important in my code but I don't get what.
The situation is the following. I'm trying to invoke some click listeners to three buttons. When I initialized them (I've tried in onCreateView() and in OnViewFragment() method, Also in OnCreate()) It's in a fragment. I attach my XML below (a part, for sure), I tried to invoke it using getActivity().findViewById(R.id.the_id_of_each_button) and also with
View view = inflater.inflate(R.layout.fragment_profile, container, false);
one_of_my_buttons =(Button) getActivity().findViewById(R.id.the_id_of_one_of_my_buttons);
I think It's because I've my buttons into some layouts, but I didn't find how to solve this.
My XML (Right now):
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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=".profileFragment">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrollableView">
<ImageView
android:id="#+id/profilePicture"
android:layout_width="0dp"
android:layout_height="225dp"
android:background="#color/azulito"
android:src="#drawable/default_prfile_picture"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/buttons_to_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="4dp"
android:backgroundTint="#FFFFFF"
android:focusable="true"
android:tint="#color/azulito"
android:src="#drawable/ic_baseline_add_24"
app:backgroundTint="#color/azulito"
app:borderWidth="0.5dp"
app:layout_constraintBottom_toBottomOf="#id/profilePicture"
app:layout_constraintEnd_toEndOf="#id/profilePicture" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/edit_profile_picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:focusable="true"
android:visibility="invisible"
android:layout_marginBottom="64dp"
android:backgroundTint="#FFFFFF"
android:src="#drawable/ic_baseline_image_24"
android:tint="#color/azulito"
app:backgroundTint="#color/azulito"
app:borderWidth="0.5dp"
app:fabSize="mini"
app:layout_constraintBottom_toTopOf="#id/buttons_to_edit"
app:layout_constraintEnd_toEndOf="#+id/buttons_to_edit"
app:layout_constraintStart_toStartOf="#+id/buttons_to_edit"
app:rippleColor="#color/azulito" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/edit_profile"
android:visibility="invisible"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:layout_marginEnd="8dp"
android:focusable="true"
android:layout_marginBottom="4dp"
android:backgroundTint="#FFFFFF"
android:src="#drawable/ic_baseline_edit_24"
app:backgroundTint="#color/azulito"
app:borderWidth="0.5dp"
app:fabSize="mini"
app:layout_constraintBottom_toTopOf="#id/edit_profile_picture"
app:layout_constraintEnd_toEndOf="#+id/edit_profile_picture"
app:layout_constraintStart_toStartOf="#+id/edit_profile_picture" />
<!-- here is more XML code, but nothing really relevant for this purposes-->
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
And my Java code (for this particular fragment because others are working fine):
package com.janus.janusapp;
import android.content.Context;
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.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
* Use the {#link profileFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class profileFragment extends Fragment{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private Animation rotateOpen ;
private Animation rotateClose ;
private Animation fromBottom ;
private Animation toBottom ;
//Here is where I declare those three buttons
private Button more_buttons;
private Button edit_profile_picture;
private Button edit_profile;
private boolean clicked = false;
/**====================================================================================================*/
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public profileFragment() {
// Required empty public constructor
}
public static profileFragment newInstance(String param1, String param2) {
profileFragment fragment = new profileFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
/*===================The OnCreateMethod===================================*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
/*==================================================================================================
* Here are some functions used by the buttons, but there's not where it fails, so, I just mention it.
/*
private void deployMoreButtons();
private void setVisibility(boolean clicked);
private void setAnimation(boolean clicked);
private void setClickable(boolean clicked);
/*=====================================The onCreateView() Method====================================*/
#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);
rotateOpen = AnimationUtils.loadAnimation(getActivity(),R.anim.rotate_open_anim);
rotateClose = AnimationUtils.loadAnimation( getActivity(),R.anim.rotate_close_anim);
fromBottom = AnimationUtils.loadAnimation(getActivity(),R.anim.from_bottom_anim);
toBottom = AnimationUtils.loadAnimation( getActivity(),R.anim.to_bottom_anim);
/* I initialize my buttons right here, In the ways I tried before. When I use getActivity() it passes but the value of the burron seems to be null, and in the other way it just fails*/
more_buttons =(Button) getActivity().findViewById(R.id.buttons_to_edit);
edit_profile = (Button)getActivity().findViewById(R.id.edit_profile);
edit_profile_picture =(Button) view.findViewById(R.id.edit_profile_picture);
/* My button SetOnClickListeners, here is where my execution fails using getActivity()*/
more_buttons.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deployMoreButtons();
}
});
edit_profile_picture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Do Something
}
});
edit_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do Something
}
});
return view;
}
}
So what I'm doing wrong and what can I do? Thanks for your help.
As you declared the inflated layout for the fragment as "view", now if you want to call anything from the view so you have to use it as...
view.edit_profile
Here when you type view. Is means you are calling view from the layout you inflated as view.
you use Fragment and already Inflate. So
more_buttons =(Button) getActivity().findViewById(R.id.buttons_to_edit);
edit_profile = (Button)getActivity().findViewById(R.id.edit_profile);
edit_profile_picture =(Button) view.findViewById(R.id.edit_profile_picture);
to
more_buttons =(Button) view.findViewById(R.id.buttons_to_edit);
edit_profile = (Button) view.findViewById(R.id.edit_profile);
edit_profile_picture =(Button) view.findViewById(R.id.edit_profile_picture);
You are using activity reference to find the id of the buttons, but the button is in your Fragment xml which you have inflated and then you can find the id's of buttons defined in fragment xml using view as shown below
View view = inflater.inflate(R.layout.fragment_profile, container, false);
one_of_my_buttons =(Button) view.findViewById(R.id.the_id_of_one_of_my_buttons);
In onCreateView use
view.findViewById(YourId);
Okay, now maybe I'm going to gain some hate...
The class of the buttons I had are FloatingActionButton that's why they didn't work using view inflater. Now it works fine. I used the solutions everyone took here. Thanks.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
I tried to create a RecyclerView on a Fragment with a custom layout, so I used an adapter, but, when I tried to set the adapter, I got these errors:
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference
I've tried some solutions on the Internet, everyone suggest to try finding the recyclerview inside the OnViewCreated. But my code still cant find the recyclerview inside the layout file.
This is my fragment_hadiah.xml File
<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=".HadiahFragment"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:padding="20dp"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_video"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="x Dopa Eggs"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginStart="10dp"/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tukarkan pointmu"/>
</LinearLayout>
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal"
android:paddingVertical="10dp">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GOPAY"
android:layout_marginLeft="20dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OVO"
android:layout_marginLeft="20dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DANA"
android:layout_marginLeft="20dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Coming Soon"
android:layout_marginLeft="20dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Coming Soon"
android:layout_marginLeft="20dp"/>
</LinearLayout>
</HorizontalScrollView>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/hadiahRecylerView"/>
</LinearLayout>
Here is my HadiahFragment.java class
package com.dopami.projecthatchedeggs;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.dopami.projecthatchedeggs.adapter.HadiahItemAdapter;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
* Use the {#link HadiahFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class HadiahFragment extends Fragment {
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
RecyclerView hadiahRecyclerView;
public HadiahFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment HadiahFragment.
*/
public static HadiahFragment newInstance(String param1, String param2) {
HadiahFragment fragment = new HadiahFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_beranda, container, false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
List<String> itemList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
itemList.add(String.valueOf(i));
}
Toast.makeText((HomeActivity) getActivity(), "OK", Toast.LENGTH_SHORT).show();
hadiahRecyclerView = view.findViewById(R.id.hadiahRecylerView);
HadiahItemAdapter itemAdapter = new HadiahItemAdapter(itemList, (HomeActivity) getActivity());
GridLayoutManager gridLayoutManager = new GridLayoutManager((HomeActivity)getActivity(), 2);
hadiahRecyclerView.setAdapter(itemAdapter);
hadiahRecyclerView.setLayoutManager(gridLayoutManager);
}
}
Here is My HadiahItemAdapter.java Class
package com.dopami.projecthatchedeggs.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.dopami.projecthatchedeggs.R;
import java.util.List;
public class HadiahItemAdapter extends RecyclerView.Adapter<HadiahItemAdapter.ItemViewHolder>{
private List<String> mItemList;
private Context mContext;
public HadiahItemAdapter(List<String> mItemList, Context mContext) {
this.mItemList = mItemList;
this.mContext = mContext;
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.hadiah_card_item, parent, false);
return new ItemViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ItemViewHolder holder, int position) {
String item = mItemList.get(position);
holder.textView.setText(item);
}
#Override
public int getItemCount() {
return mItemList.size();
}
class ItemViewHolder extends RecyclerView.ViewHolder{
private CardView cardView;
private TextView textView;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
cardView = itemView.findViewById(R.id.hadiahCardView);
textView = itemView.findViewById(R.id.hadiahCardTextView);
}
}
}
Looking forward to the solutions from you guys, thanks for helping...
Your fragment inflates the XML like this:
View view = inflater.inflate(R.layout.fragment_beranda, container, false);
R.layout.fragment_beranda is not the layout you want (or shared fragment_hadiah.xml).
Therefore in onViewCreated
hadiahRecyclerView = view.findViewById(R.id.hadiahRecylerView);
HadiahItemAdapter itemAdapter = new HadiahItemAdapter(itemList, (HomeActivity) getActivity());
GridLayoutManager gridLayoutManager = new GridLayoutManager((HomeActivity)getActivity(), 2);
hadiahRecyclerView.setAdapter(itemAdapter);
hadiahRecyclerView does not exist in the XML file and so the variable hadiahRecyclerView is null
meaning
hadiahRecyclerView.setAdapter(itemAdapter);
this line crashes with NullPointerException
The stacktrace error you shared says exactly that:
java.lang.NullPointerException: Attempt to invoke virtual method
'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)'
on a null object reference
I read answers in this thread
And I tried it, it worked. But what it did was it opened a new dialog with the url loaded and that's not exactly what I wanted.
I wanted the url to be loaded straight into the WebView element below my button. So basically what I have is a fragment and I have EditText, Button and WebView element all inside of that fragment. What I want to do is click on "search" button and load the url from EditText right into WebView located right below the button and EditBox elements. I don't want it to open my browser or a new dialog.
I have succedeed with automatically loading some url into WebView when you go to that fragment on app, but when I tried to load some url on button click, the app is just crashing. I've tried searching for this issue fix alot before making this thread but nobody seems to have the same problem.
Here's my fragment_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".Main">
<!-- TODO: Update blank fragment layout -->
<WebView
android:id="#+id/webV"
android:layout_width="match_parent"
android:layout_height="463dp"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="48dp" />
<Button
android:id="#+id/searchBtn"
android:layout_width="99dp"
android:layout_height="43dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginTop="0dp"
android:layout_marginEnd="7dp"
android:layout_marginRight="7dp"
android:text="#string/search" />
<EditText
android:id="#+id/SVbox"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/search_url"
android:inputType="text|textPersonName"
android:autofillHints="" />
</RelativeLayout>
And here in Main.java (the java file for my fragment) I tried this:
package com.something.Something;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
/**
* A simple {#link Fragment} subclass.
*/
public class Main extends Fragment {
public Main() {
//Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_main, container, false);
WebView web = (WebView) view.findViewById(R.id.webV);
web.setWebViewClient(new WebViewClient());
web.loadUrl("http://randomsite.com");
Button btn = (Button) view.findViewById(R.id.searchBtn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText et = (EditText) view.findViewById(R.id.SVbox);
WebView webz = (WebView) view.findViewById(R.id.webV);
webz.setWebViewClient(new WebViewClient());
webz.loadUrl("" + et.getText());
}
});
return view;
}
}
When I click on button, the app crashes.. I don't know what is the issue even after long research. I'm very new to Android Studio by the way, any help appreciated.
You are making mistake here WebView webz = (WebView) view.findViewById(R.id.webV);
In onClick(View view) view is the button that got clicked. So you wouldn't find any Webview and EditText.
Inside onClick, instead of initializing webz and et you can make web final and initialize et before btn.setOnClickListener.
Below is the updated code of onCreateView that will work for you.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_main, container, false);
final WebView web = (WebView) view.findViewById(R.id.webV);
web.setWebViewClient(new WebViewClient());
web.loadUrl("http://randomsite.com");
final Button btn = (Button) view.findViewById(R.id.searchBtn);
final EditText et = (EditText) view.findViewById(R.id.SVbox);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
web.loadUrl(et.getText().toString());
}
});
return view;
}
I'm having some issues with my school project. I can't get the text from the textbox. I searched for a solution but nothing found.. I'll be grateful if somebody help me :)
So here is my Java code:
package com.src.vicnote;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
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.EditText;
import android.os.Build;
public class NewNoteActivity extends ActionBarActivity {
Button saveButton;
EditText textData;
Context context;
String text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_note);
saveButton = (Button) this.findViewById(R.id.buttonSave);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textData = (EditText) findViewById(R.id.editText);
text = textData.getText().toString();
//text = "this is sparta!";
Log.d("ADebugTag", "string: \"" + text + "\" end of note text");
new SaveClass(text/*, context.getApplicationContext()*/);
}
});
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.new_note, 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_new_note,
container, false);
return rootView;
}
}
}
And my XML
<RelativeLayout
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.src.vicnote.NewNoteActivity"
tools:ignore="MergeRootFrame" >
<Button
android:id="#+id/buttonSave"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Save" />
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/buttonSave"
android:ems="10"
android:gravity="top"
android:inputType="textMultiLine" >
<requestFocus />
</EditText>
</RelativeLayout>
Also I want to ask you what will happen if the text is cyrillic? Will be there any problem?
Can't really tell what your error is without a logCat.
but one thing that might fix your problem is replacing
textData = (EditText) findViewById(R.id.editText);
text = textData.getText().toString();
with
textData = (EditText)getActivity().findViewById(R.id.editText);
text = textData.getText().toString();
// Toast for debugging purposes
Toast.makeText(getActivity(),text,0).show();
When using Fragments you should really read about getView() & getActivity().
Update
where in the xml have you set the text?
you need to set your text to something before you actually call the getText() command.
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/buttonSave"
android:ems="10"
android:gravity="top"
----- add this line ------
android:text="whatever you want"
--------------------------
android:inputType="textMultiLine" >
Good Luck
Adding a getActivity() did the trick before accessing the editText.
For example:
EditText addressText = (EditText) getActivity().findViewById(R.id.location);
getEditableText return an editable object, and you can't edit the object like that, so it is null.
simply use "getText" instead.
I don't know about Cyrillic, but it shouldn't cause any problems.
[EDIT]: Thank you for all the meaningful answers, the problem is now solved, thank to your help. Similar issue: Android: I am unable to have ViewPager WRAP_CONTENT
I'm trying to implement the UI of my app : I want a ListView with a ViewPager in each row.
Here are my files :
MainActivity.java
package com.condi;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
public class MainActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setListAdapter(new CardListAdapter(this, getFragmentManager()));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
CardListAdapter.java
package com.condi;
import java.util.List;
import android.app.FragmentManager;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class CardListAdapter extends BaseAdapter {
private Context context;
private FragmentManager fragmentManager;
private List<Profile> profiles;
CardListAdapter(Context context, FragmentManager fragmentManager) {
this.context = context;
this.fragmentManager = fragmentManager;
this.profiles = new DatabaseHelper(context).getProfiles();
}
#Override
public int getCount() {
return profiles.size();
}
#Override
public Profile getItem(int position) {
return profiles.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = View.inflate(context, R.layout.profile_card, null);
CardPagerAdapter mCardPagerAdapter = new CardPagerAdapter(
fragmentManager);
ViewPager viewPager = (ViewPager) convertView.findViewById(R.id.pager);
viewPager.setAdapter(mCardPagerAdapter);
viewPager.setId(R.id.pager);
return convertView;
}
}
profile_card.xml (issue came from wrap_content).
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="4dp"
android:background="#drawable/card_background"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</FrameLayout>
CardPagerAdapter.java
package com.condi;
import android.app.Fragment;
import android.app.FragmentManager;
import android.support.v13.app.FragmentPagerAdapter;
public class CardPagerAdapter extends FragmentPagerAdapter {
public CardPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Fragment1();
case 1:
return new Fragment2();
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
Fragment1.java
package com.condi;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 extends Fragment {
public Fragment1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.preference_category, container, false);
}
}
Fragment2.java
package com.condi;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment2 extends Fragment {
public Fragment2() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.preference_category, container, false);
}
}
The database that furnishes the profiles is working well.
The problem is that I am getting an empty list with the correct number of item, but no ViewPager displayed at all. screenshot of my app
What am I doing wrong ?
Try to change your ViewPager's height in xml. wrap_content does not work.
To make is clear, its a bad practice to use viewpagers inside a list view as this design hits the ui performance. The best way to handle this problem is:
To do manual inflation of viewpagers and add to a layout.
Add a unique id to each viewpager so that it is identified uniquely by the system.
Extend a custom viewpager and onmeasure() measure the child layout inflated at the page selected. You can do this by setting a callback in your custom viewpager and trigger the callback from viewpagers onPageScrolled listener, passing the position to identify the child layout.
In your onMeaure() method measure the child layout height and set it as the viewpagers height using super.onMeasure() passing the newly measured specs.
Key points to make a note of :
N.B. Set a unique id to the viewpager inflated by you.
try this problem in layout height
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="4dp"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="4dp"
android:background="#drawable/card_background"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</FrameLayout>
It's a bad practice to use wrap_content for your viewpager's height. You can use match_parent or a static dp for your viewpager's height.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="4dp"
android:background="#drawable/card_background"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</FrameLayout>
If it's a must to use wrap_content for your viewpager's height you can override your viewpager's onMeasure() and calculate height. Here's an example below about it.
Android: I am unable to have ViewPager WRAP_CONTENT
I hope this'll help you.
ViewPager doesn’t support wrap_content as it stands now because it doesn’t load all of its children at the same time, meaning it can’t get an appropriate measurement. You must fix View's height in your xml or create a custom ViewPager (read more at here) and use it in your xml
Try using a fixed height ViewPager inside the ListView.ViewPager does not support wrap_content
It's taken me some time to wrap my head around fragments, but this should be my last question on fragments, since I think I just about have them down. I know this is a huge mess of code to go through. But I'd appreciate the help, to make sure I'm not breaking any fundamental rules with fragments.
I am going to post all of my code just to see if someone can "look over it" to see if I'm making any major mistakes or if I should go a simpler route. Lastly, as stated in the title, my fragment is NOT being replaced... it'd being added on top.
File Tree:
MainActivity.java:
package com.example.learn.fragments;
import android.app.Activity;
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.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends FragmentActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/* Add a class to handle fragment */
public static class SSFFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.choose_pill_frag, container,
false);
return v;
}
}
public void red(View view) {
// Create new fragment and transaction
ExampleFragments newFragment = new ExampleFragments();
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.frag, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
public void blue(View view) {
//Figure out code for "red" first
}
}
ExampleFragments.java:
package com.example.learn.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ExampleFragments extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.red_pill_frag, container, false);
}
}
ActivityMain.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" >
<fragment
android:id="#+id/frag"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.example.learn.fragments.MainActivity$SSFFragment" />
</RelativeLayout>
choose_pill_frag.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" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:onClick="blue"
android:src="#drawable/blue" />
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:onClick="red"
android:src="#drawable/red" />
</RelativeLayout>
red_pill_frag.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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="You stay in Wonderland and I show you how deep the rabbit-hole goes."
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
The application should show two buttons. The two buttons exist in a single fragment, and then if you hit a button, the fragment gets replaced with a new fragment that shows the proper text. As of right now, it should replace, but it only seems to add it on top.
Instead of <fragment> use <FrameLayout> in layout xml for activity.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container_id"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Then in FragmentActivity in onCreate add initial fragment (in your case SSFFragment):
FragmentA fragmentA = new FragmentA();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.container_id, fragmentA);
transaction.commit();
From inside fragment you can replace fragment in container.
class FragmentA extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Button button = new Button(getActivity());
button.setText("Replace");
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
FragmentB fragmentB = new FragmentB();
transaction.replace(R.id.container_id, fragmentB);
transaction.commit();
}
});
return button;
}
}
Here is the answer to your real question...since this was your second question resulting from your original post, I've modified the solution to get at that frag in another way:
Fragment details = (Fragment)getSupportFragmentManager().findFragmentById(R.id.details);
details = new ExamplesFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.details, details);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
Also, the android.support.v4.app part is just not necessary, and frankly leads to possible hours of "going down the wrong road" type efforts by adding and removing it all over your code (as long as you're using:)
import android.support.v4.app.FragmentTransaction;
In this my example, you don't need to import the support for FragmentManager. However, if you're getting errors, make sure you've imported the library itself into your "libs" folder.
This solution will fix the overlapping fragment problem, and hopefully save people hours of tinkering around with replacing frags.
well i was facing the same problem and i just replace the fragment from main layout with linear lay out and guess what its working.. its strange dont know how but its working. i am using actionbar to switch between fragments
for replacing my code is :
protected class MyTabsListener1 implements ActionBar.TabListener{
private Fragment frag ;
public MyTabsListener1 ( Fragment frag){
this.frag = frag;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
switch (tab.getPosition()){
case 0:
ft.replace(R.id.replace, homeFrag);
break;
case 1:
ft.replace(R.id.replace, createFrag);
break;
case 2:
ft.replace(R.id.replace, ioListFrag);
break;
case 3:
ft.replace(R.id.replace, settingFrag);
break;
default:
break;
}
}
and my main layout is this :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="#+id/replace"
android:layout_width="wrap_content"
android:layout_height="match_parent" >
</LinearLayout>
</LinearLayout>
In short, you CAN NOT replace fragment if u defined it in XML with fragment tag. Instead, as #pawelzieba adviced add Frame tag in your layout, find it and add,remove, replace fragments there.. Hope it helped. Cheers
The main benefit of using fragments is to be able to make them take up portions of the screen rather than the whole screen, which is what Activities do.
If you're just making an app for a small screen that will function like an Activity, but is coded in Fragments, just make a separate FragmentActivity for each of your Fragments.
Make this the onCreate of your FragmentActivity:
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.emptylayout);
FragmentManager fragmentManager = getSupportFragmentManager(); //Or getFragmentManager() if you're not using the support library
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
YourFragment fragment = new YourFragment();
fragmentTransaction.add(R.id.emptyview, fragment);
fragmentTransaction.commit();
}
Where layout/emptylayout is an XML layout file with a FrameLayout. id/emptyview is that FrameLayout.
If you want to use XML for your fragment's actual layout, make a separate XML layout for the actual fragment, and inflate it in the fragment's `onCreateView':
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.files, container, false);
// Do stuff here
return view;
}
Then just use startActivity(new Intent(getActivity(), YourFragmentActivity.class)) to launch a FragmentActivity from a Fragment.
It seems redundant, yeah, but if you're going to be targeting larger screens later (if not, why are you bothering with fragments?), it'll make it easier in the long run.