I am using the library asymmetricGridView,
The code given:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (AsymmetricGridView) findViewById(R.id.listView);
// Choose your own preferred column width
listView.setRequestedColumnWidth(Utils.dpToPx(this, 120));
final List<AsymmetricItem> items = new ArrayList<>();
// initialize your items array
adapter = new ListAdapter(this, listView, items);
AsymmetricGridViewAdapter asymmetricAdapter =
new AsymmetricGridViewAdapter<>(this, listView, adapter);
listView.setAdapter(asymmetricAdapter);
}
I am getiing an error in adapter = new ListAdapter(this, listView, items);
I don't know how to use ListAdapter, I am new to android, can anyone help me go about it?
ListAdapter is an interface, not a class. You cannot instantiate it with new, unless you are defining an anonymous inner class at the point of instantiation.
I suggest you do some searching for tutorials about using ListAdapter (and adapters on Android in general). I also recommend you use the AsymmetricRecyclerView instead from that same library (and therefore also the AsymmetricRecyclerViewAdapter) because ListView is rather old and clunky and it's functionality has been more or less superseded by RecyclerView.
This is result
Step 1: Create class Events.
import java.io.Serializable;
public class Events implements Serializable {
private String id;
private String titleEvent;
private String dateEvent;
public Events() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitleEvent() {
return titleEvent;
}
public void setTitleEvent(String titleEvent) {
this.titleEvent = titleEvent;
}
public String getDateEvent() {
return dateEvent;
}
public void setDateEvent(String dateEvent) {
this.dateEvent = dateEvent;
}
}
Step2: Create class ListAdapter extends ArrayAdapter<Events>
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.info.quanglv.eventlucky.R;
import com.info.quanglv.eventlucky.common.Events;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class ListAdapter extends ArrayAdapter<Events> {
List<Events> listProduct = new ArrayList<>();
public ListAdapter(Context context, int resource, List<Events> objects) {
super(context, resource, objects);
listProduct = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
view = inflater.inflate(R.layout.item_events, null);
}
Events events = getItem(position);
if (events != null) {
TextView txt_Title = (TextView) view.findViewById(R.id.txtTitleEvent);
txt_Title.setText(events.getTitleEvent());
TextView txt_dateEvent = (TextView) view.findViewById(R.id.txtDateEvent);
txt_dateEvent.setText(events.getDateEvent());
//ImageView img_Product = (ImageView) view.findViewById(R.id.imgProduct);
// img_Product.setImageResource(position);
// img_Product.setImageURI(product.getImg());
// new DownloadImageTask(img_Product).execute(listProduct.get(position).getImageProduct());
}
return view;
}
public static class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
Step 3: in onCreate() you can code:
new GetListProduct().execute();
private class GetListProduct extends AsyncTask<Void, Void, ArrayList<Events>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected ArrayList<Events> doInBackground(Void... params) {
ArrayList<Events> events = new ArrayList<>();
Events eventsLucky = new Events();
eventsLucky.setId("1");
eventsLucky.setTitleEvent("New Year CountDown Party");
eventsLucky.setDateEvent("10/10/12");
events.add(eventsLucky);
Events eventsLucky1 = new Events();
eventsLucky1.setId("2");
eventsLucky1.setTitleEvent("Tiger Remix Concert 2016 ");
eventsLucky1.setDateEvent("10/10/12");
events.add(eventsLucky1);
Events eventsLucky2 = new Events();
eventsLucky2.setId("3");
eventsLucky2.setTitleEvent("Tiger Remix Concert 2016 ");
eventsLucky2.setDateEvent("10/10/1212");
events.add(eventsLucky2);
Events eventsLucky3 = new Events();
eventsLucky3.setId("4");
eventsLucky3.setTitleEvent("Tiger Remix Concert 2016 ");
eventsLucky3.setDateEvent("10/10/1212");
events.add(eventsLucky3);
return events;
}
#Override
protected void onPostExecute(ArrayList<Events> events) {
super.onPostExecute(events);
listView = (ListView) findViewById(R.id.listView);
ListAdapter listAdapter = new ListAdapter(HomeActivity.this, R.layout.activity_home_activiy, events);
listView.setAdapter(listAdapter);
}
}
Step 4: Insert code under onCreate()
private class GetListProduct extends AsyncTask<Void, Void, ArrayList<Events>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected ArrayList<Events> doInBackground(Void... params) {
ArrayList<Events> events = new ArrayList<>();
Events eventsLucky = new Events();
eventsLucky.setId("1");
eventsLucky.setTitleEvent("New Year CountDown Party");
eventsLucky.setDateEvent("10/10/12");
events.add(eventsLucky);
Events eventsLucky1 = new Events();
eventsLucky1.setId("2");
eventsLucky1.setTitleEvent("Tiger Remix Concert 2016 ");
eventsLucky1.setDateEvent("10/10/12");
events.add(eventsLucky1);
Events eventsLucky2 = new Events();
eventsLucky2.setId("3");
eventsLucky2.setTitleEvent("Tiger Remix Concert 2016 ");
eventsLucky2.setDateEvent("10/10/1212");
events.add(eventsLucky2);
Events eventsLucky3 = new Events();
eventsLucky3.setId("4");
eventsLucky3.setTitleEvent("Tiger Remix Concert 2016 ");
eventsLucky3.setDateEvent("10/10/1212");
events.add(eventsLucky3);
return events;
}
#Override
protected void onPostExecute(ArrayList<Events> events) {
super.onPostExecute(events);
listView = (ListView) findViewById(R.id.listView);
ListAdapter listAdapter = new ListAdapter(HomeActivity.this, R.layout.activity_home_activiy, events);
listView.setAdapter(listAdapter);
}
}
Related
I'm trying to create a simple news application,I am able to display data in the listview, But I want to display it in grid format.I am not getting any idea how to achieve that. Please support
Updted Code
package com.journaldev.androidrssfeedtutorial;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class RSSFeedActivity extends AppCompatActivity {
private ProgressBar pDialog;
ArrayList<HashMap<String, String>> rssItemList = new ArrayList<>();
RSSParser rssParser = new RSSParser();
Toolbar toolbar;
GridView gridView;
List<RSSItem> rssItems = new ArrayList<>();
private static String TAG_TITLE = "title";
private static String TAG_LINK = "link";
private static String TAG_DESCRIPTION = "description";
private static String TAG_PUB_DATE = "pubDate";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rss_feed);
String rss_link = getIntent().getStringExtra("rssLink");
new LoadRSSFeedItems().execute(rss_link);
/* ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent in = new Intent(getApplicationContext(),
MainActivity.class);
String page_url = ((TextView)
view.findViewById(R.id.page_url)).getText().toString().trim();
in.putExtra("url", page_url);
startActivity(in);
}
});*/
}
public class LoadRSSFeedItems extends AsyncTask<String, String,
String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressBar(RSSFeedActivity.this, null,
android.R.attr.progressBarStyleLarge);
RelativeLayout relativeLayout = findViewById(R.id.relativeLayout);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
pDialog.setLayoutParams(lp);
pDialog.setVisibility(View.VISIBLE);
relativeLayout.addView(pDialog);
}
#Override
protected String doInBackground(String... args) {
// rss link url
String rss_url = args[0];
// list of rss items
rssItems = rssParser.getRSSFeedItems(rss_url);
// looping through each item
for (RSSItem item : rssItems) {
// creating new HashMap
if (item.link.toString().equals(""))
break;
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
String givenDateString = item.pubdate.trim();
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy
HH:mm:ss Z");
try {
Date mDate = sdf.parse(givenDateString);
SimpleDateFormat sdf2 = new SimpleDateFormat("EEEE, dd MMMM
yyyy - hh:mm a", Locale.US);
item.pubdate = sdf2.format(mDate);
} catch (ParseException e) {
e.printStackTrace();
}
map.put(TAG_TITLE, item.title);
map.put(TAG_LINK, item.link);
map.put(TAG_DESCRIPTION, item.description);
map.put(TAG_PUB_DATE, item.pubdate); // If you want parse the
date
// adding HashList to ArrayList
rssItemList.add(map);
}
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/* ListAdapter adapter = new SimpleAdapter( //Old code
RSSFeedActivity.this,
rssItemList, R.layout.rss_item_list_row,
new String[]{TAG_LINK, TAG_TITLE,
TAG_DESCRIPTION,TAG_PUB_DATE},
new int[]{R.id.page_url, R.id.title,
R.id.description, R.id.pub_date});
// updating listview
setListAdapter(adapter);*/
RecyclerView recyclerView = (RecyclerView)
findViewById(R.id.recyclerView);
// set a GridLayoutManager with default vertical orientation
and 2 number of columns
GridLayoutManager gridLayoutManager = new
GridLayoutManager(getApplicationContext(), 2);
recyclerView.setLayoutManager(gridLayoutManager); // set
LayoutManager to RecyclerView
// call the constructor of CustomAdapter to send the
reference and data to Adapter
CustomAdapter customAdapter = new
CustomAdapter(RSSFeedActivity.this, rssItemList, new String[]
{TAG_LINK, TAG_TITLE, TAG_DESCRIPTION,TAG_PUB_DATE});
recyclerView.setAdapter(customAdapter);
}
});
return null;
}
protected void onPostExecute(String args) {
pDialog.setVisibility(View.GONE);
}
}
}
Custom Adapter class:
public class CustomAdapter extends
RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
ArrayList rssItemList;
Context context;
public CustomAdapter(Context context, ArrayList rssItemList,String[]
from) {
this.context = context;
this.rssItemList = rssItemList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int
viewType) {
// infalte the item Layout
View v =
LayoutInflater.from(parent.getContext()).inflate(R.layout.gridview_row,
parent, false);
// set the view's size, margins, paddings and layout parameters
MyViewHolder vh = new MyViewHolder(v); // pass the view to View
Holder
return vh;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position)
{
holder.name.setText(rssItemList.get(position)); //Showing error
holder.image.setText(rssItemList.get(position)); //Showing error
}
#Override
public int getItemCount() {
return rssItemList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
// init the item view's
TextView name;
TextView image;
public MyViewHolder(View itemView) {
super(itemView);
// get the reference of item view's
name = (TextView)
itemView.findViewById(R.id.android_gridview_text1);
image = (TextView)
itemView.findViewById(R.id.android_gridview_text2);
}
}
}
No i am facing one problem.Not able to pass data to custom adapter.Pls help me to solve this issue.
I want use notifyDataSetAdpter in my list view. I read about it that i can use it when my data is updating or deleting. In my case, my whole data will show in a listView and this data i am calling from MySQL. Now, I am just displaying DB values into a list. No deletion. I want this method to show updated DB values in a list I tried using this method but it didn't work. Can you please tell me how exactly and where exactly I have to use it, in my case.
Here is my code:
See_Issue.java
package com.example.mi.mikpiadmin;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class See_Issue extends AppCompatActivity implements ListView.OnItemClickListener {
ListView listView1;
public static final String URL_GET_ISSUE = "http://10.238.4.175/new/one.php";
public static final String TAG_JSON_ARRAY="results";
public static final String TAG_ID = "id";
public static final String TAG_STORE_NAME = "store_name";
public static final String TAG_ISSUE = "issue";
public static final String TAG_DESCRIBE = "describe";
private String JSON_ISSUE_STRING;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_see__issue);
listView1=(ListView)findViewById(R.id.list_see_issue) ;
listView1.setOnItemClickListener(this);
getJSON();
}
private void showEmployee(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_ISSUE_STRING);
JSONArray result = jsonObject.getJSONArray(TAG_JSON_ARRAY);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String id = jo.getString(TAG_STORE_NAME);
String name = jo.getString(TAG_ISSUE);
String describe = jo.getString(TAG_DESCRIBE);
HashMap<String,String> employees = new HashMap<>();
employees.put(TAG_STORE_NAME,id);
employees.put(TAG_ISSUE,name);
employees.put(TAG_DESCRIBE,describe);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
See_Issue.this, list, R.layout.list_item,
new String[]{TAG_STORE_NAME,TAG_ISSUE,TAG_DESCRIBE},
new int[]{R.id.id, R.id.name, R.id.feedback});
listView1.setAdapter(adapter);
((ListAdapter) listView1.getAdapter()).notifyDataSetChanged();
}
private void getJSON(){
class GetJSON extends AsyncTask<Void,Void,String> {
private ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(See_Issue.this,"Fetching Data","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
JSON_ISSUE_STRING = s;
showEmployee();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(URL_GET_ISSUE);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this, See_Feedback.class);
HashMap<String,String> map =(HashMap)parent.getItemAtPosition(position);
String empId = map.get(Config.TAG_ID).toString();
intent.putExtra(Config.EMP_ID,empId);
startActivity(intent);
}
}
I hope you will help.
you can use adapter.notifyDataSetChanged(); :
Call notifyDataSetChanged() on your Adapter object once you've modified the data in that adapter.
It notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.
for exapmle
((BaseAdapter) yourListView.getAdapter()).notifyDataSetChanged();
or
adapter.notifyDataSetChanged();
you have to make few changes to achieve this-
1- make these global-
private ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
private HashMapAdapter adapter;
2- Write your own custom adapter class-
public class HashMapAdapter extends BaseAdapter {
private HashMap<String, String> mData = new HashMap<String, String>();
private String[] mKeys;
public HashMapAdapter(HashMap<String, String> data){
mData = data;
mKeys = mData.keySet().toArray(new String[data.size()]);
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Object getItem(int position) {
return mData.get(mKeys[position]);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
String key = mKeys[pos];
String Value = getItem(pos).toString();
//do your view stuff here
return convertView;
}
public void updateData(HashMap<String, String> updatedData){
mData = updatedData;
mKeys = updatedData.keySet().toArray(new String[data.size()]);
//notifying dataset changed
notifyDataSetChanged();
}
}
3- change your showEmployee() method
private void showEmployee(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_ISSUE_STRING);
JSONArray result = jsonObject.getJSONArray(TAG_JSON_ARRAY);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String id = jo.getString(TAG_STORE_NAME);
String name = jo.getString(TAG_ISSUE);
String describe = jo.getString(TAG_DESCRIBE);
HashMap<String,String> employees = new HashMap<>();
employees.put(TAG_STORE_NAME,id);
employees.put(TAG_ISSUE,name);
employees.put(TAG_DESCRIBE,describe);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new HashMapAdapter(list);
listView1.setAdapter(adapter);
}
4- Write an update method
private void updateAdapter((HashMap<String, String> updatedData){
//This will update the adapter data and will call the notifyDatasetChanged
apater.updatedData(updatedData);
}
Am looking sample program which could dynamically populating Spinner item from server using Retrofit 1.9 but still I couldn't find any sample can someone share if there is any sample regarding this requirement or else share the method.
How it should be done as am new for android bit struggling to find a solution thanks in advance!
Here is my spinneritem class:
public class MySpinnerItem {
public MySpinnerItem(){
}
public MySpinnerItem(String text, Integer value) {
Text = text;
Value = value;
}
public String getText() {
return Text;
}
public void setText(String text) {
Text = text;
}
public Integer getValue() {
return Value;
}
public void setValue(Integer value) {
Value = value;
}
public String Text;
public Integer Value;
}
Here is my spinner adapter:
package first.service.precision.servicefirst;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by 4264 on 25-11-2015.
*/
public class MySpinnerAdapter extends ArrayAdapter<MySpinnerItem> {
private Context context;
private List<MySpinnerItem> objects;
public MySpinnerAdapter(Context context, int resource, List<MySpinnerItem> objects) {
super(context, resource, objects);
this.context = context;
this.objects = objects;
}
#Override
public void add(MySpinnerItem object) {
this.objects.add(object);
}
#Override
public int getCount() {
return objects.size();
}
#Override
public MySpinnerItem getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView label = new TextView(context);
label.setText(objects.get(position).getText());
return label;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
TextView label = new TextView(context);
label.setText(objects.get(position).getText());
return label;
}
}
Here is the fragment where i set adapter for spinners:
package first.service.precision.servicefirst;
/**
* Created by 4264 on 23-11-2015.
*/
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import com.squareup.otto.Bus;
import java.util.ArrayList;
import java.util.List;
public class NewRequirements extends Fragment {
Bus bus;
MyListAdapter listAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
List<MySpinnerItem> SbuList = new ArrayList<MySpinnerItem>();
SbuList.add(new MySpinnerItem("Saravanan.R",1));
SbuList.add(new MySpinnerItem("Yogeshwaran",2));
SbuList.add(new MySpinnerItem("Sathesh",3));
SbuList.add(new MySpinnerItem("Barath",4));
SbuList.add(new MySpinnerItem("Deepak",5));
SbuList.add(new MySpinnerItem("Venkat",6));
SbuList.add(new MySpinnerItem("Meena",7));
SbuList.add(new MySpinnerItem("Ram",8));
SbuList.add(new MySpinnerItem("Jegan",9));
View view = inflater.inflate(R.layout.fragment_dialog_claim, container,
false);
final Button btnupdate;
btnupdate = (Button) view.findViewById(R.id.btnAdd);
final Spinner spSbuID = (Spinner) view.findViewById(R.id.spSbuID);
final Spinner spBuID = (Spinner) view.findViewById(R.id.spBuID);
final Spinner spSubBuID = (Spinner) view.findViewById(R.id.spSubBuID);
final Spinner spServiceCategoryID = (Spinner) view.findViewById(R.id.spServiceCategoryID);
final Spinner spServiceSubCategoryID = (Spinner) view.findViewById(R.id.spServiceSubCategoryID);
final EditText txtRequirements=(EditText)view.findViewById(R.id.txtRequirements);
MySpinnerAdapter myadapter = new MySpinnerAdapter(getActivity().getBaseContext(),android.R.layout.simple_spinner_dropdown_item,SbuList);
spSbuID.setAdapter(myadapter);
myadapter = new MySpinnerAdapter(getActivity().getBaseContext(),android.R.layout.simple_spinner_dropdown_item,SbuList);
spBuID.setAdapter(myadapter);
myadapter = new MySpinnerAdapter(getActivity().getBaseContext(),android.R.layout.simple_spinner_dropdown_item,SbuList);
spSubBuID.setAdapter(myadapter);
myadapter = new MySpinnerAdapter(getActivity().getBaseContext(),android.R.layout.simple_spinner_dropdown_item,SbuList);
spServiceCategoryID.setAdapter(myadapter);
myadapter = new MySpinnerAdapter(getActivity().getBaseContext(),android.R.layout.simple_spinner_dropdown_item,SbuList);
spServiceSubCategoryID.setAdapter(myadapter);
try{
Object o;
o = getFragmentManager().findFragmentByTag("add");
Log.v("FIND", o.toString());
}
catch (Exception ex) {
Log.v("FIND", ex.toString());
}
// add.notify();
btnupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LeadRequirementsView objLeadRequirementsView = new LeadRequirementsView();
MySpinnerItem item;
item = (MySpinnerItem)spSbuID.getSelectedItem();
objLeadRequirementsView.setSbuID(item.getValue());
objLeadRequirementsView.setSbuName(item.getText());
item = (MySpinnerItem)spBuID.getSelectedItem();
objLeadRequirementsView.setBuID(item.getValue());
objLeadRequirementsView.setBuName(item.getText());
item = (MySpinnerItem)spSubBuID.getSelectedItem();
objLeadRequirementsView.setSubBuID(item.getValue());
objLeadRequirementsView.setSubBuName(item.getText());
item = (MySpinnerItem)spServiceCategoryID.getSelectedItem();
objLeadRequirementsView.setServiceCategoryID(item.getValue());
objLeadRequirementsView.setServiceCategoryName(item.getText());
item = (MySpinnerItem)spServiceSubCategoryID.getSelectedItem();
objLeadRequirementsView.setServiceSubCategoryID(item.getValue());
objLeadRequirementsView.setServiceSubCategoryName(item.getText());
objLeadRequirementsView.setDescription(txtRequirements.getText().toString());
Add add;
add = (Add)getFragmentManager().findFragmentByTag("add");
add.updateListView(objLeadRequirementsView);
getActivity().getFragmentManager().popBackStack();
}
});
return view;
}
}
My doubt is i have done it using dummy data but i need to bind the json response from the server to my spinner how come i do this.
Below, is a sample for setting the spinner
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter;
List<String> data;
data = new ArrayList<>();
for (int i = 0; i < 20; i++)
data.add("Data " + (i + 1));
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, data);
spinner.setAdapter(adapter);
Here data is a dummy data , in your case it will be dummy data.
first create theretrofitapi interface
/**
* reCreated by goodlife on 1/11/2016.
*/
import java.util.List;
import retrofit.Callback;
import retrofit.client.Response;
import retrofit.http.Field;
import retrofit.http.FormUrlEncoded;
import retrofit.http.GET;
import retrofit.http.POST;
/**
* Created by Belal on 11/5/2015.
*/
public interface RetrofitInternetApi {
//#FormUrlEncoded, we have to write this if we want to send post data to the server.
//#POST, because we are using an HTTP Post request we have written this.
// Inside it we have the URL of the script that will be receiving the post request.
// Note that the URL is excluding the root URL. And we have defined the root URL in our MainActivity.
//#Field(“key”) String variable inside key we have to write what we have written inside $_POST[‘key’] in our script.
// And we have to specify it for all the values we are going to send.
//Callback<Response> callback it is also inside the retrofit library. It will receive the output from the server.
//But this is only an interface and the method is abstract.
//We will define the method inside fetchDepartmentName() method that is declared inside MainActivity.java.
#GET("/getDepartmentName.php")
public void getDepartmentName(Callback<List<DepartmentNoRealm>> response);
}
then create the function
private void fetchDepartmentName(){
//Creating a rest adapter
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(ROOT_URL)
.build();
//Creating an object of our api interface
RetrofitInternetApi retrofitInternetApi = restAdapter.create(RetrofitInternetApi.class);
//While the app fetched data we are displaying a progress dialog
final ProgressDialog loading = ProgressDialog.show(getActivity(), "Fetching Data", "Please wait...", false, false);
//Defining the method
retrofitInternetApi.getDepartmentName(new Callback<List<DepartmentNoRealm>>() {
#Override
public void success(List<DepartmentNoRealm> list, Response response) {
//Dismissing the loading progressbar
loading.dismiss();
Log.d("JSON LIST",list.toString());
//Storing the data in our list
departmentNoRealmList = list;
//Calling a method to show the list
showListinSpinner(); }
#Override
public void failure(RetrofitError error) {
//you can handle the errors here
}
});
}
then create a class model
package myafya.safaricom.co.ke.myafya.model.realm;
/**
* Created by 001557 on 1/13/2016.
*/
public class DepartmentNoRealm {
public int departmentID;
public String departmentName;
public String departmentURLimage;
public int getDepartmentID() {
return departmentID;
}
public void setDepartmentID(int departmentID) {
this.departmentID = departmentID;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public String getDepartmentURLimage() {
return departmentURLimage;
}
public void setDepartmentURLimage(String departmentURLimage) {
this.departmentURLimage = departmentURLimage;
}
}
now the code showList in Spinner
//Our method to show list
private void showListinSpinner(){
//String array to store all the book names
String[] items = new String[departmentNoRealmList.size()];
//Traversing through the whole list to get all the names
for(int i=0; i<departmentNoRealmList.size(); i++){
//Storing names to string array
items[i] = departmentNoRealmList.get(i).getDepartmentName();
}
//Spinner spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
//setting adapter to spinner
spinnerDepartments.setAdapter(adapter);
//Creating an array adapter for list view
}
Then SHARE IT AND MAKE IT EASY
MY JSON WAS
[
{
"departmentID": "1",
"departmentName": "Enterprise Business Unit (EBU)",
"departmentURLimage": "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSKOZmGNAA08NbHwRJrloAouWqs6r4x7BGXY4k-ULWiHuPEobHI"
},
{
"departmentID": "2",
"departmentName": "Consumer Business Unit (CBU)",
"departmentURLimage": "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQ0IAFhZ52KiG_0ck5VbBxweZWf_MEA9eRmgHAEr6CG-rUG_a2QEQ"
}
]
try {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService service = retrofit.create(APIService.class);
Call<List<People>> call = service.getYear(user_id);
call.enqueue(new Callback<List<People>>()
{
#Override
public void onResponse(Response<List<People>> response, Retrofit retrofit) {
posts = response.body();
String[] s =new String[posts.size()];
for(int i=0;i<posts.size();i++)
{
s[i]= posts.get(i).getYear();
final ArrayAdapter a = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_spinner_item, s);
a.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
Branch.setAdapter(a);
}
}
#Override
public void onFailure(Throwable t) { }
});
} catch (Exception e) {
Log.d("onResponse", "There is an error");
}
}
I would like to append new items to a ListView to enable endless scrolling.
private ListAdapter adapter;
ArrayList < HashMap < String, String >> listViewList;
...
class GetItems extends AsyncTask < String, String, String > {
protected String doInBackground(String...args) {
...
for (int i = 0; i < items.length(); i++) {
...
HashMap < String, String > map = new HashMap < String, String > ();
map.put("name_1", name_1);
map.put("name_2", name_3);
map.put("name_3", name_3);
listViewList.add(map);
}
}
protected void onPostExecute(String file_url) {
adapter = new CustomAdapter(Activity.this, listViewList,
R.layout.single_item, new String[] {}, new int[] {});
setListAdapter(adapter);
}
}
GetItems class gets new items based on a page number you provide. I would like to append new items to existing ListView items on onPostExecute.
Any idea how to do it?
Check out this library on GitHub
https://github.com/codepath/android_guides/wiki/Endless-Scrolling-with-AdapterViews
EDIT according to your comment:
You need to forget about ListActivity and that you ever heard it exists, it's useless for what you are trying to do.
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class DemosAdapter extends BaseAdapter {
public List<DemoItem> listOfItems;
private View v;
private ViewWrapper wrapper;
private Context context;
public DemosAdapter(Context c, List<DemoItem> listOfItems) {
this.context = c;
this.listOfItems = listOfItems;
}
#Override
public int getCount() {
return listOfItems.size();
}
#Override
public DemoItem getItem(int i) {
return listOfItems.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
public void sort() {
Collections.sort(listOfItems, new Comparator<DemoItem>() {
#Override
public int compare(DemoItem item, DemoItem item2) {
return item.getName().compareTo(item2.getName());
}
});
}
public void addItems(List<DemoItem> listOfFreshItems){
listOfItems.addAll(listOfFreshItems);
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
DemoItem itm = listOfItems.get(position);
v = convertView;
if (v == null) {
LayoutInflater inflater = LayoutInflater.from(context);
v = inflater.inflate(R.layout.demo_item, null, false);
wrapper = new ViewWrapper(v);
v.setTag(wrapper);
}
else {
wrapper = (ViewWrapper) v.getTag();
}
wrapper.getTvDemoName().setText(itm.getName());
return v;
}
private class ViewWrapper {
private View base;
private TextView tvDemoName;
public ViewWrapper(View v) {
this.base = v;
}
public TextView getTvDemoName() {
if (tvDemoName == null) {
tvDemoName = (TextView) base.findViewById(R.id.tvDemoName);
}
return tvDemoName;
}
}
}
The first time you add data, do this
demosAdapter = new DemosAdapter(this, listOfDemos);
demosAdapter.sort();
lvListOfDemos.setAdapter(demosAdapter);
When you get new items, just call
adapter.addItems(List<DemoItem> newItems);
Actually you just need to call adapter.notifyDataSetChanged in onPostExecute.
But you should not instantiate adapter many times. It should be done just one so overall it would look like this
private ListAdapter adapter;
...
void onCreate(){ // assuming this is an activity
adapter = new CustomAdapter(Activity.this, listViewList,
R.layout.single_item, new String[] {}, new int[] {});
setListAdapter(adapter);
}
class GetItems extends AsyncTask<String, String, String> {
...
protected void onPostExecute(String file_url) {
adapter.notifyDataSetChanged();
}
}
I'm trying to add to RSS Feed reader (ListActivity) ActionBar - (http://www.edumobile.org/android/android-tutorial/rssreader-in-android-development/)
I have used Fragment to do this.
Now I got error I don't know how to fix it
No enclosing instance of the type News is accessible in scope
The error is in:
rssadaptor = new RSSListAdaptor(News.this, R.layout.newslist,itemlist);
//Here
progress = ProgressDialog.show(
News.this, null, "Loading RSS Feeds...");
//Here
LayoutInflater vi = (LayoutInflater)News.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Here
Here is the full code of the activity:
package com.rss.test.actionbar;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class News extends ActionBarActivity {
private static ArrayList<NewsItem> itemlist = null;
private static MyFragment.RSSListAdaptor rssadaptor = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionbar = getSupportActionBar();
setContentView(R.layout.news);
actionbar.setDisplayShowCustomEnabled(true);
itemlist = new ArrayList<NewsItem>();
MyFragment fragment = new MyFragment();
getSupportFragmentManager().beginTransaction().replace(android.R.id.content, fragment).commit();
fragment.new RetrieveRSSFeeds().execute();
}
public static class MyFragment extends ListFragment {
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity();
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
NewsItem data = itemlist.get(position);
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(data.link));
startActivity(intent);
}
private void retrieveRSSFeed(String urlToRssFeed,ArrayList<NewsItem> list)
{
try
{
URL url = new URL(urlToRssFeed);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlreader = parser.getXMLReader();
RSSParser theRssHandler = new RSSParser(list);
xmlreader.setContentHandler(theRssHandler);
InputSource is = new InputSource(url.openStream());
xmlreader.parse(is);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private class RetrieveRSSFeeds extends AsyncTask<Void, Void, Void>
{
private ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
retrieveRSSFeed("/*RSS Url*/",itemlist);
rssadaptor = new RSSListAdaptor(News.this, R.layout.newslist,itemlist);
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(
News.this, null, "Loading RSS Feeds...");
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result) {
ListView l = (ListView)getActivity().findViewById(R.id.list);
l.setAdapter(rssadaptor);
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
private class RSSListAdaptor extends ArrayAdapter<NewsItem>{
private List<NewsItem> objects = null;
public RSSListAdaptor(Context context, int textviewid, List<NewsItem> objects) {
super(context, textviewid, objects);
this.objects = objects;
}
#Override
public int getCount() {
return ((null != objects) ? objects.size() : 0);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public NewsItem getItem(int position) {
return ((null != objects) ? objects.get(position) : null);
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(null == view)
{
LayoutInflater vi = (LayoutInflater)News.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.newslist, null);
}
NewsItem data = objects.get(position);
if(null != data)
{
TextView title = (TextView)view.findViewById(R.id.txtTitle);
TextView date = (TextView)view.findViewById(R.id.txtDate);
TextView description = (TextView)view.findViewById(R.id.txtDescription);
title.setText(data.title);
date.setText("on " + data.date);
description.setText(Html.fromHtml(data.description));
}
return view;
}
}
}
}
A static inner class like your fragment cannot access the outer class instance OuterClass.this.
For a Context in a fragment, use getActivity() rather than OuterClass.this.
Because MyFragment is static class so you are able to access News Activity context in RetrieveRSSFeeds .
Simply use RetrieveRSSFeeds class constructor to get Activity context in doInBackground :
public Context mContext;
public RetrieveRSSFeeds(Context mContext){
this.mContext=mContext;
}
and from Activity :
fragment.new RetrieveRSSFeeds(News.this).execute();