Use Android Annotations in custom dialog class - android

I'm using android annotations, I'm trying to annotate this class so that I can save a value into my shared preferences (annotated) class using #pref. I've managed to find a work around with an intent and a broadcast receiver however this is not ideal and now that I want to fetch a value from the shared preferences in this class to show as the default item selected in the spinner it's starting to leave a smell on my code.
Is there any way to annotate this class?
public class SelectNewsFeedDialog extends Dialog {
private Context context;
private Button confirmButton;
private Spinner spinnerTeams;
public SelectNewsFeedDialog(final Context context, ArrayList<Team> listTeams) {
super(context,R.style.cust_dialog);
this.context = context;
setContentView(R.layout.dialog_choose_news_feed);
spinnerTeams = (Spinner) findViewById(R.id.dialog_news_feed_spinner_teams);
confirmButton = (Button) findViewById(R.id.dialog_news_feed_button_confirm);
confirmButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Team team = (Team)spinnerTeams.getSelectedItem();
Intent intent = new Intent(context, IntentCenter_.class);
intent.putExtra(context.getString(R.string.extra_update_team_news_feed), team.url.toString());
intent.setAction(context.getString(R.string.action_update_team_news_feed));
context.sendBroadcast(intent);
dismiss();
}
});
SpinnerTeamsAdapter adapter = new SpinnerTeamsAdapter(context, listTeams);
spinnerTeams.setAdapter(adapter);
}
}

Currently, we haven't any annotation for Dialog classes. You may want to uses #EBean on this but the compiler is yelling on missing constructors.
The solution is to uses a DialogFragment instead of a Dialog and annotate this class with #EFragment. The following code should works :
#EFragment(R.layout.dialog_choose_news_feed)
public class SelectNewsFeedDialog extends DialogFragment {
#ViewById
Button confirmButton;
#ViewById
Spinner spinnerTeams;
#Extra
List<Team> listTeams;
#Click
public void confirmButtonClicked() {
Team team = (Team) spinnerTeams.getSelectedItem();
Intent intent = new Intent(context, IntentCenter_.class);
intent.putExtra(context.getString(R.string.extra_update_team_news_feed), team.url.toString());
intent.setAction(context.getString(R.string.action_update_team_news_feed));
context.sendBroadcast(intent);
dismiss();
}
#AfterViews
public void init() {
SpinnerTeamsAdapter adapter = new SpinnerTeamsAdapter(getActivity(), listTeams);
spinnerTeams.setAdapter(adapter);
}
}
However, using #Extra on a list is not a good idea. You should :
* use a list of ids annotated with #Extra
* or, uses a setter and passes this list to your adapter after the dialog was been initialized.
Hope this helps

Related

Arraylist Pass from fragment to activity

Intent intent = new Intent(getActivity(), loadactivity.class);
intent.putExtra("Arraylist", imagearraylist);
startActivity(intent)
Hope this will help you!
Paste the following code in your activity.
ArrayList<Object> imagearraylist = (ArrayList<Object>) getIntent().getSerializableExtra("Arraylist");
Reference: How to pass ArrayList<CustomeObject> from one activity to another?
Use Interface Like Mentioned In Link
Passing Data Between Fragments to Activity
Or You Can Simply Use Public static ArrayList<String> imagearraylist;
(Passing Huge Arraylist Through Intent May Leads To Crash)
For this, you have to use interface
public interface arrayInterface {
public void onSetArray(ArrayList<T>);
}
Implement this interface in your activity
public class YrActivity extends Activity implements arrayInterface.OnFragmentInteractionListener {
private ArrayList<T> allData;
#override
public void arrayInterface(ArrayList<T> data) {
allData = data;
}
}
Then you have to send the data with listner
arrayInterface listener = (arrayInterface) activity;
listener.onSetArray(allData)
And its done

Deleting items in ListView using intent

my problem is that im trying to delete items from ListView and for that I have a button in CustomAdapter.
Im setting this button an onClickListener and try to pass item name to main activity using Intent.
In Main when intent named "deleteProduct" is received the method deleteProduct is called and in this method im trying to pass to database a product name which to delete.
my CustomAdapter:
private DbItemDeleteListener deleteListener;
CustomAdapter(Context context, ArrayList<Product> productNames,DbItemDeleteListener deleteListener) {
super(context,R.layout.custom_list_row ,productNames);
this.deleteListener = deleteListener;
}
final Product singleProduct=getItem(position);
final TextView productName=(TextView)customView.findViewById(R.id.ProductName);
final Button CheckButton = (Button)customView.findViewById(R.id.CheckButton);
final Button DeleteButton = (Button)customView.findViewById(R.id.DeleteButton);
DeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String product=singleProduct.get_productname();
deleteListener.delete(product);
}
});
MY Main:
DbItemDeleteListener deleteListener;
ArrayAdapter<Product> adapter;
ArrayList<Product> productnames=new ArrayList<>();
DBHandler dbhandler;
#Override
public void delete(String productId){
dbhandler.deleteProduct(productId);
}
And my DBHandler:
public void deleteProduct(String productname){
SQLiteDatabase db=getWritableDatabase();
db.execSQL("DELETE FROM " +TABLE_PRODUCTS+ " WHERE "+ COLUMN_PRODUCTNAME+ "=\" "+ productname +"\";");
}
Also im getting this message in logcat when i click delete button:
Process: com.example.olev.shoppinglist, PID: 1836
java.lang.NullPointerException: Attempt to invoke interface method 'void com.example.olev.shoppinglist.DbItemDeleteListener.delete(java.lang.String)' on a null object reference
at com.example.olev.shoppinglist.CustomAdapter$3.onClick(CustomAdapter.java:80)
at android.view.View.performClick(View.java:4756)
You shouldn't really need to use an intent just to delete a list item. Instead, use the observer pattern. First, create an interface:
public interface DbItemDeleteListener{
public void delete(String productId);
}
Implement the interface in your Activity (your activity is probably not the greatest place to implement, but since it's where you're already doing the deleting, I'll stick with that):
public class MyActivity extends Activity implements DbItemDeleteListener{
...
#Override
public void delete(String productId){
dbhandler.deleteProduct(productId);
}
}
Then, pass an instance of your class that implements the listener to your adapter's constructor:
public CustomAdapter extends WhateverAdapter{
private DbItemDeleteListener deleteListener;
public MyAdapter(DbItemDeleteListener deleteListener){
this.deleteListener = listener;
}
}
Make sure you use this version of the constructor when you create your adapter.
Then, instead of the onClickListener sending an intent:
DeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//get the product name and use the listener to delete
...
deleteListener.delete(productId);
notifyDataSetChanged();
}
}
But if you still plan on using intents for some reason:
http://developer.android.com/reference/android/app/Activity.html#onNewIntent(android.content.Intent)
This is called for activities that set launchMode to "singleTop" in their package, or if a client used the FLAG_ACTIVITY_SINGLE_TOP flag when calling startActivity(Intent).
What I'm guessing is happening is that instead of getting the current instance of your Main activity, you're actually creating a new instance. Therefore, you should be doing the same check in onCreate() instead.
So you can either set your activity's launch mode to something that will call onNewIntent:
<activity
android:launchMode="singleTop"
...>
....
</activity>
and/or also add the flag to your intent:
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
Or, maybe easier, you can move the delete call to onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
... //other onCreate() stuff
if(getIntent() != null && getIntent().hasExtra("deleteProduct")){
if (intent.getStringExtra("deleteProduct").equals("deleteProduct")) {
deleteProduct();
}
}
}
Also, you should be checking for
intent.getStringExtra("deleteProduct").equals("deleteProduct")
not ".equals("deleteProcust") as in your sample code, but I assume that's a typo.

android one button share another java use

If I want to design a button that all java can use it without need to write it in every java,
what should I do?
For Example:
I design a Button.OnClickListener function to search bluetooth devices.
but another java also need to use this Button.OnClickListener function,
I don't want to write same way on two java.
ledWrite.xml:
<Button android:id="#+id/btnScan" />
<ToggleButton android:id="#+id/tBtnWrite" />
bluetoothUtils.java
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE = 1;
private Button button_scan;
button_scan = (Button)findViewById(R.id.button_scan);
button_scan.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
scanbt();
}
});
private void scanbt(){
Intent serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
}
then I design LedWrite.java:
private ToggleButton digitalOutBtn; //LED On/OFF
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ledwrite);
digitalOutBtn = (ToggleButton)findViewById(R.id.tBtnWrite);
digitalOutBtn.setOnClickListener(new OnClickListener()
public void onClick(View v){
if(digitalOutBtn.isChecked()){ //sendMessage("D1"); }
else{sendMessage("D0";}
}
How can I use button_scan in LedWrite.java?
If you want to call a method defined is some other Activity on press of a button, then you can make that method as static.
Let's assume that you have a method named searchBluetooth() in MainActvity and you want to call it from SecondActivity.
Define searchBluetooth() in MainActvity like,
public static void searchBluetooth()
Call this method from SecondActivity like,
MainActivity.searchBluetooth()
If you don't want to use static because of memory consumption then try with inheritance.
Create a class CommonActivity which extends Activity class
class CommonActivity extends Activity
{
// here define your searchBluetooth method
public void searchBluetooth()
{
// your code here
}
}
If you want to make use of it in Second Activity then
class SecondActivity extends CommonActivity
{
// here you can access `searchBluetooth()` method
}
enclosure a BluetoothListener class?
public BluetoothListener implements OnClickListener {
#Override
public void onClick(View v) {
do something you want...
}
}
then invoke the class in two different class, eg,
button.setOnClickListener(new BluetoothListener());
I recently started learning android and this answer may have some error, if so, please let me know, Thanks.

pass UI Controls from activity to a class

I stuck at this issue many times and I passed the problem in different ways and I'm not sure that I made it in the right way.
I simplified the problem in a the following example. I know that I can pass only the data to the class but I do want to pass the editText cause I have this problem with more difficult UI controls.
mainactivity.java
public class mainactivity extends Activity {
public EditText clickEditText;
int count =0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
newTxt();
}
public void newTxt() {
txt = new MyText(context);
txt.updateTextEdit("Main Activity");
}
}
myText.java
public class MyText
{
private Context _context;
// constructor
public MyText(Context context)
{
_context = context;
}
public void updateTextEdit(String str)
{
private EditText strEditText;
strEditText= (EditText)findViewById(_context.R.id.editTextClick); // ????
strEditText.setText(str + " and myTxt");
}
}
if you could explain me how to fix the updateTextEdit function. i passed the context of the main activity. How can I change the editText? Thank you very much!!!
If you really want to do this this way, you need to save a reference to Activity, not Context. Like this:
public class MyText
{
private Activity _activity;
// constructor
public MyText(Activity activity)
{
_activity= activity;
}
public void updateTextEdit(String str)
{
private EditText strEditText;
strEditText= (EditText)activity.findViewById(R.id.editTextClick);
strEditText.setText(str + " and myTxt");
}
}
and in newTxt() you will need to change:
txt = new MyText(context);
to:
txt = new MyText(this);
But wouldn't it be easier to just put this method inside your activity? Why do you want it in another class? If it really needs to be in another class, you could make that class an inner class of your activity and you would still have access to the activity's methods and member variables.
There's a similar question here
How to access Activity UI from my class?
You didn't say how you obtained the context, you should use this and get the mainactivity in the other class. not context.
then you can call runOnUIThread to perform UI updates.

WindowManager$BadTokenException in Android

First of all, I'm well aware that this error is occur because I'm trying to call window/dialog through a Context that is not an Activity.
But isn't there any solution to that. My requirements are; I have a Dialog with a custom style sheet in a method of a normal JAVA class. I want to call that method from any Activity class when I need to load the Dialog.
In my Activity class I'm having following code set;
HomeClass homeClass = new HomeClass();
homeClass.showSplashScreen();
Then in my HomeClass I have following code set;
public void showSplashScreen() {
splashDialog = new Dialog(HomeActivity.getAppContext(), R.style.SplashScreen);
splashDialog.setContentView(R.layout.splash_screen);
splashDialog.setCancelable(false);
splashDialog.show();
}
By maintaining this design, is there any way to get rid of the WindowManager$BadTokenException
Thank You
I am going to modify your code, that maybe helpful for you...
HomeClass homeClass = new HomeClass(this);
homeClass.showSplashScreen();
In Your Home class.. add parametric constructor..
public class Home {
private Context context;
public Home(Context context){
this.context = context;
}
public void showSplashScreen() {
splashDialog = new Dialog(context, R.style.SplashScreen);
splashDialog.setContentView(R.layout.splash_screen);
splashDialog.setCancelable(false);
splashDialog.show();
}
Pass Your Activity to showSplashScreen() Method...
Do like this..
HomeClass homeClass = new HomeClass();
homeClass.showSplashScreen(Your Actvity);
In Your Home class
public void showSplashScreen(Activity curActivity) {
splashDialog = new Dialog(curActivity, R.style.SplashScreen);
splashDialog.setContentView(R.layout.splash_screen);
splashDialog.setCancelable(false);
splashDialog.show();
}

Categories

Resources