Is this possible to change weightSum value programatically using setWeightSum(float)? - java

I am trying to control weightSum for linear layout from fragment. I wondered if it's possible to do that using setWeightSum(float) method.
I tried to control weight sum in Linear layout which id is header_Linear.
<LinearLayout
android:id="#+id/header_Linear"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:orientation="horizontal"
android:weightSum="8">
<TextView
android:id="#+id/table_0.0"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:visibility="visible"
android:background="#drawable/header_bg"/>
<TextView
android:id="#+id/table_0.1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:textAlignment="center"
android:gravity="center"
android:text="M"
android:textColor="#color/colorTableItem"
android:visibility="visible"
android:background="#drawable/header_bg"/>
<TextView
android:id="#+id/table_0.2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:text="T"
android:textColor="#color/colorTableItem"
android:visibility="visible"
android:background="#drawable/header_bg"/>
<TextView
android:id="#+id/table_0.3"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:text="W"
android:textColor="#color/colorTableItem"
android:visibility="visible"
android:background="#drawable/header_bg"/>
<TextView
android:id="#+id/table_0.4"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:text="T"
android:visibility="visible"
android:textColor="#color/colorTableItem"
android:background="#drawable/header_bg"/>
<TextView
android:id="#+id/table_0.5"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:text="F"
android:visibility="visible"
android:textColor="#color/colorTableItem"
android:background="#drawable/header_bg"/>
<TextView
android:id="#+id/table_0.6"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:text="S"
android:textColor="#color/colorTableItem"
android:visibility="visible"
android:background="#drawable/header_bg"/>
<TextView
android:id="#+id/table_0.7"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:text="S"
android:textColor="#color/sunday_text_color"
android:visibility="visible"
android:background="#drawable/header_bg"/>
</LinearLayout>
This is my fragment that using setWeightSum
public class TimeTableFragment extends Fragment {
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_timetable, container, false);
LinearLayout linearLayout = root.findViewById(R.id.header_Linear);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(Objects.requireNonNull(getContext()));
String header_value = sharedPreferences.getString("Header","0");
Toast.makeText(getContext(),""+header_value,Toast.LENGTH_LONG).show();
if (header_value.equals("0")){
linearLayout.setWeightSum(6);
}
return root;
}
When I start the app it crashes. I'd like to know if it's possible to control weightSum without errors.
Thank you very much
Upate
The reason why I got nullPointException even though I declared Linear Layout using findViewById was due to xmlns:android="http://schemas.android.com/apk/res/android"in Layout.
The View that contains xmlns:android="http://schemas.android.com/apk/res/android" would return null after using findViewById in this situation

public class TimeTableFragment extends Fragment {
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_timetable, container, false);
return root;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LinearLayout linearLayout = view.findViewById(R.id.header_Linear);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(Objects.requireNonNull(getContext()));
String header_value = sharedPreferences.getString("Header","0");
Toast.makeText(getContext(),""+header_value,Toast.LENGTH_LONG).show();
if (header_value.equals("0")){
linearLayout.setWeightSum(6);
}
}
}

Related

Android java - dynamically add ImageViews in LinearLayout

i would like to add to a LinearLayout some imageViews dynamically in my app.
My following code doesn't show errors and prints what it is supposed to on logcat each time an ImageView is added from java code.
My problem is that when i run the app the images don't appear on screen....any idea where i am doing wrong ?
thanks a lot.
public class MesListesFragment extends Fragment {
private RecyclerView mes_listes_recyclerView;
private ArrayList<ListItem> liste_items;
private LinearLayout list_card_categories;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.mes_listes_fragment, container, false);
View view2 = inflater.inflate(R.layout.list_item, container, false);
mes_listes_recyclerView = view.findViewById(R.id.mes_listes_recyclerView);
list_card_categories = view2.findViewById(R.id.list_card_recyclerView);
liste_items = new ArrayList<>();
for (int i = 0; i < 10; i ++){
liste_items.add(new ListItem("Liste des ploucs", "18 Août 198" + i));
}
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
mes_listes_recyclerView.setLayoutManager(linearLayoutManager);
mes_listes_recyclerView.setAdapter(new ListViewAdapter(getContext(), liste_items));
for (int i = 0; i < 8; i++){
ImageView image = new ImageView(getContext());
image.setImageResource(R.drawable.user);
list_card_categories.addView(image);
Log.d("view created", "...");
}
return view;
}
}
Here is the xml, the file's called list_item.xml :
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_marginHorizontal="10dp"
android:layout_marginTop="10dp"
app:cardCornerRadius="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/list_card_first_container"
android:layout_width="match_parent"
android:layout_height="100dp"
android:baselineAligned="false"
android:orientation="horizontal"
android:weightSum="100">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="50"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/list_card_textView_nom_liste"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nom de la liste"></TextView>
<TextView
android:id="#+id/list_card_textView_date_liste"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Date liste"></TextView>
</LinearLayout>
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="50">
<LinearLayout
android:id="#+id/list_card_recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="50"
android:gravity="center"
android:orientation="horizontal">
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
<LinearLayout
android:id="#+id/list_card_second_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/list_card_first_container"
android:gravity="center"
android:orientation="horizontal"
android:paddingVertical="5dp">
<Button
android:id="#+id/list_card_button_editer"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginEnd="20dp"
android:background="#color/bleu_fb"
android:text="#string/editer"></Button>
<Button
android:id="#+id/list_card_button_supprimer"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:background="#android:color/holo_red_light"
android:text="#string/supprimer"></Button>
</LinearLayout>
</RelativeLayout>
</androidx.cardview.widget.CardView>

Android Studio with Java: ArrayAdapter not working correctly

I'm making an app in which the user can enter a few items and have it displayed as he adds items. I'm using an adapter to achieve this but instead of showing me a neat list with items, the adapter creates a list of several views repeating themselves (i.e Instead of just using the given TextView as a Template for the entry in the listview, it uses all views in that activity).
Here is the code:
This is from the createEntry class. This code initiates the adapter and loads the previous entries for a particular day. It send adds them all to the adapter.
public void loadEntries() {
events = new ArrayList<>();
adapter = new EntryAdapter(this, entries);
ListView listView = findViewById(R.id.entry_list);
listView.setAdapter(adapter);
new AsyncTask<Void, Void, List<String>>() {
#Override
protected List<String> doInBackground(Void... voids) {
return appDB.entryDao().getEntriesFromDate(day, monthNum, year);
}
#Override
protected void onPostExecute(List items) {
generateEntryTable(items);
}
}.execute();
}
public void generateEntryTable(List items) {
for (int i = 0; i < items.size(); i++) {
adapter.add(new TableEntries(year, monthNum, day, entryContent));
}
}
This is my custom EntryAdapter class:
public class EntryAdapter extends ArrayAdapter<Entry> {
public EntryAdapter(Context context, ArrayList<Entry> entries) {
super(context, 0, entries);
}
#Override
public View getView(int position, View convertView, ViewGroup container {
Entry entry = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_create_event, container, false);
}
TextView newEntry = convertView.findViewById(R.id.new_entry);
newEntry.setText(entry.getContent());
return convertView;
}
}
This is the XML-file:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CreateEntry">
<TextView
android:id="#+id/date"
android:layout_width="222dp"
android:layout_height="44dp"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="215dp"
android:layout_marginRight="215dp"
android:layout_marginBottom="685dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="403dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="116dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="200dp"
android:background="#5CFF9800"
android:orientation="vertical"
app:layout_constraintBottom_toTopOf="#+id/linearLayout2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/date"
app:layout_constraintVertical_bias="0.0">
<TextView
android:id="#+id/textView3"
android:layout_width="112dp"
android:layout_height="35dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="276dp"
android:layout_marginRight="276dp"
android:layout_marginBottom="8dp"
android:text="#string/event"
android:textSize="24sp" />
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/addEvents"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:contentDescription="#string/add_events"
android:cropToPadding="true"
android:onClick="addEvent"
android:scaleType="fitStart"
android:tint="#FF3F02"
app:srcCompat="#android:drawable/ic_menu_add" />
<EditText
android:id="#+id/addEventsPrompt"
android:layout_width="353dp"
android:layout_height="30dp"
android:background="#android:color/transparent"
android:clickable="true"
android:freezesText="false"
android:gravity="start|fill|center_vertical"
android:hint="#string/startTyping"
android:inputType="textShortMessage|textLongMessage|textMultiLine|textPersonName|text"
android:textAllCaps="false"
android:textAppearance="#style/TextAppearance.AppCompat.Display1"
android:textSize="14sp" />
</TableRow>
<ListView
android:id="#+id/event_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:id="#+id/entry_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/new_entry"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="156dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent">
<TextView
android:id="#+id/toDoTitle"
android:layout_width="102dp"
android:layout_height="33dp"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="322dp"
android:layout_marginRight="322dp"
android:text="#string/to_do"
android:textSize="24sp" />
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="#+id/addToDo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:background="#00FFFFFF"
android:contentDescription="#string/add_to_dos"
android:onClick="addToDo"
android:scaleType="fitStart"
android:tint="#FF3B00"
app:srcCompat="#android:drawable/ic_menu_add" />
<EditText
android:id="#+id/addToDoPrompt"
android:layout_width="344dp"
android:layout_height="32dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_weight="100"
android:autofillHints=""
android:background="#android:color/transparent"
android:gravity="start|fill_horizontal|center_vertical"
android:hint="#string/startTyping"
android:inputType="textShortMessage|textLongMessage|textMultiLine|text"
android:textSize="14sp" />
<TextView
android:id="#+id/new_to_do"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
</TableRow>
</LinearLayout>
If you need to see any other code, please let me know.
The difference in usage of adapter to the tutorials that I have seen is that, in my app, the listview is not the only view displayed in the activity so that may be the/a problem.
You're going about this in the wrong manner. In your EntryAdapter:
#Override
public View getView(int position, View convertView, ViewGroup container {
Entry entry = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext())
.inflate(R.layout.activity_create_event, container, false);
}
...
In that inflate statement you are inflating the entire XML layout for your Activity (R.layout.activity_create_event) for every row of your ListView. Instead, you should be using a much simpler layout containing just your TextView in a separate layout XML file, for example let's call this res/layout/list_row.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/new_entry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="Placeholder Text" />
</LinearLayout>
Then replace the layout you're inflating in getView() like so:
#Override
public View getView(int position, View convertView, ViewGroup container {
Entry entry = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext())
.inflate(R.layout.list_row, container, false);
}
...
I'd also recommend looking into RecyclerView as that has now superceded ListView.

Android Fragment transaction from list's element

I have an ArrayAdapter MealAdapter and list's element meal_item, there are a few textviews and FrameLayout. I want to put fragment MealDetails in this FrameLayout by click on imageview. MealAdapter isn't used in Activity but in another fragment.
My item is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<!--icon-->
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/meal_number_icon"
android:layout_width="70dp"
android:layout_height="70dp"
android:padding="6dp"
android:src="#drawable/ic_menu_gallery"
android:layout_centerInParent="true" />
</RelativeLayout>
</LinearLayout>
<!--name-->
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:orientation="horizontal"
android:paddingBottom="10dp"
android:paddingTop="10dp">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/protein_source_name"
android:text="sdfsdfsdf"
android:textSize="15sp"
android:textStyle="bold"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fat_source_name"
android:textSize="15sp"
android:textStyle="bold"
android:text="sdfsdfsdf"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/carb_source_name"
android:textSize="15sp"
android:textStyle="bold"
android:text="sdfsdfsdf"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/vegetable_source_name"
android:textSize="15sp"
android:textStyle="bold"
android:text="sdfsdfsdf"/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/protein_source_weight"
android:text="sdfsdfsdf"
android:textSize="15sp"
android:textStyle="bold"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fat_source_weight"
android:textSize="15sp"
android:textStyle="bold"
android:text="sdfsdfsdf"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/carb_source_weight"
android:textSize="15sp"
android:textStyle="bold"
android:text="sdfsdfsdf"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/vegetable_source_weight"
android:textSize="15sp"
android:textStyle="bold"
android:text="sdfsdfsdf"/>
</LinearLayout>
</LinearLayout>
<!-- refreshMeal -->
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/meal_accept_icon"
android:layout_width="70dp"
android:layout_height="70dp"
android:padding="6dp"
android:src="#drawable/ic_menu_gallery"
android:layout_centerInParent="true" />
</RelativeLayout>
</LinearLayout>
<!--info-->
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<RelativeLayout
android:id="#+id/info_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/meal_details_icon"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="#drawable/ic_menu_gallery"
android:layout_centerInParent="true"
android:tint="#8a000000"/>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
<FrameLayout
android:id="#+id/meal_frameLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginRight="4dp">
</FrameLayout>
</LinearLayout>
and adapter:
public class MealAdapter extends ArrayAdapter {
List list = new ArrayList();
private Context context;
public MealAdapter(Context context, int resource) {
super(context, resource);
this.context = context;
}
public static class DataHandler{
ImageView numberIcon;
ImageView detailsIcon;
ImageView acceptIcon;
TextView proteinSourceName;
TextView fatSourceName;
TextView carbSourceName;
TextView vegetableSourceName;
TextView proteinSourceWeight;
TextView fatSourceWeight;
TextView carbSourceWeight;
TextView vegetableSourceWeight;
FrameLayout detailsLayout;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return this.list.size();
}
#Override
public Object getItem(int position) {
return this.list.get(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final DataHandler dataHandler;
if(convertView==null){
LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.meal_item,parent,false);
dataHandler = new DataHandler();
dataHandler.numberIcon = (ImageView) view.findViewById(R.id.meal_number_icon);
dataHandler.detailsIcon = (ImageView) view.findViewById(R.id.meal_details_icon);
dataHandler.acceptIcon = (ImageView) view.findViewById(R.id.meal_accept_icon);
dataHandler.proteinSourceName =(TextView) view.findViewById(R.id.protein_source_name);
dataHandler.fatSourceName =(TextView) view.findViewById(R.id.fat_source_name);
dataHandler.carbSourceName =(TextView) view.findViewById(R.id.carb_source_name);
dataHandler.vegetableSourceName =(TextView) view.findViewById(R.id.vegetable_source_name);
dataHandler.proteinSourceWeight =(TextView) view.findViewById(R.id.protein_source_weight);
dataHandler.fatSourceWeight =(TextView) view.findViewById(R.id.fat_source_weight);
dataHandler.carbSourceWeight =(TextView) view.findViewById(R.id.carb_source_weight);
dataHandler.vegetableSourceWeight =(TextView) view.findViewById(R.id.vegetable_source_weight);
dataHandler.detailsLayout=(FrameLayout)view.findViewById(R.id.meal_frameLayout);
view.setTag(dataHandler);
}
else{
dataHandler=(DataHandler) view.getTag();
}
LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final MealDataProvider mealDataProvider;
mealDataProvider = (MealDataProvider) this.getItem(position);
dataHandler.numberIcon.setImageResource(mealDataProvider.getNumberIcon());
dataHandler.detailsIcon.setImageResource(mealDataProvider.getShowIcon());
dataHandler.acceptIcon.setImageResource(mealDataProvider.getAcceptIcon());
dataHandler.proteinSourceName.setText(mealDataProvider.getProteinSourceName());
dataHandler.fatSourceName.setText(mealDataProvider.getFatSourceName());
dataHandler.carbSourceName.setText(mealDataProvider.getCarbSourceName());
dataHandler.vegetableSourceName.setText(mealDataProvider.getVegetableSourceName());
dataHandler.proteinSourceWeight.setText(mealDataProvider.getProteinSourceWeight());
dataHandler.fatSourceWeight.setText(mealDataProvider.getFatSourceWeight());
dataHandler.carbSourceWeight.setText(mealDataProvider.getCarbSourceWeight());
dataHandler.vegetableSourceWeight.setText(mealDataProvider.getVegetableSourceWeight());
dataHandler.detailsIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),"click",Toast.LENGTH_LONG).show();
MealDetails mealDetails = new MealDetails();
FragmentTransaction ft = ((FragmentActivity)context).getSupportFragmentManager().beginTransaction();
ft.replace(dataHandler.detailsLayout.getId(),mealDetails);
}
});
return view;
}
}
onClick method works (there is "click" toast) but nothing else happens, the is nothing in AndroidMonitor if I click dataHandler.detailsIcon.
How is it possible to put fragment in framelayout in list's element?
Edit
I forgot about commit(), so now it works but only for FrameLayout from first list's element. It doesn't matter which list's element I click, fragment MealDetails is always place in the same FrameLayout.
Probably because every FrameLayout have the same id(?) is there any way to solve it?
You have forgotten to commit() your FragmentTransaction.
If you don't commit it, nothing will happen. Android Studio should be warning about this as well.

Errors on Adding ListView to Fragment

I am trying to add a listview to an existing android fragment. I made a layout xml file for items in the listview, modified the previous fragment.xml, wrote a new arrayadapter and added something to the fragment.java. But whenever I call the notifyDataSetChanged() method in the fragment.java, I got an error: android.content.res.Resources$NotFoundException: String resource ID #0x0, and then the app crashes. Below please find my codes.
layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="7dp">
<ImageView
android:layout_width="72dp"
android:layout_height="72dp"
android:id="#+id/iv_checkIcon"
android:layout_margin="7dp"
android:background="#EEEEEE"
android:contentDescription="Provider icon"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_toRightOf="#id/iv_checkIcon"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:layout_marginLeft="5dp"
>
<TextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/tv_checkName"
android:text="Provider name"
android:textSize="20dp"
/>
<TextView
android:layout_width="250dp"
android:layout_height="wrap_content"
android:id="#+id/tv_checkInDate"
android:text="Check In Date"
android:textSize="14dp"
android:textColor="#888888"
android:layout_marginTop="4dp"/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_checkPoints"
android:layout_alignParentRight="true"
android:text="100分"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:textSize="18dp"
android:textColor="#CF1A12"
/>
</RelativeLayout>
fragment.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragment.MeActivity">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/me_bg2"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/fake_head"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:id="#+id/iv_fake_head"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/iv_fake_head"
android:text="--"
android:textSize="22dp"
android:textColor="#ffffff"
android:layout_marginTop="15dp"
android:id="#+id/tv_name"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/tv_name"
android:text="积分"
android:textColor="#ffffff"
android:layout_marginTop="15dp"
android:textSize="20dp"
android:background="#drawable/me_points_bg"
android:id="#+id/tv_points"
/>
</RelativeLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lv_histories"
android:layout_gravity="bottom" />
</FrameLayout>
Arrayadapter.java
public class RecordArrayAdapter extends ArrayAdapter<CheckInRecord.CheckInRec> {
private int resourceId;
private Context context;
private List<CheckInRecord.CheckInRec> checkInRecList;
public RecordArrayAdapter(Context context, int resourceId, List<CheckInRecord.CheckInRec> checkInRecList)
{
super(context, resourceId, checkInRecList);
this.resourceId = resourceId;
this.context = context;
this.checkInRecList = checkInRecList;
}
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(resourceId, parent, false);
}
TextView textViewName = (TextView) convertView.findViewById(R.id.tv_checkName);
TextView textViewCheckInDate = (TextView) convertView.findViewById(R.id.tv_checkInDate);
TextView textViewPoints = (TextView) convertView.findViewById(R.id.tv_checkPoints);
ImageView imageViewIcon = (ImageView) convertView.findViewById(R.id.iv_checkIcon);
CheckInRecord.CheckInRec checkInRec = checkInRecList.get(position);
textViewName.setText(checkInRec.providerName);
textViewCheckInDate.setText(checkInRec.checkInDate);
textViewPoints.setText(checkInRec.providerPoints);
ImageLoader.getInstance().displayImage(checkInRec.providerIcon, imageViewIcon, Utility.displayImageOptions);
return convertView;
}
public int getIsPrize(int position) {return (this.checkInRecList.get(position).isPrize);}
}
fragment.java
public class MeFragment extends Fragment implements ApiRequestDelegate {
private TextView textViewName;
private TextView textViewPoints;
private ProgressDialog progressDialog;
private RecordArrayAdapter recordArrayAdapter;
private List<CheckInRecord.CheckInRec> checkInRecList = new ArrayList<CheckInRecord.CheckInRec>();
public MeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ApiManager.getInstance().checkInHistories(AppDataManager.getInstance().getUserToken(), AppDataManager.getInstance().getUserPhone(),
Utility.getPictureSize(), this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View fragmentView = inflater.inflate(R.layout.fragment_me, container, false);
textViewName = (TextView) fragmentView.findViewById(R.id.tv_name);
textViewPoints = (TextView) fragmentView.findViewById(R.id.tv_points);
ListView listViewRec = (ListView) fragmentView.findViewById(R.id.lv_histories);
recordArrayAdapter = new RecordArrayAdapter(this.getActivity(), R.layout.row_record, checkInRecList);
listViewRec.setAdapter(recordArrayAdapter);
return fragmentView;
}
#Override
public void apiCompleted(ApiResult apiResult, HttpRequest httpRequest) {
if (progressDialog!=null){
progressDialog.dismiss();
}
if (!apiResult.success){
ApiManager.handleMessageForReason(apiResult.failReason, getActivity());
return;
}
CheckInRecord checkInRecord = (CheckInRecord) apiResult.valueObject;
if (checkInRecord != null){
textViewName.setText(checkInRecord.userName);
textViewPoints.setText(String.format("积分%d分", checkInRecord.userPoints));
this.checkInRecList.clear();
this.checkInRecList.addAll(checkInRecord.checkInRecList);
recordArrayAdapter.notifyDataSetChanged();
}
}
}
Make sure checkInRec.providerName, checkInRec.checkInDate and checkInRec.providerPoints values that you set as TextView text have a type of String and cast it to String if it's integer.
// cast to String if checkInRec.checkInDate is integer
textViewPoints.setText(String.valueOf(checkInRec.providerPoints));
UPD:
It seems ListView is located behind header view. Try to change root view of fragment.xml from FrameLayout to LinearLayout with android:orientation="vertical" attribute. Like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".fragment.MeActivity">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/me_bg2"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/fake_head"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:id="#+id/iv_fake_head"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/iv_fake_head"
android:text="--"
android:textSize="22dp"
android:textColor="#ffffff"
android:layout_marginTop="15dp"
android:id="#+id/tv_name"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/tv_name"
android:text="积分"
android:textColor="#ffffff"
android:layout_marginTop="15dp"
android:textSize="20dp"
android:background="#drawable/me_points_bg"
android:id="#+id/tv_points"
/>
</RelativeLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lv_histories"
android:layout_gravity="bottom" />
</LinearLayout>

Android LinearLayout casting in fragment

I'm working with AFreeChart, i'm trying to display a chart inside a fragment. I've been running around in circles for a while, i've seen a couple of posts that looks similar to my problem but i still cant get my head around it.
This is how my onCreateView() in the fragment class Looks like.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_market, container, false);
viewGroup = (ViewGroup) view.findViewById(R.id.marketGraphFrame);
chartView = (ChartView) view;
chartView.drawChart(ChartFactory.createBarChart("Headline","Time", "Value", createDataset(),PlotOrientation.VERTICAL, true, true, false));
viewGroup.addView(chartView);
return view;
}
This is the xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NYSE" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LSE" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OMX" />
<LinearLayout
android:id="#+id/marketGraphFrame"
android:layout_width="wrap_content"
android:layout_height="600dp"
android:orientation="vertical" >
</LinearLayout>
<RadioGroup
android:id="#+id/radio_group_market"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:id="#+id/candleStickMarket"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onRadioButtonChart"
android:text="#string/candle_stick" />
<RadioButton
android:id="#+id/barChartMarket"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onRadioButtonChart"
android:text="#string/bar_chart" />
<RadioButton
android:id="#+id/lineChartMarket"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onRadioButtonChart"
android:text="#string/line_chart" />
</RadioGroup>
<RadioGroup
android:id="#+id/radio_group_time_market"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:id="#+id/thirtydays"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onRadioButtonTime"
android:text="#string/thirty_days" />
<RadioButton
android:id="#+id/oneweek"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onRadioButtonTime"
android:text="#string/one_week" />
<RadioButton
android:id="#+id/oneday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onRadioButtonTime"
android:text="#string/one_day" />
</RadioGroup>
</LinearLayout>
And here is the main part of the error message.
java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to com.example.mercbisandroid.ChartView
please advice.
I got it working with these three lines inside an Activity
viewGroup = (ViewGroup) findViewById(R.id.DiaGroup);
chartView = new ChartView(this);
viewGroup.addView(chartView);
And the ChartView is declared in the class :
ChartView chartView;
I finally managed to get it working. Dont know if its 100% accurate todo it this way but :
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_market, container, false);
viewGroup = (ViewGroup) view.findViewById(R.id.marketGraph);
chartView = new ChartView(getActivity());
chartView.drawChart(ChartFactory.createBarChart("Headline","Time", "Value", createDataset(), PlotOrientation.VERTICAL, true, true, false));
viewGroup.addView(chartView);
return view;
}

Categories