Android - List items do not refresh immediately - android

I created a class activity after which inherit two activity. It looks as follows:
public abstract class VlcMediaPlayerList extends RoboActivity {
public final static int AUDIO = 1;
public final static int VIDEO = 2;
#InjectView(R.id.audio_list_view)
ListView listView;
public static ArrayList<ImageWithTwoText> list = new ArrayList<ImageWithTwoText>();
public ImageWithTwoTextArrayAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vlc_media_player_list);
adapter = new ImageWithTwoTextArrayAdapter(this, list);
listView.setAdapter(adapter);
addListenerOnItemList();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (intent != null) {
Bundle extras = intent.getExtras();
ImageWithTwoText file = null;
try {
file = (ImageWithTwoText) extras.getSerializable(FileChooserAcitivity.FILE_TYPE);
} catch (NullPointerException ex) {
}
Log.i("FILECHOOSER", String.valueOf(list.size()));
if (file != null) {
list.add(file);
}
adapter.notifyDataSetChanged();
}
}
/**
* Add File method called when addButton is clicked. Start activity
* FileChooserActivity for result as file
*
* #param ImageButton
* view
*/
public void addFile(View view) {
Intent intent = new Intent(this, FileChooserAcitivity.class);
intent.putExtra(FileChooserAcitivity.FILE_TYPE, getMediaType());
startActivityForResult(intent, getMediaType());
}
/**
* Clear the list when clearButton is clicked
*
* #param View
* view
*/
public void clearList(View view) {
list.clear();
adapter.notifyDataSetChanged();
Toast.makeText(this, getResources().getString(R.string.clear_list), Toast.LENGTH_SHORT).show();
}
/**
* Add listener on list
*/
public void addListenerOnItemList() {
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(view.getContext(),
PlayerActivity.class);
intent.putExtra(PlayerActivity.PLAYER_ELEMENT,
list.get(position).getTitle());
startActivity(intent);
}
});
}
protected abstract int getMediaType();
}
One class that extends the abstract class as follows:
public class VlcMediaPlayerAudio extends VlcMediaPlayerList {
#Override
protected int getMediaType() {
return VlcMediaPlayerList.AUDIO;
}
}
The problem occurs after calling onActivityResult () which is taken ImageWithTwoText object representing the element of the list. After calling adapter.notifyDataSetChanged (), this element is not added to the list.
Note! After exiting the activity (the return key) and re-entry to the same activity previously added element is already in the list
This is code for ImageWithTwoTextArrayAdapter:
public class ImageWithTwoTextArrayAdapter extends ArrayAdapter<String> {
public final static String TITLE_KEY = "title";
public final static String SUBTITLE_KEY = "subtitle";
public final static String IMAGE_RESOURCE_KEY = "imageResources";
private final List<ImageWithTwoText> imageWithTwoTextList;
private final Context context;
/**
* Class constructor
*
* #param context
*/
public ImageWithTwoTextArrayAdapter(Context context, List<ImageWithTwoText> imageWithTwoTextList) {
super(context, R.layout.row_view, getArrayListOfTitles(imageWithTwoTextList));
this.context = context;
this.imageWithTwoTextList = imageWithTwoTextList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.row_view, parent, false);
TextView titleView = (TextView) rowView.findViewById(R.id.title);
TextView subTitleView = (TextView) rowView.findViewById(R.id.subtitle);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
ImageWithTwoText currentElement = imageWithTwoTextList.get(position);
titleView.setText(currentElement.getTitle());
subTitleView.setText(currentElement.getSubTitle());
imageView.setImageResource(currentElement.getImageResource());
return rowView;
}
private static List<String> getArrayListOfTitles(List<ImageWithTwoText> imageWithTwoTextList) {
List<String> listOfTitles = new ArrayList<String>();
for (ImageWithTwoText imageWithTwoText : imageWithTwoTextList) {
listOfTitles.add(imageWithTwoText.getTitle());
}
return listOfTitles;
}
}

I think the problem is in your constructor for the adapter, you are calling the base constructor like this:
super(context, R.layout.row_view, getArrayListOfTitles(imageWithTwoTextList));
This is passing the result of
getArrayListOfTitles()
to the underlying list stored by the adapter, which is a copy of your provided list. This means that changes you make to the list in the activity are not being made to the copy of the list held by the adapter.
Ahh, your comment beat my edit by about a minute! Glad it is solved!

Related

How to Switch Activities using a Custom ListView Adapter?

I'm trying to use a Custom ListView Adapter to switch to different activities, but am having trouble doing so, as there is an error that I can't seem to get rid of.
Relevant code
Category Table:
public class CategoryTable extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_table);
populateTable();
goToPreviousActivity();
}
private void populateTable() {
final ListView mListView = findViewById(R.id.listView);
Category 1 = new Category(" One");
Category 2 = new Category(" Two");
Category 3 = new Category(" Three");
Category 4 = new Category(" Four");
final ArrayList<Category> categoryList = new ArrayList<>();
categoryList.add(1);
categoryList.add(2);
categoryList.add(3);
categoryList.add(4);
CategoryListAdapter adapter = new CategoryListAdapter(this, R.layout.adapter_view_layout, categoryList);
mListView.setAdapter(adapter);
}
private void goToPreviousActivity() {
ImageButton btn = findViewById(R.id.backButton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
public static Intent makeIntent(Context context) {
return new Intent(context, CategoryTable.class);
}
}
Category List Adapter:
public class CategoryListAdapter extends ArrayAdapter<Category> {
private Context mContext;
int mResource;
public CategoryListAdapter(Context context, int resource, ArrayList<Category> objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
}
#NonNull
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
String name = getItem(position).getName();
Category category = new Category(name);
final LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
Button catName = convertView.findViewById(R.id.btnNextTbl);
catName.setText(name);
catName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (position == 0) {
//error -> makeIntent(android.content.Context in AllToolsTable cannot be applied to com.test.test.CategoryListAdapter
Intent intent = AllToolsTable.makeIntent(CategoryListAdapter.this);
mContext.startActivity(intent);
} else {
Toast toast = Toast.makeText(getContext(), "Clicked2", Toast.LENGTH_SHORT);
toast.show();
}
}
});
return convertView;
}
}
(I commented above the erroneous piece of code)
All Tools Table:
public class AllToolsTable extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_tools_table);
}
public static Intent makeIntent(Context context) {
return new Intent(context, AllToolsTable.class);
}
}
I will provide any other relevant code/details if needed.
Any help will be greatly appreciated.
//error -> makeIntent(android.content.Context in AllToolsTable cannot be applied to com.test.test.CategoryListAdapter
Intent intent = AllToolsTable.makeIntent(CategoryListAdapter.this);
Your AllToolsTable.makeIntent() method requires a Context argument. Normally you'd be fine with something like AllToolsTable.makeIntent(MainActivity.this) because Activity is a subclass of Context. However, CategoryListAdapter is not.
So you need to get your hands on a Context object somehow.
Luckily, the getView() method passes you a non-null ViewGroup parent object, and all views have a context. So you can replace your intent creation with this code:
Context context = parent.getContext();
Intent intent = AllToolsTable.makeIntent(context);

Android Listview does not refresh/redraw

Problem - I have list of in app purchases loaded from app store in a Listview.
When user purchases (taps on a button in listview) the item is purchased and the button should be now hidden and the list item purchased should show an image of tick.
What I have tried -
Refresh the listview after item is purchased by calling notifyDataSetChanged
Set the visibility of the button and image using View.GONE and View.VISIBLE
None of the above seems to work.
I am using this in app billing library
public class ListViewAdapter extends ArrayAdapter<Product> {
private ArrayList<Product> iapProducts= new ArrayList<>();
private final LayoutInflater inflater;
private final Activity activity;
public ArrayList<Product> getIapProducts() {
return iapProducts;
}
public void setIapProducts(ArrayList<Product> iapProducts) {
this.iapProducts = iapProducts;
}
public ListViewAdapter(final Activity context) {
super(context, 0);
inflater = LayoutInflater.from(context);
this.activity = context;
}
#Override
public int getCount() {
return this.iapProducts.size();
}
public String getItem(String position) {
return position;
}
#Override
public boolean hasStableIds(){
return true;
}
public void addAll(ArrayList<Product> iapProducts){
this.iapProducts.addAll(iapProducts);
notifyDataSetChanged();
}
public static class ViewHolder {
public TextView name;
public ImageView imageView;
public Button purchaseButton;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(R.layout.names_filter_row, null);
holder = new ViewHolder();
holder.name = (TextView) vi.findViewById(R.id.languageName);
holder.imageView = (ImageView) vi.findViewById(R.id.imgTick);
holder.purchaseButton = (Button) vi.findViewById(R.id.iapProductPurchaseBtn);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
final Product product = iapProducts.get(position);
holder.name.setText(product.getTitle());
holder.purchaseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemPurchased(v);
}
});
holder.iapProductId.setText(product.getProductId());
holder.purchaseButton.setText(product.getPriceText());
holder.imageView.setVisibility(View.GONE);
if(product.isPurchased()){
holder.purchaseButton.setVisibility(View.GONE);
holder.imageView.setVisibility(View.VISIBLE);
}else{
holder.purchaseButton.setVisibility(View.VISIBLE);
holder.imageView.setVisibility(View.GONE);
}
return vi;
}
private void onItemPurchased(View v){
final RelativeLayout parentLayout = (RelativeLayout)v.getParent();
final TextView productId = (TextView)parentLayout.findViewById(R.id.iapProductId);
final ImageView languageCheck = (ImageView)parentLayout.findViewById(R.id.imgTick);
PurchaseActivity purchaseActivity = (PurchaseActivity) this.activity;
purchaseActivity.purchaseItem(productId.getText().toString(), v);
}
}
public class PurchaseActivity extends AppCompatActivity implements BillingProcessor.IBillingHandler {
private BillingProcessor bp;
boolean isOneTimePurchaseSupported;
private ArrayList<Product> productsToPurchase = new ArrayList<>();
private final static String TAG = PurchaseActivity.class.getName();
private ListViewAdapter adapter;
private ImageView imageTick;
private Button buttonPurchase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_purchase);
bp = BillingProcessor.newBillingProcessor(this, "billingKey", this); // doesn't bind
bp.initialize(); // binds
adapter = new ListViewAdapter(this);
nameFilterListView.setAdapter(adapter);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (!bp.handleActivityResult(requestCode, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
public void onBillingInitialized() {
isOneTimePurchaseSupported = bp.isOneTimePurchaseSupported();
if(isOneTimePurchaseSupported){
loadIAPData(false);
}else{
Toast.makeText(this,"Billing not supported",Toast.LENGTH_LONG).show();
}
}
private void loadIAPData(boolean showProgressDialog){
bp.loadOwnedPurchasesFromGoogle();
final List<SkuDetails> productDetails = bp.getPurchaseListingDetails(productList);
if(productDetails!= null && !productDetails.isEmpty()){
//fetch products and add to the list
productsToPurchase.add(product);
}
//add all the products to adapter
adapter.addAll(productsToPurchase);
}
}
public void purchaseItem(#NonNull final String productId, final View imageTick, final View button){
this.imageTick = (ImageView) imageTick;
this.buttonPurchase = (Button) button;
bp.purchase(this,productId);
}
#Override
public void onProductPurchased(String productId, TransactionDetails details) {
//hide button show image
this.imageTick.setVisibility(View.VISIBLE);
this.buttonPurchase.setVisibility(View.GONE);
adapter.setIapProducts(new ArrayList<>(productsToPurchase));
adapter.notifyDataSetChanged();
}
}
(Moved comment into a post)
After a user purchases something, is that Product within productsToPurchase updated? The adapter looks okie so maybe the list you're using isn't being updated after a purchase.
I'm assuming you need to flip the isPurchased flag of the Product in onProductPurchased() using the provided productId.

StartActivityForResult to update a row in a ListView

I've the following Activity that uses a ListView to display a list of subjects. Each row has a textview which is set to red to indicate the question for that subject has not yet been answered. When the user clicks on a row it should launch an Activity that asks a question on that subject.
I want to launch the Activity by calling startActivityForResult, this will update the row with the fact the question has been asked and turn the textview green.
My question is how to update a particular row in the listview from onActivityResult?
public class QuestionListForInTransaction extends ActionBarActivity {
ListView listView;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.questionlistforintxlayout);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.drawable.ic_launcher);
setTitle("Call Question(s)");
listView = (ListView)findViewById(R.id.txinquestionlist);
String[] values = new String[] { "Are you the driver?", "Question 2", "Question 3", };
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this, values);
listView.setAdapter(adapter);
listView.setOnItemClickListener(listener);
}//end of onCreate
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public MySimpleArrayAdapter(Context context, String[] values) {
super(context, R.layout.questionlisttxinrowlayout, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.questionlisttxinrowlayout, parent, false);
TextView question = (TextView) rowView.findViewById(R.id.tvquestionforintx);
question.setText(values[position]);
TextView answered = (TextView) rowView.findViewById(R.id.rowstatusbox);
answered.setBackgroundColor(Color.RED);
String questionStr = values[position];
rowView.setTag(questionStr);
return rowView;
}
} //end of adapter class
OnItemClickListener listener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(QuestionListForInTransaction.this, "pos = " + position, Toast.LENGTH_LONG).show();
String question = (String)view.getTag();
if(question.equalsIgnoreCase("Are you the driver?")){
//Toast.makeText(QuestionListForInTransaction.this, "Are you the driver?" + position, Toast.LENGTH_LONG).show();
final int QUESTION_REQUEST = 1;
Intent questionIntent = new Intent(QuestionListForInTransaction.this, Question.class);
startActivityForResult(questionIntent, QUESTION_REQUEST);
//TextView answered = (TextView) view.findViewById(R.id.rowstatusbox);
//answered.setBackgroundColor(Color.GREEN);
}
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
super.onActivityResult(requestCode, resultCode, intent);
Bundle extras = intent.getExtras();
if(extras != null)
int result = extras.getInt("result");
//*********************update a row green**********************
}
} //end of class
Just Create some custom wrapper class like this:
public class QuestionWrapper {
private String mQuestionText;
private boolean mIsAsked;
public QuestionWrapper(String defaultQuestionText, boolean isAsked) {
mQuestionText = defaultQuestionText;
mIsAsked = isAsked;
}
public boolean isAsked() {
return mIsAsked;
}
public void setIsAswked(boolean isAsked) {
mIsAsked = isAsked;
}
public String getQuestionText() {
return mQuestionText;
}
}
then you need to set List of this wrappers to Adapter:
public class QuestionListForInTransaction extends ActionBarActivity {
List<QuestionWrapper> mWrappers = new ArrayList<>();
MySimpleArrayAdapter mAdapter;
....
public void onCreate(Bundle icicle) {
....
wrappers.add(new QuestionWrapper("Are you the driver?",false));
wrappers.add(new QuestionWrapper("Question 2",false));
wrappers.add(new QuestionWrapper("Question 3",false));
mAdapter = new MySimpleArrayAdapter(this, wrappers);
....
and Update Your Adapter like this:
public class MySimpleArrayAdapter extends ArrayAdapter<QuestionWrapper> {
private final Context context;
private final List<QuestionWrapper> mWrappers;
public MySimpleArrayAdapter(Context context, List<QuestionWrapper> wrappers) {
super(context, R.layout.questionlisttxinrowlayout, wrappers);
this.context = context;
this.mWrappers = wrappers;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.questionlisttxinrowlayout, parent, false);
QuestionWrapper wrapper = mWrappers.get(position);
TextView question = (TextView) rowView.findViewById(R.id.tvquestionforintx);
question.setText(wrapper.getQuestionText());
TextView answered = (TextView) rowView.findViewById(R.id.rowstatusbox);
if (wrapper.isAsked()) {
answered.setBackgroundColor(Color.GREEN);
} else {
answered.setBackgroundColor(Color.RED);
}
rowView.setTag(wrapper.getQuestionText());
return rowView;
}
onActivityResult - Need to update your wrapper class and adpater:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
super.onActivityResult(requestCode, resultCode, intent);
....
mWrappersList.get(yourPosition).setAsked(true/false);
if (mAdapter!=null){
mAdapter.notifyDataSetChanged();
}
...
}
I think for RequestCode in startActivityForResult you can use Adapter click position.

Android Adding OnClickListener to listview

I have been trying to create a settings app for my new rom called "ProtoType" and i am trying to add an OnClickListener to my listview but i cant find the appropriate way to do so and as a result i have turned to here for help and i was wondering if anybody can show me how i'll post my activity below and thanks.
package fr.xgouchet.tuto.switchpreferences;
import java.util.ArrayList;
import java.util.List;
import android.preference.PreferenceActivity;
import android.widget.ListAdapter;
public class MyPrefsActivity extends PreferenceActivity {
private List<Header> mHeaders;
protected void onResume() {
super.onResume();
setTitle("Settings");
if (getListAdapter() instanceof MyPrefsHeaderAdapter)
((MyPrefsHeaderAdapter) getListAdapter()).resume();
}
protected void onPause() {
super.onPause();
if (getListAdapter() instanceof MyPrefsHeaderAdapter)
((MyPrefsHeaderAdapter) getListAdapter()).pause();
}
public void onBuildHeaders(List<Header> target) {
// Called when the settings screen is up for the first time
// we load the headers from our xml description
loadHeadersFromResource(R.xml.my_prefs_headers, target);
mHeaders = target;
}
public void setListAdapter(ListAdapter adapter) {
int i, count;
if (mHeaders == null) {
mHeaders = new ArrayList<Header>();
// When the saved state provides the list of headers,
// onBuildHeaders is not called
// so we build it from the adapter given, then use our own adapter
count = adapter.getCount();
for (i = 0; i < count; ++i)
mHeaders.add((Header) adapter.getItem(i));
}
super.setListAdapter(new MyPrefsHeaderAdapter(this, mHeaders));
}
}
On PreferenceActivity listView is hiddent behind getListView();
The simpliest example:
ListView listView = getListView();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View view, int i, long l) {
Toast.makeText(Activity.this, "myPos "+i, Toast.LENGTH_LONG).show();
}
});
Code will look like
package fr.xgouchet.tuto.switchpreferences;
import java.util.ArrayList;
import java.util.List;
import android.preference.PreferenceActivity;
import android.widget.ListAdapter;
public class MyPrefsActivity extends PreferenceActivity {
private List<Header> mHeaders;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView listView = getListView();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View view, int i, long l) {
Toast.makeText(Activity.this, "myPos "+i, Toast.LENGTH_LONG).show();
}
});
}
protected void onResume() {
super.onResume();
setTitle("Settings");
if (getListAdapter() instanceof MyPrefsHeaderAdapter)
((MyPrefsHeaderAdapter) getListAdapter()).resume();
}
protected void onPause() {
super.onPause();
if (getListAdapter() instanceof MyPrefsHeaderAdapter)
((MyPrefsHeaderAdapter) getListAdapter()).pause();
}
public void onBuildHeaders(List<Header> target) {
// Called when the settings screen is up for the first time
// we load the headers from our xml description
loadHeadersFromResource(R.xml.my_prefs_headers, target);
mHeaders = target;
}
public void setListAdapter(ListAdapter adapter) {
int i, count;
if (mHeaders == null) {
mHeaders = new ArrayList<Header>();
// When the saved state provides the list of headers,
// onBuildHeaders is not called
// so we build it from the adapter given, then use our own adapter
count = adapter.getCount();
for (i = 0; i < count; ++i)
mHeaders.add((Header) adapter.getItem(i));
}
super.setListAdapter(new MyPrefsHeaderAdapter(this, mHeaders));
}
}
I think it should be implemented in your adapter. This is example of a custom adapter. You can specify settings and listeners for elements in items.
/** Provides the custom adapter for views of words */
private class WordAdapter extends ArrayAdapter<DTOWord> {
Context context;
int layoutResourceId;
ArrayList<DTOWord> wordsArray;
/** Set up words data */
public WordAdapter(Context context, int layoutResourceId,
ArrayList<DTOWord> words)
{
super(context, layoutResourceId, words);
this.context = context;
this.layoutResourceId = layoutResourceId;
this.wordsArray = words;
}
#Override
/** Returns a view with a word */
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
if (row == null)
{
LayoutInflater inflater = ((Activity) context).
getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
}
return this.getView(row, this.wordsArray.get(position));
}
/** Set up the view of the word with specified data */
private View getView(View wordView, final DTOWord wordData)
{
View container = (View) wordView.findViewById(R.id.
layout_wordData);
TextView title = (TextView) wordView.findViewById(R.id.
textView_word);
Button btnEditWord = (Button) wordView.findViewById(R.id.
btn_wordEdit);
this.setEditListener(btnEditWord, wordData);
return wordView;
}
/** Set action which switches to the edition view of the selected word */
private void setEditListener(Button btnEditWord, final DTOWord wordData) {
btnEditWord.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(WordAdapter.this.context,
AddWord.class);
i.putExtra("word-name", wordData.getWord());
i.putExtra("word-language", wordData.getLanguage().
getName());
startActivity(i);
}
});
}
}

How to create a Multilevel list using listview

The following is my Json data from database, i want to list the interest_name in a list(only if visible is true). List must be multilevel. I parsed the json file using Gson library. But i have no idea regarding how to make a multilevel list using listview.
{"interest_id":0,"interest_name":"ROOT","visible":false,"children":
[{"interest_id":1,"interest_name":"Sports","visible":true,"children":[{"interest_id":2,"interest_name":"Archery","visible":true,"children":[]},{"interest_id":3,"interest_name":"Bow Hunting","visible":true,"children":[]}]},{"interest_id":100,"interest_name":"Contry","visible":true,"children":[{"interest_id":101,"interest_name":"Afghanistan","visible":true,"children":[]},{"interest_id":102,"interest_name":"Akrotiri","visible":true,"children":[]}]},{"interest_id":1000,"interest_name":"Education","visible":true,"children":[]},{"interest_id":1200,"interest_name":"Entertainment","visible":true,"children":[]},{"interest_id":1400,"interest_name":"Books","visible":true,"children":[]},{"interest_id":1600,"interest_name":"Services","visible":true,"children":[]},{"interest_id":1800,"interest_name":"Fitness","visible":true,"children":[]},{"interest_id":2000,"interest_name":"Fashion","visible":true,"children":[]},{"interest_id":99999,"interest_name":"Near Me","visible":false,"children":[]}]}
My code:
Home.java
Intent intent = new Intent( Home.this,InterestAddList.class);
startActivity(intent);
finish();
InterestAddList.java
public class InterestAddList extends Activity {
ListView intrestListView;
OneOnOneListAdapter adapter;
List<String> intrestList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.intrest_add);
intrestListView = (ListView) findViewById(R.id.InterestList);
//Service Called For retrieving Data
retrieveList();
}
public void retrieveList() {
intrestList = new ArrayList<String>();
StringBuilder urlc = new StringBuilder(urlPrefix + "gai");
String url=urlc.toString();
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
String result = ServiceClient.getInstance().getResponse(url);
InterestNode ni=gson.fromJson(result, InterestNode.class);
//for(int i=0;i<ni.length;i++){
//Log.e("ni", ni.getInterestName());
//Log.e("ni", String.valueOf(ni.getInterestId()));
/* how to display interest name */
intrestList.add(ni.getInterestName());
}
adapter = new OneOnOneListAdapter(InterestAddList.this,R.layout.intrest_add_row,intrestList);
intrestListView.setAdapter(adapter);
}
private class OneOnOneListAdapter extends ArrayAdapter {
public OneOnOneListAdapter(Context context, int textViewResourceId,
List objects) {
super(context, textViewResourceId, objects);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final int aposition=position;
if (v == null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.intrest_add_row, null);
}
TextView intrestText =(TextView)v.findViewById(R.id.IntrestText);
intrestText.setText(intrestList.get(aposition).toString());
v.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
System.out.println("OnItem CLicked");
Toast.makeText(InterestAddList.this,"Position clicked:"+intrestList.get(aposition).toString(),Toast.LENGTH_SHORT).show();
Intent i = new Intent(InterestAddList.this,SubIntrestAddList.class);
i.putExtra("position", aposition);
startActivityForResult(i,1);
}
});
return v;
}
}}
InterestNode.java
public class InterestNode {
#SerializedName("interest_id")
int interestId;
#SerializedName("interest_name")
String interestName;
#SerializedName("visible")
boolean isVisible;
transient InterestNode parent;
#SerializedName("children")
List<InterestNode> childList = new ArrayList<InterestNode>();
public List<InterestNode> getChildren(){
return new ArrayList<InterestNode>(childList);
}
public int getInterestId() {
return interestId;
}
public String getInterestName() {
return interestName;
}
public InterestNode getParent() {
return parent;
}
public boolean isVisible() {
return isVisible;
}
public void addChild(InterestNode intNode){
childList.add(intNode);
}
public void setInterestId(int interestId) {
this.interestId = interestId;
}
public void setInterestName(String interestName) {
this.interestName = interestName;
}
public void setParent(InterestNode parent) {
this.parent = parent;
}
public void setVisible(boolean isVisible) {
this.isVisible = isVisible;
}
}
It better to use Expandable ListView to add multilevel list, instead. But you want using listview then follow below nice tutorial here step by step three level listiview is achieved.
Android Multilevel ListView Tutorial
hope it helps you!

Categories

Resources