Pass the EditText.getText from FirstFragment to SecondFragment when the User swipes - java

what i'm trying to do:
in FirstFragment the user can type in his weight.
in SecondFragment the weight should be shown in a TextView
the Value should be passed on swipe of the user.
i tried arround 3 how-to's and read a lot about fragments but i still couldn't find a suitable solution. As i'm kind of new to fragments it could also be that i made a uncommon way to generate fragments and it therefore doesn't work but i couldn't figure it out yet.
As you can se unerneath actually there is an error in the code because i tried to get access to the method of FirstFragment through the MainActivity
To simplyfy, i don't poste the whole code of the two fragment xlm's.
first_frag.xml have a EditText (id: getWeight) Box where you only can enter numbers up to 3 digits
second_frag.xml has a TextView (id: txtAlcLvl)
activity_main.xml:
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
MainActivity.java:
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.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity {
Calculator calc = new Calculator();
ViewPager pager;
private MyPagerAdapter myPagerAdapter;
String TabFragmentB;
public void setTabFragmentB(String t){
TabFragmentB = t;
}
public String getTabFragmentB(){
return TabFragmentB;
}
public Calculator getCalc(){
return this.calc;
}
public void getWeight(){
FragmentManager fm = getSupportFragmentManager();
FirstFragment fragment = (FirstFragment)fm.findFragmentById(R.id.i_dont_know_the_id);
//failure because trying to get access to Method of FirstFragment
fragment.getWeight();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MyPagerAdapter pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(pagerAdapter);
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(final int i, final float v, final int i2) {
}
#Override
public void onPageSelected(final int i) {
YourFragmentInterface fragment = (YourFragmentInterface) pagerAdapter.instantiateItem(pager, i);
if (fragment != null) {
fragment.fragmentBecameVisible();
}
}
#Override
public void onPageScrollStateChanged(final int i) {
}
});
}
public interface YourFragmentInterface {
void fragmentBecameVisible();
}
private class MyPagerAdapter extends FragmentStatePagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 1: return new SecondFragment(); //SecondFragment.newInstance("SecondFragment, Instance 1");
case 0: return new FirstFragment();
default: return new FirstFragment(); //FirstFragment.newInstance("FirstFragment, Default");
}
}
#Override
public int getCount() {
return 2;
}
}
}
FirstFragment.java:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class FirstFragment extends Fragment implements MainActivity.YourFragmentInterface {
Button btnBeer;
Button btnBeerSmall;
Button btnWine;
Button btnLiq;
Button btnSch;
Button btnWater;
Button btnMale;
Button btnFemale;
Calculator calc;
EditText getWeight;
public String getWeight(){
return getWeight.getText().toString();
}
#Override
public void fragmentBecameVisible() {
// You can do your animation here because we are visible! (make sure onViewCreated has been called too and the Layout has been laid. Source for another question but you get the idea.
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_frag, container, false);
calc = ((MainActivity) getActivity()).getCalc();
btnBeer = (Button) v.findViewById(R.id.btnBeer);
btnBeerSmall = (Button) v.findViewById(R.id.btnBeerSmall);
btnWine = (Button) v.findViewById(R.id.btnWine);
btnLiq = (Button) v.findViewById(R.id.btnLiq);
btnSch = (Button) v.findViewById(R.id.btnSch);
btnWater = (Button) v.findViewById((R.id.btnWater));
btnMale = (Button) v.findViewById(R.id.btnMale);
btnFemale = (Button) v.findViewById(R.id.btnFemale);
getWeight = (EditText) v.findViewById(R.id.getWeight);
btnBeer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(0);
}
});
btnBeerSmall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(1);
}
});
btnWine.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(2);
}
});
btnLiq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(3);
}
});
btnSch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(4);
}
});
btnWater.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(5);
}
});
btnMale.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnMale.setBackgroundResource(R.drawable.male_false);
btnFemale.setBackgroundResource(R.drawable.female);
}
});
btnFemale.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnFemale.setBackgroundResource(R.drawable.female_false);
btnMale.setBackgroundResource(R.drawable.male);
}
});
return v;
}
public static FirstFragment newInstance(String text) {
FirstFragment f = new FirstFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
SecondFragment.java:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
public class SecondFragment extends Fragment implements MainActivity.YourFragmentInterface {
TextView txtAlcLvl;
TextView txtTimeToZero;
TextView txtPeak;
ImageButton btnReset;
Calculator calc;
String weight;
#Override
public void fragmentBecameVisible() {
calc.person.setSex(false);
calc.person.setWeight(80);
txtAlcLvl.setText(((MainActivity) getActivity()).getWeight());
//txtAlcLvl.setText(String.format("%.2f", calc.getCurrentLevel()) + "‰");
// You can do your animation here because we are visible! (make sure onViewCreated has been called too and the Layout has been laid. Source for another question but you get the idea.
}
public void setSex(){
}
public void setWeight(){
try{
} catch(NumberFormatException e){
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.second_frag, container, false);
calc = ((MainActivity) getActivity()).getCalc();
String myTag = getTag();
((MainActivity)getActivity()).setTabFragmentB(myTag);
txtAlcLvl = (TextView) v.findViewById(R.id.txtAlcLvl);
txtTimeToZero = (TextView) v.findViewById(R.id.txtTimeToZero);
txtPeak = (TextView) v.findViewById(R.id.txtPeak);
btnReset = (ImageButton) v.findViewById((R.id.btnReset));
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.resetConsumption();
}
});
return v;
}
public void updateText(String t){
txtAlcLvl.setText(t);
}
public static SecondFragment newInstance(String text) {
SecondFragment f = new SecondFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}

You could do it the over way round.
Instead of trying to get the weight in activity from your fragment, try to set the weight on the activity from the fragment.
public class MainActivity extends FragmentActivity {
...
private float weight;
public void setWeight(float weight) {
this.weight = weight;
}
public float getWeight() {
return this.weight();
}
Then in your FirstFragment:
((MainActivity)getActivity()).setWeight(...);
And finally in your SecondFragment:
float weight = ((MainActivity)getActivity()).getWeight();

Don't try to "pass" the value like you would normally expect when an activity is invoking a new fragment.
Instead, consider using some persistent storage to store the value, such as SharedPreferences or a Sqlite database. Each fragment can read and write values out of there as needed.

Related

Can't make the button add a new item on the RecyclerList, only works once

Been working on this code for a while and as im new to recyclerList I can't seem to figure out why the button works only once.
Here is the adapter:
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class AdaptadorLista extends RecyclerView.Adapter<AdaptadorLista.ViewHolderLista> {
ArrayList<ComponentesLista> listaComponentes;
public AdaptadorLista(ArrayList<ComponentesLista> listaComponentes) {
this.listaComponentes = listaComponentes;
}
#NonNull
#Override
public ViewHolderLista onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_lista, parent, false);
return new ViewHolderLista(view);
}
#Override
public void onBindViewHolder(ViewHolderLista holder, int position) {
holder.textViewDescripcion.setText(String.valueOf(listaComponentes.get(position).getDescripcion()));
holder.textViewDinero.setText(String.valueOf(listaComponentes.get(position).getDinero()));
holder.textViewCantidad.setText(String.valueOf(listaComponentes.get(position).getCantidad()));
}
#Override
public int getItemCount() {
return listaComponentes.size();
}
public class ViewHolderLista extends RecyclerView.ViewHolder {
private TextView textViewCantidad, textViewDescripcion, textViewDinero;
public ViewHolderLista(#NonNull View itemView) {
super(itemView);
textViewCantidad= (TextView) itemView.findViewById(R.id.textMuestraCantidad);
textViewDescripcion = (TextView) itemView.findViewById(R.id.textMuestraDescripcion);
textViewDinero = (TextView) itemView.findViewById(R.id.textMuestraPrecio);
}
}
}
Here is the object it works with:
public class ComponentesLista {
private String descripcion;
private String cantidad;
private String dinero;
public ComponentesLista() {
}
public ComponentesLista(String descripcion, String cantidad, String dinero) {
this.descripcion = descripcion;
this.cantidad = cantidad;
this.dinero = dinero;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getCantidad() {
return cantidad;
}
public void setCantidad(String cantidad) {
this.cantidad = cantidad;
}
public String getDinero() {
return dinero;
}
public void setDinero(String dinero) {
this.dinero = dinero;
}
}
And here is the main method (It's not the main method, it's another screen I use after a button press but it shouldn't be the issue right?)
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class PantallaLista extends AppCompatActivity {
ArrayList<ComponentesLista> componentesLista;
RecyclerView recyclerLista;
//int cont = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista);
// Seccion ArrayList Lista
componentesLista=new ArrayList<>();
recyclerLista= (RecyclerView) findViewById(R.id.recyclerViewLista);
recyclerLista.setLayoutManager(new LinearLayoutManager(this));
// Botones
Button nuevo = (Button) findViewById(R.id.nuevoButton);
nuevo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
llenarLista();
}
});
Button guardarVolver = (Button) findViewById(R.id.terminarButton);
guardarVolver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(PantallaLista.this, MainActivity.class);
startActivity(intent);
}
});
}
private void llenarLista () {
EditText textoGetDescripcion = (EditText) findViewById(R.id.textInputProducto);
EditText textoGetCantidad = (EditText) findViewById(R.id.textInputCantidad);
EditText textoGetPrecio = (EditText) findViewById(R.id.textInputPrecio);
componentesLista.add(new ComponentesLista(textoGetDescripcion.getText().toString(), textoGetPrecio.getText().toString(), textoGetCantidad.getText().toString()));
AdaptadorLista adapter = new AdaptadorLista(componentesLista);
recyclerLista.setAdapter(adapter);
//System.out.println(textoGetDescripcion.getText().toString() + textoGetPrecio.getText().toString() + textoGetPrecio.getText().toString());
}
}
You are setting an adapter every time you add the item to the list. Whenever you are adding a new item to the list, you've to use adapter.notifyItemInserted(position)
Here's the activiy
public class PantallaLista extends AppCompatActivity {
ArrayList<ComponentesLista> componentesLista;
RecyclerView recyclerLista;
AdaptadorLista adapter;
//int cont = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista);
// Seccion ArrayList Lista
componentesLista=new ArrayList<>();
recyclerLista= (RecyclerView) findViewById(R.id.recyclerViewLista);
recyclerLista.setLayoutManager(new LinearLayoutManager(this));
adapter = new AdaptadorLista(componentesLista);
recyclerLista.setAdapter(adapter);
// Botones
Button nuevo = (Button) findViewById(R.id.nuevoButton);
nuevo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
llenarLista();
}
});
Button guardarVolver = (Button) findViewById(R.id.terminarButton);
guardarVolver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(PantallaLista.this, MainActivity.class);
startActivity(intent);
}
});
}
private void llenarLista () {
EditText textoGetDescripcion = (EditText) findViewById(R.id.textInputProducto);
EditText textoGetCantidad = (EditText) findViewById(R.id.textInputCantidad);
EditText textoGetPrecio = (EditText) findViewById(R.id.textInputPrecio);
ComponentesLista tempData = new ComponentesLista(textoGetDescripcion.getText().toString(), textoGetPrecio.getText().toString(), textoGetCantidad.getText().toString())
adapter.addNewItems(tempData);
}
}
heres the adapter
public class AdaptadorLista extends RecyclerView.Adapter<AdaptadorLista.ViewHolderLista> {
ArrayList<ComponentesLista> listaComponentes;
public AdaptadorLista(ArrayList<ComponentesLista> listaComponentes) {
this.listaComponentes = listaComponentes;
}
public addNewItems(ComponentesLista tempComponent){
this.listaComponentes.add(tempComponent);
notifyDataSetChanged();
}
#NonNull
#Override
public ViewHolderLista onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_lista, parent, false);
return new ViewHolderLista(view);
}
#Override
public void onBindViewHolder(ViewHolderLista holder, int position) {
holder.textViewDescripcion.setText(String.valueOf(listaComponentes.get(position).getDescripcion()));
holder.textViewDinero.setText(String.valueOf(listaComponentes.get(position).getDinero()));
holder.textViewCantidad.setText(String.valueOf(listaComponentes.get(position).getCantidad()));
}
#Override
public int getItemCount() {
return listaComponentes.size();
}
public class ViewHolderLista extends RecyclerView.ViewHolder {
private TextView textViewCantidad, textViewDescripcion, textViewDinero;
public ViewHolderLista(#NonNull View itemView) {
super(itemView);
textViewCantidad= (TextView) itemView.findViewById(R.id.textMuestraCantidad);
textViewDescripcion = (TextView) itemView.findViewById(R.id.textMuestraDescripcion);
textViewDinero = (TextView) itemView.findViewById(R.id.textMuestraPrecio);
}
}
}
please tell if you are not understanding something.

How to set RecyclerView OnClickListener in Fragments?

I'm trying to start a new Fragment that shows the details of the item that was clicked on in the RecyclerView. I've tried this in Activities and it worked perfectly but I'm trying to convert it to use on Fragments. Every time I get an 'null object reference'.
Adapter
package com.umbrella.fragmenttest;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class BorrowedAdapter extends RecyclerView.Adapter<BorrowedAdapter.BorrowedViewHolder> {
private Context mCtx;
private List<Borrowed> borrowedList;
public BorrowedAdapter(Context mCtx, List<Borrowed> borrowedList) {
this.mCtx = mCtx;
this.borrowedList = borrowedList;
}
#Override
public BorrowedViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mCtx).inflate(R.layout.list_borrowed, parent, false);
return new BorrowedViewHolder(view);
}
#Override
public void onBindViewHolder(BorrowedViewHolder holder, int position) {
Borrowed b = borrowedList.get(position);
holder.textViewOwner.setText(b.getOwner());
holder.textViewDesc.setText(b.getDesc());
holder.textViewAmount.setText(String.valueOf(b.getAmount()));
}
#Override
public int getItemCount() {
return borrowedList.size();
}
class BorrowedViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView textViewOwner, textViewDesc, textViewAmount;
public BorrowedViewHolder(View itemView) {
super(itemView);
textViewOwner = itemView.findViewById(R.id.b_owner);
textViewDesc = itemView.findViewById(R.id.b_description);
textViewAmount = itemView.findViewById(R.id.b_amount);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Borrowed borrowed = borrowedList.get(getAdapterPosition());
AppCompatActivity activity = (AppCompatActivity) view.getContext();
NavController navController = Navigation.findNavController(activity, R.id.hostfrag);
navController.navigate(R.id.action_displayBorrowed2_to_updateBorrowedClass);
}
}
}
Fragment class with the details
package com.umbrella.fragmenttest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class UpdateBorrowedClass extends Fragment {
private EditText editTextOwner, editTextDesc, editTextAmount;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.new_borrowed, container, false);
editTextOwner = view.findViewById(R.id.u_owner);
editTextDesc = view.findViewById(R.id.u_description);
editTextAmount = view.findViewById(R.id.u_amount);
Bundle bundle = getArguments();
final Borrowed borrowed = (Borrowed) bundle.getSerializable("borrowed");
loadBorrowed(borrowed);
view.findViewById(R.id.button_update).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateBorrowed(borrowed);
}
});
view.findViewById(R.id.button_delete).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Are you sure?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
deleteBorrowed(borrowed);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog ad = builder.create();
ad.show();
}
});
return view;
}
private void loadBorrowed(Borrowed borrowed) {
editTextOwner.setText(borrowed.getOwner());
editTextDesc.setText(borrowed.getDesc());
editTextAmount.setText(String.valueOf(borrowed.getAmount()));
}
private void updateBorrowed(final Borrowed borrowed) {
final String sOwner = editTextOwner.getText().toString().trim();
final String sDesc = editTextDesc.getText().toString().trim();
final Double dAmount = Double.parseDouble(editTextAmount.getText().toString().trim());
if (sOwner.isEmpty()) {
editTextOwner.setError("Owner required");
editTextOwner.requestFocus();
return;
}
if (sDesc.isEmpty()) {
editTextDesc.setError("Description required");
editTextDesc.requestFocus();
return;
}
if (dAmount.toString().isEmpty()) {
editTextAmount.setError("Amount required");
editTextAmount.requestFocus();
return;
}
class UpdateBorrowed extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
//Creating an item
borrowed.setOwner(sOwner);
borrowed.setDesc(sDesc);
borrowed.setAmount(dAmount);
//Adding to database
DatabaseClient.getInstance(getContext())
.borrowedDao()
.update(borrowed);
return null;
}
//Returns to the {RecyclerViewFragment} because the item is created
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
DisplayBorrowed displayBorrowed = new DisplayBorrowed();
getChildFragmentManager().beginTransaction().replace(R.id.mainer, displayBorrowed).addToBackStack(null).commit();
Toast.makeText(getContext(), "Updated", Toast.LENGTH_LONG).show();
}
}
UpdateBorrowed ut = new UpdateBorrowed();
ut.execute();
}
private void deleteBorrowed(final Borrowed borrowed) {
class DeleteBorrowed extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
DatabaseClient.getInstance(getContext())
.borrowedDao()
.delete(borrowed);
return null;
}
//Returns to the {RecyclerViewFragment} because the item is created
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
DisplayBorrowed displayBorrowed = new DisplayBorrowed();
getChildFragmentManager().beginTransaction().replace(R.id.mainer, displayBorrowed).addToBackStack(null).commit();
Toast.makeText(getContext(), "Deleted", Toast.LENGTH_LONG).show();
}
}
DeleteBorrowed dt = new DeleteBorrowed();
dt.execute();
}
}
Run log
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.umbrella.fragmenttest, PID: 31428
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.os.Bundle.getSerializable(java.lang.String)' on a null object reference
at com.umbrella.fragmenttest.UpdateBorrowedClass.onCreateView(UpdateBorrowedClass.java:31)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2439)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
at androidx.fragment.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2646)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2416)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2372)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at androidx.fragment.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Application terminated.
Have a look at this link: https://developer.android.com/guide/navigation/navigation-pass-data#bundle
In your onClick()
#Override
public void onClick(View view) {
Borrowed borrowed = borrowedList.get(getAdapterPosition());
AppCompatActivity activity = (AppCompatActivity) view.getContext();
NavController navController = Navigation.findNavController(activity, R.id.hostfrag);
navController.navigate(R.id.action_displayBorrowed2_to_updateBorrowedClass);
}
You should add a bundle with your borrowed object as argument like below:
#Override
public void onClick(View view) {
Borrowed borrowed = borrowedList.get(getAdapterPosition());
Bundle bundle = new Bundle();
bundle.putSerializable("borrowed", borrowed);
AppCompatActivity activity = (AppCompatActivity) view.getContext();
NavController navController = Navigation.findNavController(activity, R.id.hostfrag);
navController.navigate(R.id.action_displayBorrowed2_to_updateBorrowedClass, bundle);
}

Activity missing in manifest when declair

There is two arrows as you see in picture ..
one indicate to Activities in my project
other one indicate to recommended activity to declare in manifest ..
but there is no recommended activity except " StreamingActivity "
when i run my application ,, application show me that message " Unfortunately , application has stopped "
this code for publisheractivity
package khaabbas.huthaifa.com.talk_listen;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.red5pro.streaming.R5Connection;
import com.red5pro.streaming.R5Stream;
import com.red5pro.streaming.R5StreamProtocol;
import com.red5pro.streaming.config.R5Configuration;
import com.red5pro.streaming.source.R5Camera;
import com.red5pro.streaming.source.R5Microphone;
//import android.graphics.Camera;
public class PublishFragment extends android.support.v4.app.Fragment implements SurfaceHolder.Callback {
public static android.support.v4.app.Fragment newInstance() {
PublishFragment fragment = new PublishFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
public PublishFragment() {
// Required empty public constructor
}
public R5Configuration configuration;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
configuration = new R5Configuration(R5StreamProtocol.RTSP, "localhost", 8554, "live", 1.0f);
configuration.setLicenseKey("NBZF-UFM2-GCEP-OUYZ");
configuration.setBundleID(getActivity().getPackageName());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_publish, container, false);
return v;
}
protected Camera camera;
protected boolean isPublishing = false;
protected R5Stream stream;
private void preview() {
camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
SurfaceView surface = (SurfaceView) getActivity().findViewById(R.id.surfaceView);
surface.getHolder().addCallback(this);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}
catch(Exception e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
}
#Override
public void onResume() {
super.onResume();
preview();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button publishButton = (Button) getActivity().findViewById(R.id.publishButton);
publishButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onPublishToggle();
}
});
}
private void onPublishToggle() {
Button publishButton = (Button) getActivity().findViewById(R.id.publishButton);
if(isPublishing) {
stop();
}
else {
start();
}
isPublishing = !isPublishing;
publishButton.setText(isPublishing ? "stop" : "start");
}
public void start() {
camera.stopPreview();
stream = new R5Stream(new R5Connection(configuration));
stream.setView((SurfaceView) getActivity().findViewById(R.id.surfaceView));
R5Camera r5Camera = new R5Camera(camera, 320, 240);
R5Microphone r5Microphone = new R5Microphone();
stream.attachCamera(r5Camera);
stream.attachMic(r5Microphone);
stream.publish("red5prostream", R5Stream.RecordType.Live);
camera.startPreview();
}
public void stop() {
if(stream != null) {
stream.stop();
camera.startPreview();
}
}
#Override
public void onPause() {
super.onPause();
if(isPublishing) {
onPublishToggle();
}
}
}
Remove both this activity because u used only single activity it define activity and two other is fragment.
<activity android:name=".S"/>
<activity android:name=".Sub"/>
and fragment call used below code..
Fragment fragment = new HomeFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
No need to declare fragment on manifest, remove fragment declaration from manifest because you are declare fragment within section in manifest file.

Android fragment tabbed layout, reselecting tab 3, listview disappears

When I select tab 3 my listview appears, yet when I select tab 1 and reselect tab 3, the listview doesn't appear.
Why is this?
https://github.com/jdavey1996/News-Android-App
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Local"));
tabLayout.addTab(tabLayout.newTab().setText("Top rated"));
tabLayout.addTab(tabLayout.newTab().setText("All"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
package com.josh_davey.news_app;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class FragmentAdapter extends FragmentPagerAdapter {
int count;
public FragmentAdapter(FragmentManager fm, int count) {
super(fm);
this.count = count;
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Fragment1 temp = new Fragment1();
return temp;
case 1:
Fragment2 temp2 = new Fragment2();
return temp2;
case 2:
Fragment3 temp3 = new Fragment3();
return temp3;
}
return null;
}
#Override
public int getCount() {
return count;
}
}
package com.josh_davey.news_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 Fragment3 extends Fragment {
public Fragment3() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GetData getData = new GetData(getContext(),getActivity());
getData.execute("lincoln");
}
#Override
public void onResume() {
super.onResume();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment3, container, false);
}
}
If you need link to the full code it's on my github. Thanks in advance for any help
https://github.com/jdavey1996/News-Android-App
Default ViewPager's offscreenPageLimit is 1. So the tab3 is detached when tab1 is re-selected. If fragment is detached, Fragment's views are destroyed.
see: ViewPager.setOffscreenPageLimit
So I recommend you to set offscreenPageLimit to 2.
viewPager.setOffscreenPageLimit(2);
Or you can hold the list of ArticleConstructor in Fragment3 like blew.
GetData.java:
public class GetData extends AsyncTask<String, String,ArrayList<ArticleConstructor>>{
Callback callback;
interface Callback {
void onArticleConstructorLoaded(ArrayList<ArticleConstructor> articleConstructors);
}
public GetData(Callback callback) {
this.callback = callback;
}
...
#Override
protected void onPostExecute(ArrayList<ArticleConstructor> result) {
callback.onArticleConstructorLoaded(result);
}
....
}
Fragment3.java:
public class Fragment3 extends Fragment implements GetData.Callback {
private ListView listView;
private ArrayList<ArticleConstructor> articleConstructors = new ArrayList<>();
private ArticleArrayAdapter adapter;
public Fragment3() {
// 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.fragment3, container, false);
listView = (ListView) view.findViewById(R.id.listView);
adapter = new ArticleArrayAdapter(getActivity(), getContext(), articleConstructors);
listView.setAdapter(adapter);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (articleConstructors.size() == 0) {
GetData getData = new GetData(this);
getData.execute("lincoln");
}
}
#Override
public void onArticleConstructorLoaded(ArrayList<ArticleConstructor> articleConstructors) {
this.articleConstructors = articleConstructors;
adapter.setArticleConstructors(articleConstructors);
}
}

Android Pich zoom Image how add ImageButton listner

I have Code Image with Pich zoom
package com.androidtutorialpoint;
import com.androidtutorialpoint.imageview.PhotoView;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
public class MainActivity extends Activity {
private ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new HackyViewPager(this);
setContentView(mViewPager);
mViewPager.setAdapter(new SamplePagerAdapter());
}
static class SamplePagerAdapter extends PagerAdapter {
private static int[] sDrawables = {
R.drawable.ic_launcher,R.drawable.ic_launcher,
};
#Override
public int getCount() {
return sDrawables.length;
}
#Override
public View instantiateItem(ViewGroup container, int position) {
PhotoView photoView = new PhotoView(container.getContext());
photoView.setImageResource(sDrawables[position]);
// Now just add PhotoView to ViewPager and return it
container.addView(photoView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
return photoView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
}
I have add imageButton listner ale marker with function switching to a new activity
My Image button lister have Code
public class MainActivity extends Activity {
private ImageView mainBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainBtn = (ImageView) findViewById(R.id.button);
mainBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
openAlert(v);
}
});
}
private void openAlert(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setTitle(this.getTitle()+ " ");
// set positive button: Yes message
alertDialogBuilder.setPositiveButton("więcej",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// go to a new activity of the app
Intent positveActivity = new Intent(getApplicationContext(), PositiveActivity.class);
startActivity(positveActivity);
}
});
// set negative button: No message
alertDialogBuilder.setNegativeButton("wyjście",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// cancel the alert box and put a Toast to the user
dialog.cancel();
Toast.makeText(getApplicationContext(), "Mapa Budnik",
Toast.LENGTH_LONG).show();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
// show alert
alertDialog.show();
}
}
My Ask how to add a tag to the image Button and when you click the trigger Activity?
When my Image Button is in layaut.xml there is invisible.please help me

Categories

Resources