Can't change TextView in Fragment from main Activity( with interface), - android

Although i have read similar post-questions, i havent found solution to my problem. As you can see in the title i cant change Textview in TextFragment.
i get this error:07-09 15:05:55.593 6441-6441/com.eguide.dimitris.campusguide E/AndroidRuntime: FATAL EXCEPTION: main
07-09 15:05:55.593 6441-6441/com.eguide.dimitris.campusguide E/AndroidRuntime: java.lang.NullPointerException
07-09 15:05:55.593 6441-6441/com.eguide.dimitris.campusguide E/AndroidRuntime: at com.eguide.dimitris.campusguide.mainActivity$1.onVisitStart(mainActivity.java:66)
So i would appreciate any help.
Thanks in advance.
mainActivity
public class mainActivity extends Activity implements inter {
public PlaceManager placeManager;
public PlaceEventListener placeEventListener;
public String name;
TextView tt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Gimbal.setApiKey(this.getApplication(), "5436462c-6400-48f4-b6af-e0ad2094550f");
CommunicationManager.getInstance().startReceivingCommunications();
tt=(TextView) findViewById(R.id.test);
}
#Override
public void respond(String data) {
FragmentManager manager2=getFragmentManager();
textFragment frag2= (textFragment) manager2.findFragmentById(R.id.text_fragment);
frag2.changeText(data);
}
#Override
public void barstatus() {
FragmentManager manager1=getFragmentManager();
imageFragment frag1=(imageFragment) manager1.findFragmentById(R.id.image_fragment);
frag1.changeStatus();
}
#Override
public void barstatus2() {
FragmentManager manager1=getFragmentManager();
imageFragment frag1=(imageFragment) manager1.findFragmentById(R.id.image_fragment);
frag1.changeStatus2();
}
public void changestatus(){
placeEventListener= new PlaceEventListener() {
#Override
public void onVisitStart(Visit visit) {
super.onVisitStart(visit);
name=visit.getPlace().getName().toString();
if (name!=null){
respond(name);
barstatus2();
}
}
};
textFragment
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class textFragment extends Fragment {
TextView text1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.text_fragment, container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
text1 = (TextView)getActivity().findViewById(R.id.textF);
text1.setText("Press Start button to find buildings near you");
}
public void changeText(String data){
text1 = (TextView)getActivity().findViewById(R.id.textF);
text1.setText(data.toString());
}
}
imageFragment
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.transition.Visibility;
import android.view.ActionProvider;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
public class imageFragment extends Fragment {
private ProgressBar bar;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.image_fragment,container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
bar=(ProgressBar) getActivity().findViewById(R.id.progressBar);
bar.setVisibility(View.INVISIBLE);
}
public void changeStatus(){
bar=(ProgressBar) getActivity().findViewById(R.id.progressBar);
bar.setVisibility(View.VISIBLE);
}
public void changeStatus2(){
bar=(ProgressBar) getActivity().findViewById(R.id.progressBar);
bar.setVisibility(View.INVISIBLE);
}
}
interface
public interface inter {
public void respond(String data);
public void barstatus();
public void barstatus2();
}
Guys also note tha i have tried and this in mainActivity but nothing changed.
inter inte;
public void changestatus(){
placeEventListener= new PlaceEventListener() {
#Override
public void onVisitStart(Visit visit) {
super.onVisitStart(visit);
name=visit.getPlace().getName().toString();
if (name!=null){
inte.respond(name);
inte.barstatus2();
}
}
};
EDIT:
if instead of
public void changestatus(){
placeEventListener= new PlaceEventListener() {
#Override
public void onVisitStart(Visit visit) {
super.onVisitStart(visit);
name=visit.getPlace().getName().toString();
if (name!=null){
respond(name);
barstatus2();
}
}
use
#Override
protected void onStart() {
super.onStart();
placeEventListener= new PlaceEventListener() {
#Override
public void onVisitStart(Visit visit) {
super.onVisitStart(visit);
name=visit.getPlace().getName();
if (name!=null){
respond(name);
barstatus2();
}
}
};
i can make changes...can you explain me why??
i dont want this block of code running onStart().
i want this block of code working inside a method.

You need to make little change in your textFragment, initialize TextView in onCreateView() method as,
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.text_fragment, container,false);
text1 = (TextView)getActivity().findViewById(R.id.textF);
text1.setText("Press Start button to find buildings near you");
return view;
}

Related

Why does RecyclerView not get updated from the LiveData in the Viewmodel?

I have a fragment (Inventory Fragment) that displays some CardView objects in a RecyclerView. These objects get their data from an Adapter after the data has been received from the ViewModel. Inside the adapter, there are certain functions that can change the Livedata. All of these functions first open another Fragment (Food Editor), and this where the new data is set to the ViewModel.
My problem is that even after this, the RecyclerView does not get the new object. I used notifyDataSetChanged(). What am I doing wrong? Is there an easier way to achieve what I am trying to do (Add, Delete, Modify and such)?
Inventory Fragment:
package com.coffeetech.kittycatch;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
public class InventoryFragment extends Fragment {
//GLOBAL VARIABLES
RecyclerView recyclerView;
FoodAdapter foodAdapter;
FloatingActionButton add_button;
FrameLayout frameLayout;
FoodViewModel foodViewModel;
//FOOD LIST
private List<Food> foodList;
public InventoryFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_inventory, container, false);
//GETTING THE FOOD VIEW MODEL
foodViewModel = new ViewModelProvider(this,ViewModelProvider.AndroidViewModelFactory.getInstance(getActivity().getApplication())).get(FoodViewModel.class); //TODO:HERE
foodList = foodViewModel.getFoods().getValue();
foodAdapter = new FoodAdapter(foodList);
recyclerView=v.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(foodAdapter);
//SETTING THE FOOD VIEW MODEL
foodViewModel.getFoods().observe(getActivity(), new Observer<List<Food>>() {
#Override
public void onChanged(List<Food> foods) {
foodAdapter.setFoods(foods);
foodList=foods;
foodAdapter.notifyDataSetChanged(); //TODO: MAKE THIS BETTER
}
});
//setting up the frameLayout
frameLayout = v.findViewById(R.id.food_editor_frame);
//setting up the Add button
add_button=v.findViewById(R.id.add_button);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { //for new food addition to list
openFoodEditorFragment(-1);
}
});
foodAdapter.setOnFoodcardClickListener(new FoodAdapter.OnFoodcardClickListener() {
#Override
public void deleteFood(int position) { //code that deletes current food
foodViewModel.delete(foodList.get(position));
foodAdapter.notifyItemRemoved(position);
}
#Override
public void onEdit(int position) { //code that runs the edit of each food
openFoodEditorFragment(position);
foodAdapter.notifyItemChanged(position);
}
#Override
public void decrease(int position) {
foodList.get(position).decrease();
foodViewModel.update(foodList.get(position));
foodAdapter.notifyItemChanged(position);
}
#Override
public void increase(int position) {
foodList.get(position).increase();
foodViewModel.update(foodList.get(position));
foodAdapter.notifyItemChanged(position);
}
#Override
public void setSeekBar(int position,int progress) {
foodList.get(position).setQuantity(progress);
foodViewModel.update(foodList.get(position));
foodAdapter.notifyItemChanged(position);
}
});
return v;
}
public void openFoodEditorFragment(int position){ //position = -1 for new, and an integer (position) for edit
FoodEditorFragment foodEditorFragment;
switch(position){
case -1:
foodEditorFragment = new FoodEditorFragment(foodViewModel);
break;
default:
foodEditorFragment = new FoodEditorFragment(foodList.get(position),foodViewModel);
break;
}
FragmentTransaction transaction=getFragmentManager().beginTransaction();
transaction.replace(R.id.food_editor_frame,foodEditorFragment);
transaction.commit();
}
}
RecyclerView's adapter:
package com.coffeetech.kittycatch;
import android.app.Application;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.FoodViewHolder> {
//VARIABLE THAT CONTAINS THE FOOD LIST (array list)
public List<Food> foods;
int size;
private OnFoodcardClickListener onFoodcardClickListener;
//listener interface
public interface OnFoodcardClickListener{
void deleteFood(int position);
void onEdit(int position);
void decrease(int position);
void increase(int position);
void setSeekBar(int position, int progress);
}
public void setOnFoodcardClickListener(OnFoodcardClickListener activity){ //this is called in MainActivity
onFoodcardClickListener=activity;
}
public FoodAdapter(List<Food>foods){
this.foods=foods;
}
public static class FoodViewHolder extends RecyclerView.ViewHolder{
//VARIABLES FOR EACH WIDGET IN FOODCARD
TextView name,quantity; //to modify according to current food
ImageButton decreaseButton,increaseButton; //to hide or show
SeekBar seekbar; //according to current type
ImageButton deleteButton,editButton;
public FoodViewHolder(#NonNull View itemView, final OnFoodcardClickListener listener) {//'itemView' is the card
super(itemView);
name=itemView.findViewById(R.id.name);
quantity=itemView.findViewById(R.id.quantity);
decreaseButton=itemView.findViewById(R.id.decrease_button);
increaseButton=itemView.findViewById(R.id.increase_button);
seekbar=itemView.findViewById(R.id.seekbar);
deleteButton=itemView.findViewById(R.id.delete_button);
editButton=itemView.findViewById(R.id.edit_button);
editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener!=null){
int position=getAdapterPosition();
if (position!= RecyclerView.NO_POSITION){
listener.onEdit(position);
}
}
}
});
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener!=null){
int position=getAdapterPosition();
if (position!= RecyclerView.NO_POSITION){
listener.deleteFood(position);
}
}
}
});
decreaseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener!=null){
int position=getAdapterPosition();
if (position!= RecyclerView.NO_POSITION){
listener.decrease(position);
}
}
}
});
increaseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener!=null){
int position=getAdapterPosition();
if (position!= RecyclerView.NO_POSITION){
listener.increase(position);
}
}
}
});
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if(listener!=null){
int position=getAdapterPosition();
if (position!= RecyclerView.NO_POSITION){
listener.setSeekBar(position,seekBar.getProgress());
}
}
}
});
}
}
#NonNull
#Override
public FoodViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.foodcard, parent, false); //inflating Foodcard
FoodViewHolder vw = new FoodViewHolder(v,onFoodcardClickListener);
return vw;
}
#Override
public void onBindViewHolder(#NonNull FoodViewHolder holder, int position) { //'holder' is the foodcard here
Food currentFood=foods.get(position);
holder.name.setText(currentFood.getName());
holder.quantity.setText(String.valueOf(currentFood.getQuantity()));
holder.seekbar.setProgress(currentFood.getQuantity());
//code to hide or show certain widgets based on food type
if(currentFood.getType()==0){ //for discrete food
holder.increaseButton.setVisibility(View.VISIBLE);
holder.decreaseButton.setVisibility(View.VISIBLE);
holder.quantity.setVisibility(View.VISIBLE);
holder.seekbar.setVisibility(View.GONE);
}else{// for continuous food
holder.increaseButton.setVisibility(View.GONE);
holder.decreaseButton.setVisibility(View.GONE);
holder.quantity.setVisibility(View.GONE);
holder.seekbar.setVisibility(View.VISIBLE);
}
}
#Override
public int getItemCount() {
return size;
}
//FUCNTION TO GET LIVE DATA HERE
public void setFoods (List<Food> foods){
this.foods=foods;
notifyDataSetChanged();
}
}
Food Editor Fragment:
package com.coffeetech.kittycatch;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class FoodEditorFragment extends Fragment {
private TextView name,quantity,min_quantity;
private ImageButton save,cancel;
private RadioGroup radioGroup;
protected int t,mode;
protected Food food;
FoodViewModel foodViewModel;
public FoodEditorFragment() {
// Required empty public constructor
}
public FoodEditorFragment (Food food, FoodViewModel foodViewModel){
this.food=food;
this.foodViewModel=foodViewModel;
mode=1;
}
public FoodEditorFragment (FoodViewModel foodViewModel){
this.foodViewModel=foodViewModel;
this.food = new Food();
mode=0;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_food_editor, container, false);
name=view.findViewById(R.id.name_editor);
quantity=view.findViewById(R.id.quantity_editor);
min_quantity=view.findViewById(R.id.min_quantity_editor);
save=view.findViewById(R.id.save_button_editor);
cancel=view.findViewById(R.id.cancel_button_editor);
radioGroup=view.findViewById(R.id.radioGroup_editor);
if (mode==1){ //for editing Food
//CODE TO SETUP EDITOR ACCORDING TO INITIAL DETAILS
name.setText(food.getName());
quantity.setText(String.valueOf(food.getQuantity()));
min_quantity.setText(String.valueOf(food.getMin_quantity()));
t=food.getType();
if(t==0){//for discrete food
radioGroup.check(R.id.discrete_radioButton);
}else{//for cont food
radioGroup.check(R.id.cont_radioButton);
}
}
setButtons();
return view;
}
public void setButtons(){
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { //USE BELOW 'food' TO PASS NEW DATA TO ACTIVITY
try {
if ((!name.getText().toString().isEmpty()) && ((radioGroup.getCheckedRadioButtonId() == R.id.discrete_radioButton) || (radioGroup.getCheckedRadioButtonId() == R.id.cont_radioButton))) {
food.setName(name.getText().toString());
food.setQuantity(Integer.parseInt(quantity.getText().toString()));
food.setMin_quantity(Integer.parseInt(min_quantity.getText().toString()));
if (radioGroup.getCheckedRadioButtonId() == R.id.discrete_radioButton) {
food.setType(0);
} else if (radioGroup.getCheckedRadioButtonId() == R.id.cont_radioButton) {
food.setType(1);
}
switch (mode){
case 0:
foodViewModel.insert(food);
break;
case 1:
foodViewModel.update(food);
break;
}
//CLOSE THE FRAGMENT
getFragmentManager().beginTransaction().remove(FoodEditorFragment.this).commit();
} else {
throw new Exception();
}
}catch (Exception e){
Toast.makeText(getContext(),"Please set all details",Toast.LENGTH_SHORT).show();
}
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { //CODE IF USER PRESSES ON CANCEL
//CLOSE THE FRAGMENT
getFragmentManager().beginTransaction().remove(FoodEditorFragment.this).commit();
}
});
}
}
ViewModel I am using:
package com.coffeetech.kittycatch;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import java.util.ArrayList;
import java.util.List;
public class FoodViewModel extends AndroidViewModel {
private FoodRepository repository;
private LiveData<List<Food>> foods;
public FoodViewModel(#NonNull Application application) {
super(application);
repository = new FoodRepository(application);
foods=repository.getAll();
}
public void insert(Food food){
repository.insert(food);
}
public void update(Food food){
repository.update(food);
}
public void delete(Food food){
repository.delete(food);
}
public void deleteAll(){
repository.deleteAll();
}
public LiveData<List<Food>> getFoods(){
return foods;
}
public LiveData<List<Food>> getBuying () {return repository.getBuying();}
}
In FoodAdapter's getItemCount() method, You set itemcount static. You have to change it to foods.size()

Fragment dynamic layout save ui changes screen orientation

I am trying to maintain the ui changes so that when restarting the activity, the instance of my fragment become used with the changes of the buttons. So I found setRetainInstance(true) doesn't destroy the fragment object, however, the resulted view is destroyed. So I overrode onSaveInstance in the fragment class to save the ids of the resources that is called in the event handlers for setting it the next time the activity is created. The result was unexpected, at least for me:
1. The view of the fragment is destroyed when recreating the activity and the fragments instance become reattached to the new activity instance.
2. Event handlers become non-operational, so I don't know where is the problem.
Here is the code of the activity class:
package com.voicenoteinc.ticatactoy;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
Tic_Fragment s;
FragmentManager manager;
String TAG_FRAGMENT = "tag_fragment";
FragmentTransaction trans;
boolean retained = true;
String COLOR_ARRAY;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager = getFragmentManager();
s = (Tic_Fragment) manager.findFragmentByTag(TAG_FRAGMENT);
if(s == null){
s = new Tic_Fragment();
retained = false;
trans = manager.beginTransaction();
trans.add(R.id.fragment_container,s,TAG_FRAGMENT).commit();
}
}
}
and Here is the code for the Fragment class:
package com.voicenoteinc.ticatactoy;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Switch;
public class Tic_Fragment extends Fragment {
public Button bu1,bu2,bu3,bu4,bu5,bu6,bu7,bu8,bu9;
int COLOR[] = new int[9];
public String COLOR_KEY = "COLOR_KEY";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
for(int i =0; i<9;i++){
COLOR[i] = R.color.granite;
}
return inflater.inflate(R.layout.tic_fragment,container,false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
for(int i =0; i<9;i++){
COLOR[i] = R.color.granite;
}
super.onViewCreated(view, savedInstanceState);
if(savedInstanceState!=null){
COLOR=savedInstanceState.getIntArray(COLOR_KEY);
bu1.setBackgroundResource(COLOR[0]);
bu2.setBackgroundResource(COLOR[1]);
bu3.setBackgroundResource(COLOR[2]);
bu4.setBackgroundResource(COLOR[3]);
bu5.setBackgroundResource(COLOR[4]);
bu6.setBackgroundResource(COLOR[5]);
bu7.setBackgroundResource(COLOR[6]);
bu8.setBackgroundResource(COLOR[7]);
bu9.setBackgroundResource(COLOR[8]);
}else{
bu1 = getView().findViewById(R.id.bu1);
bu2 = getView().findViewById(R.id.bu2);
bu3 = getView().findViewById(R.id.bu3);
bu4 = getView().findViewById(R.id.bu4);
bu5 = getView().findViewById(R.id.bu5);
bu6 = getView().findViewById(R.id.bu6);
bu7 = getView().findViewById(R.id.bu7);
bu8 = getView().findViewById(R.id.bu8);
bu9 = getView().findViewById(R.id.bu9);
}
eventhandlers();
}
public void eventhandlers(){
bu1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu1,1);
}
});
bu2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu2,2);
}
});
bu3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu3,3);
}
});
bu4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu4,4);
}
});
bu5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu5,5);
}
});
bu6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu6,6);
}
});
bu7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu7,7);
}
});
bu8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu8,8);
}
});
bu9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu9,9);
}
});
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putIntArray(COLOR_KEY,COLOR);
}
public void display(Button bu, int i){
int backgroundColor = R.color.greenery;
bu.setBackgroundResource(backgroundColor);
COLOR[i-1] = backgroundColor;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
}
Thank ou for helping, and by the way I am new to using Fragments and Dynamic Layouts

How to set the library in android studio

I am trying to set a waveInApp library http://www.materialup.com/posts/waveinapp
I have declared all the required thing .The app
working but the background wave is not working .I am not able to set the wave function as a beginner in android development .
I am able to set the all the basic things including the media player.
Here I am not able to set the speech recognization handler
Here is what I have done
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import com.cleveroad.audiovisualization.AudioVisualization;
import com.cleveroad.audiovisualization.DbmHandler;
import com.cleveroad.audiovisualization.SpeechRecognizerDbmHandler;
import com.cleveroad.audiovisualization.VisualizerDbmHandler;
public class MainActivity extends AppCompatActivity {
private AudioVisualization audioVisualization;
private Context context;
private ImageButton button1,button2;
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audioVisualization = (AudioVisualization)findViewById(R.id.visualizer_view);
button1=(ImageButton)findViewById(R.id.imageButton);
button2=(ImageButton)findViewById(R.id.imageButton2);
mediaPlayer =MediaPlayer.create(this,R.raw.song);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"playing",Toast.LENGTH_SHORT).show();
mediaPlayer.start();
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"pause",Toast.LENGTH_SHORT).show();
mediaPlayer.pause();
VisualizerDbmHandler vizualizerHandler = DbmHandler.Factory.newVisualizerHandler(getContext(), 0);
audioVisualization.linkTo(vizualizerHandler);
// set speech recognizer handler
SpeechRecognizerDbmHandler speechRecHandler = DbmHandler.Factory.newSpeechRecognizerHandler(context);
speechRecHandler.innerRecognitionListener(...);
audioVisualization.linkTo(speechRecHandler);
}
});
}
#Override
public void onResume() {
super.onResume();
audioVisualization.onResume();
}
#Override
public void onPause() {
audioVisualization.onPause();
super.onPause();
}
}
So how to set the above handeler. I am not able to set the connect audio visualization view to audio output . How to set the following method with the media player
// set speech recognizer handler
SpeechRecognizerDbmHandler speechRecHandler = DbmHandler.Factory.newSpeechRecognizerHandler(context);
speechRecHandler.innerRecognitionListener(...);
audioVisualization.linkTo(speechRecHandler);
// set audio visualization handler. This will REPLACE previously set speech recognizer handler
VisualizerDbmHandler vizualizerHandler = DbmHandler.Factory.newVisualizerHandler(getContext(), 0);
audioVisualization.linkTo(vizualizerHandler);
Except this all are working.any hint or advice will be helpfull.
I tried to search
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.cleveroad.audiovisualization.AudioVisualization;
import com.cleveroad.audiovisualization.DbmHandler;
import com.cleveroad.audiovisualization.SpeechRecognizerDbmHandler;
public class SpeechRecognitionFragment extends Fragment {
public static SpeechRecognitionFragment newInstance() {
return new SpeechRecognitionFragment();
}
private AudioVisualization audioVisualization;
private Button btnRecognize;
private SpeechRecognizerDbmHandler handler;
private boolean recognizing;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gles, container, false);
audioVisualization = (AudioVisualization) view.findViewById(R.id.visualizer_view);
btnRecognize = (Button) view.findViewById(R.id.btn_recognize);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
btnRecognize.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (recognizing) {
handler.stopListening();
} else {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getContext().getPackageName());
handler.startListening(intent);
}
btnRecognize.setEnabled(false);
}
});
handler = DbmHandler.Factory.newSpeechRecognizerHandler(getContext());
handler.innerRecognitionListener(new SimpleRecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
super.onReadyForSpeech(params);
onStartRecognizing();
}
#Override
public void onResults(Bundle results) {
super.onResults(results);
onStopRecognizing();
}
#Override
public void onError(int error) {
super.onError(error);
onStopRecognizing();
}
});
audioVisualization.linkTo(handler);
}
private void onStopRecognizing() {
recognizing = false;
btnRecognize.setText(R.string.start_recognition);
btnRecognize.setEnabled(true);
}
private void onStartRecognizing() {
btnRecognize.setText(R.string.stop_recognition);
btnRecognize.setEnabled(true);
recognizing = true;
}
#Override
public void onDestroyView() {
audioVisualization.release();
super.onDestroyView();
}
private static class SimpleRecognitionListener implements RecognitionListener {
#Override
public void onReadyForSpeech(Bundle params) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int error) {
}
#Override
public void onResults(Bundle results) {
}
#Override
public void onPartialResults(Bundle partialResults) {
}
#Override
public void onEvent(int eventType, Bundle params) {
}
}
}
from https://github.com/Cleveroad/WaveInApp/blob/master/app/src/main/java/com/cleveroad/example/SpeechRecognitionFragment.java
So can some one tell me why fragment is used and how I can set this in my main activity?
I know i am late to post this answer...but for future use try this
check my code you will find your answer
first of all in the liberay you have to make some changes in your xml.
<com.cleveroad.audiovisualization.GLAudioVisualizationView
android:id="#+id/visualizer_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:av_bubblesSize= "#dimen/bubble_size"
app:av_bubblesRandomizeSizes= "true"
app:av_wavesHeight= "#dimen/wave_height"
app:av_wavesFooterHeight="#dimen/footer_height"
app:av_wavesCount="7"
app:av_layersCount="4" />
then
private VisualizerDbmHandler handler;
MediaPlayer mp ;
private AudioVisualization audioVisualization;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View ve = inflater.inflate(R.layout.cat, container, false);
ibCapture = (ImageButton) ve.findViewById(R.id.ibCapture);
audioVisualization = (AudioVisualization)ve.findViewById(R.id.visualizer_view);
hell();
return ve;
}
ibCapture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (bool) {
bool = false;
mp = MediaPlayer.create(getContext(), R.raw.blackcat);
mp.setLooping(true);
handler = VisualizerDbmHandler.Factory.newVisualizerHandler(getContext(),mp);
audioVisualization.linkTo(handler);
mp.start();
((home)getActivity()).vis();
} else {
bool = true;
((home)getActivity()).visgone();
stopPlaying();
}
}
});
Replace
audioVisualization = (AudioVisualization) glAudioVisualizationView;
With
audioVisualization = (AudioVisualization)findViewById(R.id.glAudioVisualizationView);
glAudioVisualizationView should be id of AudioVisualization in your layout file
define
private AudioVisualization audioVisualization;
initialize it
audioVisualization = (AudioVisualization) view.findViewById(R.id.visualizer_view);
for speech use below code
SpeechRecognizerDbmHandler speechRecHandler = DbmHandler.Factory.newSpeechRecognizerHandler(getContext());
speechRecHandler.innerRecognitionListener();
audioVisualization.linkTo(speechRecHandler);
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getContext().getPackageName());
speechRecHandler.startListening(intent);
for a media on your device use below code, Sandeep Singh Answer
MediaPlayer mp = MediaPlayer.create(getContext(), R.raw.blackcat);
mp.setLooping(true);
handler = VisualizerDbmHandler.Factory.newVisualizerHandler(getContext(),mp);
audioVisualization.linkTo(handler);
mp.start();

Android Fragment onAttach Error

i have problem on my on Attach its doing red line on him and writing me :
"overrides deprecated method in 'android.support.v4.app.Fragment' "
Please help me understand what i am doing wrong ?
ty you for all the helpers !!
package com.example.omermalka.memecreator;
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
/**
* Created by omermalka on 14/11/2015.
*/
public class TopSectionFragment extends Fragment {
private static EditText TopText;
private static EditText BottomText;
TopSectionListener acitivtyCommander;
public interface TopSectionListener{
public void createMime(String top , String Bottom);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try{
acitivtyCommander = (TopSectionListener) activity;
}catch (ClassCastException e){
throw new ClassCastException(activity.toString());
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.top_section_fragment, container, false);
TopText = (EditText) view.findViewById(R.id.TopTextInput);
BottomText = (EditText) view.findViewById(R.id.BottomTextInput);
final Button button = (Button) view.findViewById(R.id.BottomTextInput);
button.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonClicked(v);
}
}
);
return view;
}
public void buttonClicked(View v) {
acitivtyCommander.createMime(TopText.getText().toString(),BottomText.getText().toString());
}
}
You need to change
public void onAttach(Activity activity)
to
public void onAttach(Context context)
Final code:
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
acitivtyCommander = (TopSectionListener) context;
} catch (ClassCastException e){
throw new ClassCastException(context.toString());
}
}

View.onRestoreInstanceState not being called when fragment setRetainInstance(true) (double screen orientation change when fragment is in a back stack)

I have two fragments: one on top of another. Fragments has setRetainInstance(true) in their constructors.
When I do a double screen flip and press back key, top fragment gets popped and bottom fragment becomes visible. But bottom fragment's view do not receive onRestoreInstanceState.
When I remove setRetainInstance(true) everything works just fine. But I need that setRetainInstance(true) to work with multiple threads, so I can't solve my problem that simple. :)
How to guarantee onRestoreInstanceState to be called in this case?
Here is some example code:
package com.example.saverestoreviewstate;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction().replace(android.R.id.content, new Fragment1()).commit();
}
}
public static class SaveRestoreView extends TextView {
public SaveRestoreView(Context context) {
super(context);
}
String value;
public void setValue(String value) {
this.value = value;
setText(value);
}
#Override
public Parcelable onSaveInstanceState() {
Bundle bundle = new Bundle();
bundle.putParcelable("super", super.onSaveInstanceState());
bundle.putString("value", value);
return bundle;
}
#Override
public void onRestoreInstanceState(Parcelable state) {
Bundle bundle = (Bundle)state;
super.onRestoreInstanceState(bundle.getParcelable("super"));
value = bundle.getString("value");
setText(value);
}
}
public static class Fragment1 extends Fragment {
private static boolean firstRun = true;
public Fragment1() {
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Context context = inflater.getContext();
LinearLayout layout = new LinearLayout(context);
layout.setId(12);
layout.setOrientation(LinearLayout.VERTICAL);
SaveRestoreView saveRestore = new SaveRestoreView(context);
saveRestore.setId(128);
if (firstRun) {
saveRestore.setValue("*******save this string*******");
firstRun = false;
}
layout.addView(saveRestore);
Button button = new Button(inflater.getContext());
button.setText("Create 2nd fragment");
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().beginTransaction().replace(android.R.id.content, new Fragment2()).addToBackStack(null).commit();
}
});
layout.addView(button);
return layout;
}
}
public static class Fragment2 extends Fragment {
public Fragment2() {
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return new View(inflater.getContext());
}
}
}
So, I've finished implementing save/restore logic manually.
The minus is that I can't turn off save\restore that already exist, so onSaveInstance/onRestoreInstance is called twice on a View. Except of that one time when it is not called by itself - then it IS called once B-).
To make it work just add to Fragment1 class:
SparseArray<Parcelable> savedState;
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (savedState != null)
view.restoreHierarchyState(savedState);
}
#Override
public void onDestroyView() {
super.onDestroyView();
savedState = new SparseArray<Parcelable>();
getView().saveHierarchyState(savedState);
}

Categories

Resources