List view does not update at all - android

Hi i am using view pager indicator with three fragments and in one of the i have a list view that show the content of my SQLite Database but when a add data to my table the list view doesn't show he new data that i have added here is my code:
public class caleryhistory extends SherlockListFragment {
List<calery_lagari> Calery_lagari;
calery_lagari_SQLiteData data;
ArrayAdapter<calery_lagari> adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.calery_history, null);
data = new calery_lagari_SQLiteData(getActivity());
data.open();
Calery_lagari = data.findall();
adapter = new ArrayAdapter<calery_lagari>(getActivity(),
R.layout.listback_layout, Calery_lagari);
adapter.notifyDataSetChanged();
setListAdapter(adapter);
adapter.notifyDataSetChanged();
return v;
}
so any help?
Thanks in advance! :)
Update
import java.util.List;
import mr.chag.va.lagar.R;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.actionbarsherlock.app.SherlockListFragment;
public class caleryhistory extends SherlockListFragment {
List<calery_lagari> Calery_lagari;
calery_lagari_SQLiteData data;
ArrayAdapter<calery_lagari> adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.calery_history, null);
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
data = new calery_lagari_SQLiteData(getActivity());
data.open();
Calery_lagari = data.findall();
adapter = new ArrayAdapter<calery_lagari>(getActivity(),
R.layout.listback_layout, Calery_lagari);
adapter.notifyDataSetChanged();
ListView listView = (ListView)view.findViewById(android.R.id.list);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
super.onViewCreated(view, savedInstanceState);
}
}
my layout
<?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:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="clear"
android:text="clear all" />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>

The best way when extending SherlockListFragments is to have onCreateView return the the inflated view, then override onViewCreated. And put your code that changes your view in there.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle b){
return inflater.inflate(R.layout.calery_history, null);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
data = new calery_lagari_SQLiteData(getActivity());
data.open();
Calery_lagari = data.findall();
adapter = new ArrayAdapter<calery_lagari>(getActivity(), view.R.layout.listback_layout, Calery_lagari);
adapter.notifyDataSetChanged();
setListAdapter(adapter);
adapter.notifyDataSetChanged();
}

First problem is that you set adapter in onCreateView. In onCreateView list view is not created yet. Second you need to set adapter to correct list view. Because you override oncreateview you can't use setListAdapter because it's referring to list view from default viet. Try this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.calery_history, null);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
data = new calery_lagari_SQLiteData(getActivity());
data.open();
Calery_lagari = data.findall();
adapter = new ArrayAdapter<calery_lagari>(getActivity(),
view.R.layout.listback_layout, Calery_lagari);
ListView listView = (ListView)view.findViewById(R.id.YOUR_LISTVIEW_ID);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}

You cannot call setListAdapter at this point, as the view is not yet set.
You need to wait until onViewCreated.

Related

spinner in a fragment

Can I use a spinner in a fragment? I want to use a spinner in one of the fragment of my activity to set the time on my countdown timer. All the tutorials and videos I've seen uses activity and not fragment and i'm not sure if its the same way to make a spinner in a fragment.
package com.softeng.applockerproject;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.TimeUnit;
public class page2 extends Fragment {
private static final String TAG = "page2";
private Button btntest;
private TextView timer;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.page2_fragment,container,false);
btntest = (Button) view.findViewById(R.id.button2);
timer = (TextView) view.findViewById(R.id.Timer);
btntest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
countDownTimer.start();
}
});
return view;
}
//timer part
private CountDownTimer countDownTimer = new CountDownTimer(7200000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
long millis= millisUntilFinished;
String hms= String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))
//TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);
timer.setText(hms);
}
#Override
public void onFinish() {
Toast.makeText(getActivity(), "timer stopped",Toast.LENGTH_SHORT).show();
}
};
}
The following is how you'd set a spinner in a fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.manual, container, false);
String [] values =
{"Time at Residence","Under 6 months","6-12 months","1-2 years","2-4 years","4-8 years","8-15 years","Over 15 years",};
Spinner spinner = (Spinner) v.findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, values);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner.setAdapter(adapter);
return v;
}
Replace the layout files with the ones in which you are using, good luck :)
In terms of adding components, Fragments and Activities behave in a similar way. Fragments can be thought of mini-activities with there own lifecycle methods with some additional methods like onCreateView() and onDestroyView(). You can add a spinner to the fragment in the following way:
Here's the code for Fragment's Java File:
public class MainFragment extends Fragment {
// Default Constructor to instantiate a Fragment object
public MainFragment(){
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_fragment,container,false);
Spinner spinner = (Spinner) view.findViewById(R.id.spinner);
// Creating an Array Adapter to populate the spinner with the data in the string resources
ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(getContext(),R.array.spinner_choices
,android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(spinnerAdapter);
return view;
}
}
The code for the layout file used for the Fragment is :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Spinner
android:id="#+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"/>
</LinearLayout>
Now to attach the fragment to an activity the code is as follows:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainFragment fragment = new MainFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().add(R.id.fragment_container,fragment).commit();
}
}
The string resource used to provide the ArrayAdapter with data is in the strings.xml file. It is as follows:
<string-array name="spinner_choices">
<item>Deafult Choice</item>
<item>Choice 1</item>
<item>Choice 2</item>
<item>Choice 3</item>
<item>Choice 4</item>
<item>Choice 5</item>
</string-array>
The only difference between adding a spinner item to a Fragment and an Activity is here:
ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(getContext(),R.array.spinner_choices
,android.R.layout.simple_spinner_item);
In an Activity you would have to replace the getContext() with this or ActivityName.this. Rest of the code will be same.
Note: You should write the code to fetch the Spinner from Fragment Layout file in the onCreateView() method only because it is called before the Parent Activity's onCreate() method to ensure that all views are created before the fragment being attached to the parent activity.
Try this in your fragment to set and use spinner
public class ExamsFragment extends Fragment {
private static final String[] spinner_data= {"Term I", "Term II", "Term III"};
View view;
Spinner mySpinner;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_layout, container, false);
setSpinnerData();
mySpinner.setEnabled(true);
//Setting the UI.
return view;
}
method to initialize spinner and set adapter
private void setSpinnerData() {
mySpinner= (Spinner) getActivity().findViewById(R.id.spinner_sp);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(getActivity(),
R.layout.spinner_item_layout, testTypes);
mySpinner.setAdapter(spinnerAdapter);
}
spinner_item_layout.xml //your spinner item layout
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/white"
android:gravity="start"
android:paddingLeft="#dimen/padding_10"
android:paddingRight="#dimen/padding_10"
android:paddingTop="#dimen/padding_3"
android:paddingBottom="#dimen/padding_3"
android:background="#color/colorPrimary"
android:textSize="16sp"/>
fragment_layout.xml // put this in your main layout
<Spinner
android:id="#+id/spinner_sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold">
</Spinner>

My fragment keeps crashing when it is being refreshed

I want to refresh the fragment on a button click - i.e, destroy the fragment and force recall on onCreateView() method. However, it keeps crashing because of a GRRRR NullPointerException on the line fragment.getFragmentManager().findFragmentByTag("Frag1");
This is my code:
import android.app.ProgressDialog;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class UserListRecycler extends Fragment {
RecyclerView recyclerView;
static UserAdapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<UserInfo> list;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.userlistGUI, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.reUsers);
recyclerView.setHasFixedSize(true);
list = new ArrayList<UserInfo>();
// Instantiate new adapter here
adapter = new MusicRecyclerAdapter(list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
// Sets the adapter here
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return rootView;
}
#Override
public void onStart() {
super.onStart();
populateRecyclerList();
}
public void populateList(){
PopulateUsers userList = new PopulateUsers(list, adapter, recyclerView);
userList.execute();
}
public void recallFragment(){
Fragment fragment = null;
fragment.getFragmentManager().findFragmentByTag("TabOne");
getFragmentManager().beginTransaction()
.detach(fragment)
.attach(fragment)
.commit();
}
}
It is the recallFragment() method that is causing the issue. I want to recall on onCreateView() as that would physically refresh the fragment and redisplay the recyclerview. It is getting NullPointerException on fragment.getFragmentManager().findFragmentByTag("TabOne");. This is my stack trace:
java.lang.NullPointerException
at lukazs.usersapp.UserListRecycler.recallFragment()(TabOne.java:160)
at lukazs.usersapp.UserListRecycler$RecommendUser.onPostExecute(TabOne.java:300)
at lukazs.usersapp.UserListRecycler$RecommendUser.onPostExecute(TabOne.java:306)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
This is my onCreateView() method:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.userlistGUI, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.reUsers);
recyclerView.setHasFixedSize(true);
list = new ArrayList<UserInfo>();
// Instantiate new adapter here
adapter = new MusicRecyclerAdapter(list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
// Sets the adapter here
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return rootView;
}
UPDATED 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:id="#+id/rLayouts">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listFrag"
class="lukazs.usersapp.UserListRecycler"/>
<view
android:layout_width="wrap_content"
android:layout_height="wrap_content"
class="android.support.v4.view.ViewPager"
android:id="#+id/viewPager"
android:layout_alignParentStart="true" />
<android.support.v7.widget.RecyclerView
android:id="#+id/usersList"
android:layout_width="match_parent"
android:layout_height="420dp"
android:layout_gravity="center_horizontal|top"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"></android.support.v7.widget.RecyclerView>
</RelativeLayout>
Fragment fragment = new WhatEverFragmentClassYouHave();
You set your fragment to null that is why you have a null exception.
If you're going to detach and then attach something. Just call replace() if you know how to use it.
<fragment
android:id="#+id/article_fragment"
android:layout_weight="2"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.example.android.fragments.ArticleFragment"
/>
For the Refresh
public void recallFragment(){
Fragment fragment = new WhatEverFragmentClass();
getFragmentManager().beginTransaction().replace(R.id.article_fragment,fragment,"MyFragmentTag").commit();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.userlistGUI, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclerView = (RecyclerView) rootView.findViewById(R.id.reUsers);
recyclerView.setHasFixedSize(true);
list = new ArrayList<UserInfo>();
// Instantiate new adapter here
adapter = new MusicRecyclerAdapter(list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
// Sets the adapter here
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
Instead of detaching and attaching the fragment, you should either have an API in your fragment that tells it to refresh its content, or you should create a new instance of the fragment and replace the existing instance with the new one. Telling the fragment to refresh itself is obviously more efficient than destroying and creating a new fragment.

Android ListView displays nothing but doesn't crash

I followed all the steps from various sources for getting listviews to work but my one
doesn't seem to display anything. This list view code(shown below) is activated with a tab fragment manager I won't put that here as to not bog you all down with code as there's a lot here already. It is most likely a problem with the ListFragment itself but I suppose it could be the adapter.
What happens is nothing gets displayed at all just the searchview that I have put in the main xml layout. I can switch freely between tabs with no crashes but just nothing displays in any of my listviews. I have another list which is a friends list(not included in this code snippet) and that uses a generic view holder interface and that one does not work either which suggests the problem is most likely in my ListFragment but I just can't pinpoint it. Any help is appreciated and I hope some can learn something from this, Thank you.
This is my adapter for the settings category list
package codeblox.com.listfragmentexample;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;
import java.util.ArrayList;
import codblox.com.listfragmentexample.R;
public class SettingsAdapter extends ArrayAdapter<Settings.SettingsCategories>
{
private final Activity context;
String[] text;
ArrayList<Settings.SettingsCategories> itemsCopy;
class ViewHolder
{
public TextView txt;
public CheckBox state;
public ImageView settingImg;
public EditText input;
public ToggleButton toggle;
public Button settingInfo; // click it to show what the setting does
}
public SettingsAdapter(Context context, ArrayList<Settings.SettingsCategories> items)
{
super(context, R.layout.settings_category_row, items);
this.context = (Activity) context;
this.itemsCopy = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = new ViewHolder();
int viewType = this.getItemViewType(position);
if(convertView == null)
{
// inflate the GridView item layout
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.settings_category_row, parent, false);
// initialize the view holder
holder = new ViewHolder();
holder.settingImg = (ImageView) convertView.findViewById(R.id.settingCategoryImg);
holder.txt = (TextView) convertView.findViewById(R.id.settingCategoryName);
convertView.setTag(holder);
} else {
// recycle the already inflated view
holder = (ViewHolder) convertView.getTag();
}
// fill data
holder = (ViewHolder) convertView.getTag();
String s = getItem(position).toString();
holder.txt.setText(itemsCopy.get(position).getSettingText());
holder.settingImg.setImageResource(itemsCopy.get(position).getImgResId());
return convertView;
}
}
This is my list fragment
package codeblox.com.listfragmentexample
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import codeblox.com.listfragmentexample.R;
public class Settings extends ListFragment implements View.OnLongClickListener
{
private ListView settingsList;
private ArrayList<SettingsCategories> mItems;
private ArrayAdapter<SettingsCategories> settingsAdapter;
private int numCategories;
String[] CategoryArray = new String[] {"Privacy and Security","Account","Networks","Camera Options","Storage","Accesibility","Features"};
int[] resIds = new int[] {R.drawable.security_settings_icon,R.drawable.account_settings_icon,
R.drawable.network_settings_icon,R.drawable.camera_settings_icon,R.drawable.storage_settings_icon,
R.drawable.accessibility_settings_icon,R.drawable.feature_settings_icon,};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View settingsView = inflater.inflate(R.layout.settings, container, false);
settingsList = (ListView)settingsView.findViewById(android.R.id.list);
// initialize the items list
return settingsView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
// remove the dividers from the ListView of the ListFragment
settingsList = getListView();
settingsList.setDivider(null);
mItems = new ArrayList<SettingsCategories>();
Resources resources = getResources();
for(int c = 0; c < numCategories; c++)
{
mItems.add(new SettingsCategories(CategoryArray[c],resIds[c]));
}
// initialize and set the list adapter
// settingsAdapter = new SettingsAdapter(this.getActivity(), mItems);
setListAdapter(new SettingsAdapter(getActivity(), mItems));
settingsList.setAdapter(settingsAdapter);
}
public Settings()
{
this.numCategories = CategoryArray.length;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public boolean onLongClick(View v)
{
return false;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
Object i = l.getItemAtPosition(position);
}
public class SettingsCategories
{
private String settingText;
private int imgResId;
SettingsCategories(String settingText,int imgResId)
{
this.settingText = settingText;
this.imgResId = imgResId;
}
public String getSettingText()
{
return this.settingText;
}
public int getImgResId()
{
return this.imgResId;
}
}
}
and finally these are my xml layouts (the first one is the main view and the second one is the view of a single item in the list
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<SearchView
android:id="#+id/searchFunction"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</SearchView>
<ListView
android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>
</RelativeLayout>
this represents an individual item in the list
<?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"
>
<ImageView
android:layout_width="52dp"
android:layout_height="52dp"
android:id="#+id/settingCategoryImg"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="52dp"
android:text=""
android:id="#+id/settingCategoryName"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/settingCategoryImg"
/>
</RelativeLayout>
You are setting null adapter so it is not refreshing.
you are commented initialization part
check in the following method:
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
// remove the dividers from the ListView of the ListFragment
settingsList = getListView();
settingsList.setDivider(null);
mItems = new ArrayList<SettingsCategories>();
Resources resources = getResources();
for(int c = 0; c < numCategories; c++)
{
mItems.add(new SettingsCategories(CategoryArray[c],resIds[c]));
}
// initialize and set the list adapter
// settingsAdapter = new SettingsAdapter(this.getActivity(), mItems);
setListAdapter(new SettingsAdapter(getActivity(), mItems));
settingsList.setAdapter(settingsAdapter);
}
Your are using ListFragement and again inflating layout. that is not a good idea. when you are extending listfragment then inflating the layout is not required and and modify above method like:
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
// remove the dividers from the ListView of the ListFragment
settingsList = getListView();
settingsList.setDivider(null);
mItems = new ArrayList<SettingsCategories>();
Resources resources = getResources();
for(int c = 0; c < numCategories; c++)
{
mItems.add(new SettingsCategories(CategoryArray[c],resIds[c]));
}
// initialize and set the list adapter
settingsAdapter = new SettingsAdapter(this.getActivity(), mItems);
//setListAdapter(new SettingsAdapter(getActivity(), mItems));
settingsList.setAdapter(settingsAdapter);
}

Passing data from ListView to Fragment

I have a ListView in my fist screen that shows some information. When I click on each item, I have another listView with new information and textview in the same page, I want to show the pervious list view row in text view,
would you please let me know how can I implement this,
Thanks in advance!
here is my xml file
<RelativeLayout 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="######">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:visibility="gone"
android:text="test" />
<TextView
android:id="#+id/list_textview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
android:text="#string/no_message"
android:textColor="#000000"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Medium"
android:gravity="center"></TextView>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView" />
</LinearLayout>
Here is my java file that shows the listview and
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
listView = (ListView)view.findViewById(R.id.listView);
listView.setOnItemClickListener(this);
getActivity().getActionBar().setTitle(R.string.title_forms);
TextView details = (TextView)view.findViewById(R.id.detail_header);
details.setVisibility(View.VISIBLE);
return view;
}
Here is one of my fragment that has onItemClick Listener
public class ListFragment extends Fragment implements AdapterView.OnItemClickListener {
public static final String TAG = "ListFragment";
private ListView listView;
private ArrayList<String> testIds;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
tripIds = new ArrayList<String>();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
listView = (ListView) view.findViewById(R.id.listView);
listView.setOnItemClickListener(this);
registerForContextMenu(listView);
return view;
}
Here is my onItemClick :
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
chooseTest(testIds.get(position));
String selectedTestId = testIds.get(position);
Helpers.saveToSharedPreferences(getActivity(),
Constants_Prefs.SELECTED_TOP_LEVEL_RECORD,
Constants_Keys.SELECTED_TEST_ID,
selectedTestId);
I don't know how can I get that information
FormTypeListFragment passDataTo = new FormTypeListFragment();
Bundle bundle = new Bundle();
bundle.putString("DATA", selectedTestId);
passDataTo.setArguments(bundle);
}
Before launching your fragment to display selected item use setArguments() method to add key value pair of string in your case, Then in your fragment on createView use fragments method getArguments() to retain your passed string
Pass the value in bundle as :
Set :
YourFragment fragmnt = new YourFragment ();
Bundle bundle = new Bundle();
bundle.putString("item","name");
fragmnt.setArgument(bundle);
Get :
Then in your Fragment, retrieve the data (e.g. in onCreate()) with:
Bundle bundle = this.getArguments();
String myValue = bundle.getInt("item", "");

Android + ListFragment with a custom view hierarchy

I'm attempting to customize the fragment layout by returning my own view hierarchy from onCreateView(LayoutInflater, ViewGroup, Bundle). This inflates my custom view, but seems to stack the views instead of inflating within, I see everything at once. Any help is appreciated.
MyActivity.java:
public class MyActivity extends FragmentActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) {
ArrayListFragment list = new ArrayListFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, list).commit();
}
}
public static class ArrayListFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
inflater.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.main, container);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String List[] = {"Larry", "Moe", "Curly"};
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, List));
}
}
}
main.xml
<?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:paddingLeft="8dp"
android:paddingRight="8dp">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="THIS IS A BUTTON" />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FF00"
android:layout_weight="1"
android:drawSelectorOnTop="false" />
<TextView
android:id="#android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"
android:text="No data" />
</LinearLayout>
I wasn't returning the new view within the onCreateView method of the ListFragment class. For instance:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main, null);
return view;
}
All works well now in the land of Android!
I think you'd better
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.main, container, false);
return root;
}
optimized way and shot code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.list_alphabet, container, false);
}
getSupportFragmentManager().beginTransaction().add(android.R.id.content, list).commit();
List is not accepted, it's looking for a fragment.
use this pattern, works perfectly!
inflater.inflate(R.layout.list_layout, container, false);
public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot)
attachToRoot Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML.

Categories

Resources