How to create a Multilevel list using listview - android

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!

Related

i have an issue with checked textview

i have used checked textview with base adapter to fill listview it's working fine but when i try to scroll CheckedTextView lost the selection.please find the code bellow and help me.
public class AttendancePage extends AppCompatActivity {
List<String> studentNames = new ArrayList<String>();
String[] sNames;
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance_page);
databaseHelper = new DatabaseHelper(getApplicationContext());
Cursor res = databaseHelper.getStudentNames();
setTitle("Attendance Sheet");
ListView listView = (ListView) findViewById(R.id.listView);
while (res.moveToNext()) {
studentNames.add(res.getString(0));
}
sNames = new String[studentNames.size()];
sNames = studentNames.toArray(sNames);
Student_Attandence_Addapter customAdapter = new Student_Attandence_Addapter(getApplicationContext(), sNames);
listView.setAdapter(customAdapter);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
}
My custom Adapter class:
public class Student_Attandence_Adapter extends BaseAdapter {
String[] names;
Context context;
LayoutInflater inflter;
String value;
public Student_Attandence_Adapter(Context context, String[] names) {
this.context = context;
this.names = names;
inflter = (LayoutInflater.from(context));
}
#Override
public int getCount() {
return names.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
view = inflter.inflate(R.layout.student_attandence_listview, null);
final CheckedTextView simpleCheckedTextView = (CheckedTextView) view.findViewById(R.id.simpleCheckedTextView);
simpleCheckedTextView.setText(names[position]);
simpleCheckedTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (simpleCheckedTextView.isChecked()) {
value = "un-Checked";
simpleCheckedTextView.setCheckMarkDrawable(0);
simpleCheckedTextView.setChecked(false);
} else {
value = "Checked";
simpleCheckedTextView.setCheckMarkDrawable(R.drawable.checked);
simpleCheckedTextView.setChecked(true);
}
}
});
return view;
}
}
Basically what happens is the state of the ChekedTextView will be reset whenever the getView method will be called according to the previous cached state of the list item. So in short you need to store the checked state of an item and when the getView method will be called you need to set it again. For example you need an object containing name and checked state
public class Student {
private String name;
private boolean checked;
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public boolean isChecked() {
return checked;
}
}
and your getView method will be like this,
#Override
public View getView(int position, View view, ViewGroup parent) {
/*
* ListView caches the view so only inflate when there
* is no cached view aka null
*/
if (view == null) {
view = inflter.inflate(R.layout.student_attandence_listview, null);
}
Student aStudent = students[position];
final CheckedTextView simpleCheckedTextView = (CheckedTextView) view.findViewById(R.id.simpleCheckedTextView);
simpleCheckedTextView.setText(aStudent.getName());
simpleCheckedTextView.setCheckMarkDrawable(aStudent.isChecked() ? R.drawable.checked : 0);
simpleCheckedTextView.setChecked(aStudent.isChecked());
simpleCheckedTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (simpleCheckedTextView.isChecked()) {
aStudent.setChecked(false);
notifyDataSetChanged();
} else {
aStudent.setChecked(true);
notifyDataSetChanged();
}
}
});
return view;
}
That's the theme. Modify it as you need.

The content of the adapter has changed but ListView did not receive a notification. How can i notify the list?

This is my fragment where I create the listview. When the data changed the listview is not notify. How can I do this? I make the request in viewModel using volley. I receive the next error: java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. Make sure your adapter calls notifyDataSetChanged() when its content changes. [in ListView(2131558620, class android.widget.ListView) with Adapter(class pharma.com.pharmaapp.Common.EventsArrayAdapter)]
at android.widget.ListView.layoutChildren(ListView.java:1582)
public class EventesFragment extends Fragment {
private final String TAG = EventesFragment.class.getSimpleName();
private ArrayList<EvenimentType> events = new ArrayList<>();
private ListView eventsListView;
private SwipeRefreshLayout swipeContainer;
public EventsArrayAdapter eventsArrayAdapter;
private EventsFragmentViewModel eventsFragmentViewModel = new EventsFragmentViewModel();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_events, container, false);
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), SearchActivity.class);
startActivity(intent);
}
});
if(events.size() != 0) {
events.clear();
}
eventsListView = (ListView) view.findViewById(R.id.listView_events);
swipeContainer = (SwipeRefreshLayout) view.findViewById(R.id.swipeContainer);
eventsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = ((EvenimentType) eventsListView.getAdapter().getItem(position)).getName();
Log.d(TAG, "Click " + name);
Intent intent = new Intent(getActivity(), SelectedEventActivity.class);
intent.putExtra("Parceable", events.get(position));
startActivity(intent);
}
});
eventsListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
String name = ((EvenimentType) eventsListView.getAdapter().getItem(position)).getName();
return false;
}
});
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
events.clear();
eventsFragmentViewModel.loadEvents(getActivity());
eventsFragmentViewModel.setInterface(new EventsFragmentViewModel.EventsFragmentInterface() {
#Override
public void takeData(ArrayList<EvenimentType> list) {
if(eventsArrayAdapter == null) {
eventsArrayAdapter = new EventsArrayAdapter(getActivity(), list);
eventsListView.setAdapter(eventsArrayAdapter);
swipeContainer.setRefreshing(false);
} else {
events = list;
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
eventsArrayAdapter.notifyDataSetChanged();
}
});
swipeContainer.setRefreshing(false);
}
}
});
}
});
loadEvents();
return view;
}
public void loadElementsToArrayAdapter() {
eventsArrayAdapter = new EventsArrayAdapter(getContext(), events);
// eventsArrayAdapter.notifyDataSetChanged();
swipeContainer.setRefreshing(false);
eventsListView.setAdapter(eventsArrayAdapter);
eventsFragmentViewModel.saveEvents(events, getActivity());
}
public void loadEvents() {
eventsFragmentViewModel.loadEvents(getActivity());
eventsFragmentViewModel.setInterface(new EventsFragmentViewModel.EventsFragmentInterface() {
#Override
public void takeData(ArrayList<EvenimentType> list) {
events = list;
loadElementsToArrayAdapter();
}
});
}
#Override
public void onResume() {
super.onResume();
// eventsFragmentViewModel.getUserEventsId(getActivity());
}
}
This is the Base Adapter class:
public class EventsArrayAdapter extends BaseAdapter {
private static final String TAG = EventsArrayAdapter.class.getSimpleName();
private Context context;
private List<EvenimentType> list = null;
public EventsArrayAdapter(Context context, List<EvenimentType> objects) {
this.context = context;
this.list = objects;
}
public void addAll(List<EvenimentType> objects) {
if(list == null) {
list = new ArrayList<>();
}
list.addAll(objects);
notifyDataSetChanged();
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(convertView == null) {
convertView = inflater.inflate(R.layout.item_array_adapter, null);
}
TextView title = (TextView) convertView.findViewById(R.id.text_simposion_title);
TextView date = (TextView) convertView.findViewById(R.id.text_simposion_date);
TextView location = (TextView) convertView.findViewById(R.id.text_simposion_location);
TextView price = (TextView) convertView.findViewById(R.id.text_simposion_price);
ImageView image = (ImageView) convertView.findViewById(R.id.image_event);
Log.d(TAG, "Checking: " + checkEvent(list.get(position)));
if (checkSelection(list.get(position)) == true) {
title.setText(list.get(position).getName());
date.setText(list.get(position).getDate());
location.setText(list.get(position).getLocation());
price.setText(list.get(position).getPaid());
image.setImageResource(R.drawable.ic_simposions);
} else {
title.setText(list.get(position).getName());
date.setText(list.get(position).getDate());
location.setText(list.get(position).getLocation());
price.setText(list.get(position).getPaid());
}
Log.d(TAG, "getView");
return convertView;
}
This is the viewModel where I make the request
public class EventsFragmentViewModel extends LoginViewModel {
private static final String TAG = EventsFragmentViewModel.class.getSimpleName();
private ArrayList<EvenimentType> events = new ArrayList<>();
EventsFragmentInterface listener = null;
public void loadEvents(final Context context) {
DataServices dataServices = new DataServices(context);
dataServices.getEvents();
dataServices.setCommunicationInterface(new RequestToServer.CommunicationInterface() {
#Override
public void takeResponse(JSONObject response) {
try {
Log.d(TAG, response.toString());
EvenimentType evenimentType = new EvenimentType();
JSONArray obj = response.getJSONArray("entry");
Log.d(TAG, obj.length() + "");
for (int i = 0; i < obj.length(); i++) {
events.add(evenimentType.createEvent(obj.getJSONObject(i)));
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d(TAG, "EVENTS: " + events.size());
if(listener!= null) {
listener.takeData(events);
}
}
});
}
public void saveEvents(ArrayList<EvenimentType> list, Context context) {
Preferences preferences = new Preferences(context);
preferences.saveToSharedPreferencesEvents(list);
preferences.getFromSharedPreferencesEvents();
}
public void setInterface(EventsFragmentInterface listener) {
this.listener = listener;
}
public interface EventsFragmentInterface {
public void takeData(ArrayList<EvenimentType> list);
}
}

update listview using spinner data in android

Am trying to update my listview on every selection of the spinner. but its not working. Instead of getting new data, listview is repeating the same values.
I am unable to find out what is my mistake.
here is my avtivity code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
setContentView(R.layout.activity_performance_details);
PerfList = new ArrayList<PerformanceListItem>();
months = (Spinner) findViewById(R.id.load_month);
listview_performance = (ListView) findViewById(R.id.performance_details_list);
sadapter = new PerformanceAdapter(PerformanceDetails.this, PerfList);
months.setOnItemSelectedListener(this);
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Spinner a=(Spinner)parent;
if(a.getId() == R.id.load_month) {
monthid =1+(int)months.getSelectedItemPosition();
Toast.makeText(getApplicationContext(),""+monthid,Toast.LENGTH_LONG).show();
new setAsyncTask_performance().execute();
}
}
after selecting spinner data it is sent to server and from server its relevant data is fetched and sent back to the list view. now when i first time select the spinner it show the data accordingly. But on second selection it will include the previous data without updating the listview
Adapter Code:
public class PerformanceAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private Context context;
private List<PerformanceListItem> performanceList;
public PerformanceAdapter(Activity activity, List<PerformanceListItem> PList) {
this.activity = activity;
this.performanceList = PList;
}
#Override
public int getCount() {
return performanceList.size();
}
#Override
public Object getItem(int position) {
return performanceList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.performance_itemlist, null);
}
Animation slideUp = AnimationUtils.loadAnimation(activity, R.anim.slide_up);
TextView staffName = (TextView) convertView.findViewById(R.id.perf_staffName);
TextView staffDesignation = (TextView) convertView.findViewById(R.id.perf_Design);
TextView staffPerformance = (TextView) convertView.findViewById(R.id.perf_performance);
PerformanceListItem plist = performanceList.get(position);
staffName.setText(plist.getpStaffName());
staffDesignation.setText(plist.getpDesignation());
staffPerformance.setText(plist.getpPerformance());
slideUp.setDuration(500);
convertView.startAnimation(slideUp);
slideUp = null;
return convertView;
}
}
and this is my performance list to get and set data
PerformanceListItems code:
public class PerformanceListItem {
private String pSid;
private String pStaffName;
private String pDesignation;
private String pPerformance;
private String pList;
public PerformanceListItem(){
}
public PerformanceListItem(String pList){
this.pList = pList;
}
public String getpSid(){
return pSid;
}
public void setpSid(String pSid){
this.pSid = pSid;
}
public String getpStaffName(){
return pStaffName;
}
public void setpStaffName(String pStaffName){
this.pStaffName = pStaffName;
}
public String getpDesignation(){
return pDesignation;
}
public void setpDesignation(String pDesignation){
this.pDesignation = pDesignation;
}
public String getpPerformance(){
return pPerformance;
}
public void setpPerformance(String pPerformance){
this.pPerformance = pPerformance;
}
}
After debugging the entire code i found that my JSONObject is not updating with new value
any help would be appreciable.
Update the data of your adapter when you execute this
new setAsyncTask_performance().execute();
If you want to show only the new data just remove all your listview items then update the data and set the adapter again.
dont set adapter in oncreate. Set your adapter in Asynctask Post execute. and set your array inside doinbackground along with getting data task.

Passing data in from list to detail view in Android

I have a list view populated threw an SQlitedatabase but I need to pass to a detail activity from the list view. The problem is in passing the details from the listview activity to the detail activity because when I click the detail activity it gives me blank edit texts
Here is my listview activity:
public class consulter_note extends Activity implements AdapterView.OnItemClickListener{
ListView list;
SQLiteDatabase sqLiteDatabase;
DataBaseOperationstwo dataBaseOperationstwo;
Cursor cursor;
ListDataAdapter listDataAdapter;
String titre,objet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_consulter_note);
list = (ListView) findViewById(R.id.listView);
listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.notelist_row);
list.setAdapter(listDataAdapter);
list.setOnItemClickListener(this);
dataBaseOperationstwo = new DataBaseOperationstwo(getApplicationContext());
sqLiteDatabase = dataBaseOperationstwo.getReadableDatabase();
cursor = dataBaseOperationstwo.getInformations(sqLiteDatabase);
if (cursor.moveToFirst())
{
do
{
titre = cursor.getString(0);
objet = cursor.getString(1);
DataProvider dataProvider = new DataProvider(titre,objet);
listDataAdapter.add(dataProvider);
}while (cursor.moveToNext());
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this, note_details.class);
startActivity(intent);
intent.putExtra("titre", titre);
intent.putExtra("objet", objet);
}
}
And here is my array adapter:
public class ListDataAdapter extends ArrayAdapter{
List list = new ArrayList();
public ListDataAdapter(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler
{
TextView TITRE,OBJET;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.notelist_row,parent,false);
layoutHandler = new LayoutHandler();
layoutHandler.TITRE = (TextView) row.findViewById(R.id.titredemo);
layoutHandler.OBJET = (TextView) row.findViewById(R.id.objetdemo);
row.setTag(layoutHandler);
}
else
{
layoutHandler = (LayoutHandler) row.getTag();
}
DataProvider dataProvider = (DataProvider) this.getItem(position);
layoutHandler.TITRE.setText(dataProvider.getTitre());
layoutHandler.OBJET.setText(dataProvider.getObjet());
return row;
}
}
The data provider class used in the array adapter:
public class DataProvider {
private String titre,objet;
public DataProvider(String titre,String objet)
{
this.titre = titre;
this.objet = objet;
}
public String getTitre() {
return titre;
}
public void setTitre(String titre) {
this.titre = titre;
}
public String getObjet() {
return objet;
}
public void setObjet(String objet) {
this.objet = objet;
}
}
And finally my details activity. I'm only interested in the intent part; the rest has nothing to do with my problem:
public class note_details extends Activity {
ImageButton Del;
EditText PASSTITRE,USEROBJET;
String Passtitre,Userobjet;
DataBaseOperationstwo DOP;
Context CTX = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent =getIntent();
if(intent != null)
{
String objet = intent.getStringExtra("objet");
String titre= intent.getStringExtra("titre");
PASSTITRE.setText(objet);
USEROBJET.setText(objet);
}
setContentView(R.layout.activity_note_details);
Del = (ImageButton) findViewById(R.id.suppnote);
PASSTITRE = (EditText) findViewById(R.id.titree);
USEROBJET = (EditText) findViewById(R.id.objett);
Del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Passtitre = PASSTITRE.getText().toString();
Userobjet = USEROBJET.getText().toString();
DOP = new DataBaseOperationstwo(CTX);
DOP.deleteNote(DOP,Passtitre,Userobjet);
Toast.makeText(getBaseContext(),"note supprimé",Toast.LENGTH_LONG).show();
finish();
}
});
}
public void liste(View v)
{
Intent i = new Intent(this, consulter_note.class);
startActivity(i);
}
public void supprimer(View v)
{
}
}
My logcat doesn’t show any errors but the details activity shows with empty edittexts.
You should first add extras to the Intent and then fire it:
Intent intent = new Intent(this, note_details.class);
intent.putExtra("titre", titre);
intent.putExtra("objet", objet);
startActivity(intent);
Another thing worth mentioning is that you should avoid doing DB queries on the main thread, as it will slow down your app. Use Loaders, or just run queries on worker threads.

OnItemClickListener getting data from model

I am fairly new to Android development and I am trying to build a ListView which get data from web service using gson. I have a model class, a list class, an adapter class and the activity class.
The list works fine and it got the data, and now I want to integrate the OnItemClickListener to it and pass the data to the 2nd activity. And I'd like to get the item id (DistrictId) and pass it to the next Activity(listView) instead of the row id. It would be great if someone could show me the light... as the documentation is not as clear to understand and because I am new.
Below is my code.
The model class
package com.sample.myapp;
public class DistrictModel {
private String id;
private String districtName;
public String getDistrictId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDistrictName(){
return districtName;
}
public void setDistrictEN(String districtName){
this.districtName = districtName;
}
}
The List class
public class DistrictList {
private List<DistrictModel> districts;
public List<DistrictModel> getDistricts(){
return districts;
}
public void setDistrictList(List<DistrictModel> districts){
this.districts = districts;
}
}
The Adapter class
public class DistrictAdapter extends ArrayAdapter<DistrictModel>{
int resource;
String response;
Context context;
private LayoutInflater dInflater;
public DistrictAdapter(Context context, int resource, List<DistrictModel> objects) {
super(context, resource, objects);
this.resource = resource;
dInflater = LayoutInflater.from(context);
}
static class ViewHolder {
TextView title;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
//Get the current location object
DistrictModel lm = (DistrictModel) getItem(position);
//Inflate the view
if(convertView==null)
{
convertView = dInflater.inflate(R.layout.item_district, null);
holder = new ViewHolder();
holder.title = (TextView) convertView
.findViewById(R.id.district_name);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.title.setText(lm.getDistrictName());
return convertView;
}
}
The activity class
public class DistrictListActivity extends Activity{
LocationManager lm;
ArrayList<DistrictModel> districtArray = null;
DistrictAdapter districtAdapter;
DistrictList list;
ListView lv;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.districtlist_layout);
lv = (ListView) findViewById(R.id.list_district);
districtArray = new ArrayList<DistrictModel>();
districtAdapter = new DistrictAdapter(DistrictListActivity.this, R.layout.item_district, districtArray);
lv.setTextFilterEnabled(true);
lv.setAdapter(districtAdapter);
try {
new DistrictSync().execute("http://aws.something.com/service");
} catch(Exception e) {}
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(DistrictListActivity.this);
adb.setTitle("LVSelectedItemExample");
adb.setMessage("Selected Item is = "+(lv.getItemIdAtPosition(position)));
adb.setPositiveButton("Ok", null);
adb.show();
}
}); **//i'd like to get the DistrictId from the json data.**
}
private class DistrictSync extends AsyncTask<String, Integer, DistrictList> {
protected DistrictList doInBackground(String... urls) {
DistrictList list = null;
int count = urls.length;
for (int i = 0; i < count; i++) {
try {
// ntar diganti service
RestClient client = new RestClient(urls[i]);
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String json = client.getResponse();
list = new Gson().fromJson(json, DistrictList.class);
//
} catch(Exception e) {}
}
return list;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(DistrictList dislist) {
for(DistrictModel lm : dislist.getDistricts())
{
districtArray.add(lm);
}
districtAdapter.notifyDataSetChanged();
}
}
}
For testing purpose, now I click the row it will show me the row id, so I know the onclick listener works, but I just want it to grab me the DistrictId so I can use it to pass to the next activity.
Thank you so much.
(out of my head) Try this:
((DistrictModel)lv.getAdapter().getItem(position)).getDistrictId();
Generally when you want to pass data from one Activity to another, you just place it into the Intent that you use to create the new Activity.
For example (and here are some additional examples):
Intent i = new Intent(context, MyNewActivity.class);
i.putExtra("MyCurrentHealth", mCurrentHealth);
context.startActivity(i);
To retrieve the data do this:
Bundle extras = getIntent().getExtras();
if (extra != null) {
... // Do stuff with extras
}

Categories

Resources