Getting access to globals in DialogFragment static class - android

I've followed Google docs and created an inner class to popup a dialog in my android app.
I've been running it fine in eclipse for a while, unbeknownst to me there was an error that came up when I imported the app into android studio to start using the stable release. I was getting the "Fragment inner class should be static" error upon trying to build.
OK so I understand now after researching that this is a bad thing, but when I change it to static, I now have a bunch of references to (a) global variables , and (b) "MainActivity.class" , that are now errors.
So inside this DialogFragment inner class, how do I access my globals, or pass them in, and how do I reference MainActivity.class ?
Eg:
final EditText input = new EditText(MainActivity.this);
for (NewsEvent ne : filteredList) { //filteredList is global List of objects
...
I am calling the dialog in the onOptionsItemSelected like this:
AlertDialogFragment alert = new AlertDialogFragment();
alert.show(this.getFragmentManager(), "Alerts");

To send a Data to the DialogFragment use static newInstance(params) method.
Put the Data in a Intent and on the onCreate() method get your Data from the Intent.
Check this example from the Android dev

Related

Could not find class 'android.widget.ThemedSpinnerAdapter'

I have ,in a fragment, a method call who open an AlertDialog when an user tap on an button, in that dialog I would like to show a Spinner with countries ( Spain, Italy, French....)
My code for the spinner is the following:
RestCountries restCountries = new RestCountries();
List<RestCountries.Datum> countries = restCountries.data;
String mCities ="";
ArrayList<String> citiesArrayList = new ArrayList<>();
for(RestCountries.Datum data : countries){
mCities = data.name;
citiesArrayList.add(mCities);
}
ArrayAdapter spinnerAdapter = new ArrayAdapter(getActivity(),android.R.layout.simple_spinner_dropdown_item, citiesArrayList );
mCountrySpinner.setAdapter(spinnerAdapter);
The spinner is showed emphy after the dialog is opened.
On the logcat I get
Could not find class 'android.widget.ThemedSpinnerAdapter', referenced
from method
android.support.v7.widget.AppCompatSpinner$DropDownAdapter.<init>
Any idea about what I am doing wrong
In my case I solved the problem just setting for all the modules in the project the same SDKCompileVersion. Here it is my complete answer in a similar question
Cheers
Could not find class 'android.widget.ThemedSpinnerAdapter' [Android Studio]
I faced and win this problem!
In case if you are using AndriodAnnotations here the problem is that I filled the lists in the method onCreate().
I used to get View via findViewById(R.id...) and worked with them.
Now, as it turned out during debugging, all Views is not created in onCreate() yet!
The problem was solved when I found an annotation #AfterViews in the docs, and the method under this annotation now fills all my actions and does initialization of fields.
So, anyway, check your code on NullPointerException caused by invoking empty view object.
This may not help everyone, but I was having this issue trying to add a spinner to a PopupWindow.
I updated my compileSdkTarget from 23 to 25, and my support library version to 25.1.0, but it didn't help.
It turned out that changing the spinnerMode to "dialog" worked round the problem:
<Spinner
android:id="#+id/group_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:spinnerMode="dialog"
/>
It doesn't completely fix it of course if you really want a dropdown spinner.
There are several different causes of this problem.
In my case (was trying to sign up to Parse), I got this error trying the app on a tablet.When I switched to an Android phone, I got the error message:
You must register this ParseObject subclass before instantiating it
So, In my App.java class I did this:
public class App extends Application {
public void onCreate() {
super.onCreate();
Parse.enableLocalDatastore(this);
Parse.initialize(this, "PARSE APPLICATION ID", "PARSE CLIENT KEY");
}
}
and then in my manifest, I did this:
<application
android:name=".App"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
...
That was it.Had nothing to do with Spinner

Application with different requests sent to a database (SQL) depending on buttons clicked

I still am a beginner in Android development and will try to make my question as clear as possible with a schema of what I have in my mind.
Purpose of this application:
- I want the user to have the choice between a few buttons and when clicking on any of them, it would open a list view with different content according to the button.
ex : if you click on "Category_1" button, only elements with a fitting id will appear in the listview.
So far, I have :
- defined my "handler" class (extends SQLiteOpenHelper) : name/path of DB, definition of CRUD, .getReadableDatabase, etc.
- define a class for my table, in my case "Restaurants.java" with getters/setters and constructor.
- defined my MainActivity with empty listeners for my button.
- defined my "DatabaseAdapter.java" in which I want to define the methods/sql requests which will communicate with the database and get the information I want from it.
- defined my ListViewActivity with nothing to display so far.
Here is a schema of what I want with the idea of how to make it to try to optimize my application :
To sum up:
- I want a listener for each button setting a variable to a certain value (for example: "if you click on 1 then set the value of A to 1") and opening the ListViewActivity.
- There would be a method defined in "...Adapter.java" sending a request to the database and having the variable A defined earlier as an input.
- And then, when clicking on the button, the ListViewActivity will open and call the method from "..Adapter.java", and finally display the results.
So, here are my questions :
- First of all, is the design optimized enough to allow my application to run fast? I think it should as all the button open only one activity and there is only one method defined for all buttons.
- I have a hard time defining the method in "...Adapter.java" which will be called from my ListViewAcitivity. The input should be the variable obtained when clicking on the button but I don't really know how to get a variable in one activity, open a second activity where to display results by using the variable in a third activity... :s
Is it fine to set a variable to a certain value when we click on a button and use this variable in another class as an input for a method?
public findNameInTable(int A){
string sql = " select NAME from MY_TABLE where CAT1 = " + A;
c = database.rawQuery(sql, null); }
Thanks in advance for any indications, suggestions or links which could help me to make my application come true, and sorry if some questions really sounds newbie, I am starting !
Have a good day !
Part 1: The best way I have found to pass variables to other activities is with a putExtra(String, variable);. Say you change the variable name on a button press, you can then call:
YourNewActivityClassName var = new YourNewActivityClassName();
Intent i = new Intent(context, YourNewActivityClassName.class);
i.putExtra("name", name);
startActivity(i);
Then in the activity you just created, you can call this in the onCreate method:
Intent i = getIntent();
final String name = i.getStringExtra("name");
Of course this is assuming the variable was defined as a String before the putExtra was called.
If you want to use other variable types, there are different get***Extra commands you can call like getIntExtra(int, defaultval) but the putExtra will still be used to send it.
Part 2: For calling a method with a variable assigned in a button click, I have found the best way to do this is with a "holder class" this holder can be defined as a final, and a button press assigns a value to one of it's slots. Here is my holder for Integers:
public class holder {
int to;
public void setTo(int to){
this.to = to;
}
public int getTo(){
return to;
}
}
I instantiate my class as final within my on create final holder hold = new holder();
then call my hold.setTo(int); within a list click listener. When I want to get the data, I simply call hold.getTo(); and I have my integer.
Heres a similar post: Pass value outside of public void onClick
Hope this helps!
Mike

Android Development :: View Objects

I'm fairly new to Java & Android, so I have little idea what I am doing.
My test program successfully creates view objects, so now I am trying to organize my code.
I want to make a separate class to manage my GUI, but it always fails.
Basic info about my gui class:
package horc.gui;
...
public class GUI{
private Context context;
From my main activity, I constructed that gui class with the app context.
gui=new GUI(getApplicationContext()); // gui is a var of type GUI, & this sets the context of the class
The problem is when I make/modify a view object that is in the class from outside, it throws an exception.
My main activity...
package horc.test;
...
GUI gui;
LinearLayout test=gui.newLinear("ff", "v"); // <-- this sets fill parent for width/height
// & vertical orientation of the vertical layout.
// Doesnt work for the reason stated above.
// I cannot manage any view objects from a separate class.
gui.lastText.setText("##########"); // <-- a variable in the class to hold the view object I am manipulating
setContentView(t);
...calls this class function:
public TextView newText(String text){
TextView test=new TextView(context);
lastLinear.addView(test);
return test;
}
I tested this similar body within the main activity & it worked fine. It only fails when I do anything from outside that gui class.
Is there a common issue that people run into when managing view objects in separate classes? I have absolutely no idea what I am doing at this point. Coming from C++, java seems like a nutty language. I cannot plan things the way I would in C++.
instead of
gui=new GUI(getApplicationContext());
try
gui=new GUI(MyActivity.this);
Please put your activity name instead of MyActivity

Pulling data from one Tab Activity to another

Everything I've read about Intents talks about using them to push data, or to start one Activity from another Activity. I want to pull data from an Activity that's already running.
The Tab Layout tutorial at http://developer.android.com/resources/tutorials/views/hello-tabwidget.html illustrates what I want to do. (My app is doing some engineering calculations instead, but the tutorial code provides a good analogy to my app.) The tutorial creates an app with three tabs, and each tab hosts a separate activity.
To expand on the example in the tutorial, suppose I select an artist in the Artists tab/activity. I want to be able to select the Albums tab/activity and have it display all the albums featuring that artist.
It seems to me that I need to use an Intent to do this. All of the tutorials I've found assume that I would create a "See albums" Button in the Artists tab/activity, and that pressing the Button would execute an Intent that starts the Albums activity and passes artistName.
I DO NOT want to create that Button. Real estate on the Artists layout is precious, and I have a perfectly good Albums tab, AND the HelloTabWidget activity already contains an intent to create the Albums tab.
Besides, a user will want to skip back and forth between Album and Artist in order to change artist selections, and the tabs are a perfectly good way to do this. There's no need to complicate the UI with another button.
So how can I have the Albums activity PULL artistName from the Artists activity when the Albums tab is selected (or the Albums layout is displayed), rather than have the Artists activity START Albums and PUSH the artistName?
Equivalents I can think of from other programming worlds:
Global variables. Discouraged in Android devt, right? And if they do exist, what are they called?
A getter, like artistName = Artists.getArtistName(); . I get the feeling that it's not that easy.
Writing to, and reading from, a file - that is, mass storage or non-volatile memory. I don't need the artistName value to be permanent. It will be reset to null every time the user launches the application.
So how is it done in the Android world? Do I use an Intent - and if so, how?
Global variables were the right answer.
I thought Java discouraged their use, but a couple of links that appeared in the "Related" links on the right margin of this window mentioned them directly. One was "Android: How to declare global variables?" and the other was "how to pass value betweeen two tab in android". Both pointed to the Application Class as the place to define global variables and methods. Armed with this new knowledge, I found an article called "Android Application Class" on the Xoriant blog that expanded on the StackOverflow answers.
It's best to review those three links first. I need to add some tips to what those authors have said.
Your Application class has to be in its own separate file. (That might be a "duh" to some people, but not to everybody.) Here's a good framework for an example called Something.java:
public class Something extends Application {
// Put application wide (global) variables here
// Constants are final, so they don't have to be private
// But other variables should be declared private;
// use getters/setters to access them
public final boolean FEET = false;
public final boolean METERS = true;
private boolean units = FEET;
#Override
public void onCreate() {
super.onCreate();
// Put any application wide (global) initialization here
}
// Put application wide (global) methods here
public boolean getUnits() {
return units;
}
public void setUnits(boolean whichOne) {
units = whichOne;
}
}
I'm using Eclipse with the ADT plug-in, in Windows XP. Eclipse doesn't always behave properly if you edit XML code directly, so it's best to open AndroidManifest.xml, then select the Application tab and enter your application name in the Name field. You don't need to put a dot or period in front of the name. Just type in the name of your class, like "Globals" or "MyApplication" or whatever. (Note that this is the default application in your Manifest. You don't have to create a separate <application></application> tag.
This step may not be necessary on an actual Android device, but it was necessary for the emulator: you need to use the getApplicationContext() command in every onCreate() and every method that will be accessing the global variables and methods. I tried to put it outside of onCreate() with the rest of my activity wide variables, and it didn't work. Putting it inside every method seems wasteful, but both the emulator and the Android device work fine with it that way. Here's a sample showing how I used it:
public void fooBar() {
// Access to global variables and methods
final Something s = (Something)getApplicationContext();
// ...
// This next line demonstrates both a global method and a global variable
if (s.getUnits() == s.FEET) {
// do something with feet
} else {
// do something with meters instead
}
// ...
}
Those were the only hiccups I encountered. The three references that I have listed, taken together, are otherwise pretty complete.

Android - Issue dealing with static method (?) and the last step

This is really doing my head in, I have been following these instructions but it won't work. Step three is causing me trouble. I'm note sure exactly what needs to be added where. It says;
"In the onCreate() method of your app instance, save your context (e.g. this) to a static >field named app and create a static method that returns this field, e.g. getApp():"
But I only have this at the top of my main java file:
protected static final String App = null;
The error I get is on this line, it says "The method getContext() is undefined for the type String":
String[] items = App.getContext().getResources().getStringArray(testholderint);
I figure the issues is with not following step three, and was wondering what exactly I need to add.
Once I've got this rectified my project is basically finished...
I think this line
protected static final String App = null;
shouldn't appear at all. The link you provided tells you to create a subclass of your application, like
public class App extends Application { ... }
In this subclass you should put the onCreate() and getContext() methods indicated in the code provided at that link. After doing so your last line (String[] items...) should work just fine.

Categories

Resources