I'm completely new to Android programming. I'm writing an where there are two Fragments: Query and Results. There is a Button and an EditText in the Query Fragment. When the user clicks on the Button, the results from the EditText should be displayed in the TextView that is present the Results Fragment.
Here is the Main Activity (Starting Point):
public class StartingPoint extends FragmentActivity
{
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
viewPager = (ViewPager)findViewById(R.id.pager);
viewPager.setAdapter(new FragmentsPagerAdapter(getSupportFragmentManager()));
}
}
Here is the QueryFragment.java:
public class QueryFragment extends Fragment
{
EditText queryET, endpointET;
Button execute;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Get the view from fragmenttab1.xml
View view = inflater.inflate(R.layout.query_fragment, container, false);
queryET = (EditText) view.findViewById(R.id.sparqlQueryET);
endpointET = (EditText) view.findViewById(R.id.sparqlEndpointET);
execute = (Button) view.findViewById(R.id.executeButton);
execute.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
String query = queryET.toString();
String endpoint = endpointET.toString();
Query q = QueryFactory.create(query, Syntax.syntaxARQ);
q.setOffset(1);
QueryExecution qe = QueryExecutionFactory.sparqlService(endpoint, query);
ResultSet rs = qe.execSelect();
StringBuffer results = new StringBuffer();
List<String> columnNames = rs.getResultVars();
while(rs.hasNext())
{
QuerySolution qs = rs.next();
for(String var: columnNames)
{
results.append(var +":");
if(qs.get(var) == null)
results.append("{null}");
else if (qs.get(var).isLiteral())
results.append(qs.getLiteral(var).toString());
else
results.append(qs.getResource(var).getURI());
results.append('\n');
}
results.append("----------------\n");
}
qe.close();
}
});
return view;
}
}
Here is the ResultsFragment:
public class ResultsFragment extends Fragment
{
TextView r;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Get the view from fragmenttab1.xml
View view = inflater.inflate(R.layout.results_fragment, container, false);
r = (TextView) view.findViewById(R.id.resultsTV);
return view;
}
}
Now my question is how do I pass the result processed in the onClick method (of the QueryFragment), which is a String, to the ResultsFragment where the String would be displayed in a TextView?
Simple approach will be : Make public static String field in parent activity. onClick method will set info into this value, and onCreateView result fragment will try to take it from there.
onClick(View v){
MainActivity.myResultString = "result code";
}
and get it when you need it;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.results_fragment, container, false);
r = (TextView) view.findViewById(R.id.resultsTV);
r.setText(MainActivity.myResultString);
return view;
}
Something like this. Its not completed solution but can help you ) good luck.
Related
I'm a newbie and i tried to learn the navigation drawer.
I want to set a onClick listener on a button in Fragment but when i run the App, the button do nothing.
this is WeightFragment.java:
`
public class WeightFragment extends Fragment {
private FragmentWeightBinding binding;
private EditText edtNumber;
private Button addBtn;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
WeightViewModel weightViewModel =
new ViewModelProvider(this).get(WeightViewModel.class);
binding = FragmentWeightBinding.inflate(inflater, container, false);
View root = binding.getRoot();
View view = inflater.inflate(R.layout.fragment_weight, container, false);
addBtn = view.findViewById(R.id.addBtn);
edtNumber = view.findViewById(R.id.edtNumber);
String weight = String.valueOf(edtNumber.getText());
SimpleDateFormat sdf = new SimpleDateFormat("'Date\n'dd-MM-yyyy HH:mm:ss");
String currentDateAndTime = sdf.format(new Date());
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(),weight + currentDateAndTime, Toast.LENGTH_SHORT).show();
}
});
final TextView textView = binding.txtDate;
weightViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
return root;
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
}
I've tried with:
public class WeightFragment extends Fragment implements View.OnClickListener
and implement the method but it doesn't work anyway.
It's because you are setting the onClickListener on a View that you throw away.
Here is the binding (pay attetion to the root):
binding = FragmentWeightBinding.inflate(inflater, container, false);
View root = binding.getRoot();
but you are setting the listener on a button that is in:
View view = inflater.inflate(R.layout.fragment_weight, container, false);
addBtn = view.findViewById(R.id.addBtn);
addBtn.setOnClickListener(...);
and at the end you return root;
The view that has the onClick listener is there, you create it but in the end it's thrown away.
Just replace view with binding and it will work.
public View onCreateView(
#NonNull LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState
) {
WeightViewModel weightViewModel = new ViewModelProvider(this).get(WeightViewModel.class);
binding = FragmentWeightBinding.inflate(inflater, container, false);
View root = binding.getRoot();
addBtn = binding.addBtn;
edtNumber = binding.edtNumber;
String weight = String.valueOf(edtNumber.getText());
SimpleDateFormat sdf = new SimpleDateFormat("'Date\n'dd-MM-yyyy HH:mm:ss");
String currentDateAndTime = sdf.format(new Date());
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(),weight + currentDateAndTime, Toast.LENGTH_SHORT).show();
}
});
final TextView textView = binding.txtDate;
weightViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
return root;
}
I use tablayout and push item tab by java class to connect it with fragment but I need to sent data from Adapter use another fragment ,to fragment I use bundle and it take data from adapter but when reach to fragment bundle is null.
I have the following code in BindViewHolder in Adapter:
holder.btn_tobuy.setOnClickListener(new View.OnClickListener() {
FragmentShoping fragmentShoping = new FragmentShoping();
#Override
public void onClick(View v) {
String name_meal=holder.Name_Meal.getText().toString();
Bundle bundle = new Bundle();
bundle.putString("name",name_meal);
Log.i("BUNDLE", bundle.toString());
fragmentShoping.setArguments(bundle);
}
});
then this code in fragment :
Bundle bundle = this.getArguments();
if(bundle!=null) {
String i = bundle.getString("name", "un_name");
shopingMeals.setName_Meal(i);
shopingMeals.setPrice(10);
shopingMeals.setCount(5);
shopingMeals.setImg_meal(R.drawable.burger_1);
list.add(shopingMeals);
}
**I try to put this code in createdview or oncreate in fragment but the same problem I need to send data from adapter to fragment by bundle or another way.
edit code , fragment transaction I try a lot of way :
public FragmentShoping() {
// Required empty public constructor
}
RecyclerView recycler;
View view;
ConstraintLayout rootlayout;
AdapterShoping adapterShoping;
ArrayList<ShopingMeals> list = new ArrayList<>();
ShopingMeals shopingMeals ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view= inflater.inflate(R.layout.fragment_shoping, container, false);
recycler=view.findViewById(R.id.main_recycler_shoping);
rootlayout = view.findViewById(R.id.shoping_rootlayout);
recycler.setLayoutManager(new LinearLayoutManager(getActivity()));
getMyitem();
adapterShoping=new AdapterShoping(getActivity().getApplicationContext(),list);
recycler.setRotationY(180);
recycler.setAdapter(adapterShoping);
// meals.add(new Meals("mamoun","fff",50,R.drawable.ic_meal));
// meals.add(new Meals("mamoun","fff",50,R.drawable.ic_meal));
// meals.add(new Meals("mamoun","fff",50,R.drawable.ic_meal));
// meals.add(new Meals("mamoun","fff",50,R.drawable.ic_meal));
// recycler.setHasFixedSize(true);
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Bundle bundle = this.getArguments();
// if (bundle != null) {
// String i = bundle.getString("name", "un_name");
// Log.i("BUNDLE2", i);
// }
}
Bundle bundle;
String i;
public ArrayList<ShopingMeals> getMyitem() {
bundle =this.getArguments();
if(bundle!=null) {
i = bundle.getString("name", "un_name");
}
shopingMeals = new ShopingMeals();
shopingMeals.setName_Meal(i);
shopingMeals.setPrice(10);
shopingMeals.setCount(5);
shopingMeals.setImg_meal(R.drawable.burger_1);
list.add(shopingMeals);
// String a = Objects.requireNonNull(this.getActivity()).getSharedPreferences("MySharedPref", MODE_PRIVATE).getString("name", "def");
// SharedPreferences sh = getActivity().getSharedPreferences("MySharedPref", Context.MODE_PRIVATE);
// String s =sh.getString("name","def");
// shopingMeals.setName_Meal(a);
return list;
}
thanks,**
Greate answer provided here
Try to retrieve values instead of bundle
So:
if(getArguments() != null)
shippingMeals.setName_Meal(getArguments().getString("name"));
I want to be able to click a button on my settings fragment, which will change an image on another fragment called home fragment. My app keeps crashing once i click the button and im not sure why.
Settings Fragment :
public class SettingsFragment extends Fragment {
public Button button;
public ImageView Torso;
public ImageView ShopGreenTorso;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
button = (Button) getView().findViewById(R.id.button1);
Torso = (ImageView) getView().findViewById(R.id.Torso);
ShopGreenTorso= (ImageView) getView().findViewById(R.id.ShopGreenTorso);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Purchased", Toast.LENGTH_SHORT).show();
Intent i = new Intent(SettingsFragment.this.getActivity(), AvatarFragment.class);
//i.putExtra("resID", R.drawable.torso2green);
Bundle b= new Bundle();
b.putInt("resID", R.drawable.torso2green);
SettingsFragment.this.setArguments(b);
//setArguments(bundle);
startActivity(i);
}
});
}
Avatar Fragment:
public class AvatarFragment extends Fragment {
public ImageView IV;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_avatar, container, false);
// init image view
IV = (ImageView) rootView.findViewById( R.id.Torso );
// getting extras
//Bundle bundle = getActivity().getIntent().getExtras();
// Bundle bundle=getArguments();
Bundle b=getArguments();
if(b!= null)
{
int resid = b.getInt("resID");
IV.setBackgroundResource(resid);
}
return rootView;
}
}
I believe the error is coming from IV.setImageResource(resid) but im not entirely sure, any help would be much appreciated.
It's hard to tell without seeing the exception, but it might be because Bundle mappings are case-sensitive.
Your SettingsFragment uses "ResId", but your HomeFragment is expecting "resID". If no mapping is found in the Bundle, you'll be given the default value of 0 for resID. It's possible that you're crashing when calling IV.setImageResource(0);.
Your image implementation in code is wrong, you need to init your image view like this :
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_avatar, container, false);
// init image view
IV = (ImageView) rootView.findViewById( R.id.Torso );
// getting extras
Bundle bundle = getActivity().getIntent().getExtras();
if(bundle!= null)
{
int resid = bundle.getInt("resId");
IV.setImageResource(resid);
}
return rootView;
}
Don't pass value from Fragment to Fragment directly.
You should use setArguments from SettingsFragment and getArguments in HomeFragment
Ive got a Button in one of my Fragments. But it seems to be "not-clickable". There is no Log.d. Message when I click the Button (In another Fragment (Same onclicklistenercode) everything is fine.
For greater overview I added the whole Class and the part of my layout file which defindes the button.
public class ListViewFragment extends Fragment {
DbHelper mydb;
Button buttondeletedb;
Button buttonexport;
private EditText roomnr;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_listview, container, false);
Context context = getContext();
mydb = new DbHelper(context);
buttondeletedb = (Button) view.findViewById(R.id.button_deletelist_list);
buttonexport = (Button) view.findViewById(R.id.button_export);
String dataList = mydb.getAllElements();
String [] dataListArray = dataList.split("\n");
List<String> dataListFinal = new ArrayList<>(Arrays.asList(dataListArray));
ArrayAdapter<String> dataListAdapter = new ArrayAdapter<>(
getActivity(),
R.layout.list_item_datalist,
R.id.list_item_datalist_textview,
dataListFinal);
View rootView=inflater.inflate(R.layout.fragment_listview, container, false);
ListView dataListListView = (ListView) rootView.findViewById(R.id.datalist);
dataListListView.setAdapter(dataListAdapter);
buttondeletedb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("buttondeletelist", "clicked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
mydb.deleteAll();
}
});
return rootView;
}
}
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/deletelist"
android:id="#+id/button_deletelist_list"
android:layout_gravity="center_horizontal" />
You can not click the button because the root view of Fragment is not view, you returned rootView. The button is child view of view.
Change return rootView; to return view;.
It should work
//Remove rootView and return view instead of rootView
public class ListViewFragment extends Fragment {
DbHelper mydb;
Button buttondeletedb;
Button buttonexport;
private EditText roomnr;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_listview, container, false);
Context context = getContext();
mydb = new DbHelper(context);
buttondeletedb = (Button) view.findViewById(R.id.button_deletelist_list);
buttonexport = (Button) view.findViewById(R.id.button_export);
String dataList = mydb.getAllElements();
String [] dataListArray = dataList.split("\n");
List<String> dataListFinal = new ArrayList<>(Arrays.asList(dataListArray));
ArrayAdapter<String> dataListAdapter = new ArrayAdapter<>(
getActivity(),
R.layout.list_item_datalist,
R.id.list_item_datalist_textview,
dataListFinal);
// Change made here. replace view instead of rootView and remove rootView
ListView dataListListView = (ListView) view.findViewById(R.id.datalist);
dataListListView.setAdapter(dataListAdapter);
buttondeletedb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("buttondeletelist", "clicked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
mydb.deleteAll();
}
});
// Replace rootView with view.
return view;
}
}
Link between XML file and Class file of the Element (Button) is not there.Add this line in your onCreateView()
Button buttondeletedb = (Button) view.findViewById(R.id.buttonid);
I'm using ListFragment in my android project. I decided to make a listView, each listview item consist of music frequency imageView. I will try to animate the imageView of music frequency. Each listView has a button called play, once the play is clicked, the music frequency start to animate.
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragmentmusiclist, container, false);
lv = (ListView) v.findViewById(R.id.list);
mp = new MediaPlayer();
mp = null;
Song s1 = new Song("Love Story",(float) 2.5, onMusicPlayListener);
Song s2 = new Song("Sad Story",(float) 1.0, onMusicPlayListener);
Song s3 = new Song("Breakup Story",(float) 3.5, onMusicPlayListener);
songs = new ArrayList<Song>();
songs.add(s1);
songs.add(s2);
songs.add(s3);
adapter = new MusicListAdapter(getActivity(),songs);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
OnClickListener onMusicPlayListener = new OnClickListener() {
#Override
public void onClick(View v) {
final int position = getListView().getPositionForView((LinearLayout)v.getParent());
animMusicFreq = (ImageView) v.findViewById(R.id.music_anim);
animMusicFreq.setBackgroundResource(R.anim.anim_music);
animMusicFreq.post(new Runnable() {
#Override
public void run() {
AnimationDrawable frameAnimation =
(AnimationDrawable) animMusicFreq.getBackground();
frameAnimation.start();
}
});
You are inflating your view inside onCreateView, but you don't pass it to the system. Instead you tell it to inflate its own (you return super). It doesn't make any sense.
You should return your v view like so:
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragmentmusiclist, container, false);
// ...
return v;
}