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
Related
I have an app, where I have one Activity (main), and there in the layout, I have a ViewPager2. That ViewPager2's adapter is set with 2 fragments. Let's call one of these as Fragment A.
When Fragment A opens up, users have the option to open another fragment, Fragment B from within itself. (by transaction; I have an empty FrameLayout inside Fragment A). Fragment B provides a dialog box to edit the data shown with a RecyclerView in Fragment A. Fragment A itself also has a few options to change the data in its RecyclerView.
This data is populated from Shared preferences. Now, here's the problem - since the Fragments can be made to communicate only with the Activity with Interfaces, I can save the data in the Activity, but then I have no other option but to reload the entire RecyclerView in Fragment A since Fragment A doesn't know at which position it got the new data.
Please advice. Below are the Fragments and the Activity that I mentioned.
MainActivity.java:
package com.coffeetech.kittycatch;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements FoodEditorFragment.SendFoodFromEditor{
ViewPager2 viewPager;
TabLayout tab_menu;
SwipeAdapter adapter;
ArrayList<Food> foods;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager=findViewById(R.id.viewpager);
adapter=new SwipeAdapter(this);
viewPager.setAdapter(adapter);
//SETTING TABS
tab_menu = findViewById(R.id.tab_menu);
new TabLayoutMediator(tab_menu, viewPager, true, new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
switch(position){
case 0:
tab.setText("INVENTORY");
break;
case 1:
tab.setText("SHOPPING LIST");
}
}
}).attach();
}
#Override
public void onBackPressed() {
super.onBackPressed(); //TODO: CONFIGURE THIS
}
#Override
public void sendFood(Food food, int position) { //TODO: CODE TO REPLACE DATA TO SPECIFIC POSITION
loadData();
saveData();
}
#Override
public void sendFood(Food food) { //TODO: CODE TO ADD DATA TO POSITION 0
loadData();
saveData();
}
public void loadData(){
//TODO: LOAD THE LIST HERE
}
public void saveData(){
//TODO: SAVE THE DATA HERE
}
}
The FragmentStateAdapter for the ViewPager2:
package com.coffeetech.kittycatch;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
public class SwipeAdapter extends FragmentStateAdapter {
Fragment fragment;
public SwipeAdapter(FragmentActivity fa){
super(fa);
}
#NonNull
#Override
public Fragment createFragment(int position) {
switch (position){
case 0: //START INVENTORY FRAGMENT
fragment = new InventoryFragment();
break;
case 1: //START SHOPPING LIST FRAGMENT
fragment = new ShoppingListFragment();
break;
}
return fragment;
}
#Override
public int getItemCount() {
return 2;
}
}
Fragment 'A':
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.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;
public class InventoryFragment extends Fragment {
//GLOBAL VARIABLES
RecyclerView recyclerView;
FoodAdapter foodAdapter;
ArrayList<Food> foods = new ArrayList<Food>();
FloatingActionButton add_button;
FrameLayout frameLayout;
Food food;
int q; //for use in decrease and functions
public InventoryFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onPause() { //TODO:CODE TO SAVE DATA
saveData();
super.onPause();
}
#Override
public void onResume() { //TODO:CODE TO LOAD DATA
loadData();
super.onResume();
//food constructor takes arguments -> (String name, int type, int quantity, int min_quantity)
}
#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);
foodAdapter = new FoodAdapter(foods);
recyclerView=v.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(foodAdapter);
//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();
}
});
foodAdapter.setOnFoodcardClickListener(new FoodAdapter.OnFoodcardClickListener() {
#Override
public void deleteFood(int position) { //code that deletes current food
foods.remove(position);
foodAdapter.notifyItemRemoved(position);
}
#Override
public void onEdit(int position, int mode) { //code that runs the edit of each food, mode=1 for edit
openFoodEditorFragment(position,foods.get(position)); //TODO: SEE IF YOU NEED 'mode' AT ALL
}
#Override
public void decrease(int position) {
food = foods.get(position);
q=food.getQuantity();
food.setQuantity(q-1);
foodAdapter.notifyItemChanged(position);
}
#Override
public void increase(int position) {
food = foods.get(position);
q=food.getQuantity();
food.setQuantity(q+1);
foodAdapter.notifyItemChanged(position);
}
#Override
public void setSeekBar(int position,int progress) {
food = foods.get(position);
food.setQuantity(progress);
Toast.makeText(getContext(),"Quantity set to "+progress+"%",Toast.LENGTH_SHORT).show();
foodAdapter.notifyItemChanged(position);
}
});
return v;
}
public void openFoodEditorFragment(int position,Food food){ //code for Editor in Edit Old mode
//creating new Bundle and passing each member data of 'food'
Bundle bundle = new Bundle();
bundle.putString("name",food.getName());
bundle.putInt("type",food.getType());
bundle.putInt("quantity",food.getQuantity());
bundle.putInt("min_quantity",food.getMin_quantity());
bundle.putInt("mode",1);
bundle.putInt("position",position);
//setting up arguments for Fragment
FoodEditorFragment foodEditorFragment = new FoodEditorFragment();
foodEditorFragment.setArguments(bundle);
//creating the Fragment
FragmentTransaction transaction=getFragmentManager().beginTransaction();
transaction.replace(R.id.food_editor_frame,foodEditorFragment);
transaction.commit();
}
public void openFoodEditorFragment(){ //code for Editor in Add New mode
//creating new Bundle and passing each member data of 'food'
Bundle bundle = new Bundle();
bundle.putInt("position",0);
bundle.putInt("mode",0);
//setting up arguments for Fragment
FoodEditorFragment foodEditorFragment = new FoodEditorFragment();
foodEditorFragment.setArguments(bundle);
//creating the Fragment
FragmentTransaction transaction=getFragmentManager().beginTransaction();
transaction.replace(R.id.food_editor_frame,foodEditorFragment);
transaction.commit();
}
protected void setData(int position, Food food){
foods.remove(position);
foods.add(position,food);
foodAdapter.notifyItemChanged(position);
}
protected void setData(Food food){
foods.add(0,food);
foodAdapter.notifyItemInserted(0);
Toast.makeText(getContext(),"Added to the top",Toast.LENGTH_SHORT).show();
}
void loadData(){
//TODO: CODE TO LOAD DATA
}
void saveData(){
//TODO: CODE TO SAVE DATA
}
}
Fragment 'B':
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 mode,t,position;
protected Food food = new Food();
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
sffe = (SendFoodFromEditor)context;
}
public FoodEditorFragment() {
// Required empty public constructor
}
public interface SendFoodFromEditor{
void sendFood(Food food,int position); //FOR EDITING FOOD
void sendFood(Food food); //FOR NEW FOOD
}
SendFoodFromEditor sffe;
#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);
mode=getArguments().getInt("mode");
position=getArguments().getInt("position");
if (mode==1){ //for editing Food
//CODE TO SETUP EDITOR ACCORDING TO INITIAL DETAILS
name.setText(getArguments().getString("name"));
quantity.setText(String.valueOf(getArguments().getInt("quantity")));
min_quantity.setText(String.valueOf(getArguments().getInt("min_quantity")));
t=getArguments().getInt("type");
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);
}
//CODE TO SEND THE FOOD TO ACTIVITY
if (mode == 1) {
sffe.sendFood(food, position);
} else {
sffe.sendFood(food);
}
//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();
}
});
}
}
You need to make following changes.
In Fragment A,
Replace
transaction.replace(R.id.food_editor_frame,foodEditorFragment);
With
transaction.add(R.id.food_editor_frame,foodEditorFragment);
Reason: using replace will remove the fragmentA and FragmentA will always be recreated.
In MainActivity
#Override
public void sendFood(Food food, int position){
//find fragment by Id
Fragment fragmentA = (Fragment)
getSupportFragmentManager().findFragmentById(R.id.fragmetnA);
fragment.setData(position,food)
//code for save data here
}
#Override
public void sendFood(Food food) {
Fragment fragmentA = (Fragment)
getSupportFragmentManager().findFragmentById(R.id.fragmetnA);
fragment.setData(food)
//code for save data here
}
I want to change the TextView of editor activity by clicking on Button buttonExpense which should also open editor activity and show value of the result in
EditText mAmountEditText.
I am getting java.lang.ClassCastException in which it is clearly written that MainActivity cannot be cast to EditorActivity
Calculator.java
package com.example.harshitbahri.expensebook;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Calculator extends android.support.v4.app.Fragment {
Button button0;
Button button1;
Button button2;
Button button3;
Button button4;
Button button5;
Button button6;
Button button7;
Button button8;
Button button9;
Button buttonAdd;
Button buttonSubstract;
Button buttonMul;
Button buttonDiv;
Button buttonClear;
Button buttonEqual;
Button buttonExpense;
String result;
String tmp;
String operator;
TextView resultTextView;
FragmentActivity fa2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fa2 = (FragmentActivity) super.getActivity();
final View RootView= inflater.inflate(R.layout.activity_calculator, container, false);
button0 = (Button)RootView.findViewById(R.id.button0);
button1 = (Button)RootView.findViewById(R.id.button1);
......
buttonAdd = (Button)RootView.findViewById(R.id.buttonAdd);
buttonClear = (Button)RootView.findViewById(R.id.buttonClear);
buttonSubstract = (Button)RootView.findViewById(R.id.buttonSub);
buttonMul = (Button)RootView.findViewById(R.id.buttonMul);
buttonDiv = (Button)RootView.findViewById(R.id.buttonDiv);
buttonEqual = (Button)RootView.findViewById(R.id.buttonEqual);
buttonExpense= (Button)RootView.findViewById(R.id.buttonExp);
resultTextView = (TextView)RootView.findViewById(R.id.text_view_result);
button0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("0");
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("1");
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("2");
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("3");
}
});
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("4");
}
});
button5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("5");
}
});
button6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("6");
}
});
button7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("7");
}
});
button8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("8");
}
});
button9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("9");
}
});
buttonClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClearButtonClicked();
}
});
buttonSubstract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
onOperatorButtonClicked("-");
}
});
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onOperatorButtonClicked("+");
}
});
buttonMul.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onOperatorButtonClicked("X");
}
});
buttonDiv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onOperatorButtonClicked("/");
}
});
buttonEqual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onEqualButtonClicked();
}
});
buttonExpense.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(fa2, EditorActivity.class);
startActivity(intent);
((EditorActivity) getActivity()).updateGoldTextView(result);
/*Intent intent = new Intent(fa2, EditorActivity.class);
intent.putExtra(, result);
final int result2=1;
startActivityForResult(intent, result2);*/
}
});
return RootView;
}
private void onEqualButtonClicked() {
int res = 0;
try {
int number = Integer.valueOf(tmp);
int number2 = Integer.valueOf(resultTextView.getText().toString());
switch (operator) {
case "+":
res = number + number2;
break;
case "/":
res = number / number2;
break;
case "-":
res = number - number2;
break;
case "X":
res = number * number2;
break;
}
result = String.valueOf(res);
resultTextView.setText(result);
}
catch (Exception e) {
e.printStackTrace();
}
}
public void onOperatorButtonClicked(String operator) {
..
}
public void onClearButtonClicked() {
...
}
public void onNumberButtonClicked(String pos) {
..
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}`
EditorActivity.java
package com.example.harshitbahri.expensebook;
import android.app.AlertDialog;
import android.app.LoaderManager;
...
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class EditorActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
private static final int EXISTING_EXPENSE_LOADER = 0;
private Uri mCurrentExpenseUri;
private EditText mAmountEditText;
private EditText mDescEditText;
private Spinner mCategorySpinner;
private String mCategory = ExpenseEntry.CATEGORY_GENERAL;
private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
mExpenseHasChanged = true;
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
// Examine the intent that was used to launch this activity,
// in order to figure out if we're creating a new pet or editing an existing one.
Intent intent = getIntent();
mCurrentExpenseUri = intent.getData();
// If the intent DOES NOT contain a pet content URI, then we know that we are
// creating a new pet.
if (mCurrentExpenseUri == null) {
// This is a new pet, so change the app bar to say "Add a Pet"
setTitle("Add Expense");
yet.)
invalidateOptionsMenu();
} else {
// Otherwise this is an existing pet, so change app bar to say "Edit Pet"
setTitle("Edit Expense");
getLoaderManager().initLoader(EXISTING_EXPENSE_LOADER, null, this);
}
mAmountEditText = (EditText) findViewById(R.id.exp_amount);
mDescEditText = (EditText) findViewById(R.id.description);
mCategorySpinner = (Spinner) findViewById(R.id.spinner_category);
.....
}
......
finish();
}
public void updateGoldTextView(String goldAmount) {
mAmountEditText.setText(goldAmount);
}
}
MainActivity.java
package com.example.harshitbahri.expensebook;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements
Calculator.OnFragmentInteractionListener ,
Entries.OnFragmentInteractionListener,Info.OnFragmentInteractionListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TabLayout tabLayout = (TabLayout)findViewById(R.id.tablayout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
final Pageradapter adapter = new Pageradapter(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.setCurrentItem(1, false);
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) {
}
});
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
Your fragment is loaded from MainActivity and not EditorActivity, hence the class cast exception. If you want to pre-fill some data in the editor activity, you can pass that in the intent ( the code you commented on your onclick listener) and retrieve in the EditorActivity and set your UI elements.
Edited
buttonExpense.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(fa2, EditorActivity.class);
intent.putExtra("result", result);
startActivity(intent);
}});
In your EditorActivity class, in on create
String result=getIntent().getStringExtra("result")
updateGoldTextView(result)
I am new to android development and I am trying to pass a Boolean value from dialog fragment to the activity.
the boolean value is supposed to be decided by the user(depends on which button user clicked). However, the boolean immediately turned to false without clicking any button.
I have tried various method recommended I found on internet but none of them works for me(I guess I have some part screwed up...), these method include:
-broadcasting
-implementing interface
-intent.putExtra
and below is the code that I have came up with, could anyone help me take a look? Any help is appreciated.
Stage:
package com.example.fuj.valorsafeworldbytrade;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import static com.example.fuj.valorsafeworldbytrade.LosingDialogFragment.LOSING_FRAGMENT;
public class Stage extends AppCompatActivity {
String stage;
FragmentManager fragmentManager = getSupportFragmentManager();
LosingDialogFragment losingDialogFragment = new LosingDialogFragment();
BasicInfo basicInfo = new BasicInfo();
public void setText(){
TextView cpuReputation = (TextView) findViewById(R.id.cpu_reputation);
TextView cpuGold = (TextView) findViewById(R.id.cpu_gold);
TextView pGoldText = (TextView) findViewById(R.id.player_gold);
TextView pRepText = (TextView) findViewById(R.id.player_reputation);
cpuReputation.setText(String.valueOf(basicInfo.cRep));
cpuGold.setText(String.valueOf(basicInfo.cGold));
pGoldText.setText(String.valueOf(basicInfo.pGold));
pRepText.setText(String.valueOf(basicInfo.pRep));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stage);
setText();
}
protected void onStart() {
super.onStart();
stage = getIntent().getStringExtra(StageChoosingMenu.STAGE);
}
public void playerChoice(View view) {
boolean deceiveEnabled;
switch (view.getId()) {
case R.id.cooperate_button:
deceiveEnabled = false;
break;
case R.id.deceive_button:
deceiveEnabled = true;
break;
default:
throw new RuntimeException("Unknown Button ID");
}
switch (stage){
case "xumo":
xuMo(deceiveEnabled);
break;
}
}
public void xuMo(boolean playerDeceiveEnabled){
boolean cpuDeceiveEnabled;
cpuDeceiveEnabled = (Math.random() - basicInfo.faith > 0);
if (cpuDeceiveEnabled){
if (playerDeceiveEnabled){
basicInfo.playerDvsCpuD();
// faith changes to be amend w/ proper value, need record on the change of status
}
if (!playerDeceiveEnabled){
basicInfo.playerCvsCpuD();
}
}
if (!cpuDeceiveEnabled){
if (playerDeceiveEnabled){
basicInfo.playerDvsCpuC();
}
if (!playerDeceiveEnabled){
basicInfo.playerCvsCpuC();
}
}
if(basicInfo.pGold <= 0 || basicInfo.cGold <= 0 || basicInfo.pRep <= 0 || basicInfo.cRep <= 0){
//to be changed
setText();
losingDialogFragment.show(fragmentManager,LOSING_FRAGMENT);
//trying to show a alert dialog fragment
Log.d("True", String.valueOf(losingDialogFragment.tryAgainEnabled));
if(losingDialogFragment.tryAgainEnabled){//tryAgainEnabled is always false
//This is the part that I wanted to retrieve data from the user(if they want to try again or not)
basicInfo.reset();
losingDialogFragment.dismiss();
}else{
losingDialogFragment.dismiss();
}
}
setText();
// to be changed
}
}
LosingDialogFragment:
package com.example.fuj.valorsafeworldbytrade;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/**
* Created by fuj on 20/1/2017.
*/
public class LosingDialogFragment extends DialogFragment{
public static final String LOSING_FRAGMENT = "LOSING";
public boolean tryAgainEnabled;
Intent intent = new Intent();
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_lose, container, false);;
//the following code is used to set the boolean value after the user click the button
final Button tryAgainButton = (Button)rootView.findViewById(R.id.try_again_button);
tryAgainButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tryAgainEnabled = true;
}
});
Button giveUpButton =(Button)rootView.findViewById(R.id.give_up_button);
giveUpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tryAgainEnabled = false;
}
});
getDialog().setTitle(LOSING_FRAGMENT);
return rootView;
}
}
I am also sorry that I am not the best with English, if any things is not clear or not polite because of my poor English, please kindly let me know. I apologize in advance for any mistakes I have made.
It's because you check the value of tryAgainEnabled exactly right after showing the Dialog. Dialog starts Asynchronously, It means that it starts in diffrent Thread and your current thread doesn't wait for dismissing Dialog, So this line of your code if(losingDialogFragment.tryAgainEnabled){ runs exactly after you show dialog, befor you set value to tryAgainEnabled. Because the default value of boolean is always false, you will get false everytime.
I suggest that use listener for this:
Dialog:
public class LosingDialogFragment extends DialogFragment {
public static final String LOSING_FRAGMENT = "LOSING";
public boolean tryAgainEnabled;
Intent intent = new Intent();
private View.OnClickListener onTryAgainButtonClickLisnter;
private View.OnClickListener onGiveUpButtonClickLisnter;
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_lose, container, false);;
final Button tryAgainButton = (Button)rootView.findViewById(R.id.try_again_button);
tryAgainButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(onTryAgainButtonClickLisnter!=null)
onTryAgainButtonClickLisnter.onClick(v);
}
});
Button giveUpButton =(Button)rootView.findViewById(R.id.give_up_button);
giveUpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(onGiveUpButtonClickLisnter!=null)
onGiveUpButtonClickLisnter.onClick(v);
}
});
getDialog().setTitle(LOSING_FRAGMENT);
return rootView;
}
public void setOnTryAgainButtonClickLisnter(View.OnClickListener onTryAgainButtonClickLisnter) {
this.onTryAgainButtonClickLisnter = onTryAgainButtonClickLisnter;
}
public void setOnGiveUpButtonClickLisnter(View.OnClickListener onGiveUpButtonClickLisnter) {
this.onGiveUpButtonClickLisnter = onGiveUpButtonClickLisnter;
}
}
In your activity call dialog like this:
LosingDialogFragment losingDialogFragment = new LosingDialogFragment();
losingDialogFragment.setOnTryAgainButtonClickLisnter(new View.OnClickListener() {
#Override
public void onClick(View v) {
tryAgain();
losingDialogFragment.dismiss();
}
});
losingDialogFragment.setOnGiveUpButtonClickLisnter(new View.OnClickListener() {
#Override
public void onClick(View v) {
giveUp();
losingDialogFragment.dismiss();
}
});
losingDialogFragment.show(fragmentManager, "");
Declare public boolean tryAgainEnabled; in your Stage Activity and youd can update that variable using ((Stage)context).tryAgainEnabled.
package com.example.fuj.valorsafeworldbytrade;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import static com.example.fuj.valorsafeworldbytrade.LosingDialogFragment.LOSING_FRAGMENT;
public class Stage extends AppCompatActivity {
String stage;
FragmentManager fragmentManager = getSupportFragmentManager();
LosingDialogFragment losingDialogFragment = new LosingDialogFragment();
BasicInfo basicInfo = new BasicInfo();
public boolean tryAgainEnabled;
public void setText(){
TextView cpuReputation = (TextView) findViewById(R.id.cpu_reputation);
TextView cpuGold = (TextView) findViewById(R.id.cpu_gold);
TextView pGoldText = (TextView) findViewById(R.id.player_gold);
TextView pRepText = (TextView) findViewById(R.id.player_reputation);
cpuReputation.setText(String.valueOf(basicInfo.cRep));
cpuGold.setText(String.valueOf(basicInfo.cGold));
pGoldText.setText(String.valueOf(basicInfo.pGold));
pRepText.setText(String.valueOf(basicInfo.pRep));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stage);
setText();
}
protected void onStart() {
super.onStart();
stage = getIntent().getStringExtra(StageChoosingMenu.STAGE);
}
public void playerChoice(View view) {
boolean deceiveEnabled;
switch (view.getId()) {
case R.id.cooperate_button:
deceiveEnabled = false;
break;
case R.id.deceive_button:
deceiveEnabled = true;
break;
default:
throw new RuntimeException("Unknown Button ID");
}
switch (stage){
case "xumo":
xuMo(deceiveEnabled);
break;
}
}
public void xuMo(boolean playerDeceiveEnabled){
boolean cpuDeceiveEnabled;
cpuDeceiveEnabled = (Math.random() - basicInfo.faith > 0);
if (cpuDeceiveEnabled){
if (playerDeceiveEnabled){
basicInfo.playerDvsCpuD();
// faith changes to be amend w/ proper value, need record on the change of status
}
if (!playerDeceiveEnabled){
basicInfo.playerCvsCpuD();
}
}
if (!cpuDeceiveEnabled){
if (playerDeceiveEnabled){
basicInfo.playerDvsCpuC();
}
if (!playerDeceiveEnabled){
basicInfo.playerCvsCpuC();
}
}
if(basicInfo.pGold <= 0 || basicInfo.cGold <= 0 || basicInfo.pRep <= 0 || basicInfo.cRep <= 0){
//to be changed
setText();
losingDialogFragment.show(fragmentManager,LOSING_FRAGMENT);
Log.d("True", String.valueOf(losingDialogFragment.tryAgainEnabled));
if(losingDialogFragment.tryAgainEnabled){//tryAgainEnabled is always false
basicInfo.reset();
losingDialogFragment.dismiss();
}else{
losingDialogFragment.dismiss();
}
}
setText();
// to be changed
}
}
And in Fragment
package com.example.fuj.valorsafeworldbytrade;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/**
* Created by fuj on 20/1/2017.
*/
public class LosingDialogFragment extends DialogFragment{
public static final String LOSING_FRAGMENT = "LOSING";
Context context;
Intent intent = new Intent();
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_lose, container, false);;
final Button tryAgainButton = (Button)rootView.findViewById(R.id.try_again_button);
tryAgainButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((Stage)context).tryAgainEnabled = true;
}
});
Button giveUpButton =(Button)rootView.findViewById(R.id.give_up_button);
giveUpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((Stage)context).tryAgainEnabled = false;
}
});
getDialog().setTitle(LOSING_FRAGMENT);
return rootView;
}
}
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;
}
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();