Hi I have an activity which holds a layout, the layout is divided into two linear layouts. The first layout has 4 buttons. The second one has fragments. Basically with each button press, a new fragment is displayed. All the fragments hold a layout . This layout has an edit text field, a button and a list view. Now everything is working fine, no errors till now. But the problem I am having is , when I try to create a database object and pass the context of the fragment class as parameter in the contructor, it simply shows an error. Here's the code...Please have a look and guide me how can I solve the problem.
String text = null;
EditText enter_task;
// enter_task would be provided with its id, not a problem,
text = enter_task.getText().toString();
try{
// this is where te problem is
// normally I could pass the context of the activity within the constructr of database class as parameter. But since this class is a fragment, I am simply not able to do so.
myDatabase_today = new Database(MyFragment_today.this);
}
The solution which eclispe provides to the problem are:
1-> Change contructor Database(Context) to Database(MyFragment_today).
// here MyFragment_today is the fragment class's name
2-> Create contructor Database(MyFragment_today).
Could anyone please solve this problem. I mean we can pass the activity's context , but not the fragment class's context, then how to proceede further.
Use getActivity() instead of the Fragment class name
myDatabase_today = new Database(getActivity());
Related
I have one fragment in which I'm generating an ArrayList. After the ArrayList is generated, I'm sending it to the Activity using interface
Inside my fragment-
public interface sendTheArraylist{
void ArrayList(ArrayList<Song> songArrayList);
}
And in the MainActivity-
#Override
public void accessArrayList(ArrayList<Song> songArrayList) {
this.queueArrayList=songArrayList;
queueAdapter =new SongAdapter(this,queueArrayList);
....
}
However, I see that whenever any changes are made in the queueArrayList in MainActivity, the songArrayList in the fragment is also getting affected. How can I stop the ArrayList in the Fragment from getting changed?
Try with the following.
this.queueArrayList.clear();
this.queueArrayList.addAll(songArrayList);
The reason is that you are referencing the arraylist to queueArrayList directly which also reflects changes back in songArrayList
Using an interface you pass the reference of that list so whenever you change that list will also affect on fragment list too. so the solution is rather than pass a reference to that list create one new list and make copy of it.
You can try and give a look at the Collections.copy method:
public static void copy(List dest, List src)
Copies all of the elements from one list into another. After the operation, the index of each copied element in the destination list will be identical to its index in the source list. The destination list must be at least as long as the source list. If it is longer, the remaining elements in the destination list are unaffected. This method runs in linear time.
Parameters: dest - The destination list. src - The source list.
hope it will help you.
Here is the complete solution:
before calling sendTheArraylist Inside your fragment-
ArrayList<Song> songArrayListToPass= new ArrayList<Song>(songArrayList.size());
Collections.copy(songArrayListToPass, songArrayList);
YourActivityRef.sendTheArraylist(songArrayListToPass);
This way your any update on your songArrayListToPass inside Activity will not reflect in Fragment.
I have an android app that I have decided to rewrite, one of the reasons for the rewrite is because I could have 10+ TextViews with text set based on a variable in a class e.g.:
MyClass myClass = new MyClass();
myClass.myNumber = 5; // inside MyClass - public int myNumber;
LinearLayout mainLayout = (LinearLayout) view.findViewById(R.id.mainLayout);
TextView myTextView = new TextView(getActivity()); //In a fragment
myTextView.setText(String.format("myNumber currently has a value of %d", myClass.myNumber));
mainLayout.addView(myTextView);
return view;
Up until now I have been using .setOnClickListener on the buttons/views that change myNumber, to set the text of the view again when the value of myNumber changes, which then calls .invalidate() to redraw the TextView, this has worked fine, but I use this method very heavily and code is getting quite repetitive and changing one integer can affect quite a lot of views (all of which use it differently - such as different wording, or a calculation (e.g. myNumber * 2)). I guess it's because it's made an immutable string in the TextView.
I have tried to create a custom TextView that implements Observer (making MyClass extend Observable) and in the update method I can get it to invalidate itself for the refresh, but it still has the same text. I have also tried creating single element arrays, in an attempt to pass the reference not the value in the hope that when it is changed and then the view is invalidated it will pick up the new value but the text still ends up remaining the same.
How can I get a TextView that will auto update when the value of myNumber has changed? Some sort of binding?
Bindroid works perfectly for this, just a note for users, using fragments the sample application is using this from an Activity so the bind method using Activity is called, so in the fragment I was using getActivity() which caused it to not work properly, digging around in the library I found a bind method that takes a View and passed in my view which gets inflated in the fragment and it works great!!! This is super easy to integrate btw it was just me not getting it!
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
I'm trying to add a text switcher dynamically but I get the error:
The method setFactory(ViewSwitcher.ViewFactory) in the type ViewSwitcher is not applicable for the arguments...
Here's my code:
TextSwitcher ts = (TextSwitcher) new TextSwitcher(this);
ts.setFactory(this);
Animation in = AnimationUtils.loadAnimation(this,android.R.anim.fade_in);
Animation out = AnimationUtils.loadAnimation(this,android.R.anim.fade_out);
ts.setInAnimation(in);
ts.setOutAnimation(out);
The setFactory method expects a ViewSwitcher.ViewFactory type argument and not Activity (which I presume is your this.)
You have 3 options:
you can implement your own ViewSwitcher.ViewFactory. you can see an example here.
you can use ViewSwitcher.addView to dynamically add your child views
you can define the child views in your layout xml
Either one should work OK for you.
Your activity class needs to implement android.widget.ViewSwitcher.ViewFactory interface.
I want to have a class "Utils", that will have several methods used all over my code. For example, I have a top bar with a textview and two ImageButtons that must display different texts and icons on different activities.
I find myself writing stuff like this on every activity:
(TextView) topBarText = (TextView) findViewById(R.id.topBarText);
topBarText.setText(R.id.mytextForThisView);
I'd like to findViewById once in my whole app, and call a method setupTopBar(String text, R.id.iconForImageButton1, R.id.iconForImageButton2), or even pass the current Activity's id and let the method figure out what to show in the text and images.
I created the class Util, but it doesn't extend Activity. The problem is that if it doesn't, findViewById isn't accessible, so I can't use it.
What's the pattern to do something like this in Android?
Your helper methods should look like
public static void setTopBarText(Activity act, int textId){
(TextView) topBarText = (TextView)act.findViewById(R.id.topBarText);
topBarText.setText(textId);
}
Then you can do a static import from Activity and call
setTopBarText(this, R.id.mytextForThisView);
The Answer is not good for some situation.
This is my method:
In your Activity:
YouCustomClassObject.passView((View)findViewById(R.id.aview));
Using parameter passing can solve this kind of problem.