So I'm trying to update a textview from another class. However,whenever I'm calling the method, It seems the textview is null?
I have no idea why that would be the case.
Here is the relevant code
MediaPlayerService:
#Override
public void onPrepared(MediaPlayer mp) {
UI = new MediaPlayerUI();
mp.start();
int minutesDuration = mp.getDuration() / 6000;
int secondsDuration = (mp.getDuration() % 6000) / 1000;
UI.setDurationText(minutesDuration,secondsDuration);
UI.setProgressBarVisibility(0);
UI.setPauseButtonVisibility(1);
UI.playback();
}
MediaPlayerUI:
public class MediaPlayerUI extends MediaPlayerFragment {
public MediaPlayerUI(){
}
public void setSeekBarProgress(int position){
seekBar.setProgress(position);
}
public void setSeekBarMax(int max){
seekBar.setMax(max);
}
public int getSeekBarProgress(){
return seekBar.getProgress();
}
public void setDurationText(int minutes, int seconds){
}
public void setProgressBarVisibility(int code){
if(code == 0){
progressBar.setVisibility(ProgressBar.GONE);
}else{
progressBar.setVisibility(ProgressBar.VISIBLE);
}
}
public void setPauseButtonVisibility(int code){
if(code == 0){
pauseButton.setVisibility(View.GONE);
}else{
pauseButton.setVisibility(View.VISIBLE);
}
}
MediaPlayerFragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_media_player, container, false);
mSeriesImage = (ImageView) v.findViewById(R.id.series_image);
progressBar = (ProgressBar) v.findViewById(R.id.progress_bar);
seekBar = (SeekBar) v.findViewById(R.id.seek_bar);
playButton = (ImageButton) v.findViewById(R.id.play_button);
pauseButton = (ImageButton) v.findViewById(R.id.pause_button);
messageTitle = (TextView) v.findViewById(R.id.message_title);
seriesTitle = (TextView) v.findViewById(R.id.series_name);
mProgressText = (TextView) v.findViewById(R.id.progress_text);
mDurationText = (TextView) v.findViewById(R.id.duration_text);
mNoAudioText = (TextView) v.findViewById(R.id.no_audio_text);
mNoAudioText.setVisibility(v.GONE);
playButton.setVisibility(v.GONE);
pauseButton.setVisibility(v.GONE);
mAudioURL = getArguments().getString(Keys.AUDIO_URL_KEY);
mModel = getArguments().getParcelable(Keys.INTENT_SERIES_MODEL_OBJECT_KEY);
mPosition = getArguments().getInt(Keys.POSTION_KEY);
messageTitle.setText(mModel.getmMessageTitle().get(mPosition));
seriesTitle.setText(mModel.getmSeriesName());
Intent intent = new Intent(getActivity(), MediaPlayerService.class);
intent.putExtra(Keys.INTENT_SERIES_MODEL_OBJECT_KEY,mModel);
intent.putExtra(Keys.POSTION_KEY,mPosition);
intent.putExtra(Keys.AUDIO_URL_KEY,mAudioURL);
getActivity().bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
seekBar.setEnabled(true);
return v;
}
public void setDurationTextView(int minutes,int seconds){
Log.i(TAG,"mDurationText...."+mDurationText);
}
Log Output:
10-29 20:25:00.091 26349-26349/com.tubbs.citychurchob I/MediaPlayerFragment: mDurationText....null
Also, if I call the method directly inside MediaPlayerFragment, the method does NOT return a null value.
I'm really just shooting in the dark on how to update the UI from a Service so any helpful advice on that would be great also. Thank you.
Because it's not guaranteed that the TextView is already created or not when you are calling setDurationText().
In that case you can register a broadcast receiver in your fragment and then send broadcast from the service
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("update_media_ui");
updateMediaUiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get the data here and then set the text if
// the TextView is not null or save the data first
// and set it later if the TextView is null.
}
};
registerReceiver(updateMediaUiReceiver, intentFilter);
and then you also need to unregister the receiver in Fragment onDestroy()
unregisterReceiver(updateMediaUiReceiver);
This is how to send broadcast from service
Intent serviceIntent = new Intent();
serviceIntent.setAction("update_media_ui");
this.sendBroadcast(serviceIntent);
Related
So I defined a switch button in ProfileSettingsfragment but i am using that button in Explanation.class. What I am really trying to do is when switch button is checked i want start service else i don't want to star service from Explanation.class
SO I tried Some code and it showing me this error " java.lang.NullPointerException: Attempt to invoke virtual method 'boolean androidx.appcompat.widget.SwitchCompat.isChecked()' on a null object reference
at com.harsh.preacher.ui.Home.Explaination$1.onClick(Explaination.java:43)"
P.S I have designed switch button in ProfileSettingsfragment.xml
Here is ProfileSettingsfragment class code
public class ProfileSettingsFragment extends Fragment {
private GoogleSignInClient mGoogleSignInClient;
public SwitchCompat notePopUp;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_profilesettings, container, false);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(requireContext(), gso);
final ProfileSettingsFragment profileSettingsFragment =new ProfileSettingsFragment();
Button signOut1 = root.findViewById(R.id.signOut);
signOut1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//TODO Custom Alert Dialog Bar
// signOut();
Intent intent = new Intent(getContext(), AndarAwoo.class);
startActivity(intent);
// Animation(signOut1);
}
});
notePopUp = (SwitchCompat) root.findViewById(R.id.notePopUp);
RelativeLayout EditName = root.findViewById(R.id.EditName);
RelativeLayout ProfileSettingsLayout= root.findViewById(R.id.profileSettingsCardView);
TextView EditNameText = root.findViewById(R.id.EditNameText);
EditNameText.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onClick(View view) {
if(EditName.getVisibility() == View.GONE){
TransitionManager.beginDelayedTransition(ProfileSettingsLayout,new AutoTransition());
EditName.setVisibility(View.VISIBLE);
}else {
TransitionManager.beginDelayedTransition(ProfileSettingsLayout,new AutoTransition());
EditName.setVisibility(View.GONE);
}
}
});
return root;
}
Here is my explanation class code
public class Explaination extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_explaination);
Intent intent = getIntent();
String about = intent.getStringExtra("about");
TextView about1 = findViewById(R.id.about);
about1.setText(about);
Button resource = findViewById(R.id.Resource);
resource.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = getIntent();
String url = intent.getStringExtra("button");
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
ProfileSettingsFragment checkNotePopUp = new ProfileSettingsFragment();
checkNotePopUp.notePopUp = findViewById(R.id.notePopUp);
if(checkNotePopUp.notePopUp.isChecked()){
startService(new Intent(Explaination.this, NotePopUpHead.class));
}
else{
stopService(new Intent(Explaination.this,NotePopUpHead.class));
}
finish();
startActivity(i);
}
});
}
}
There is something I want to ask, I have recycle view where is pass from adapter to activity, my question is :
I need to get value/data checkbox from adapter viewHolder Recycleview to activity who is use the adapter for show recycleview
CartAdapter.java
private Context mContext;
private ArrayList<CartModel> mCartList;
public boolean isSelectedAll = true;
public CartAdapter(Context context, ArrayList<CartModel> CartList){
mContext = context;
mCartList = CartList;
}
#NonNull
#Override
public CartViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(mContext).inflate(R.layout.masteritem_cardview_cart, viewGroup, false);
return new CartViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull CartViewHolder cartViewHolder, int i) {
CartModel currentItem = mCartList.get(i);
cartViewHolder.mCartCheckbox.setChecked(true); //i want pass this value
ShoppingCartActivity.java
private RecyclerView mRecyclerView;
private CartAdapter mCartAdapter;
private ArrayList<CartModel> mCartModelList;
private RequestQueue mRequestQueue;
boolean cartfirst;
private Button mButtonCheckout;
public CheckBox mCartCheckAll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_cart);
cartfirst = false;
mNavigationView = findViewById(R.id.navigation_view);
mNavigationView.setNavigationItemSelectedListener(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.cart_drawer);
mToogle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToogle);
mToogle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mRecyclerView = findViewById(R.id.recycler_view_cart);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mCartModelList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJsonCartItem();
mButtonCheckout = findViewById(R.id.checkOut_btn);
mCartCheckAll = findViewById(R.id.cartChecKall_checkBox);
//firsttime checkall
mCartCheckAll.setChecked(true);
mButtonCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(ShoppingCartActivity.this);
builder.setTitle("Confirm Checkout");
builder.setMessage("Do you really want to Checkout?");
builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
for (int i = 0; i < mCartModelList.size(); i++){
//to here, for checking value if true they will checkout, else do nothing
//checkOutChartJSON();
}
}
startActivity(new Intent(getApplicationContext(),ShoppingCartActivity.class));
finish(); //finish current activity
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}});
builder.setNegativeButton(android.R.string.no, null);
builder.create().show();
}
});
To check validation if checkbox is true they will do function checkOutChartJSON, else do nothing
If you wanna pass the data or value from an adapter to new activity then you can do it by using Intent and if you wanna pass the value to existing activity then interface is the best way to do it.
For new activity.
// Passing data to TargetActivity.class
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
intent.putExtra("message", str);
startActivity(intent);
// Get the data in TargetActivity.class
Intent intent=getIntent();
String msg = intent.getStringExtra("message");
For existing activity.
First, make an interface. OnPassingData
public interface OnPassingData {
void onPassing(int value1, String value2,...,int valueN);
}
In the adapter.
OnPassingData onPassingData;
if (onPassingData != null) {
onPassingData .onPassing(value1, value2,..,valueN);
}
public void setOnPassingData(OnPassingData onPassingData) {
this.onPassingData= onPassingData;
}
At the adapter calling in activity.
adapter.setOnPassingData((value1, value2,...,valueN) -> {
Log.i(TAG, "value1 : " + value1);
Log.i(TAG, "value2 : " + value2);
});
Thanks for checking out my question!
I have a relativly ismple loop which will add a onClickListener to each ImageView I add to my Layout, however when trying to add a new Intent to it, it gives me one of the following errors:
String[] imageURLs = imageURLsString.split("/");
for (int i = 0; i < imageURLs.length; i++){
ImageView image = new ImageView(this);
image.setLayoutParams(new android.view.ViewGroup.LayoutParams(getPx(182),getPx(256)));
image.setPadding(getPx(3),getPx(3),getPx(3),getPx(3));
final String imageURL = ".../images/" + imageURLs[i];
Picasso.with(this).load(imageURL).into(image);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent;
intent = new Intent(this, ImageActivity.class);
intent.putExtra("URL", imageURL);
startActivity(intent);
}
});
linearLayout.addView(image);
}
Will result in the "Cannot resolve Constructor 'Intent ...." error.
So when I was looking for a solution, people suggested to change "this" to "MainActivity.this", but...
String[] imageURLs = imageURLsString.split("/");
for (int i = 0; i < imageURLs.length; i++){
ImageView image = new ImageView(this);
image.setLayoutParams(new android.view.ViewGroup.LayoutParams(getPx(182),getPx(256)));
image.setPadding(getPx(3),getPx(3),getPx(3),getPx(3));
final String imageURL = ".../images/" + imageURLs[i];
Picasso.with(this).load(imageURL).into(image);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent;
intent = new Intent(MainActivity.this, ImageActivity.class);
intent.putExtra("URL", imageURL);
startActivity(intent);
}
});
linearLayout.addView(image);
}
resulted into: com.myName.appName.MainActivity is not an enclosing class
Here is the ImageActivity class:
public class ImageActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
String URL = getIntent().getExtras().getString("URL");
ImageView imageView = (ImageView) findViewById(R.id.image);
imageView.getLayoutParams().height = (int) (imageView.getLayoutParams().width * (Float.valueOf(String.valueOf(1.41))));
Picasso.with(this).load(URL).into(imageView);
}
The weird thing is that I have done numerous new Intent's during my play time with creating apps, but I cant seem to solve this one. What am I missing here?
FULL CODE FROM HERE
public class DetailsActivity extends AppCompatActivity {
TextView TVWeChatIdValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
String dataString = getIntent().getExtras().getString("dataString");
String[] itemData = dataString.split(",");
String category = itemData[0];
Log.e("DetailsActivity", category);
String itemID = itemData[1];
Log.e("DetailsActivity", itemID);
String imageURLsString = itemData[2];
Log.e("DetailsActivity", imageURLsString);
String description = itemData[3];
Log.e("DetailsActivity", description);
String price = itemData[4];
Log.e("DetailsActivity", price);
String itemCode = category + itemID;
TextView textView;
textView = (TextView) findViewById(R.id.Title);
textView.setText(getResources().getString(R.string.app_name));
textView = (TextView) findViewById(R.id.ItemReferralValue);
textView.setText(itemCode);
textView = (TextView) findViewById(R.id.ItemPriceValue);
textView.setText(price);
TVWeChatIdValue = (TextView) findViewById(R.id.WeChatIDValue);
new DatabaseTask(this, "details", "GETWECHATID").execute();
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.ItemDetailsContent);
String[] imageURLs = imageURLsString.split("/");
for (int i = 0; i < imageURLs.length; i++){
ImageView image = new ImageView(this);
image.setLayoutParams(new android.view.ViewGroup.LayoutParams(getPx(182),getPx(256)));
image.setPadding(getPx(3),getPx(3),getPx(3),getPx(3));
final String imageURL = ".../images/" + imageURLs[i];
Picasso.with(this).load(imageURL).into(image);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent;
intent = new Intent(this, ImageActivity.class);
intent.putExtra("URL", imageURL);
startActivity(intent);
}
});
linearLayout.addView(image);
}
ImageView imageView = (ImageView) findViewById(R.id.ItemDetailsDescription);
String imageURL = ".../images/" + description;
Picasso.with(this).load(imageURL).into(imageView);
}
public void SetWeChatId(String mValue) {
TVWeChatIdValue.setText(mValue);
}
public int getPx(int dimensionDp) {
float density = getResources().getDisplayMetrics().density;
return (int) (dimensionDp * density + 0.5f);
}
}
WORKING CODE
public class MainActivity extends AppCompatActivity {
TextView TVWeChatIdValue;
LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView;
textView = (TextView) findViewById(R.id.Title);
textView.setText(getResources().getString(R.string.app_name));
textView = (TextView) findViewById(R.id.SubTitle);
textView.setText(getResources().getString(R.string.slogan));
textView = (TextView) findViewById(R.id.MoreForWomen);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
OpenCatalog("women");
}
});
textView = (TextView) findViewById(R.id.MoreForMen);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
OpenCatalog("men");
}
});
textView = (TextView) findViewById(R.id.MoreForKids);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
OpenCatalog("kids");
}
});
}
public void GetData() {
TVWeChatIdValue = (TextView) findViewById(R.id.WeChatIDValue);
new DatabaseTask(this, "main", "GETWECHATID").execute();
linearLayout = (LinearLayout) findViewById(R.id.NewItemsForWomenContent);
linearLayout.removeAllViewsInLayout();
new DatabaseTask(this, linearLayout, "WOMEN", "GETNEWESTITEMS").execute();
linearLayout = (LinearLayout) findViewById(R.id.NewItemsForMenContent);
linearLayout.removeAllViewsInLayout();
new DatabaseTask(this, linearLayout, "MEN", "GETNEWESTITEMS").execute();
linearLayout = (LinearLayout) findViewById(R.id.NewItemsForKidsContent);
linearLayout.removeAllViewsInLayout();
new DatabaseTask(this, linearLayout, "KIDS", "GETNEWESTITEMS").execute();
}
public void SetWeChatId(String mValue) {
TVWeChatIdValue.setText(mValue);
}
public void ProcessNewItems(LinearLayout mLinearLayout, final String mCategory, final HashMap<Integer, Item> mItems){
for (int i = 0; i < mItems.size(); i++) {
ImageView image = new ImageView(this);
image.setLayoutParams(new android.view.ViewGroup.LayoutParams(getPx(96),getPx(128)));
image.setPadding(getPx(3),getPx(3),getPx(3),getPx(3));
String imageURL = ".../images/" + mItems.get(i).getImageURLs()[0];
Picasso.with(this).load(imageURL).into(image);
mLinearLayout.addView(image);
final int index = i;
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ShowItemDetails(mCategory, mItems.get(index));
}
});
}
}
void ShowItemDetails(String mCategory, Item mItem){
Intent intent = new Intent(this, DetailsActivity.class);
intent.putExtra("dataString", mItem.GetDataString());
Log.e("CatalogActivity", mItem.GetDataString());
startActivity(intent);
}
void OpenCatalog(String mCategory){
//show catalog
Intent intent = new Intent(this, CatalogActivity.class);
intent.putExtra("category", mCategory);
startActivity(intent);
}
public int getPx(int dimensionDp) {
float density = getResources().getDisplayMetrics().density;
return (int) (dimensionDp * density + 0.5f);
}
#Override
public void onResume() {
super.onResume();
GetData();
}
}
You need to use the name of the Activity subclass which contains the code that creates the OnClickListener. In many examples, this is MainActivity. However, this doesn't seem to be the case in your code. Since you are in a class named DetailsActivity then use that name:
Intent intent = new Intent(DetailsActivity.this, ImageActivity.class);
From what I can see of your code here, I strongly suggest that you learn about ListView and RecyclerView. They are a bit complex, but once you understand them, they do much of the work for you similar to what you are trying to do here. For one thing, they are more efficient than your own code because they only create as many views as are visible.
Let's look more closely at your other example:
public class MainActivity extends AppCompatActivity {
// ...
void ShowItemDetails(String mCategory, Item mItem){
Intent intent = new Intent(this, DetailsActivity.class);
intent.putExtra("dataString", mItem.GetDataString());
startActivity(intent);
}
}
Notice that the ShowItemDetails() is inside the MainActivity class. So this refers to an instance of that class which can be used wherever a Context is needed. (For more details about this you need to read about inheritance and polymorphism.)
On the other hand, your original code creates an Intent in a method which is inside an anonymous subclass of OnClickListener which cannot be used as a Context. However the anonymous inner class is in a method inside DetailsActivity which inherits from Context. In order to access an instance of this outer class, you have to use DetailsActivity.this.
For more details you should learn about the special this reference and inner classes.
You have this block
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent;
intent = new Intent(MainActivity.this, ImageActivity.class);
intent.putExtra("URL", imageURL);
startActivity(intent);
}
});
Change MainActivity.this to whatever Activity subclass that is setting the OnClickListener. That would be DetailsActivity.this in your case. Basically the enclosing activity just means the name of the class file (which is also the name of the Activity class) in which the Activity is being defined, this Activity encapsulates the call to .setOnClickListener() to which you are passing an anonymous inner class, which is being enclosed inside your DetailsActivity, hence the name enclosing activity. Hope that makes sense
So i made a bunch of 4 buttons , put an intent to each of them . They all navigate to the same Fragment class . But their extras are different, so if button1 was clicked , Fragment would open and do a certain action , if button2 was clicked , Fragment would do another action and so on. I tried the code on normal activities and it worked , but in fragments its not working . It just returns me "Id is null"
Class sending the intent
public class Intennt extends ActionBarActivity {
Button bt1,bt2,bt3,bt4;
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intennt);
bt1 = (Button) findViewById(R.id.button);
bt2 = (Button) findViewById(R.id.button2);
bt3 = (Button) findViewById(R.id.button3);
bt4 = (Button) findViewById(R.id.button4);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, ItemListActivity.class);
i.putExtra(ItemDetailFragment.ID_ACTION,ItemDetailFragment.ACTION_1);
startActivity(i);
}
});
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, ItemListActivity.class);
i.putExtra(ItemDetailFragment.ID_ACTION,
ItemDetailFragment.ACTION_2);
startActivity(i);
}
});
}
Fragment receiving the intent and extras
public class ItemDetailFragment extends Fragment {
public static final int ACTION_1 = 1;
public static final int ACTION_2 = 2;
public static final int ACTION_3 = 3;
public static final int ACTION_4 = 4;
public static final int ACTION_NULL = -1;
public static final String ID_ACTION = "action_id";
public static final String ARG_ITEM_ID = "item_id";
private DummyContent.DummyItem mItem;
public ItemDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments().containsKey(ARG_ITEM_ID)) {
// Load the dummy content specified by the fragment
// arguments. In a real-world scenario, use a Loader
// to load content from a content provider.
mItem =
DummyContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));
}
int id = getActivity().getIntent().getIntExtra(ID_ACTION, -1);
if (id == ACTION_NULL) {
Log.d("TAG", "id is null");
Toast.makeText(getActivity(), "id is null!",
Toast.LENGTH_SHORT).show();
} else if (id == ACTION_1) {
Log.i("TAG", "ALLOHA! from button 1");
Toast.makeText(getActivity(), "Aloha from button 1!",
Toast.LENGTH_LONG).show();
} else if (id == ACTION_2) {
Log.i("TAG", "Hello from button 2");
Toast.makeText(getActivity(),"Hello from button 2!",
Toast.LENGTH_LONG).show();
}
else if (id == ACTION_3) {
Log.i("TAG", "Hello from button 3");
Toast.makeText(getActivity(),"Hello from button 2!",
Toast.LENGTH_LONG).show();
}
else if (id == ACTION_4) {
Log.i("TAG", "Hello from button 4");
Toast.makeText(getActivity(),"Hello from button 2!",
Toast.LENGTH_LONG).show();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_item_detail,
container, false);
return rootView;
}
}
To navigate to a fragment, you need to instantiate the fragment class then use the FragmentManager to proceed to a transaction :
FragmentClass fragment = new FragmentClass();
getFragmentManager()
.beginTransaction()
.replace(R.id.your_fragment_view, fragment)
.commit();
You can proceed to every action right in the current activity (as it stays the main activity).
public class Questions extends DialogFragment {
private static Button Submit;
public int count = 0;
public interface DialogListener {
void onQuestionsFinish(ArrayList<xmlQuestion> l);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_questions, container, false);
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
//getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Submit = (Button) rootView.findViewById(R.id.SubmitButton);
Submit.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0){
for(int i = 0; i<questionList.size(); i++)
{
questionList.get(i).setAnswer();
}
DialogListener activity = (DialogListener) getActivity();
activity.onQuestionsFinish(questionList);
Questions.this.dismiss();
}
});
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
yInch = metrics.ydpi;
pixHeight = metrics.heightPixels;
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point(); display.getSize(size);
screenWidth=size.x; screenHeight=size.y;
LinearLayout.LayoutParams bodyParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,screenHeight*900/1024);
BodyLayout.setLayoutParams(bodyParams);
WindowManager.LayoutParams wmlp = getDialog().getWindow().getAttributes();
wmlp.height=screenHeight; wmlp.width=screenWidth;
getDialog().getWindow().setAttributes(wmlp);
WindowManager.LayoutParams lp = getDialog().getWindow().getAttributes();
lp.dimAmount=0.4f;
getDialog().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
getDialog().setCanceledOnTouchOutside(true);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_FRAME, android.support.v7.appcompat.R.style.Theme_AppCompat_Light);
}
public Questions()
{
}
}
You don't have to use intents to start fragments. My main benefit for using fragments is being able to reference the data in each one much easier. You can simply create a new instance of your fragment class, and assign it's public variables. Then start it like so...
Questions q = new Questions();
q.count = 0;
q.show(getSupportFragmentManager(), "Dialog Fragment");
I can't believe I have so much trouble with this. I have this variable in my game activity:
public static int numberOfPointsA;
and in another activity
public static int numberOfPointsB;
Now I need these values to pass to another activity, where I should total these values and set result to textView. Since these are public static variables I tried:
public static int totalScore = ClassA.numberOfPointsA + ClassB.numberOfPointsB;
textView.setText("" + totalScore);
But that's not working. So I tried with intent:
In game classA:
Intent intent = new Intent(this, Menu.class);
intent.putExtra("foobar", numberOfPointsA);
startActivity(intent);
and in menu class:
Intent intent = getIntent();
int numberOfPointsA = intent.getIntExtra("foobar", 0);
But that's not working either. If I place in the scope of activity, as soon as activity starts it crashes. If I place it in onCreate method, I can's use my int variable anymore, I don't need it in onCreate method, I need it elsewhere.
So how to set my variable in game class, pass to menu class, save it there and then make it wait until I finish my game class B and do the same with that variable, and then total those two variables and set it successfuly to the textView?
Menu activity:
public class Izbor extends Activity implements OnClickListener{
private int asocijacijeUkupno = 0;
private int thUkupno = 0;
int ukupanBrojPoena = asocijacijeUkupno + thUkupno;
Button toploHladno, asocijacije, cigle, spojnice, nazad, poeniTH, poeniAso, poeniCigle, poeniSpojnice, poeniUkupno;
TextView naslov;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
asocijacijeUkupno = getIntent().getIntExtra("RUNNING_TOTAL", 0);
thUkupno = getIntent().getIntExtra("RUNNING_TOTAL2", 0);
setContentView(R.layout.izbor);
addListenerOnButton();
}
private void addListenerOnButton() {
naslov = (TextView) findViewById(R.id.tvIzborNaslov);
toploHladno = (Button) findViewById(R.id.bIzbor1);
asocijacije = (Button) findViewById(R.id.bIzbor2);
cigle = (Button) findViewById(R.id.bIzbor3);
spojnice = (Button) findViewById(R.id.bIzbor4);
nazad = (Button) findViewById(R.id.bIzborNazad);
poeniTH = (Button) findViewById(R.id.bPoeniTH);
poeniAso = (Button) findViewById(R.id.bPoeniAso);
poeniCigle = (Button) findViewById(R.id.bPoeniCigle);
poeniSpojnice = (Button) findViewById(R.id.bPoeniSpojnice);
poeniUkupno = (Button) findViewById(R.id.bPoeniUkupno);
toploHladno.setOnClickListener(this);
asocijacije.setOnClickListener(this);
cigle.setOnClickListener(this);
spojnice.setOnClickListener(this);
nazad.setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
if(asocijacijeUkupno != 0){
poeniAso.setText("" + asocijacijeUkupno);
}else{
poeniAso.setText("");
}
if(thUkupno != 0){
poeniTH.setText("" + thUkupno);
}else{
poeniTH.setText("");
}
if(ukupanBrojPoena != 0){
poeniUkupno.setText("" + ukupanBrojPoena);
}else{
poeniUkupno.setText("");
}
}
public void onClick(View v) {
switch(v.getId()){
case R.id.bIzbor1:
if(music == true){
buttonClicks.start();
}
startActivity(new Intent("rs.androidaplikacije.toplo_hladno.TOPLOHLADNO"));
break;
case R.id.bIzbor2:
if(music == true){
buttonClicks.start();
}
startActivity(new Intent("rs.androidaplikacije.toplo_hladno.ASOCIJACIJE"));
break;
case R.id.bIzbor3:
if(music == true){
buttonClicks.start();
}
break;
case R.id.bIzbor4:
if(music == true){
buttonClicks.start();
}
break;
case R.id.bIzborNazad:
if(music == true){
buttonBack.start();
}
finish();
break;
}
}
}
The following is a very basic example, using two activities to pass an int around.
First Activity, which you start from:
public class FirstActivity extends Activity {
private int mTotal = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//.... onCreate code, layout stuff etc....
}
// this is tied to a View onClick call
public void moveToSecondAct(View view) {
Intent intent = new Intent();
intent.putExtra("RUNNING_TOTAL",mTotal);
intent.setClass(this, SecondActivity.class);
//... any other options like ...
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// start the second Activity
startActivity(intent);
}
}
And the second Activity example is something like:
public class SecondActivity extends Activity {
private int mTotal = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTotal = getIntent().getIntExtra("RUNNING_TOTAL", 0);
//.... onCreate code, layout stuff etc....
Log.i("Running total is:"+ mTotal);
// update the total on the TextView
TextView tv = (TextView) findViewById(R.id.poeniUkupno);
tv.setText("Total: "+ mTotal);
}
}
Edit: Some changes to try help make things clearer
I didn't completely get what you have been trying to say but what I got was you want to create a variable in FirstActivity send its value to SecondActivity and then pass their sum to ResultActivity if its so then here you go
//First Activity
public class FirstActivity extends Activity{
int firstValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
firstValue = 10;
}
public sendValueToSecondActivity(View view){
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("firstValue", firstValue);
startActivity(intent);
}
}
//Second Activity
public class SecondActivity extends Activity{
int sumOfFirstAndSecond;
int secondValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
secondValue = 20;
}
public sendValueToSecondActivity(View view){
sumOfFirstAndSecond = getIntent().getIntExtra("firstValue") + secondValue;
Intent intent = new Intent(this, ResultActivity.class);
intent.putExtra("sumOfFirstAndSecond", sumOfFirstAndSecond);
startActivity(intent);
}
}
//Result Activity
public class ResultActivity extends Activity{
TextView textView;
int result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
secondValue = 20;
textView = (TextView) findViewById(R.id.textView);
}
public setResultToTextView(View view){
result = getIntent().getIntExtra("sumOfFirstAndSecond");
textView.setText(""+result);
}
}