I am trying to update my listview directly after I submit new data from DialogFragment.
But when I call notifyDataSetChanged() it give me an NullPointerException and my app is close.
So this is the scenario what I want
And this is my code
This activity that I use to get data from the server
public class LayoutActivity extends Fragment {
private ListView listview;
private ListItemAdapter theAdapter;
String URL = "http://localhost/api/question/get_newest_except/0/0/15";
ProgressDialog pDialog;
NodeList nodelist;
public LayoutActivity() {
super();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.layout_main, container,false);
DownloadXML a = new DownloadXML(this);
a.execute(URL);
listview = (ListView) rootview.findViewById(R.id.list01);
return rootview;
}
public class DownloadXML extends AsyncTask<String, Void, Void>{
private LayoutActivity aku;
ArrayList<ListItemObject> data;
public DownloadXML(LayoutActivity aku) {
super();
this.aku = aku;
}
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.show();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
data = new ArrayList<ListItemObject>();
ListItemObject itemData;
try{
for (int temp = 0; temp < nodelist.getLength(); temp++) {
Node nNode = nodelist.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
itemData = new ListItemObject();
itemData.setId(getNode("pb__question__id",eElement));
itemData.setOwner(getNode("pb__question__consumer__id",eElement));
if(!getNode("pb__question__consumer__id",eElement).equalsIgnoreCase("0")){
itemData.setName(getNode("pb__question__consumer__name",eElement));
itemData.setJob(getNode("pb__question__consumer__occupation", eElement));
itemData.setProfilePic(getNode("pb__question__consumer__pp",eElement));
}
itemData.setStatus(getNode("pb__question__title",eElement));
itemData.setExtras(getNode("pb__question__topic__name", eElement));
if(!getNode("att__pict",eElement).isEmpty()){
itemData.setImage(getNode("att__pict", eElement));
}
if(getNode("pb__question__type", eElement).equalsIgnoreCase("1")){
itemData.setOpini(getNode("pb__question__total__opini", eElement));
}else if(getNode("pb__question__type", eElement).equalsIgnoreCase("2") || getNode("pb__question__type", eElement).equalsIgnoreCase("3")){
itemData.setOpini(getNode("pb__question__total__polling", eElement));
}else if(getNode("pb__question__type", eElement).equalsIgnoreCase("4")){
itemData.setOpini(getNode("pb__question__total__rating", eElement));
}
itemData.setTipe(getNode("pb__question__type", eElement));
itemData.setIkuti(getNode("pb__question__total__follow", eElement));
itemData.setSebarkan(getNode("pb__question__total__share", eElement));
data.add(itemData);
}
}
theAdapter = new ListItemAdapter(aku.getActivity(),data);
listview.setAdapter(theAdapter);
}catch(Exception e){
Toast.makeText(getActivity(), "Koneksi dengan server gagal", Toast.LENGTH_SHORT).show();
}
pDialog.dismiss();
}
#Override
protected Void doInBackground(String... Url) {
// TODO Auto-generated method stub
try {
URL url = new URL(Url[0]);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
nodelist = doc.getElementsByTagName("pb__question");
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
}
private static String getNode(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
String result = "";
if(nValue!=null){
result = nValue.getNodeValue();
}
return result;
}
}
and this is the listview adapter, in this adapter I call Dialog from each item
public class ListItemAdapter extends BaseAdapter{
private ArrayList<ListItemObject> itemCards;
private Context mContext;
private FragmentManager mFragmentManager;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public ListItemAdapter(FragmentActivity fa, ArrayList<ListItemObject> d) {
super();
this.mContext = fa;
this.itemCards= d;
mFragmentManager = fa.getSupportFragmentManager();
}
#Override
public int getCount() {
return itemCards.size();
}
#Override
public Object getItem(int pos) {
return itemCards.get(pos);
}
#Override
public long getItemId(int pos) {
return pos;
}
#Override
public View getView(final int position, View convertview, ViewGroup parent) {
// TODO Auto-generated method stub
View row=null;
row = convertview;
row = View.inflate(mContext, R.layout.item_layout, null);
final boolean[] mHighlightedPositions = new boolean[itemCards.size()];
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
LinearLayout containerPP = (LinearLayout) row.findViewById(R.id.idCon);
NetworkImageViewCircle fotoPP = (NetworkImageViewCircle) row.findViewById(R.id.pp);
TextView nama = (TextView) row.findViewById(R.id.name);
TextView kerjaan = (TextView) row.findViewById(R.id.jobs);
NetworkImageView gambar = (NetworkImageView) row.findViewById(R.id.feedImage1);
TextView status = (TextView) row.findViewById(R.id.txtStatusMsg);
TextView extra = (TextView) row.findViewById(R.id.txtUrl);
TextView opinion = (TextView) row.findViewById(R.id.opini);
TextView follow = (TextView) row.findViewById(R.id.ikuti);
TextView share = (TextView) row.findViewById(R.id.sebarkan);
Button Opini = (Button) row.findViewById(R.id.Button01);
Button Ikuti = (Button) row.findViewById(R.id.Button02);
Button Sebarkan = (Button) row.findViewById(R.id.Button03);
Ikuti.setTag(position);
Opini.setTag(position);
ListItemObject item = itemCards.get(position);
if(item.getName()==null){
containerPP.setVisibility(View.GONE);
}
if(item.getExtras().equalsIgnoreCase("Pertanyaan Pengguna")){
extra.setVisibility(View.GONE);
}
if(item.getImage()==null){
gambar.setVisibility(View.GONE);
}
if(item.getTipe().equals("4")){
opinion.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.star_icon, 0);
}else if(item.getTipe().equals("2") || item.getTipe().equals("3")){
opinion.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.poll_icon, 0);
}
nama.setText(item.getName());
kerjaan.setText(item.getJob());
fotoPP.setImageUrl(item.getProfilePic(), imageLoader);
status.setText(item.getStatus());
extra.setText(item.getExtras().replaceAll("\n",""));
opinion.setText(item.getOpini());
follow.setText(item.getIkuti());
share.setText(item.getSebarkan());
gambar.setImageUrl(item.getImage(), imageLoader);
if(mHighlightedPositions[position]) {
Ikuti.setBackgroundResource(R.color.ijo);
Ikuti.setTextColor(Color.WHITE);
}else{
Ikuti.setBackgroundResource(R.color.abu2);
Ikuti.setTextColor(Color.BLACK);
}
Opini.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddKomentar(v,position);
}
});
Ikuti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Sebarkan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return row;
}
public void AddKomentar(View v,int pos){
FragmentActivity activity = (FragmentActivity)(mContext);
FragmentManager fm = activity.getSupportFragmentManager();
ListItemObject item = itemCards.get(pos);
DialogAddOpini dialog = new DialogAddOpini();
Bundle args = new Bundle();
args.putString("question",item.getId());
args.putString("owner",item.getOwner());
dialog.setArguments(args);
dialog.show(fm, "Dialog");
}
}
and this is the DialogFragment
public class DialogAddOpini extends DialogFragment{
ListItemAdapter theAdapter;
String question_id,owner_id;
EditText question_field;
ProgressDialog pDialog;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.addopini, null);
Bundle mArgs = getArguments();
question_id = mArgs.getString("question");
owner_id = mArgs.getString("owner");
builder.setTitle("Tambahkan Opini");
builder.setView(dialogView)
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
question_field = (EditText) dialogView.findViewById(R.id.content);
SendComment send = new SendComment();
send.execute(question_field.getText().toString());
}
});
Dialog dialog = builder.create();
return dialog;
}
private class SendComment extends AsyncTask<String, Void, Void>{
public SendComment() {
super();
}
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Submitting...");
pDialog.setIndeterminate(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... params) {
String content = params[0];
postData(content);
return null;
}
#Override
protected void onPostExecute(Void result) {
theAdapter.notifyDataSetChanged();
pDialog.dismiss();
}
}
public void postData(String content) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/api/opini/add");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("pb_question_id", question_id));
nameValuePairs.add(new BasicNameValuePair("owner_id", owner_id));
nameValuePairs.add(new BasicNameValuePair("opini_text", content));
nameValuePairs.add(new BasicNameValuePair("is_anonym", "1"));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
HttpResponse response = httpclient.execute(httppost);
Log.d("Http Response:", response.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I call notifyDataSetChanged() inside onPostExecute inside DialogFragment, but it give me NullPointerException.
Can anyone help me?
This the log
Thanks
theAdapter is not initialized in class DialogAddOpini, You need to initialized it before using it in OnPostExecute.
I will prefer to use Listener to return the data from DialogFragment and update List in the Adapter only.
public class DialogAddOpini extends DialogFragment {
private Listener mListener;
public void setListener(Listener listener) {
mListener = listener;
}
static interface Listener {
void returnData();
}
Set the listener while creating Dialog :
public void AddKomentar(View v,int pos){
FragmentActivity activity = (FragmentActivity)(mContext);
FragmentManager fm = activity.getSupportFragmentManager();
ListItemObject item = itemCards.get(pos);
DialogAddOpini dialog = new DialogAddOpini();
Bundle args = new Bundle();
args.putString("question",item.getId());
args.putString("owner",item.getOwner());
dialog.setArguments(args);
dialog.setListener(this);
dialog.show(fm, "Dialog");
}
And return the data like :
#Override
protected void onPostExecute(Void result) {
if (mListener != null) {
mListener.returnData();
}
pDialog.dismiss();
}
And override returnData in Adapter and update the list:
public class ListItemAdapter extends BaseAdapter implements DialogAddOpini.Listener {
#Override
public void returnData() {
notifyDataSetChanged();
}
}
Update :
You have to pass the data and set it in the Adapter's Arraylist to reflect the changes.
Track the position while you show the dialog :
Integer selected_position =-1 ;
public void AddKomentar(View v,int pos){
FragmentActivity activity = (FragmentActivity)(mContext);
FragmentManager fm = activity.getSupportFragmentManager();
ListItemObject item = itemCards.get(pos);
DialogAddOpini dialog = new DialogAddOpini();
Bundle args = new Bundle();
args.putString("question",item.getId());
args.putString("owner",item.getOwner());
dialog.setArguments(args);
selected_position = pos;
dialog.setListener(this);
dialog.show(fm, "Dialog");
}
#Override
public void returnData( String counter) {
itemCards.get(selected_position).setOpini(counter);
notifyDataSetChanged();
selected_position=-1;
}
Hope it helps ツ
Related
I am working on an Activity which is a search page. It contains some values with edittext and spinner. After giving the values and clicking on search button it moves to tab fragments, there contains search results divided by three tabs (By date, By price, By city). I just tested to do on date first but it is not displaying. Please help me on this.
Search Page:
public class Search extends AppCompatActivity {
EditText name,to,from;
Spinner cscope,strainer,sinstitute,scity,scountry,cstype,sgender,sdisable,sprice;
String[] able={"Yes","No"};
String[] sex={"Male only","Female only","Both Male and Female"};
String[] price={"Free","1900S.R","1500S.R"};
String[] city={"Riyadh"};
Button search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
name= (EditText) findViewById(R.id.search_csname);
cscope= (Spinner) findViewById(R.id.search_scope);
strainer= (Spinner) findViewById(R.id.search_trainerName);
sinstitute= (Spinner) findViewById(R.id.search_instName);
scity= (Spinner) findViewById(R.id.search_city);
scountry= (Spinner) findViewById(R.id.search_country);
cstype= (Spinner) findViewById(R.id.search_ctype);
sgender= (Spinner) findViewById(R.id.search_gender);
sdisable= (Spinner) findViewById(R.id.search_disabled);
sprice= (Spinner) findViewById(R.id.search_price);
search= (Button) findViewById(R.id.searchNow);
ArrayAdapter<String> gen=new ArrayAdapter<String>(Search.this,android.R.layout.simple_spinner_item,sex);
gen.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sgender.setAdapter(gen);
ArrayAdapter<String> disableness=new ArrayAdapter<String>(Search.this,android.R.layout.simple_spinner_item,able);
disableness.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sdisable.setAdapter(disableness);
ArrayAdapter<String> pricess=new ArrayAdapter<String>(Search.this,android.R.layout.simple_spinner_item,price);
pricess.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sprice.setAdapter(pricess);
ArrayAdapter<String> cities=new ArrayAdapter<String>(Search.this,android.R.layout.simple_spinner_item,city); cities.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
scity.setAdapter(cities);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String sname=name.getText().toString();
final String seprice=sprice.getSelectedItem().toString();
final String secity=scity.getSelectedItem().toString();
final String sedate=from.getText().toString();
Intent s=new Intent(getApplicationContext(),SearchResults.class);
s.putExtra("csname",sname);
s.putExtra("csprice",seprice);
s.putExtra("cscity",secity);
s.putExtra("csdate",sedate);
startActivity(s);
}
});
}
public void selectToDate(View view){
DialogFragment tofrag=new SelectTodateFragment();
tofrag.show(getSupportFragmentManager(),"Date Picker");
}
public void poptoDate(int date,int month,int year){
to= (EditText) findViewById(R.id.search_to);
assert to != null;
to.setText(date+"/"+month+"/"+year);
}
#SuppressLint("ValidFragment")
public class SelectTodateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
public Dialog onCreateDialog(Bundle savedInstanceState){
final Calendar tocal=Calendar.getInstance();
int yy=tocal.get(Calendar.YEAR);
int mm=tocal.get(Calendar.MONTH);
int dd=tocal.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
}
#Override
public void onDateSet(DatePicker view, int year, int mm, int dd) {
poptoDate(year, mm+1, dd);
}
}
public void selectFromDate(View view){
DialogFragment newfrag=new SelectFromdateFragment();
newfrag.show(getSupportFragmentManager(),"Date Picker");
}
public void popDate(int date,int month,int year){
from= (EditText) findViewById(R.id.search_from);
assert from != null;
from.setText(date+"/"+month+"/"+year);
}
#SuppressLint("ValidFragment")
public class SelectFromdateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
public Dialog onCreateDialog(Bundle savedInstanceState){
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
}
#Override
public void onDateSet(DatePicker view, int year, int mm, int dd) {
popDate(year, mm+1, dd);
}
}
}
Search Results Page:
public class SearchResults extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
private TabLayout tabs;
private ViewPager viewPager;
Bundle bundle=new Bundle();
private SearchPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_results);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
tabs = (TabLayout) findViewById(R.id.search_tabLayout);
viewPager = (ViewPager) findViewById(R.id.search_pager);
tabs.addTab(tabs.newTab().setText("By Price"));
tabs.addTab(tabs.newTab().setText("By Date"));
tabs.addTab(tabs.newTab().setText("By City"));
tabs.setTabGravity(tabs.GRAVITY_FILL);
tabs.setHorizontalScrollBarEnabled(false);
pager = new SearchPager(getSupportFragmentManager(), tabs.getTabCount());
viewPager.setAdapter(pager);
Intent h=getIntent();
String cname=h.getStringExtra("csname");
String byprice=h.getStringExtra("csprice");
String bydate=h.getStringExtra("csdate");
String bycity=h.getStringExtra("cscity");
bundle.putString("coname",cname);
bundle.putString("coprice",byprice);
bundle.putString("codate",bydate);
bundle.putString("cocity",bycity);
pager.getData(bundle);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabs));
tabs.setOnTabSelectedListener(this);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
Search pagerAdapter:
public class SearchPager extends FragmentStatePagerAdapter {
int tabCount;
private Bundle args=new Bundle();
public SearchPager(FragmentManager fm, int tabCount) {
super(fm);
this.tabCount = tabCount;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Fragment tab1 = new SearchPrice();
getData(args);
tab1.setArguments(args);
return tab1;
case 1:
Fragment tab2 = new SearchDate();
getData(args);
tab2.setArguments(args);
return tab2;
case 2:
Fragment tab3 = new SearchCity();
getData(args);
tab3.setArguments(args);
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return tabCount;
}
public void getData(Bundle bundle) {
this.args=bundle;
}
}
Search BYPrice:
public class SearchPrice extends Fragment {
private ListView listView;
private ProgressDialog mprogress;
ArrayList<HashMap<String, String>> alist = new ArrayList<>();
private SpriceAdapter adapter;
TextView id;
Handler mHandler;
static String sname;
static String sprice;
public SearchPrice() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_search_price, container, false);
mHandler = new Handler();
id = (TextView) rootView.findViewById(R.id.copriceId);
listView = (ListView) rootView.findViewById(R.id.searchPriceList);
adapter = new SpriceAdapter(getActivity(), alist);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setScrollingCacheEnabled(false);
if (getArguments() != null) {
sname = this.getArguments().getString("coname");
sprice = this.getArguments().getString("coprice");
}
final String turl = "http://adoxsolutions.in/numuww/services/courses";
new ByPrice(this).execute(turl);
return rootView;
}
private class ByPrice extends AsyncTask<String, Void, Void> {
private ProgressDialog dialog;
public ByPrice(SearchPrice activity) {
dialog = new ProgressDialog(activity.getContext());
}
#Override
protected void onPreExecute() {
dialog.setMessage("Loading Data...");
dialog.show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
protected Void doInBackground(String... turl) {
try {
URL url = new URL(turl[0]);
HttpURLConnection connect = (HttpURLConnection) url.openConnection();
connect.setRequestMethod("POST");
System.out.println("Response Code:" + connect.getResponseCode());
InputStream in = new BufferedInputStream(connect.getInputStream());
String response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(response);
Log.d("VALUE:", response);
JSONObject obj = new JSONObject(response);
JSONArray jsArray = obj.optJSONArray("Course");
for (int k = 0; k < jsArray.length(); k++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jobj = jsArray.getJSONObject(k);
final String cid = jobj.getString("id");
final String cn = jobj.getString("course");
final String dt = jobj.getString("date");
map.put("id", cid);
map.put("course", cn);
map.put("date", dt);
map.put("trainer", jobj.getString("trainer"));
map.put("country", jobj.getString("country"));
map.put("city", jobj.getString("city"));
map.put("days", jobj.getString("no_days"));
map.put("hours", jobj.getString("tot_hrs"));
map.put("img", jobj.getString("img"));
alist.add(map);
mHandler.post(new Runnable() {
#Override
public void run() {
if (cn.equals(sname) || dt.equals(sprice)) {
Log.d("Value", cid);
id.setText(cid);
listView.setAdapter(adapter);
}
}
});
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
class SpriceAdapter extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();
private Typeface typeface;
public SpriceAdapter(Context c, ArrayList<HashMap<String, String>> list) {
context = c;
MyArr = list;
}
#Override
public int getCount() {
return MyArr.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final String id = MyArr.get(position).get("id");
if (convertView != null) {
convertView = inflater.inflate(R.layout.searchlist, parent, false);
TextView cname = (TextView) convertView.findViewById(R.id.searchlistName);
TextView tname = (TextView) convertView.findViewById(R.id.strainerName);
TextView country = (TextView) convertView.findViewById(R.id.searchcoName);
TextView city = (TextView) convertView.findViewById(R.id.searchciName);
TextView date = (TextView) convertView.findViewById(R.id.sdateTime);
TextView time = (TextView) convertView.findViewById(R.id.scourseTime);
TextView hours = (TextView) convertView.findViewById(R.id.scourseHours);
ImageView image = (ImageView) convertView.findViewById(R.id.scphoto);
String cn = (MyArr.get(position).get("course"));
String tn = (MyArr.get(position).get("trainer"));
String co = (MyArr.get(position).get("country"));
String ci = (MyArr.get(position).get("city"));
String dat = (MyArr.get(position).get("date"));
String dys = (MyArr.get(position).get("days"));
String hrs = (MyArr.get(position).get("hours"));
String c = context.getString(R.string.comma);
String ob = " ( ";
String cb = " ) ";
String h = " Hours";
String d = " Days";
String trainerName = tn + c;
String cdays = dys + d;
String chrs = ob + hrs + h + cb;
try {
if(hrs != null || !hrs.equals("")) {
String h1="0 Hours";
String chs=ob + h1 + cb;
hours.setText(chs);
}else{
hours.setText(chrs);
}
// image.setImageBitmap(loadBitmap(hlist.get(position).get("img")));
Glide.with(context).load(MyArr.get(position).get("img")).into(image);
cname.setText(cn);
tname.setText(trainerName);
country.setText(co);
city.setText(ci);
date.setText(dat);
time.setText(cdays);
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent o=new Intent(context,CourseScreen.class);
o.putExtra("id",id);
context.startActivity(o);
}
});
} catch(Exception e){
e.printStackTrace();
}
}
return convertView;
}
}
}
Search ByDate:
public class SearchDate extends Fragment {
private ListView listView;
private ProgressDialog mprogress;
TextView id;
ArrayList<HashMap<String, String>> alist = new ArrayList<>();
private SdateAdapter adapter;
Handler mHandler;
static String sname;
static String sdate;
public SearchDate() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_search_date, container, false);
mHandler = new Handler();
id= (TextView) rootView.findViewById(R.id.courseId);
listView= (ListView) rootView.findViewById(R.id.searchDateList);
adapter = new SdateAdapter(getActivity(), alist);
listView.setAdapter(adapter);
listView.setScrollingCacheEnabled(false);
adapter.notifyDataSetChanged();
if (getArguments() != null) {
sname = this.getArguments().getString("coname");
sdate = this.getArguments().getString("codate");
}
final String turl = "http://adoxsolutions.in/numuww/services/courses";
new ByDate(this).execute(turl);
return rootView;
}
private class ByDate extends AsyncTask<String, Void, Void> {
private ProgressDialog dialog;
public ByDate(SearchDate activity)
{
dialog = new ProgressDialog(activity.getContext());
}
#Override
protected void onPreExecute() {
dialog.setMessage("Loading Data...");
dialog.show();
}
protected Void doInBackground(String... turl) {
try {
URL url = new URL(turl[0]);
HttpURLConnection connect = (HttpURLConnection) url.openConnection();
connect.setRequestMethod("POST");
System.out.println("Response Code:" + connect.getResponseCode());
InputStream in = new BufferedInputStream(connect.getInputStream());
String response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(response);
Log.d("VALUE:", response);
JSONObject obj = new JSONObject(response);
JSONArray jsArray = obj.optJSONArray("Course");
for (int k = 0; k < jsArray.length(); k++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jobj = jsArray.getJSONObject(k);
final String cid=jobj.getString("id");
final String cn=jobj.getString("course");
final String dt=jobj.getString("date");
map.put("id",cid);
map.put("course",cn);
map.put("date", dt);
map.put("trainer", jobj.getString("trainer"));
map.put("country", jobj.getString("country"));
map.put("city", jobj.getString("city"));
map.put("days", jobj.getString("no_days"));
map.put("hours", jobj.getString("tot_hrs"));
map.put("img", jobj.getString("img"));
alist.add(map);
mHandler.post(new Runnable() {
#Override
public void run() {
if(cn.equals(sname) || dt.equals(sdate) ) {
Log.d("Value",cid);
id.setText(cid);
}
}
});
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
class SdateAdapter extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();
private Typeface typeface;
public SdateAdapter(Context c, ArrayList<HashMap<String, String>> list) {
context = c;
MyArr = list;
}
#Override
public int getCount() {
return MyArr.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final String id = MyArr.get(position).get("id");
final String dt=MyArr.get(position).get("date");
if (convertView != null) {
convertView = inflater.inflate(R.layout.searchlist, parent, false);
TextView cname = (TextView) convertView.findViewById(R.id.searchlistName);
TextView tname = (TextView) convertView.findViewById(R.id.strainerName);
TextView country = (TextView) convertView.findViewById(R.id.searchcoName);
TextView city = (TextView) convertView.findViewById(R.id.searchciName);
TextView date = (TextView) convertView.findViewById(R.id.sdateTime);
TextView time = (TextView) convertView.findViewById(R.id.scourseTime);
TextView hours = (TextView) convertView.findViewById(R.id.scourseHours);
ImageView image = (ImageView) convertView.findViewById(R.id.scphoto);
String cn = (MyArr.get(position).get("course"));
String tn = (MyArr.get(position).get("trainer"));
String co = (MyArr.get(position).get("country"));
String ci = (MyArr.get(position).get("city"));
String dat = (MyArr.get(position).get("date"));
String dys = (MyArr.get(position).get("days"));
String hrs = (MyArr.get(position).get("hours"));
String c = context.getString(R.string.comma);
String ob = " ( ";
String cb = " ) ";
String h = " Hours";
String d = " Days";
String trainerName = tn + c;
String cdays = dys + d;
String chrs = ob + hrs + h + cb;
try {
if(hrs != null || !hrs.equals("")) {
String h1="0 Hours";
String chs=ob + h1 + cb;
hours.setText(chs);
}else{
hours.setText(chrs);
}
// image.setImageBitmap(loadBitmap(hlist.get(position).get("img")));
Glide.with(context).load(MyArr.get(position).get("img")).into(image);
cname.setText(cn);
tname.setText(trainerName);
country.setText(co);
city.setText(ci);
date.setText(dat);
time.setText(cdays);
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent o=new Intent(context,CourseScreen.class);
o.putExtra("id",id);
context.startActivity(o);
}
});
} catch(Exception e){
e.printStackTrace();
}
}
return convertView;
}
}
}
Same as Search ByCity:
this is my adapter class where i am having a add to cart button
public class ServiceSelectionOptionsListAdapter extends ArrayAdapter<ServiceSelectionOptionsDataModel> {
private Context context;
private int layoutResourceId;
ListView list;
static final String TAG = "LISTT";
HashMap<Integer, Integer> hashMap;
String response;
ProgressDialog pdilog;
SharedPreferences prefs;
String serverresponse1;
private List<ServiceSelectionOptionsDataModel> data;
String custid;
JSONArray _jsonarray;
JSONObject jsonObject;
String subsrvceopid;
String quantity = "1";
String cartcounter;
TextView counter;
public ServiceSelectionOptionsListAdapter(Context context, int layoutResourceId,
List<ServiceSelectionOptionsDataModel> data) {
super(context, R.layout.serviceselectionoptionslist, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
hashMap = new HashMap<Integer, Integer>();
prefs = context.getSharedPreferences(AppConstants.VERIFICATION,
Context.MODE_PRIVATE);
custid = prefs.getString(AppConstants.CUSTOMERID, "");
cartcounter = prefs.getString(AppConstants.CARTITEMCOUNTER, "");
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
View row = convertView;
final ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.optionname = (TextView) row.findViewById(R.id.tvsubserviceoptionname);
holder.addtocart = (Button) row.findViewById(R.id.btnaddtocart);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final ServiceSelectionOptionsDataModel item = data.get(position);
holder.optionname.setText(item.getOptionname());
holder.addtocart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Integer index = (Integer) view.getTag();
subsrvceopid = data.get(position).getId();
new addtocart().execute(custid, subsrvceopid, quantity);
new cartitemsdetails().execute(custid);
SharedPreferences.Editor editor = context.getSharedPreferences(AppConstants.VERIFICATION, context.MODE_PRIVATE).edit();
editor.putString(AppConstants.SUBSERVIEOPTIONID, subsrvceopid);
editor.commit();
notifyDataSetChanged();
}
});
return row;
}
static class ViewHolder {
TextView optionname;
// TextView charges;
Button addtocart;
TextView counter;
}
and this is my activity class where i m getting the size of the cart items list
class cartitemsdetails extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
pdilog = new ProgressDialog(ServiceSelectionOptionsListActivity.this);
pdilog.setMessage("Please Wait....");
pdilog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
String response = JSONFunctions.getJSONfromURL("http://cpanel.smartindiaservice.com/api/cartdetails?customerid=" + params[0]);
try {
jsonarray = new JSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
size = jsonarray.length();
counter.setText(String.valueOf(size));
if (size == 0 )
{
viewcart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ServiceSelectionOptionsListActivity.this, NoItemsInTheCart.class);
startActivity(intent);
}
});
cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ServiceSelectionOptionsListActivity.this, NoItemsInTheCart.class);
startActivity(intent);
}
});
}
if(size>0) {
viewcart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ServiceSelectionOptionsListActivity.this, MyCart.class);
startActivity(intent);
}
});
cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ServiceSelectionOptionsListActivity.this, MyCart.class);
startActivity(intent);
}
});
}
pdilog.dismiss();
super.onPostExecute(aVoid);
}
}
class OptionsSelection extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
response = JSONFunctions.getJSONfromURL("http://cpanel.smartindiaservice.com/api/subserviceoptions?subserviceid=" + params[0]);
try {
_jsonarray = new JSONArray(response);
for (int i = 0; i < _jsonarray.length(); i++) {
ServiceSelectionOptionsDataModel datamodel = new ServiceSelectionOptionsDataModel();
jsonObject = _jsonarray.getJSONObject(i);
optionname = jsonObject.getString("OptionName");
datamodel.setOptionname(optionname);
charge = jsonObject.getString("Charges");
datamodel.setCharge(charge);
subserviceoptionid = jsonObject.getString("SubServiceOptionID");
datamodel.setId(subserviceoptionid);
lstDataModel.add(datamodel);
}
} catch (Exception e) {
System.out.println(e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
ServiceSelectionOptionsListAdapter adapter = new ServiceSelectionOptionsListAdapter(ServiceSelectionOptionsListActivity.this, R.layout.serviceselectionoptionslist, lstDataModel);
options.setAdapter(adapter);
adapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
I need to display description of news in ShowNews activity and I used the intent
and put extra method to pass the description to the ShowNews Activity that contain a textview for setting Description. What is wrong in my code?
public class Downloader extends AsyncTask<Void,Void,Object> {
Context c;
String urlAddress ;
ListView lv;
ProgressDialog pd;
public Downloader(Context c,String urlAddress,ListView lv)
{
this.c = c;
this.urlAddress =urlAddress;
this.lv = lv;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Fetching Data");
pd.setMessage("Fetchinf Data...please wait ");
pd.show();
}
#Override
protected Object doInBackground(Void... voids) {
return this.downloadData();
}
#TargetApi(Build.VERSION_CODES.CUPCAKE)
#Override
protected void onPostExecute(Object data) {
super.onPostExecute(data);
pd.dismiss();
if (data.toString().startsWith("Error"))
{
Toast.makeText(c,data.toString(),Toast.LENGTH_LONG).show();
}
else {
// parsing
new ReadRss(c, (InputStream) data,lv).execute();
}
}
private Object downloadData()
{
Object connection = Connector.connect(urlAddress);
if (connection.toString().startsWith("Error"))
{
return connection.toString();
}
try {
HttpURLConnection con = (HttpURLConnection) connection;
int responsecode = con.getResponseCode();
if (responsecode == con.HTTP_OK) {
InputStream is = new BufferedInputStream(con.getInputStream());
return is;
}
return ErrorTracer.RESPONSE_ERROR+con.getResponseMessage();
} catch (IOException e) {
e.printStackTrace();
return ErrorTracer.IO_ERROR;
}
}
}
public class ReadRss extends AsyncTask<Void,Void,Boolean> {
Context c;
InputStream is;
ListView lv;
ProgressDialog pd;
CustomAdapter adapter ;
ArrayList<Site> sites = new ArrayList<>();
public ReadRss(Context c,InputStream is,ListView lv)
{
this.c = c;
this.is =is;
this.lv = lv;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("parsing Data");
pd.setMessage("parsing Data...please wait ");
pd.show();
}
#Override
protected Boolean doInBackground(Void... voids) {
return this.parseRss();
}
#Override
protected void onPostExecute(Boolean isparsed) {
super.onPostExecute(isparsed);
pd.dismiss();
if (isparsed)
{
//bind
lv.setAdapter(new CustomAdapter(c,sites));
}
else {
Toast.makeText(c,"Unable to parse",Toast.LENGTH_LONG).show();
}
}
private Boolean parseRss()
{
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
parser.setInput(is,null);
int event = parser.getEventType();
String value = null;
sites.clear();
Site site = new Site();
do {
String name = parser.getName();
switch (event)
{
case XmlPullParser.START_TAG:
if (name.equals("item"))
{
site = new Site();
}
break;
case XmlPullParser.TEXT:
value = parser.getText();
break;
case XmlPullParser.END_TAG:
if (name.equals("title"))
{
site.setTitle(value);
}else if (name.equals("description"))
{
site.setDescription(value);
}else if (name.equals("pubDate"))
{
site.setData(value);
}else if (name.equals("link"))
{
site.setLink(value);
}
if (name.equals("item"))
{
sites.add(site);
}
break;
}
event = parser.next();
}while (event!=XmlPullParser.END_DOCUMENT);
return true;
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
}
public class CustomAdapter extends BaseAdapter {
Context c;
ArrayList<Site> sites;
public CustomAdapter(Context c,ArrayList<Site> sites)
{
this.c = c;
this.sites = sites;
}
#Override
public int getCount() {
return sites.size();
}
#Override
public Object getItem(int i) {
return sites.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view==null)
{
view = LayoutInflater.from(c).inflate(R.layout.row,viewGroup,false);
}
TextView titletxt = (TextView) view.findViewById(R.id.textView);
TextView desctxt = (TextView) view.findViewById(R.id.textView2);
TextView datetxt = (TextView) view.findViewById(R.id.textView3);
Site site = (Site) this.getItem(i);
titletxt.setText(site.getTitle());
desctxt.setText(site.getDescription());
datetxt.setText(site.getData());
return view;
}
}
public class MainActivity extends AppCompatActivity {
String ulrAddress = "http://www.alahlytv.net/Rss_Feeds.aspx";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
final ListView lv = (ListView) findViewById(R.id.lv);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(MainActivity.this,ShowNews.class);
Site site = new Site();
intent.putExtra("one",site.getDescription());
startActivity(intent);
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new Downloader(MainActivity.this,ulrAddress,lv).execute();
}
});
public class ShowNews extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_news);
TextView textView = (TextView) findViewById(R.id.textView4);
Intent intent = getIntent();
Bundle bd = intent.getExtras();
if(bd != null)
{
String getName = (String) bd.get("one");
textView.setText(getName);
}
}
}
When you add any extra in your intent, don't try to get it from the Bundle. So change your reading passed data code to:
Intent intent = getIntent();
String getName = intent.getStringExtra("one", "default_value_if_null");
textView.setText(getName);
change your code like this
Intent intent = getIntent();
if(intent != null)
{
String getName = intent.getExtras().getString("one");
textView.setText(getName);
}
this is my Main class:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_lead, container, false);
prefs = getActivity().getSharedPreferences(AppConstants.LOGIN_PREFS,
Context.MODE_PRIVATE);
agentcode= prefs.getString(AppConstants.agentcode, "");
listview = (ListView) rootView.findViewById(R.id.listView);
new LeadsBackground().execute();
return rootView;
}
class LeadsBackground extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setTitle("Searching");
pDialog.setMessage("Please wait...");
pDialog.setCanceledOnTouchOutside(false);
pDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
try {
Response = JSONfunctions.getJSONfromURL(Constants.LeadsURl + "AgentCode=" + agentcode);
JSONArray _jsonarray = new JSONArray(Response);
for (int i = 0; i < _jsonarray.length(); i++) {
JSONObject _jsobject = _jsonarray.getJSONObject(i);
DataModel datamodel = new DataModel();
datamodel.setJobNumber(_jsobject.getString("JobNumber"));
datamodel.setPhoneNumber(_jsobject.getString("PhoneNumber"));
datamodel.setCustomerName(_jsobject.getString("CustomerName"));
datamodel.setCustomerAddress(_jsobject.getString("CustomerAddress"));
datamodel.setCity(_jsobject.getString("City"));
datamodel.setPinCode(_jsobject.getString("PinCode"));
datamodel.setAppointmentDate(_jsobject.getString("AppointmentDate"));
datamodel.setAppointmentTime(_jsobject.getString("AppointmentTime"));
lstDataModel.add(datamodel);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
ListViewAdapter listviewadapter = new ListViewAdapter(getActivity(), R.layout.leadslistitem,
lstDataModel,agentcode);
listview.setAdapter(listviewadapter);
pDialog.dismiss();
}
}
this is my adapter class:
public class ListViewAdapter extends ArrayAdapter<DataModel> {
// Declare Variables
Context context;
LayoutInflater inflater;
List<DataModel> datamodel;
String response;
ProgressDialog pDialog;
// LeadsFragment leads;
String agentcode;
public ListViewAdapter(Context context, int resourceId,
List<DataModel> worldpopulationlist, String agentcode) {
super(context, resourceId, worldpopulationlist);
this.context = context;
this.datamodel = worldpopulationlist;
this.agentcode = agentcode;
inflater = LayoutInflater.from(context);
}
private class ViewHolder {
TextView JobNumberTextView;
TextView PhoneNumberTextView;
TextView NameTextView;
TextView AdressTextView;
TextView DateTextView;
ImageView acceptedbutton;
ImageView rejectedbutton;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.leadslistitem, null);
//
holder.JobNumberTextView = (TextView) view.findViewById(R.id.textView1);
holder.PhoneNumberTextView = (TextView) view.findViewById(R.id.textView);
holder.NameTextView = (TextView) view.findViewById(R.id.textView3);
holder.AdressTextView = (TextView) view.findViewById(R.id.textView2);
holder.DateTextView = (TextView) view.findViewById(R.id.textView7);
holder.acceptedbutton = (ImageView) view.findViewById(R.id.imageButton2);
holder.rejectedbutton = (ImageView) view.findViewById(R.id.imageButton);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Html.fromHtml("<b>Job No:</b> ")
String sourceString = "<b>" + "JobNo:" + "</b> ";
holder.JobNumberTextView.setText(Html.fromHtml(sourceString) + datamodel.get(position).getJobNumber());
holder.PhoneNumberTextView.setText(datamodel.get(position).getPhoneNumber());
holder.NameTextView.setText(Html.fromHtml("Name : ") + datamodel.get(position).getCustomerName());
holder.AdressTextView.setText(datamodel.get(position).getCustomerAddress() + "," + datamodel.get(position).getCity() +
"-" + datamodel.get(position).getPinCode());
holder.DateTextView.setText(String.valueOf(Funcations.ConvertDatetime(datamodel.get(position).getAppointmentDate(), datamodel.get(position).getAppointmentTime()))
);
// Capture position and set to the TextViews
holder.acceptedbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AccepteRejectBackground().execute(datamodel.get(position).getJobNumber(), "true");
sendBroadcaset(true);
}
});
holder.rejectedbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AccepteRejectBackground().execute(datamodel.get(position).getJobNumber(), "false");
sendBroadcaset(true);
}
});
return view;
}
class AccepteRejectBackground extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setTitle("Searching");
pDialog.setMessage("Please wait...");
pDialog.setCanceledOnTouchOutside(false);
pDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... strings) {
response = HttpUtil.doGet(Constants.AcceptrejectURl + "AgentCode=" + agentcode + "&Jobid=" + strings[0] + "&response=" + strings[1]);
String url = Constants.AcceptrejectURl + "AgentCode=" + agentcode + "&Jobid=" + strings[0] + "&response=" + strings[1];
Log.e("Response", response);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (response.equalsIgnoreCase("1\n") || response.equals("1")) {
Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "NOt OK", Toast.LENGTH_LONG).show();
}
pDialog.dismiss();
}
}
private void sendBroadcaset(boolean b) {
// TODO Auto-generated method stub
LocalBroadcastManager.getInstance(context).sendBroadcast(
new Intent("update_boolean_variable").putExtra("action", b));
}
}
i have two button accept and reject button i want to to refresh or update listview on Button click of but my listview is not updating while i try to use notifydataset change but unable to refresh while i ma getting data from server in Json Format on accept button and reject button i have to send parameter true false and respectively i have refresh listview please help me how i will do this
For refreshing listview from the adapter, you need to call notifyDatasetChanged(). but in this manner.
AdapterClassName.this.notifyDatasetChanged();
For your class
ListViewAdapter.this.notifyDatasetChanged();
hi i have popup button. When I click pop up button, it displays radio button.For every radio button selection, I am fetching datas and updating in UI.
Problem is for first radio button it is updating UI. But for second radio button and so on, UI is not updating. How to solve this?
Code is as follows:
public class DataList extends Activity {
private Button popUpClick;
private Dialog sortFilterDialog;
private RadioGroup radioGroup;
private RadioButton ascToDesradioButton, desToAscradioButton,
highToLowradioButton, lowToHighradioButton, popularityradioButton;
private int popupselectionItem;
private ImageView closeButton;
private String sessionId;
private String sortName,sortOrder;
ArrayList<SortFilterProducts> personsList;
private ListView list;
private DataListAdapter gridAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.sortfilterclick);
personsList= new ArrayList<SortFilterProducts>();
popUpClick = (Button) findViewById(R.id.popupButton);
list=(ListView)findViewById(R.id.sortFilterList);
gridAdapter = new DataListAdapter(this, R.layout.sort_filter_listrow, personsList);
list.setAdapter(gridAdapter);
popUpClick.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sortFilterDialog = new Dialog(SortFilterPopupActivity.this);
sortFilterDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
sortFilterDialog.setContentView(R.layout.sortfilterrow);
radioGroup = (RadioGroup) sortFilterDialog
.findViewById(R.id.radioGroup);
ascToDesradioButton = (RadioButton) sortFilterDialog
.findViewById(R.id.asc_to_des);
desToAscradioButton = (RadioButton) sortFilterDialog
.findViewById(R.id.des_to_asc);
highToLowradioButton = (RadioButton) sortFilterDialog
.findViewById(R.id.high_to_low);
lowToHighradioButton = (RadioButton) sortFilterDialog
.findViewById(R.id.low_to_high);
popularityradioButton = (RadioButton) sortFilterDialog
.findViewById(R.id.popularity);
ascToDesradioButton
.setOnClickListener(radioButtonOnClickListener);
desToAscradioButton
.setOnClickListener(radioButtonOnClickListener);
highToLowradioButton
.setOnClickListener(radioButtonOnClickListener);
lowToHighradioButton
.setOnClickListener(radioButtonOnClickListener);
popularityradioButton
.setOnClickListener(radioButtonOnClickListener);
}
private final OnClickListener radioButtonOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
switch (popupselectionItem = v.getId()) {
case R.id.asc_to_des:
sortName="atoz";
sortOrder="SORT_ASC";
new SortFilterElement().execute();
//new AscToDesElements().execute();
break;
case R.id.des_to_asc:
sortName="atoz";
sortOrder="SORT_DESC";
new SortFilterElement().execute();
//new DescToAscElements().execute();
break;
case R.id.high_to_low:
sortName="lowtohigh";
sortOrder="SORT_ASC";
new SortFilterElement().execute();
//new PriceHightoLow().execute();
break;
case R.id.low_to_high:
sortName="lowtohigh";
sortOrder="SORT_DESC";
//new PriceLowtoHigh().execute();
new SortFilterElement().execute();
break;
case R.id.popularity:
sortName="popularity";
sortOrder="SORT_ASC";
//new Popularity().execute();
new SortFilterElement().execute();
break;
default:
}
sortFilterDialog.dismiss();
}
class SortFilterElement extends AsyncTask<String,String,String>{
ProgressDialog dialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog=new ProgressDialog(SortFilterPopupActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected String doInBackground(String... args) {
try {
SoapSerializationEnvelope env = new SoapSerializationEnvelope(
SoapSerializationEnvelope.VER11);
env.dotNet = false;
env.xsd = SoapSerializationEnvelope.XSD;
env.enc = SoapSerializationEnvelope.ENC;
if (sessionId == null) {
JSONObject json = new JSONObject();
json.put("page", "1");
json.put("limit", "10");
json.put("sort_name", sortName);
json.put("sort_order", sortOrder);
String params = json.toString();
requests.addProperty("args", params);
env.setOutputSoapObject(requests);
androidHttpTransport.call("", env);
Object results = env.getResponse();
Log.e("Sort results", results.toString());
if (results.toString() != null) {
JSONObject jsono = new JSONObject(results
.toString());
JSONArray jarray = jsono
.getJSONArray("result");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
SortFilterProducts products = new SortFilterProducts();
String id = object.getString("id");
int productPrice = object.getInt("price");
String imageUrl = object
.getString("image_url");
int ratings=object.getInt("ratings");
products.setProductName(productName);
products.setImageUrl(imageUrl);
personsList.add(products);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.cancel();
gridAdapter.notifyDataSetChanged();
}
}
};
});
}
}
and My DataListAdapter:
public class DataListAdapter extends BaseAdapter {
LayoutInflater layoutInflater;
int Resource;
ViewHolder viewHolder;
Activity activity;
public ImageLoader loader;
private final ArrayList<SortFilterProducts> itemLists;
public DataListAdapter(Activity a, int resource,
ArrayList<SortFilterProducts> itemList) {
layoutInflater = (LayoutInflater) a
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
itemLists = itemList;
activity = a;
loader = new ImageLoader(a.getApplicationContext());
}
#Override
public int getCount() {
return itemLists.size();
}
#Override
public Object getItem(int position) {
return itemLists.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v= convertView;
try {
if(v==null){
viewHolder = new ViewHolder();
v = layoutInflater.inflate(Resource, null);
viewHolder.productName=(TextView)v.findViewById(R.id.productName);
viewHolder.productPrice=(TextView)v.findViewById(R.id.price);
v.setTag(viewHolder);
}
else{
viewHolder = (ViewHolder) v.getTag();
}
final String productName=itemLists.get(position).getProductName();
final int productPrice=itemLists.get(position).getProductPrice();
viewHolder.productName.setText(productName);
viewHolder.productPrice.setText(Integer.toString(productPrice));
}
catch (Exception ex) {
ex.printStackTrace();
}
return v;
}
static class ViewHolder {
public TextView productName,productPrice;
}
}
Invalidate the items of the ListView while expanding the ArrayList<SortFilterProducts> passed to adapter.
list.invalidateViews();
Good Luck. :)
As I mention in comments, you should call notifyDataSetChanged() method after adding new objects to your list.
First of all, add following method to your DataListAdapter
public void addItem(SortFilterProducts product) {
itemLists.add(product);
notifyDataSetChanged();
}
Then, remove the line personsList.add(products); on your onCreate() method and add the following line.
DataListAdapter adapter = (DataListAdapter)list.getAdapter();
adapter.addItem(products);
Your ListView automatically updated whenever new item is added.
Hope this may help.