Dynamic CustomListView not getting updated - android

I implemented a custom list view using customadapter. When I press on refresh button, the data is fetched from database and updated in list view. But in my case the items get appended after the previous items i.e. if i have 2 items in databse and I press refresh button without changing the database items,the same items gets appended and 4 listitems get displayed. Quick help required. notifyDatasetChanged() is used in code. But I don't know if it's correct.
Here is code for MainActivity.java
public class MainActivity extends Activity {
ListView lv;
TextView tv1,tv2,tv3;
ArrayList<String> a=new ArrayList<String>();
ArrayList<String> b=new ArrayList<String>();
ArrayList<String> c=new ArrayList<String>();
ArrayList<String> d=new ArrayList<String>();
String mydata,name,name1,society,date,venue;
public String[] s1 = new String[50];
public String[] s2=new String[50];
public String[] s3=new String[50];
public String[] s4=new String[50];
public int[] img = {R.drawable.rty, R.drawable.sf, R.drawable.rty};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1=(TextView)findViewById(R.id.textView);
lv = (ListView) findViewById(R.id.listView);
ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
Boolean isInternetPresent = cd.isConnectingToInternet(); // true or false
if(isInternetPresent) {
new MyData().execute();
}
else
Toast.makeText(MainActivity.this,"No Internet Connection",Toast.LENGTH_SHORT).show();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent in = new Intent(MainActivity.this, listclick.class);
in.putExtra("position", position);
startActivity(in);
}
});
}
public void abc(View v)
{
Intent in=new Intent(MainActivity.this,webform.class);
startActivity(in);
}
public void ref(View v)
{
ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
Boolean isInternetPresent = cd.isConnectingToInternet();
if(isInternetPresent) {
new MyData().execute();
}
else
Toast.makeText(MainActivity.this,"No Internet Connection",Toast.LENGTH_SHORT).show();
}
public class MyData extends AsyncTask<String,String,String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
CustomAdapter cad = new CustomAdapter(MainActivity.this, s1, img,s2,s3,s4);
lv.setAdapter(cad);
cad.notifyDataSetChanged();
}
#Override
protected String doInBackground(String... params) {
getData();
return null;
}
}
public void getData()
{
try {
HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost("http://collegeevents.esy.es/abc.php");
HttpResponse response=httpClient.execute(httpPost);
HttpEntity httpEntity=response.getEntity();
InputStream is=httpEntity.getContent();
BufferedReader reader=new BufferedReader(new InputStreamReader(is,"utf-8"),8);
StringBuilder strbuilder=new StringBuilder();
String line=null;
while ((line=reader.readLine())!=null)
{
strbuilder.append(line);
}
is.close();
mydata=strbuilder.toString();
JSONArray obj=new JSONArray(mydata);
for(int i=0;i<obj.length();i++)
{
JSONObject obj1=obj.getJSONObject(i);
a.add(i,obj1.getString("Name"));
b.add(i,obj1.getString("society"));
c.add(i,obj1.getString("venue"));
d.add(i,obj1.getString("date"));
}
String[] s = new String[a.size()];
s=a.toArray(s);
s1 = s;
String[] soc = new String[b.size()];
soc=b.toArray(soc);
s2 = soc;
String[] ven = new String[c.size()];
ven=c.toArray(ven);
s3 = ven;
String[] dat = new String[d.size()];
dat=d.toArray(dat);
s4 = dat;
}
catch (Exception e)
{
}
}
}
Here is CustomAdapter.java
public class CustomAdapter extends ArrayAdapter<String> {
Context c1;
String s1[],soc[],ven[],dat[];
int s2[];
CustomAdapter(Context c,String s[],int s3[],String society[],String venue[],String date[])
{
super(c, R.layout.listcustom, s);
this.c1=c;
this.s1=s;
this.s2=s3;
this.soc=society;
this.ven=venue;
this.dat=date;
}
#Override
public View getView(int position, View v, ViewGroup parent) {
LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=li.inflate(R.layout.listcustom,parent,false);
TextView tv=(TextView)v.findViewById(R.id.textView);
TextView tv1=(TextView)v.findViewById(R.id.society);
TextView tv2=(TextView)v.findViewById(R.id.venue);
TextView tv3=(TextView)v.findViewById(R.id.date);
tv.setText(s1[position]);
tv1.setText(soc[position]);
tv2.setText(ven[position]);
tv3.setText(dat[position]);
if(position%2==0) {
tv.setTextColor(Color.parseColor("#01579B"));
tv3.setTextColor(Color.parseColor("#01579B"));
}
else{
tv.setTextColor(Color.parseColor("#00897B"));
tv3.setTextColor(Color.parseColor("#00897B"));
}
v.setTag(position);
//notifyDataSetChanged();
return v;
}
}

I finally got it. The short answer for you question — you are not clearing a, b, c, d ArrayLists. So each getData() call adds data while previous data is still there. So, you should add a.clear(), b.clear() ... etc. at the start of getData.
However i would suggest to make the following improvements:
Introduce entity for adapter data. This entity will contain 4 fields: name, society, venue, date.
Thus you don't need to use 4 arrays and 4 ArrayLists. For convience i will use "Event" as entity name. This will lok something like:
AsyncTask:
public class MyData extends AsyncTask<String, String, Event[]> {
#Override
protected Event[] doInBackground(String... params) {
return getData();
}
#Override
protected void onPostExecute(Event[] s) {
cad.clear();
cad.addAll(s)
}
}
Activity:
public class MainActivity extends Activity {
private CustomAdapter cad;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
lv = (ListView) findViewById(R.id.listView);
cad = new CustomAdapter(getApplicationContext());
}
}
CustomAdapter:
public class CustomAdapter extends ArrayAdapter<Event> {
private final LayoutInflater inflater;
public CustomAdapter(Context c, Event ev[]) {
super(context, ev[]);
inflate = LayoutInflater.from(context);
}
CustomAdapter(Context c) {
this(context, new Event[0]);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final View v;
if(convertView == null) {
v = inflater.inflate(...)
} else {
v = convertView;
}
// find views or event better — use ViewHolder pattern
Event evt = getItem(position);
tv.setText(evt.getName());
...
return v;
}
}
Don't use onClick tag. Use view#setOnClickListener instead. onClick binds layout and activity implementation and that's not good.
Use clear names. Something like LoadDataTask instead of MyData.

Related

How to populate autocomplete textview based on the selection of first?

There are 2 autocomplete textview one for the city and one for the state. I want that when a user enters the state in autocomplete textview then based on state selection, city autocomplete text view should be automatically filled. Like the ecommerce app whenever someone enters the postal code in the address section then the city and state get automatically filled and also the user has the option to select.
MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText edtxt_name_address, edtxt_email_address, edtxt_mobile_address, edtxt_alt_mob_address, edtxt_pincode, edtxt_addline1, edtxt_addline2;
Button buttonSaveAddress;
AutoCompleteTextView edtxt_city, edtxt_state;
private static final String KEY_STATE = "state";
private static final String KEY_CITIES = "cities";
private ProgressDialog pDialog;
private String cities_url = "http://api.androiddeft.com/cities/cities_array.json";
final List<State> statesList = new ArrayList<>();
final List<String> states = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtxt_city = findViewById(R.id.edtxt_city);
edtxt_state = findViewById(R.id.edtxt_state);
loadStateCityDetails();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, states);
edtxt_state.setThreshold(1);//will start working from first character
edtxt_state.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView
//edtxt_city.setTextColor(Color.BLACK)
edtxt_state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
buttonSaveAddress = findViewById(R.id.buttonSaveAddress);
buttonSaveAddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveAddress();
}
});
}
private void loadStateCityDetails() {
JsonArrayRequest jsArrayRequest = new JsonArrayRequest
(Request.Method.GET, cities_url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray responseArray) {
try {
//Parse the JSON response array by iterating over it
for (int i = 0; i < responseArray.length(); i++) {
JSONObject response = responseArray.getJSONObject(i);
String state = response.getString(KEY_STATE);
JSONArray cities = response.getJSONArray(KEY_CITIES);
List<String> citiesList = new ArrayList<>();
for (int j = 0; j < cities.length(); j++) {
citiesList.add(cities.getString(j));
}
statesList.add(new State(state, citiesList));
states.add(state);
Log.d("lskd", String.valueOf(statesList));
Log.d("lskd", String.valueOf(states));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//pDialog.dismiss();
//Display error message whenever an error occurs
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsArrayRequest);
}
private void saveAddress() {
if (TextUtils.isEmpty(city)) {
edtxt_city.setError("Please enter your City");
edtxt_city.requestFocus();
return;
}
if (TextUtils.isEmpty(state)) {
edtxt_state.setError("Please enter your State");
edtxt_state.requestFocus();
return;
}
Intent profile_next = new Intent(MainActivity.this, ProfileNextActivity.class);
startActivity(profile_next);
}
}
State.java
public class State {
private String stateName;
private List<String> cities;
public State(String stateName, List<String> cities) {
this.stateName = stateName;
this.cities = cities;
}
public String getStateName() {
return stateName;
}
public List<String> getCities() {
return cities;
}
}
State and city has one to many relation, I didn't particularly understand what you meant by automatically filled. If you want to populate the related cities of the selected state do the following.
Inside your edtxt_state.setOnItemSelectedListener
edtxt_state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
statesList.get(position).getCities(); //get your cities from selected state
//set adapter or notify city list of your `edtxt_city` AutoCompleteTextView
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
try this...
edtxt_state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
List<String> cityList = statesList.get(position).getCities();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, cityList);
edtxt_city.setThreshold(1);//will start working from first character
edtxt_city.setAdapter(adapter);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
set your adapter inside loadStateCityDetails(); after getting stateList
statesList.add(new State(state, citiesList));
states.add(state);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, states);
edtxt_state.setThreshold(1);//will start working from first character
edtxt_state.setAdapter(adapter);
EDIT
edtxt_state.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
int pos = -1;
for (int i = 0; i < statesList.size(); i++) {
if (statesList.get(i).getStateName().equals(selection)) {
pos = i;
break;
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.select_dialog_item, statesList.get(pos).getCities());
edtxt_city.setThreshold(1);//will start working from first character
edtxt_city.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView
}
});
you must get stateList
set city adapter as above

Android listview onclicklistener with dynamic buttons

I built a listview that displays dynamic buttons with the name of tables in a database. When a person clicks the button it's supposed to grab the text of the button and then pass that to the next activity which would populate the information corresponding to the database table and display that text at the top of the screen. The code I've written keeps crashing when I click the button. Is there something else I need to call or does this code not work with a button?
public class UserArea extends AppCompatActivity {
SectionListAdapter sectionListAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_area);
TextView tvWelcomeMsg = (TextView) findViewById(R.id.tvWelcome);
/**Get Sections and Display as buttons*/
listView = (ListView) findViewById(R.id.lvSections);
sectionListAdapter = new SectionListAdapter(this, R.layout.section_layout);
listView.setAdapter(sectionListAdapter);
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
/** If data successfully gathered*/
if (success) {
JSONArray jsonArray= jsonResponse.getJSONArray("Flights");
int count = 0;
String flight;
while(count<jsonArray.length()) {
JSONObject SL = jsonArray.getJSONObject(count);
flight = SL.getString("Flight");
SectionList sl = new SectionList(flight);
sectionListAdapter.add(sl);
count++;
}
}
/** If data is not gathered*/
else {
AlertDialog.Builder builder = new AlertDialog.Builder(UserArea.this);
builder.setMessage("Failed to connect")
.setNegativeButton("Retry", null)
.create()
.show();
}
}
/** if any other response is received*/
catch (JSONException e) {
e.printStackTrace();
}
}
};
/**Creates Request to get the data*/
GetSectionRequest getSections = new GetSectionRequest(responseListener);
/**Creates a queue to run the code*/
RequestQueue queue = Volley.newRequestQueue(UserArea.this);
queue.add(getSections);
/**End*/
/**Creates onclicklistener to pass clicked section name*/
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
Intent intent = new Intent (UserArea.this, Personnel.class);
intent.putExtra("section", listView.getItemAtPosition(i).toString());
UserArea.this.startActivity(intent);
}
});
SectionListAdapter
public class SectionListAdapter extends ArrayAdapter {
List list = new ArrayList();
public SectionListAdapter(Context context, int resource) {
super(context, resource);
}
public void add(SectionList 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;
row = convertView;
SectionListAdapter.SectionListHolder sectionListHolder;
if (row == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.section_layout, parent, false);
sectionListHolder = new SectionListAdapter.SectionListHolder();
sectionListHolder.bSection = row.findViewById(R.id.bSectionName);
}else{
sectionListHolder = (SectionListAdapter.SectionListHolder)row.getTag();
}
SectionList SectionList = (SectionList) this.getItem(position);
sectionListHolder.bSection.setText(SectionList.getFlight());
return row;
}
static class SectionListHolder{
Button bSection;
}
}
Log Cat
10-10 19:31:26.797 6595-6595/com.example.yikes.recall E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.example.yikes.recall, PID: 6595
java.lang.NullPointerException: Attempt to read from field 'android.widget.Button com.example.yikes.recall.SectionListAdapter$SectionListHolder.bSection' on a null object reference
I'm try code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ListView listView = new ListView(this);
listView.setBackgroundColor(Color.WHITE);
setContentView(listView);
final String[] activities = new String[]{"Item1", "Item2", "Item3", "Item4"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line);
listView.setAdapter(adapter);
for (String item : activities) {
adapter.add(item);
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
Intent intent = new Intent(MainActivity.this, SampleActivity.class);
intent.putExtra("item", item);
MainActivity.this.startActivity(intent);
}
});
}
It's working, I think
/**Creates Request to get the data*/
GetSectionRequest getSections = new GetSectionRequest(responseListener);
/**Creates a queue to run the code*/
RequestQueue queue = Volley.newRequestQueue(UserArea.this);
queue.add(getSections);
Need some time, you can add ProgressDialog when start app and dismiss when response callback. Hope it can help you!

How can I display specific CSV content to the clicked list item?

I'm trying to display specific CSV content to the clicked list item but with my current code, I can only display the entire CSV file. Here for example, when I click on level 2, all the CVS list is displayed, but what I'm trying to do here is to show only the level 2 elements of the CSV.
This is my first view :
This is the view I get when level 2 is clicked :
But here, the level 1 CSV elements are also display, how can I only display the level 2 elements ? And when the "Level 1" is clicked, how to display only the level 1 elements ? etc...
MainActivity.java
public class MainActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array
// R.array.levels is in list_levels.xml
String[] levels = getResources().getStringArray(R.array.levels);
// Binding resources Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label_level, levels));
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String list = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
// sending data to new activity
i.putExtra("list", list);
startActivity(i);
}
});
}
}
Here is my file CSVFile.java
public class CSVFile {
InputStream inputStream;
public CSVFile(InputStream inputStream){
this.inputStream = inputStream;
}
public List<String[]> read(){
List<String[]> resultList = new ArrayList<String[]>();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String csvLine;
while ((csvLine = reader.readLine()) != null) {
String[] row = csvLine.split(",");
resultList.add(row);
}
}
catch (IOException ex) {
throw new RuntimeException("Error in reading CSV file: "+ex);
}
finally {
try {
inputStream.close();
}
catch (IOException e) {
throw new RuntimeException("Error while closing input stream: "+e);
}
}
return resultList;
}
}
My ItemArrayAdapter.java class
public class ItemArrayAdapter extends ArrayAdapter<String[]> {
private List<String[]> stimuliList = new ArrayList<String[]>();
static class ItemViewHolder {
TextView level_number;
TextView stimuli_name;
}
public ItemArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public void add(String[] object) {
stimuliList.add(object);
super.add(object);
}
#Override
public int getCount() {
return this.stimuliList.size();
}
#Override
public String[] getItem(int index) {
return this.stimuliList.get(index);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ItemViewHolder viewHolder;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.single_list_item_view, parent, false);
viewHolder = new ItemViewHolder();
viewHolder.level_number = (TextView) row.findViewById(R.id.level_number);
viewHolder.stimuli_name = (TextView) row.findViewById(R.id.stimuli_name);
row.setTag(viewHolder);
} else {
viewHolder = (ItemViewHolder)row.getTag();
}
String[] stat = getItem(position);
viewHolder.level_number.setText(stat[0]);
viewHolder.stimuli_name.setText(stat[1]);
return row;
}
}
SingleListItem.java
public class SingleListItem extends Activity{
private ListView listView;
private ItemArrayAdapter itemArrayAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.single_list_item_view);
TextView txtList = (TextView) findViewById(R.id.list_label);
Intent i = getIntent();
// getting attached intent data
String list = i.getStringExtra("list");
// displaying selected list name
txtList.setText(list);
listView = (ListView) findViewById(R.id.stimuli_list);
itemArrayAdapter = new ItemArrayAdapter(getApplicationContext(), R.layout.single_list_item_view);
Parcelable state = listView.onSaveInstanceState();
listView.setAdapter(itemArrayAdapter);
listView.onRestoreInstanceState(state);
InputStream inputStream = getResources().openRawResource(R.raw.stimulis);
CSVFile csvFile = new CSVFile(inputStream);
List<String[]> stimuliList = csvFile.read();
for(String[] stimuliData:stimuliList ) {
itemArrayAdapter.add(stimuliData );
}
}
}
And finally, a quick view of my CSV file, stimulis.csv
level 1,feu
level 1,fête
level 2,blanc
level 2,blague
...
Is this possible ?
I am afraid it isn't possible.

Add load more button to listview in android

I am working on android projects. In my application I am getting the data from php webservice. I added my data to different arraylists and set them to listadapter. But my problem is it is taking very long time to display the data in list. Hence now I want to display first 10 items and want to keep a loadmore button at the bottom of the screen. Once the load more button is clicked the next 10 items need to display. Please can anybody help me in this regard. I would really appreciate for this help.
Thank you in advance.
Code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
Longop op = new Longop();
op.execute("");
}
public void loadSomeDummyData() {
try {
response = CustomHttpClient
.executeHttpPost(
"http://website.com/folder/testfile.php",
postParameters);
for (int i = 1; i < arr1.length - 1; i++) {
id.add(new String(arr[0]));
name.add(new String(arr[1]));
dateofbirth.add(new String(arr[2]));
status.add(new String(arr[3]));
}
} catch (Exception e) {
e.printStackTrace();
}
}
private class Longop extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
loadSomeDummyData();
return "Executed";
}
#Override
protected void onPostExecute(String result) {
mdialog.dismiss();
myListView.setAdapter(new MyArrayAdapter(Sample.this,
R.layout.list, id, name, dateofbirth,
status));
}
#Override
protected void onPreExecute() {
mdialog = ProgressDialog.show(Sample.this, "Please wait...",
"Retrieving data ...", true);
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
private class MyArrayAdapter extends ArrayAdapter<String> {
// this list hold the data that we will see in listview
private List<String> myData = new ArrayList<String>();
private List<String> myData1 = new ArrayList<String>();
private List<String> myData2 = new ArrayList<String>();
private List<String> myData3 = new ArrayList<String>();
public MyArrayAdapter(Context context, int textViewResourceId,
List<String> objects, List<String> objects1,
List<String> objects2, List<String> objects3) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
context = getContext();
myData = objects;
myData1 = objects1;
myData2 = objects2;
myData3 = objects3;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list, null);
// Log.d(EKSI, "Getting the inflater from the system context");
}
String sid = myData.get(position);
String sname = myData1.get(position);
String dob = myData2.get(position);
String sstatus = myData3.get(position);
TextView entryTextView = (TextView) v.findViewById(R.id.id1);
entryTextView.setText(sid);
TextView entryTextView1 = (TextView) v
.findViewById(R.id.id2);
entryTextView1.setText(sname);
TextView entryTextView2 = (TextView) v
.findViewById(R.id.id3);
entryTextView2.setText(dob);
TextView entryTextView3 = (TextView) v
.findViewById(R.id.id4);
entryTextView3.setText(sstatus);
return v;
}
}
You could also use this lib
https://github.com/chrisbanes/Android-PullToRefresh.
I implement this function not base ListView that can do this;
Custom loading view,override onDraw menthod
Add loading view at the end of LinearLayout view. When loading view is show, it should call some methods to get data from server by HTTP.
you just need to inflate an xml in
lstView.addFooterView(R.layout.footer);
and handle onclick of the button residing in footer

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