https://stackoverflow.com/a/14164318/3575963
Here, he used
View myFragmentView = inflater.inflate(R.layout.fragment_a, container, false);
From parent class. Also I don't have inflater in my parent, it is a map.
And from asynctask doitbackground, I returned 5 arraylists to make textview in postexecute.
But I can't do because I can't use findviewbyid because I can't get activity. I got context but it does not do anything.
Here is my postexecute
protected void onPostExecute(Wrapper wrap){
TextView name = new TextView (mContext);
TextView type = new TextView (mContext);
TextView location = new TextView (mContext);
TextView distance = new TextView (mContext);
List<Double> dist = new ArrayList();
List<String> loc = new ArrayList();
List<String> nme = new ArrayList();
List<String> typ = new ArrayList();
List<Calendar> start = new ArrayList();
List<Calendar> endd = new ArrayList();
dist = wrap.getDist();
loc = wrap.getLocation();
nme = wrap.getName();
typ = wrap.getType();
start = wrap.getsDate();
endd = wrap.geteDate();
int idx = -1;
LinearLayout shw_evnt = (LinearLayout) shw_evnt.findViewById(R.id.);
for(Double dis:dist){
idx++;
name.setText(nme.get(idx));
type.setText(typ.get(idx));
location.setText(loc.get(idx));
distance.setText(dist.get(idx).toString()+" meters");
This part is faulty
LinearLayout shw_evnt = (LinearLayout) shw_evnt.findViewById(R.id.);
I tried other things but it did not work. I will use another layout that was not used before.
show_events.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
android:id="#+id/shwevnt"
</LinearLayout>
Here caller mapactivity class
public class MapActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private int strokeColor = 0xffff0000; //red outline
private int shadeColor = 0x44ff0000; //opaque red fill
private int count=0;
private GoogleMap googleMap;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private LocationRequest mLocationRequest;
private Context mContext;
private String TAG = "Chic";
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private int radius;//in meters
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "inside map oncreaste");
mContext = getApplicationContext();
View myFragmentView = inflater.inflate(R.layout.show_events, container, false);
super.onCreate(savedInstanceState);
setUpMapIfNeeded();
Log.d(TAG, "buildgoogleapi called");
buildGoogleApiClient();
Log.d(TAG, "after buildgoogleapi called");
}//end of oncreate
here error on that
View myFragmentView = inflater.inflate(R.layout.show_events, container, false);
because i dont have inflater
I dont want to return from postexecute to main class or another wrapper class. I think i can do inside postexecute, cant i?
LayoutInflater inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
if i do this, i will take current view, not the view i want to create?
I tried
private Inflater inflater;
View myFragmentView = inflater.inflate(R.layout.show_events, container, false);
Yep, just pass the Activity to the Asynctask:
AsyncTask myAsyncTask = new MyTask(this);
And then you will find the element inside the layout of the Activity:
public class MyTask extends AsyncTask<String, String, String>{
public MyActivity activity;
public MyTask(MyActivity a){
this.activity = a;
}
protected void onPostExecute(String result){
...
...
LinearLayout shw_evnt = (LinearLayout) activity.findViewById(R.id.shwevnt);
...
...
}
}
Like Daniel describes it would be a bad practice.
I recommend to you an Interface.
for example:
a) Create interface class.
public interface AsyncResponse {
void processFinish(String output);
}
b) Go to your AsyncTask class, and declare interface AsyncResponse as a field :
public class MyAsyncTask extends AsyncTask{
public AsyncResponse delegate = null;
#Override
protected void onPostExecute(String result) {
delegate.processFinish(result);
}
}
c) In your main Activity you need to implements interface AsyncResponse.
public class MainActivity implements AsyncResponse{
MyAsyncTask asyncTask =new MyAsyncTask();
#Override
public void onCreate(Bundle savedInstanceState) {
//this to set delegate/listener back to this class
asyncTask.delegate = this;
//execute the async task
asyncTask.execute();
}
//this override the implemented method from asyncTask
void processFinish(String output){
//Here you will receive the result fired from async class
//of onPostExecute(result) method.
LinearLayout shw_evnt = (LinearLayout) findViewById(R.id.shwevnt);
}
}
this is the solution..
facturas_edittext=(EditText)((Activity)context).findViewById(R.id.mye);
Just pass the Activity as a parameter to the AsyncTask class. See here. Note that its bad practice to store context as a member variable since the context may change.
Related
MainActivity on startup add a fragment layout to Relativeview, then i send a data to fragment to add it to ExpandablelistView but my app shows me error that couldn't recognize ExpandablelistView.
MainActivity:
public class MainActivity extends AppCompatActivity implements FragmentAddCatergory.onClickButtonListener {
private FragmentManager manager;
private FragmentTransaction transactionShowList;
private FragmentTransaction transactionAddCatergory;
private FragmentAddCatergory addCatergory;
private FragmentShowCategory showCategory;
private boolean addcategory;
private TextView txtAddCategory;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager = getFragmentManager();
transactionShowList = manager.beginTransaction();
showCategory = new FragmentShowCategory();
addCatergory=new FragmentAddCatergory();
transactionShowList.add(R.id.Fragment_container, showCategory);
transactionShowList.commit();
addcategory=false;
txtAddCategory = (TextView) findViewById(R.id.txtaddcategory);
txtAddCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ChangeFragment();
}
});
}
public void ChangeFragment(){
transactionAddCatergory=manager.beginTransaction();
if (addcategory){
transactionAddCatergory.replace(R.id.Fragment_container,addCatergory);
txtAddCategory.setText("Do you want to see your List?Show me!");
addcategory=false;
}else{
transactionAddCatergory.replace(R.id.Fragment_container,showCategory);
txtAddCategory.setText("Do you want to add a Category?Create One");
addcategory=true;
}
transactionAddCatergory.commit();
}
#Override
public void ClickButton(String group, String child) {
FragmentShowCategory a=new FragmentShowCategory();
a.showExpand(this,group,child);
}}
in last above code i make object from first fragment and send a data and in below code is code of first fragment
public class FragmentShowCategory extends Fragment {
private View view;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
view = inflater.inflate(R.layout.activity_expandable_list_view, container, false);
return view;
}
public void showExpand(Context context, String g, String c) {
Toast.makeText(context, g + " is " + c, Toast.LENGTH_LONG).show();
HashMap<String, List<String>> carsDetails = DataProvider.getInfo(g, c);
List<String> carsBrands = new ArrayList<String>(carsDetails.keySet());
ItemClass adapter = new ItemClass(context, carsDetails, carsBrands);
ExpandableListView list = (ExpandableListView) view.findViewById(R.id.expandList);
list.setAdapter(adapter);
}}
but when i ran my app, i get error that i don't know why in line of:
ExpandableListView list = (ExpandableListView) view.findViewById(R.id.expandList);
i'd appreciate to help me.
Your fragment's view hierarchy is not inflated automatically just because you created an instance of your fragment, as you do in ClickButton. The onCreateView() method that has to be called first in order to inflate your views is part of the fragment's lifecycle. You should let Android instantiate your fragment, and acquire it's instance through the FragmentManager.
This tutorial explains basics about fragments very well.
I'm more googling to find how can i pass simple view as an object to fragment, but i can't.
for example in MainActivity i have simple view as :
TextView text = (TextView) findviewById(R.id.tv_text);
now i want to pass that to fragment. this below code is my attach Fragment on MainActivity
MainActivity :
public void attachFragment() {
fts = getActivity().getFragmentManager().beginTransaction();
mFragment = new FragmentMarketDetail();
fts.replace(R.id.cardsLine, mFragment, "FragmentMarketDetail");
fts.commit();
}
and this is my Fragment:
public class FragmentMarketDetail extends Fragment implements ObservableScrollViewCallbacks {
public static final String SCROLLVIEW_STATE = "scrollviewState";
private ObservableScrollView scrollViewTest;
private Context context;
private int scrollY;
public static FragmentMarketDetail newInstance() {
FragmentMarketDetail fragmentFirst = new FragmentMarketDetail();
return fragmentFirst;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_online_categories, container, false);
scrollViewTest = (ObservableScrollView) view.findViewById(R.id.scrollViewTest);
scrollViewTest.setScrollViewCallbacks(this);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity().getBaseContext();
}
}
It wouldn't be good practise to pass a view that way. If you want to access the view in your activity from within your fragment class, use getActivity() to access the activity to which your fragment is attached, and from there you find your TextView.
TextView text = (TextView) getActivity().findViewById(R.id.tv_text);
How about adding a set function in your custom fragment
e.g.
public void setTextView(TextView tv){
this.tv = tv
}
and then calling it after
mFragment = new FragmentMarketDetail();
mFragment.setTextView(textView)
Find fragment by tag and invoke a function on it:
mFragment = (FragmentMarketDetail ) getActivity().getFragmentManager().findFragmentByTag(FragmentMarketDetail .class.getSimpleName());
mFragment.passTextView(textView);
Of course fragment must be added to backstack.
I have MainActivity activity which has 3 fragments. Those 3 fragments use same arrayadapter class MessageListAdapter. When i populate listView in my fragments using different ArrayLists using MessageListAdapter it combines all those ArrayLists and displays in each fragment. I want each fragment to display its own list.
MessageListAdapter:
public class MessageListAdapter extends ArrayAdapter<Message>{
Context context;
public MessageListAdapter(Context c, int resourceId, ArrayList<Message> list) {
super(c, resourceId, list);
this.context = c;
}
//...
}
HomeFragment:
public class HomeFragment extends Fragment {
View view;
ListView listView1;
ArrayList<Message> contactMessages;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.home_layout, container, false);
TextView welcomeMessage = (TextView) view.findViewById(R.id.welcomeMessage);
Account acc = new Account();
welcomeMessage.setText("Welcome " + acc.getName() + "!");
contactMessages = new Message().getContactMessages();
listView1 = (ListView) view.findViewById(R.id.homeList);
MessageListAdapter adapter = new MessageListAdapter(this.getActivity(), R.layout.activity_message, contactMessages);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
}
});
return view;
}
}
ProfileFragment:
public class ProfileFragment extends Fragment implements View.OnClickListener, OnItemClickListener {
View view;
Intent intent;
ListView listView2;
ArrayList<Message> personalMessages;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.profile_layout, container, false);
Button button = (Button) view.findViewById(R.id.addMessage);
button.setOnClickListener(this);
Button addFriendButton = (Button) view.findViewById(R.id.addFriend);
addFriendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent = new Intent(getActivity(), AddFriendActivity.class);
startActivity(intent);
}
});
personalMessages = new Message().getPersonalMessages();
// Log.i("Personal messages ArrayList: ", personalMessages.toString());
listView2 = (ListView) view.findViewById(R.id.profileList);
MessageListAdapter adapter = new MessageListAdapter(this.getActivity(), R.layout.activity_message, personalMessages);
listView2.setAdapter(adapter);
listView2.setOnItemClickListener(this);
return view;
}
}
Also have 3rd fragment which will use this same MessageListAdapter, but i have not implemented it yet due to running into this problem.
I made screenshots to make it easier to understand:
Items with orange pictures are supposed to be shown only in ProfileFragment and item with blue picture is supposed to be shown only in HomeFragment
Problem lies in using static ArrayList inside Message class. addPersonalMessage adds Message object into personalMessages list and addContactMessage adds Message object into contactMessages list. After i built all the messages according to their type and put them inside lists separately, for some reason application combines those 2 lists. This is why i end up with similar content in both listviews in fragments. Solved problem by using SQLite database instead of using static variables.
Message:
public class Message {
private String author;
private String messageTitle;
private Bitmap messageImage;
private static ArrayList<Message> personalMessages = new ArrayList<Message>();
private static ArrayList<Message> contactMessages = new ArrayList<Message>();
public Message() {
}
public Message(String a, String t, Bitmap b) {
this.author = a;
this.messageTitle = t;
this.messageImage = b;
}
public void addPersonalMessage() {
personalMessages.add(this);
}
public void addContactMessage() {
contactMessages.add(this);
}
}
I want change view linearlayout from class
But not work this code
main.java
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ComNet.readDb();
}
}
And :
ComNet.java
public class ComNet {
public static Context context;
public static void readDb() {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewMain = inflater.inflate(R.layout.main, null);
LinearLayout lnrPart = (LinearLayout) viewMain.findViewById(R.id.lnrPart);
lnrPart.setVisibility(View.GONE);
}
}
How change lnrPart from main.xml in class ( ComNet ) ?
View viewMain = inflater.inflate(R.layout.main, null);
with this line you are creating a new View, with the content of main.xml. This object is different from the one you are seeing at screen in your MainActivity. setVisibility is working. You are calling it on the wrong instance
Send the activities rootView to readDB function.
main.java
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ComNet.readDb(findViewById(R.id.main));
}
}
ComNet.java
public static void readDb(View viewMain) {
LinearLayout lnrPart = (LinearLayout) viewMain.findViewById(R.id.lnrPart);
viewMain.setVisibility(View.GONE);
}
This is what i am trying to do, this my main class file
private View TicTacStart;
//onCreate
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
TicTacStart = new Game(this);
//reference to base layout..
LinearLayout baseView = (LinearLayout)findViewById(R.id.baseView);
//I cant INFLATE THE VIEW SINCE I AM NOT USING XML AND RATHER USING ANOTHER CLASS GAME WHICH EXTENDS VIEW
LayoutInflater vi = (LayoutInflater)thisActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View thisScreensView = vi.inflate(TicTacStart, null);
//add the view to the base view...
baseView.addView(thisScreensView);
}
This is game class
public class Game extends View {
private Cell[][] singlesquare = null;
int x = 3;
int y = 3;
private int l;
private int a;
private boolean whatdrawn = false;
private int playerwin = 3;
private Paint caneta;
Data Data MORE classes
}
so basically what I want to do is add Game view class into baseview in my main class file. Is there someway i can make this work as i don't want to use xml's now.
Yuu can directly add GameView into baseview for ex:
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
TicTacStart = new Game(this);
//reference to base layout..
LinearLayout baseView = (LinearLayout)findViewById(R.id.baseView);
baseView.addView(TicTacStart );
}