How to display db mysql data after selecting the item from spinner - android

I want to display status and wilayah details from tbl_pegawai table.. If i select an item (name) from the spinner, i want to display the corresponding data (status and wilayah) matches with that item from the database.
Here is my android MainActivity.class file..
Spinner spinnernama, spinnerstatus, spinnerwilayah;
EditText inputstatus, inputwilayah;
Adapterspinner adapter;
List<String> valueId = new ArrayList<String>();
List<String> valueNama = new ArrayList<String>();
List<ModelSpinner> listspinner = new ArrayList<ModelSpinner>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cobaspinner);
spinnernama = findViewById(R.id.spin1);
spinnerstatus = findViewById(R.id.spin2);
spinnerwilayah = findViewById(R.id.spin3);
inputstatus = findViewById(R.id.input1);
inputwilayah = findViewById(R.id.input2);
spinnernama.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
inputstatus.setText(listspinner.get(position).getStatus());
inputwilayah.setText(listspinner.get(position).getWilayah());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
adapter = new Adapterspinner(cobaspinner.this, listspinner);
spinnernama.setAdapter(adapter);
callData();
}
private void callData() {
AndroidNetworking.get("http://192.168.43.20:8080/mopp/getDataPegawai.php")
.setTag("Get Data")
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
Boolean status = response.getBoolean("status");
if(status){
JSONArray jsonArray = response.getJSONArray("result");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
ModelSpinner item =new ModelSpinner();
item.setId(jsonObject.getString("id"));
item.setNama(jsonObject.getString("nama"));
item.setStatus(jsonObject.getString("status"));
item.setWilayah(jsonObject.getString("wilayah"));
listspinner.add(item);
}
}
} catch (Exception e){
e.printStackTrace();
}
}
#Override
public void onError(ANError anError) {
}
});
}
}
here is my spinneradapter...
private Activity activity;
private LayoutInflater inflater;
private List<ModelSpinner> item;
public Adapterspinner(Activity activity, List<ModelSpinner> item) {
this.activity = activity;
this.item = item;
}
#Override
public int getCount() {
return item.size();
}
#Override
public Object getItem(int location) {
return item.get(location);
}
#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.activity_cobaspinner, null);
EditText status = (EditText) convertView.findViewById(R.id.input1);
EditText wilayah = (EditText) convertView.findViewById(R.id.input1);
ModelSpinner data;
data = item.get(position);
status.setText(data.getStatus());
wilayah.setText(data.getWilayah());
return convertView;
Here output when I running and select data from spinner no data display on spinner

Related

Search items from listview with custom adapter

Am trying search from listview using custom adapter. i have search widget in toolbar menu and i can display widget. when i click on search icon, it expands, but when i start typing, search does not happen and list gets cleared. can someone plz trace this issue .
Here's my code from Main Activity:
public class VideoActivity extends BaseActivity {
ListView listView;
ArrayList<Video> videoArrayList;
public VideoListAdapter videoListAdapter;
String vid_id, vid_title, vid_type, vid_path, vid_img;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
initializeToolbar();
listView = (ListView) findViewById(R.id.listview_video);
videoArrayList = new ArrayList<Video>();
videoListAdapter = new VideoListAdapter(VideoActivity.this, videoArrayList);
jsonParser = new JSONParser();
new VideoTask().execute();
public class VideoTask extends AsyncTask<String, String, JSONObject> {
#Override
protected JSONObject doInBackground(String... strings) {
jsonObject = jsonParser.makeHttpRequest2(Network_constants.video_list_page, "POST");
Log.e("json data", "" + jsonObject);
return jsonObject;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
progressDialog.dismiss();
if (jsonObject != null) {
try {
jsonArray = jsonObject.getJSONArray("videos");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
Log.d("jsonObject1", "" + jsonObject1);
Video video = new Video();
vid_id = jsonObject1.getString("video_id");
vid_title = jsonObject1.getString("video_channel_name");
vid_type = jsonObject1.getString("video_channel_link");
vid_path = jsonObject1.getString("video_channel_description");
vid_img = jsonObject1.getString("video_img_path");
video.set_vTitle(vid_title);
TextView t1 = (TextView) findViewById(R.id.video_title);
TextView t2 = (TextView) findViewById(R.id.video_type);
video.set_vArtist(vid_title);
video.set_vType(vid_type);
videoArrayList.add(video);
}
} catch (JSONException e) {
e.printStackTrace();
}
listView.setAdapter(videoListAdapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView cnt = (TextView) view.findViewById(R.id.video_type);
String cn = cnt.getText().toString();
Intent i = new Intent(VideoActivity.this, Youtube.class);
i.putExtra("url", cn);
startActivity(i);
}
});
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.clear();
getMenuInflater().inflate(R.menu.main,menu);
MenuItem menuItem = menu.findItem(R.id.menu_search);
final SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if(TextUtils.isEmpty(newText)){
LogHelper.e("Query Result","Filter is Empty");
}else{
videoListAdapter.filter(newText);
}
return true;
}
});
return true;
}
}
And this is my CustomAdapter class :
public class VideoListAdapter extends BaseAdapter {
private Activity activity;
private static LayoutInflater inflater = null;
ImageView imageView;
private String mCurrentArtUrl;
private ArrayList<Video> video;
private ArrayList<Video> searchListView = null;
public VideoListAdapter(Activity a, ArrayList<Video> b){
this.activity = a;
this.video = b;
this.searchListView = new ArrayList<Video>();
this.searchListView.addAll(video);
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return video.size();
}
#Override
public Object getItem(int position) {
return video.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.video_list_item, null);
final TextView v_title = (TextView)vi.findViewById(R.id.video_title);
final TextView v_type = (TextView)vi.findViewById(R.id.video_type);
final TextView v_artist = (TextView)vi.findViewById(R.id.video_artist);
imageView = (ImageView) vi.findViewById(R.id.video_image);
Video video1 = video.get(position);
v_title.setText(video1.get_vTitle());
v_type.setText(video1.get_vType());
v_artist.setText(video1.get_vArtist());
String img = video1.get_vImage();
String profile = Network_constants.image_url + img;
fetchImageAsync(profile);
return vi;
}
// Filter method
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
video.clear();
if(charText.length() == 0){
video.addAll(searchListView);
}else{
for(Video v : searchListView){
LogHelper.e("Query","Entered For Loop");
if(v.get_vTitle().contains(charText)){
video.add(v);
}else{
LogHelper.e("Query","Could not create list");
}
}
}
notifyDataSetChanged();
}
}
I think my code is not working with the for loop in the filter function i guess.
You should implements Filterable in your Adapter

Listview is not updating after SwipeRefreshLayout

I have code to show listview from my server, but when I update the data from server and refresh it in my app, the listview still getting the old data, and after several minutes when I open the app again, it updated the new data that I updated before.
My Main Fragment
public class DosenFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
ListView list;
SwipeRefreshLayout swipe;
List<Dosen> itemList = new ArrayList<>();
AdapterDosen adapter;
private static final String TAG = DosenFragment.class.getSimpleName();
private static String url_select = Server.URL + "select.php";
public static final String TAG_ID_DOSEN = "id_dosen";
public static final String TAG_NAME = "name";
public static final String TAG_STATUS = "status";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.matkul_list, container, false);
swipe = (SwipeRefreshLayout) v.findViewById(R.id.swipe_refresh_layout);
list = (ListView) v.findViewById(R.id.list);
adapter = new AdapterDosen(getActivity(), itemList);
list.setAdapter(adapter);
swipe.setOnRefreshListener(this);
swipe.post(new Runnable() {
#Override
public void run() {
swipe.setRefreshing(true);
itemList.clear();
adapter.notifyDataSetChanged();
callVolley();
}
});
return v;
}
#Override
public void onRefresh() {
itemList.clear();
adapter.notifyDataSetChanged();
callVolley();
}
private void callVolley() {
swipe.setRefreshing(true);
JsonArrayRequest jArr = new JsonArrayRequest(url_select, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Dosen item = new Dosen();
item.setId_dosen(obj.getString(TAG_ID_DOSEN));
item.setName(obj.getString(TAG_NAME));
item.setAlamat(obj.getString(TAG_STATUS));
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
AppController.getInstance().addToRequestQueue(jArr);
}
}
I have tried to do something with itemList.clear(); and adapter.notifyDataSetChanged(); but nothing change.
My Main Adapter
public class AdapterDosen extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Dosen> items;
public AdapterDosen(Activity activity, List<Dosen> items) {
this.activity = activity;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int location) {
return items.get(location);
}
#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.list_row, null);
Dosen data = items.get(position);
TextView id = (TextView) convertView.findViewById(R.id.id);
TextView name = (TextView) convertView.findViewById(R.id.nama);
TextView alamat = (TextView) convertView.findViewById(R.id.alamat);
id.setText(data.getId_dosen());
name.setText(data.getName());
alamat.setText(data.getAlamat());
return convertView;
}
}
I'm sorry for my bad english.
Please help.
try this , add this method in your adatper
public void updateList(List<Dosen> newlist) {
items.clear();
items.addAll(newlist);
this.notifyDataSetChanged();
}
and in callVolley() method , replace this
adapter.notifyDataSetChanged();
with
adapter.updateList();
Hope this helps
Use the below Code...
/* Within the RecyclerView.Adapter class */
// Clean all elements of the recycler
public void clear() {
items.clear();
notifyDataSetChanged();
}
// Add a list of items -- change to type used
public void addAll(List<Dosen> newlist) {
items.addAll(newlist);
notifyDataSetChanged();
}
callvolly() method inside.
adapter.clear();
adapter.addAll(item);
public void onRefresh() {
callVolley();
}
please try this code i have changed something it will work fine
public class AdapterDosen extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Dosen> items;
public AdapterDosen(Activity activity, List<Dosen> items) {
this.activity = activity;
this.items = items;
}
public void setData(List<Dosen> items){
this.items = items
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int location) {
return items.get(location);
}
#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.list_row, null);
Dosen data = items.get(position);
TextView id = (TextView) convertView.findViewById(R.id.id);
TextView name = (TextView) convertView.findViewById(R.id.nama);
TextView alamat = (TextView) convertView.findViewById(R.id.alamat);
id.setText(data.getId_dosen());
name.setText(data.getName());
alamat.setText(data.getAlamat());
return convertView;
}
}
public class DosenFragment extends Fragment implements
SwipeRefreshLayout.OnRefreshListener {
ListView list;
SwipeRefreshLayout swipe;
List<Dosen> itemList = new ArrayList<>();
AdapterDosen adapter;
private static final String TAG = DosenFragment.class.getSimpleName();
private static String url_select = Server.URL + "select.php";
public static final String TAG_ID_DOSEN = "id_dosen";
public static final String TAG_NAME = "name";
public static final String TAG_STATUS = "status";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.matkul_list, container, false);
swipe = (SwipeRefreshLayout)
v.findViewById(R.id.swipe_refresh_layout);
list = (ListView) v.findViewById(R.id.list);
adapter = new AdapterDosen(getActivity(), itemList);
list.setAdapter(adapter);
swipe.setOnRefreshListener(this);
swipe.post(new Runnable() {
#Override
public void run() {
swipe.setRefreshing(true);
itemList.clear();
adapter.notifyDataSetChanged();
callVolley();
}
});
return v;
}
#Override
public void onRefresh() {
//itemList.clear();
//adapter.notifyDataSetChanged();
callVolley();
}
private void callVolley() {
swipe.setRefreshing(true);
JsonArrayRequest jArr = new JsonArrayRequest(url_select, new
Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
itemList .clear();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj =
response.getJSONObject(i);
Dosen item = new Dosen();
item.setId_dosen(obj.getString(TAG_ID_DOSEN));
item.setName(obj.getString(TAG_NAME));
item.setAlamat(obj.getString(TAG_STATUS));
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.setData(itemList );
adapter.notifyDataSetChanged();
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
AppController.getInstance().addToRequestQueue(jArr);
}

Android:Receive Array of Objects and display in listView

Hello to all android folks over there!!
I want to get list of objects from web service and want to display them in list view.Now i am able to fetch those values and collected them in arraylist.But i am facing problem to display them in list view.below is my code.
Using everyones suggestion ,i solved my problem.Thats the spirit of android buddies.I am pasting my answer in UPDATED block.Hope it will be helpful in future.
UPDATED
public class TabFragment2 extends android.support.v4.app.Fragment {
ListView FacultyList;
View rootView;
LinearLayout courseEmptyLayout;
FacultyListAdapter facultyListAdapter;
String feedbackresult,programtype,programname;
Boolean FeedBackResponse;
String FacultiesList[];
public ArrayList<Faculty> facultylist = new ArrayList<Faculty>();
SharedPreferences pref;
FacultyListAdapter adapter;
SessionSetting session;
public TabFragment2(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = getActivity().getSharedPreferences("prefbook", getActivity().MODE_PRIVATE);
programtype = pref.getString("programtype", "NOTHINGpref");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_studenttab2, container, false);
session = new SessionSetting(getActivity());
new FacultySyncerBg().execute("");
courseEmptyLayout = (LinearLayout) rootView.findViewById(R.id.feedback_empty_layout);
FacultyList = (ListView) rootView.findViewById(R.id.feedback_list);
facultyListAdapter = new FacultyListAdapter(getActivity());
FacultyList.setEmptyView(rootView.findViewById(R.id.feedback_list));
FacultyList.setAdapter(facultyListAdapter);
return rootView;
}
public class FacultyListAdapter extends BaseAdapter {
private final Context context;
public FacultyListAdapter(Context context) {
this.context = context;
if (!facultylist.isEmpty())
courseEmptyLayout.setVisibility(LinearLayout.GONE);
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ViewHolder TabviewHolder;
if (convertView == null) {
TabviewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_feedback,
parent, false);
TabviewHolder.FacultyName = (TextView) convertView.findViewById(R.id.FacultyName);//facultyname
TabviewHolder.rating = (RatingBar) convertView.findViewById(R.id.rating);//rating starts
TabviewHolder.Submit = (Button) convertView.findViewById(R.id.btnSubmit);
// Save the holder with the view
convertView.setTag(TabviewHolder);
} else {
TabviewHolder = (ViewHolder) convertView.getTag();
}
final Faculty mFac = facultylist.get(position);//*****************************NOTICE
TabviewHolder.FacultyName.setText(mFac.getEmployeename());
// TabviewHolder.ModuleName.setText(mFac.getSubject());
TabviewHolder.rating.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
feedbackresult =String.valueOf(rating);
}
});
return convertView;
}
#Override
public int getCount() {
return facultylist.size();
}
#Override
public Object getItem(int position) {return facultylist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
static class ViewHolder {
TextView FacultyName;
RatingBar rating;
Button Submit;
}
private class FacultySyncerBg extends AsyncTask<String, Integer, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog= ProgressDialog.show(getActivity(), "Faculty Feedback!","Fetching Faculty List", true);
}
#Override
protected Void doInBackground(String... params) {
//CALLING WEBSERVICE
Faculty(programtype);
return null;
}
#Override
protected void onPostExecute(Void result) {
/*if (FacultyList.getAdapter() != null) {
if (FacultyList.getAdapter().getCount() == 0) {
FacultyList.setAdapter(facultyListAdapter);
} else
{
facultyListAdapter.notifyDataSetChanged();
}
} else {
FacultyList.setAdapter(facultyListAdapter);
}
progressDialog.dismiss();*/
if (!facultylist.isEmpty()) {
// FacultyList.setVisibiltity(View.VISIBLE) ;
courseEmptyLayout.setVisibility(LinearLayout.GONE);
if (FacultyList.getAdapter() != null)
{
if (FacultyList.getAdapter().getCount() == 0)
{
FacultyList.setAdapter(facultyListAdapter);
}
else
{
facultyListAdapter.notifyDataSetChanged();
}
}
else
{
FacultyList.setAdapter(facultyListAdapter);
}
}else
{
courseEmptyLayout.setVisibility(LinearLayout.VISIBLE);
// FacultyList.setVisibiltity(View.GONE) ;
}
progressDialog.dismiss();
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && isResumed()) {
new FacultySyncerBg().execute("");
}
}//end*
//**************************WEBSERVICE CODE***********************************
public void Faculty(String programtype)
{
String URL ="http://detelearning.cloudapp.net/det_skill_webservice/service.php?wsdl";
String METHOD_NAMEFACULTY = "getUserInfo";
String NAMESPACEFAC="http://localhost", SOAPACTIONFAC="http://detelearning.cloudapp.net/det_skill_webservice/service.php/getUserInfo";
String faculty[]=new String[4];//changeit
String webprogramtype="flag";
String programname="DESHPANDE SUSANDHI ELECTRICIAN FELLOWSHIP";
// Create request
SoapObject request = new SoapObject(NAMESPACEFAC, METHOD_NAMEFACULTY);
request.addProperty("fellowshipname", programname);
// Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
// Set output SOAP object
envelope.setOutputSoapObject(request);
// Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
//my code Calling Soap Action
androidHttpTransport.call(SOAPACTIONFAC, envelope);
// ArrayList<Faculty> facultylist = new ArrayList<Faculty>();
java.util.Vector<SoapObject> rs = (java.util.Vector<SoapObject>) envelope.getResponse();
if (rs != null)
{
for (SoapObject cs : rs)
{
Faculty rp = new Faculty();
rp.setEmployeename(cs.getProperty(0).toString());//program name
rp.setEmployeeid(cs.getProperty(1).toString());//employee name
facultylist.add(rp);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
if (lstView.getAdapter() != null) {
if (lstView.getAdapter().getCount() == 0) {
lstView.setAdapter(finalAdapter);
} else {
finalAdapter.notifyDataSetChanged();
}
} else {
lstView.setAdapter(finalAdapter);
}
and setVisibiltity(View.VISIBLE)for listview
Put this code here
#Override
protected void onPostExecute(Void result) {
if (!facultylist.isEmpty()) {
FacultyList.setVisibiltity(View.VISIBLE) ;
courseEmptyLayout.setVisibility(LinearLayout.GONE);
if (FacultyList.getAdapter() != null) {
if (FacultyList.getAdapter().getCount() == 0) {
FacultyList.setAdapter(facultyListAdapter);
} else {
facultyListAdapter.notifyDataSetChanged();
}
} else {
FacultyList.setAdapter(facultyListAdapter);
}
}else{
courseEmptyLayout.setVisibility(LinearLayout.VISIBLE);
FacultyList.setVisibiltity(View.GONE) ;
}
progressDialog.dismiss();
}
you can try this:
this is the adapter class code.
public class CustomTaskHistory extends ArrayAdapter<String> {
private Activity context;
ArrayList<String> listTasks = new ArrayList<String>();
String fetchRefID;
StringBuilder responseOutput;
ProgressDialog progress;
String resultOutput;
public String getFetchRefID() {
return fetchRefID;
}
public void setFetchRefID(String fetchRefID) {
this.fetchRefID = fetchRefID;
}
public CustomTaskHistory(Activity context, ArrayList<String> listTasks) {
super(context, R.layout.content_main, listTasks);
this.context = context;
this.listTasks = listTasks;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_task_history, null, true);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
LinearLayout linearLayout = (LinearLayout) listViewItem.findViewById(R.id.firstLayout);
//System.out.println("client_id" + _clientID);
//TextView textViewDesc = (TextView) listViewItem.findViewById(R.id.textViewDesc);
//ImageView image = (ImageView) listViewItem.findViewById(R.id.imageView);
if (position % 2 != 0) {
linearLayout.setBackgroundResource(R.color.sky_blue);
} else {
linearLayout.setBackgroundResource(R.color.white);
}
textViewName.setText(listTasks.get(position));
return listViewItem;
}
}
and now in the parent class you must have already added a list view in your xml file so now display code for it is below:
CustomTaskHistory customList = new CustomTaskHistory(TaskHistory.this, task_history_name);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(customList);
you can also perform any action on clicking cells of listview.If needed code for it is below add just below the above code:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent nextScreen2 = new Intent(getApplicationContext(), SubscribeProgrammes.class);
nextScreen2.putExtra("CLIENT_ID", _clientID);
nextScreen2.putExtra("REFERENCE_ID", reference_IDs.get(i));
startActivity(nextScreen2);
Toast.makeText(getApplicationContext(), "You Clicked " + task_list.get(i), Toast.LENGTH_SHORT).show();
}
});

android ListActivity how to populate data with Json Volley Library

android ListActivity how to make Custom Adapter getter setter using ,call json Volley library populate data ListActivity ? could not populate data with Json how to implement ,Please Help me
my code
ItemFragment Class
public class ItemFragment extends ListActivity {
RequestParse requestParse;
MySharedPreferences prefs;
String UsrId;
Context context;
ArrayList<BizForumArticleInfo> list = new ArrayList<>();
private List<BizForumArticleInfo> CountryCodeNumber = new ArrayList<>();
MobileArrayAdapter adapter;
LinearLayoutManager mLayoutManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_android_example);
requestParse = new RequestParse();
prefs = MySharedPreferences.getInstance(this, SESSION);
UsrId = prefs.getString("UsrID", "");
context = getApplicationContext();
setListAdapter(new MobileArrayAdapter(this,0, list));
getJson(60);
}
public void getJson(final int limit){
requestParse.postJson(ConfigApi.postArticleBiz(), new RequestParse.VolleyCallBackPost() {
#Override
public void onSuccess(String result) {
list = parseResponse(result);
}
#Override
public void onRequestError(String errorMessage) {
}
#Override
public Map OnParam(Map<String, String> params) {
params.put("sessionid", UsrId);
params.put("offset", "0");
params.put("limit", String.valueOf(limit));
params.put("viewtype", "all");
params.put("access_token","e3774d357aa7d4bd14e9763b5459ee9cf7ebe36161c142551836ee510d98814a:b349b76b334a94b2");
return params;
}
});
}
public static ArrayList<BizForumArticleInfo> parseResponse(String response) {
ArrayList<BizForumArticleInfo> bizList = new ArrayList<>();
try {
JSONObject json = new JSONObject(response);
JSONArray data = json.getJSONArray(DATA);
for (int i = 0; i < data.length(); i++) {
BizForumArticleInfo ls = new BizForumArticleInfo();
JSONObject item = data.getJSONObject(i);
String ArticleTitle = item.getString("ArticleTitle");
String Article = item.getString("Article");
M.i("===================",ArticleTitle);//working
ls.setArticleTitle(ArticleTitle);
ls.setArticleArticle(Article);
bizList.add(ls);
}
} catch (JSONException e) {
e.printStackTrace();
}
return bizList;
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String selectedValue = (String) getListAdapter().getItem(position);
Toast.makeText(this, selectedValue, Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.putExtra("selectedValue", selectedValue);
setResult(RESULT_OK, intent);
finish();
//startActivity(new Intent(v.getContext(), MainActivity.class));
}
}
Adapter Class
public class MobileArrayAdapter extends ArrayAdapter<BizForumArticleInfo> {
private Activity activity;
private ArrayList<BizForumArticleInfo> lPerson;
private static LayoutInflater inflater = null;
public MobileArrayAdapter (Activity activity, int textViewResourceId,ArrayList<BizForumArticleInfo> _lPerson) {
super(activity, textViewResourceId, _lPerson);
try {
this.activity = activity;
this.lPerson = _lPerson;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
} catch (Exception e) {
}
}
public int getCount() {
return lPerson.size();
}
public BizForumArticleInfo getItem(BizForumArticleInfo position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
public TextView display_name;
public TextView display_number;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
try {
if (convertView == null) {
vi = inflater.inflate(R.layout.list_mobile, null);
holder = new ViewHolder();
holder.display_name = (TextView) vi.findViewById(R.id.label);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
holder.display_name.setText(lPerson.get(position).getArticleTitle());
} catch (Exception e) {
}
return vi;
}
}

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);
}
}

Categories

Resources