I am learning to use DialogFragments
In my main activity in a condition i have
MyAlertDialogFragment alert = new MyAlertDialogFragment();
alert.show(getFragmentManager(), "Alert_Dialog");
MyAlertDialogFragment.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.widget.TextView;
import android.support.v4.app.DialogFragment;
import com.example.findmybuffet.R;
public class MyAlertDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
OnClickListener positiveClick = new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity().getBaseContext(), "Application finishing ...", Toast.LENGTH_SHORT).show();
getActivity().finish();
}
};
OnClickListener negativeClick = new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity().getBaseContext(), "No option selecting", Toast.LENGTH_SHORT).show();
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Do you want Yes or No ?");
builder.setNegativeButton("No", negativeClick);
builder.setPositiveButton("Yes", positiveClick);
builder.setTitle("Confirmation");
Dialog dialog = builder.create();
return dialog;
}
}
my problem::
In the line alert.show(getFragmentManager(), "Alert_Dialog");
I am getting error as The method show(FragmentManager, String) in
the type DialogFragment is not applicable for the arguments
(FragmentManager, String)
How to resolve this so that i am able to pop the fragment
As you're using android.support.v4.app.DialogFragment, you should pass to show() an instance of android.support.v4.app.FragmentManager which can be queried using an getSupportFragmentManager() call instead of getFragmentManager().
Replace getFragmentManager() with getSupportFragmentManager().
Related
I have been trying to figure out why the toast is not showing. from the code, the onReceive method does get executed and change the button color, but the Toast does not display. I dont know why.
client = new Client(
(publisher, topic, params) -> runOnUiThread(
() -> onReceive((Publisher) publisher, topic, params)
));
client.connectToServer("192.168.3.52",5050);
private void onReceive(Publisher publisher, String topic, Map<String, Object> params) {
sendBtn.setBackgroundColor(getColor(R.color.white));
Toast.makeText(MainActivity.this, "Hey", Toast.LENGTH_LONG).show();
}
Imports
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
Class name
public class MainActivity extends AppCompatActivity {
hey can you share your file name and import section ........
or else try to run on clicklistener after sendbtn and try to link with your button
I'm trying to show contextmenu on longpress in MainActivity.java. But I'm getting error "Method does not override method from its superclass" on #Override and "Cannot resolve symbol ... " for both ContextMenu and ContextMenuInfo in the onCreateContextMenu method.
My code is:
package com.syver.adhper;
import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.*;
import android.view.View;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.io.IOException;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.Queue;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
createpnl();
//more codes here
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
//some codes here
//error is only in this section at #Override, ContextMenu and ContextMenuInfo
}
public void createpnl()
{
registerForContextMenu(...); //... means a layout
//more codes here
}
}
Why am I getting this error? What should I do to avoid this error? Please give me corrected complete code as I'm new in android developing. I have searched here and also google, but proper ans I did't find and also didn't understand.
My API is 19 (kitkat)
try this, it work in my android studio
#Override
public void onCreateContextMenu (ContextMenu menu,
View v,
ContextMenu.ContextMenuInfo menuInfo)
{
}
reference:https://developer.android.com/reference/android/app/Activity.html
also import the class by click the red, and press alt+enter, choose import the class, I think this would solve your problem
i want to toggle the background music on and off using settings , which is an activity and it can be launched by pressing the menu button through the main activity and selecting settings. the problem I am facing now is that when i tick the background music checkbox , upon clicking save and returning to the main activity , my music stops playing. how to i make sure that the music keeps playing after going back to the main activity? And when i stop the app and relaunch the activity , i want the settings to remain the way they were selected (using sharedpreferences). Can anyone take a look at my codes and see what I am doing wrong?
my MainActivity.java
package sp.com;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.Button;
import android.widget.TextView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import android.app.TabActivity;
import android.widget.TabHost;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.media.MediaPlayer;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.KeyEvent;
public class MainActivity extends Activity {
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.setting:
Intent intent = new Intent(MainActivity.this, Settings.class);
startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
}
My settings.java
package sp.com;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.View.OnClickListener;
import android.content.SharedPreferences.Editor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
public class Settings extends Activity implements OnClickListener {
CheckBox Backmusic;
Button button1;
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.xml.preferences);
Backmusic = (CheckBox) findViewById(R.id.backmusic);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);
loadSavedPreferences();
}
private void loadSavedPreferences(){
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
boolean checkBoxValue = sharedPreferences.getBoolean("CheckBox_Value",false);
if (checkBoxValue){
Backmusic.setChecked(true);
} else {
Backmusic.setChecked(false);
}
}
private void savePreferences(String key, boolean value){
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
#Override
public void onClick(View v){
savePreferences("CheckBox_Value",Backmusic.isChecked());
if (Backmusic.isChecked()){
mp = MediaPlayer.create(getBaseContext(), R.raw.sound);
mp.start();
} else {
mp.stop();
finish();
}
}
#Override
protected void onStop() {
super.onStop();
mp.stop();
finish();
}
}
Thanks in advance.
So right now you are just playing the music within your Settings activity. In fact you are calling mp.stop() in onStop(). That's why when it closes the music stops.
You should also put code in your MainActivity in onCreate() and onResume() to read from sharedpreferences and if the background music is true, play music. That could look something like this:
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
boolean backgroundMusic = sp.getBoolean("CheckBox_Value",false);
if (backgroundMusic)
{
MediaPlayer mp = MediaPlayer.create(getBaseContext(), R.raw.sound);
mp.start();
}
else
{
mp.stop();
}
Note that you'll now want to write to SharedPreferences in Settings using getApplicationContext() instead of this. That way the preferences will be saved across the entire application and not just one activity.
I have toggle button which has android:onClick=onToggleClicked. I tried to reference the onToggleClicked method from the java code but the problem is, eclipse underscore the onToggleClicked with red and does not recognizes it. How to fix this error.
Imports:
import java.util.Set;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.os.Build;
JavaCode:
if (myBluetoothAdapter == null) {
tb_OnOFF.setEnabled(false);
btnFind.setEnabled(false);
btnPaired.setEnabled(false);
tvStatusCaption.setText("Status: Not Supported.");
Toast.makeText(getApplicationContext(), "Your Device Does Not Support " +
"Bluetooth", Toast.LENGTH_LONG).show();
} else {
public void onToggleClicked (View view) {
boolean on = ((ToggleButton) view).isChecked();
if (on) {
//enable bluetooth
}
if (!on) {
//disable bluetooth
}
}
}
XML:
<ToggleButton
android:id="#+id/btnToggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="#string/toggle_turn_on"
android:textOff="#string/toggle_turn_off"
android:checked="true"
android:onClick="onToggleClicked" />
onToggleClicked is a public method and needs to be attached to your Activity. You cannot use this method as an inner method inside onCreate method.
USE THIS
mToggleButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (mToggleButton.isChecked()) {
//your code
}
else{
//your code
}
}
});
I am trying to add an ActionBarSherlock with 4 tabs to my application.
I tried to extend from SherlockActivitythenSherlockFragmentActivity`, but I still get this Exception:
java.lang.IllegalStateException: Action Bar Tab must have a Callback.
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.json.JSONArray;
import org.json.JSONObject;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.ActionBar.TabListener;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class HomeActivity extends SherlockFragmentActivity implements OnClickListener, OnItemClickListener, TabListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.homelayout);
try{
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab homeTab = actionBar.newTab();
homeTab.setIcon(R.drawable.tab_home);
Tab exploreTab = actionBar.newTab();
exploreTab.setIcon(R.drawable.tab_explore);
Tab leaderBoardTab = actionBar.newTab();
leaderBoardTab.setIcon(R.drawable.tab_leaderboard);
Tab profileTab = actionBar.newTab();
profileTab.setIcon(R.drawable.tab_profile);
actionBar.addTab(homeTab);
actionBar.addTab(exploreTab);
actionBar.addTab(leaderBoardTab);
actionBar.addTab(profileTab);
}catch(Exception ex){
Log.e("error from onCreate" , ex.toString());
Log.e("error from onCreate" , ex.getStackTrace().toString());
}
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
You must register an ActionBar.TabListener on a Tab before adding it to the actionBar.
In your case:
Tab homeTab = actionBar.newTab();
homeTab.setTabListener(this) //'this' because your activity implements a TabListener
...
actionBar.addTab(homeTab);
Otherwise I would recommend you to implement your listeners in their own classes so that your Activity doesn't loose its purpose and is also easily understendable and readable.
You may repeat the tab listener as this
ActionBar.Tab tab1 = actionBar.newTab();
tab1.setText("Tab 1");
tab1.setTabListener(this);
ActionBar.Tab tab2 = actionBar.newTab();
tab2.setText("Tab 2");
tab2.setTabListener(this);
ActionBar.Tab tab3 = actionBar.newTab();
tab3.setText("Tab 3");
tab2.setTabListener(this); **// this is must be tab3 not tab2**