How to send multiple selected check box values to a server? - android

I want to send multiple selected checkbox travel id value to a server.
The code is working, but the value is not updating.
When the submit button is pressed, I want all the selected checkbox values to be sent to the server and the selected check box values are updated on the server.
package com.example.fiffa.fifaa;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ViewSubmission extends AppCompatActivity{
final Context context = this;
ListView listView;
String travelid;
TextView txtvisit,txtsum,txtsystem;
Button submit,back;
String MyPREFERENCES = "loginInfo";
SharedPreferences sharedpreferences;
ProgressDialog pDialog;
String ss="";
String userid;
boolean[] present;
boolean[] absent;
String takenatt="";
double gtotal=0.0;
List<Submitconvencelistitem> rowItems;
ArrayList<Submitconvencelistitem> feedsList;
Submitconvenceadapter adapter;
int count;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_submission);
submit = (Button) findViewById(R.id.submit);
back = (Button) findViewById(R.id.backviewsub);
txtvisit=(TextView)findViewById(R.id.txtvisit);
txtsum=(TextView)findViewById(R.id.txttotal);
//txtsystem=(TextView)findViewById(R.id.txtsystem);
listView = (ListView) findViewById(R.id.lstconveynce);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent viewsub=new Intent(ViewSubmission.this,Submitconveyance.class);
startActivity(viewsub);
}
});
String viewdata = getIntent().getExtras().getString("response", "");
Log.e("viewdata", viewdata);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
//conveyncetravelid = sharedpreferences.getString("travelid", "");
//Log.e("econveyncetravelid", conveyncetravelid);
userid = sharedpreferences.getString("userId", "");
Log.e("userId", userid);
try {
//feedsList=getSubmit(false);
JSONArray js = new JSONArray(viewdata);
feedsList=new ArrayList<>();
for (int i = 0; i < js.length(); i++) {
JSONObject jObject = js.getJSONObject(i);
Submitconvencelistitem st=new Submitconvencelistitem();
String total_amount=jObject.getString("total_amount");
Log.e("total_amount",total_amount);
//String travelid = jObject.getString("travelid");
//Log.e("conveyncetravelid", travelid);
st.settravelid(jObject.optString("travelid"));
st.setsubdate(jObject.optString("startdate"));
st.setstartlocation(jObject.optString("startlocation"));
st.setendlocation(jObject.optString("endlocation"));
st.setccno(jObject.optString("cc_no"));
st.setcustomername(jObject.optString("custname"));
st.setcallstatus(jObject.optString("callstatus"));;
st.setmodeofconveynce(jObject.optString("travel_mode"));
st.setkmstravelled(jObject.optString("KM"));
st.setclaimamout(jObject.optString("total_amount"));
//st.setSelected(true);
feedsList.add(st);
/* gtotal += Double.parseDouble(feedsList.get(i).getclaimamout());
Log.e("Total", String.valueOf(gtotal));
txtsum.setText(Double.toString(gtotal));*/
//Toast.makeText(MainActivity.this,result.toString(),Toast.LENGTH_LONG).show();
/* Log.e("shams", viewdata.toString());
String startdate = js.getJSONObject(0).getString("startdate");
Log.e("startdate",startdate);
String startlocation = js.getJSONObject(0).getString("startlocation");
Log.e("startlocation",startlocation);
String endlocation = js.getJSONObject(0).getString("endlocation");
Log.e("endlocation",endlocation);
String cc_no = js.getJSONObject(0).getString("cc_no");
Log.e("cc_no",cc_no);
String custname = js.getJSONObject(0).getString("custname");
Log.e("custname",custname);
String callstatus = js.getJSONObject(0).getString("callstatus");
Log.e("callstatus",callstatus);
String travel_mode = js.getJSONObject(0).getString("travel_mode");
Log.e("travel_mode",travel_mode);
String KM = js.getJSONObject(0).getString("KM");
Log.e("KM",KM);
String total_amount = js.getJSONObject(0).getString("total_amount");
Log.e("total_amount",total_amount);
st.setsubdate(startdate);
st.setstartlocation(startlocation);
st.setendlocation(endlocation);
st.setccno(cc_no);
st.setcustomername(custname);
st.setcallstatus(callstatus);
st.setmodeofconveynce(travel_mode);
st.setkmstravelled(KM);
st.setclaimamout(total_amount);
st.setSelected(true);*//*
feedsList.add(st);*/
/* JSONObject post = js.getJSONObject(i);
Submitconvencelistitem st=new Submitconvencelistitem();
st.setsubdate(post.optString("startdate"));
st.setstartlocation(post.optString("startlocation"));
st.setendlocation(post.optString("endlocation"));
st.setccno(post.optString("cc_no"));
st.setcustomername(post.optString("custname"));
st.setcallstatus(post.optString("callstatus"));
st.setmodeofconveynce(post.optString("travel_mode"));
st.setkmstravelled(post.optString("KM"));
st.setclaimamout(post.optString(("total_amount")));
st.setSelected(true);
feedsList.add(st);*/
}
adapter = new Submitconvenceadapter(ViewSubmission.this, feedsList);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
count=adapter.getCount();
txtvisit.setText(Integer.toString(count));
}
catch (JSONException e) {
e.printStackTrace();
}
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//final List<Submitconvencelistitem> selectedItems = adapter.getSelectedItems();
//Use this data for sending to your webserver
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ViewSubmission.this);
alertDialogBuilder.setMessage("Submit the Selected Conveynce");
alertDialogBuilder.setPositiveButton("yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
for (int strt=0;strt<present.length;strt++) {
if (present[strt]) {
travelid = feedsList.get(strt).gettravelid();
}
new Asyncupdate_travelforconv().execute();
}
//Toast.makeText(ViewSubmission.this,"Your conveyance has been submitted ",Toast.LENGTH_LONG).show();
}
});
alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent view=new Intent(ViewSubmission.this,Submitconveyance.class);
startActivity(view);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
//new Asncselect_travelforconvsub().execute();
}
});
}
/* private ArrayList<Submitconvencelistitem> getSubmit(boolean isSelect){
ArrayList<Submitconvencelistitem> list = new ArrayList<>();
for(int i = 0; i < feedsList.size(); i++){
Submitconvencelistitem st = new Submitconvencelistitem();
st.setSelected(isSelect);
feedsList.add(st);
}
return list;
}
*/
/*Asynctask For Insertstart travel details*/
private class Asyncupdate_travelforconv extends AsyncTask<String, Integer, String> {
String SOAP_ACTION = "http://tempuri.org/IFIFA/update_travelforconv";
String NAMESPACE = "http://tempuri.org/";
String METHOD_NAME = "update_travelforconv";
String URL = "http://migadget.aforeserve.co.in/FIFA.svc?singleWsdl";
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... strings) {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("travelid", travelid);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
//envelope.setOutputSoapObject(request);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
Object result = null;
result = (Object) envelope.getResponse();
Log.e("conveynce", String.valueOf(result));
System.out.println("APIresult:" + result.toString());
ss = result.toString();
Log.e("APIRESULT", ss);
} catch (Exception e) {
System.out.println("Error" + e);
}
return ss;
} catch (Exception ex) {
ex.printStackTrace();
return "";
}
}
#Override
protected void onPostExecute(String result) {
Log.e("APIResult", result);
Toast.makeText(getBaseContext(), "Data Updated", Toast.LENGTH_LONG).show();
}
}
/*Adapter class For Submit conveynce */
public class Submitconvenceadapter extends BaseAdapter {
ArrayList<Submitconvencelistitem> listData;
private LayoutInflater layoutInflater;
Context context;
List<Submitconvencelistitem> rowItems;
String MyPREFERENCES = "loginInfo";
String travelid;
SharedPreferences sharedpreferences;
public Submitconvenceadapter(Context ViewSubmission,ArrayList<Submitconvencelistitem> results)
{
listData = results;
context=ViewSubmission;
present=new boolean[listData.size()];
Arrays.fill(present, true);
}
#Override
public int getCount()
{
return listData.size();
}
#Override
public Object getItem(int position)
{
return listData.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
LayoutInflater layoutInflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_item_submitconveynce, null);
holder = new ViewHolder();
//holder.checkbox=(CheckBox) convertView.findViewById(R.id.cb1);
holder.date = (TextView) convertView.findViewById(R.id.subdate);
holder.startlocation = (TextView) convertView.findViewById(R.id.startlocation);
holder.endlocation=(TextView)convertView.findViewById(R.id.endlocation);
holder.ccno = (TextView) convertView.findViewById(R.id.ccno);
holder.customername = (TextView) convertView.findViewById(R.id.tv_name);
holder.callstatus = (TextView)convertView.findViewById(R.id.tv_callstatus);
holder.modeofconveynce = (TextView)convertView.findViewById(R.id.tv_modconveynce);
holder.Kmtravelled = (TextView)convertView.findViewById(R.id.tv_km);
holder.claimamount = (TextView)convertView.findViewById(R.id.claim_amount);
holder.checkbox=(CheckBox)convertView.findViewById(R.id.chk1);
/*//holder.checkbox.setChecked(true);
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
listData.get(position).setSelected(isChecked);
}
});*/
convertView.setTag(holder);
holder.checkbox.setChecked(present[position]);
}
else
{
holder = (ViewHolder) convertView.getTag();
holder.checkbox.setChecked(present[position]);
}
holder.checkbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.checkbox.isChecked())
present[position] = true;
else
present[position] = false;
}
});
//travelid=listData.get(position).gettravelid();
//holder.travelid.setText(listData.get(position).gettravelid());
holder.date.setText(listData.get(position).getsubdate());
holder.startlocation.setText(listData.get(position).getstartlocation());
holder.endlocation.setText(listData.get(position).getendlocation());
holder.ccno.setText(listData.get(position).getccno());
holder.customername.setText(listData.get(position).getcustomername());
holder.callstatus.setText(listData.get(position).getcallstatus());
holder.modeofconveynce.setText(listData.get(position).getmodeofconveynce());
holder.Kmtravelled.setText(listData.get(position).getkmstravelled());
holder.claimamount.setText(listData.get(position).getclaimamout());
//holder.checkbox.setChecked(true);
return convertView;
}
public class ViewHolder {
CheckBox checkbox;
TextView date;
TextView startlocation;
TextView endlocation;
TextView ccno;
TextView customername;
TextView callstatus;
TextView modeofconveynce;
TextView Kmtravelled;
TextView claimamount;
TextView travelid;
}
/* public List<Submitconvencelistitem> getSelectedItems()
{
List<Submitconvencelistitem> selectedItems = new ArrayList<>();
for(Submitconvencelistitem item : listData)
{
selectedItems.add(item);
}
return selectedItems;
}*/
}
}

I am assuming that you are using php over your server.What you can do is send the comma separated travel id's over server like this:-
Put travel id's into an arraylist or array like this:-
ArrayList<String> selectedTravelId= new ArrayList<>();
selectedTravelId.add(travelId); // add travel ids
StringBuilder travelId = new StringBuilder();
for (int i = 0; i < selectedTravelId.size(); i++) {
travelId .append(selectedTravelId.get(i));
if (!(i == selectedTravelId.size() - 1)) {
travelId .append(",");
}
}// to create travelId string
travelId.toString();// to convert StringBuilder to String
After this execute your AsyncTask.
You will get a string like e.g. 1,2,134,142.Now send this travelId to sever.
At server side retrieve
Try explode:
$mytravelId = " 1,2,134,142";
$myArray = explode(',', $mytravelId );
print_r($myArray);
Output :
Array
(
[0] => 1
[1] => 2
[2] => 134
[3] => 142
)

Related

get data from recycler card view into our main activity

// data is fetched from card but randon data is fetched using viewholder
//how to get proper and exact data.
//here are the all codes that i am using to recycler view
1. List item
package com.example.jains.attendencemanagementsystem;
/**
* Created by jains on 6/28/2017.
*/
import android.content.Context;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import java.util.List;
import static com.example.jains.attendencemanagementsystem.ViewHolder.IdTextView;
import static com.example.jains.attendencemanagementsystem.ViewHolder.NameTextView;
/**
* Created by JUNED on 6/16/2016.
*/
public class RecyclerViewAdapter extends RecyclerView.Adapter<ViewHolder> {
Context context;
RadioGroup myradiogroup;
RadioButton mySelectedRadioButton;
private RadioButton lastCheckedRB = null;
List<GetDataAdapter> getDataAdapter;
public RecyclerViewAdapter(List<GetDataAdapter> getDataAdapter, Context context){
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final GetDataAdapter getDataAdapter1 = getDataAdapter.get(position);
NameTextView.setText(getDataAdapter1.getName());
IdTextView.setText(String.valueOf(getDataAdapter1.getId()));
// holder.status.setText(String.valueOf());
/** holder.setButtonClickListener(new ButtonClickListener() {
#Override
public void onButtonClick(View v, int pos) {
Snackbar.make(v, "Student " + getDataAdapter.get(pos).getName() + getDataAdapter.get(pos).getId() + " is selected", Snackbar.LENGTH_SHORT).show();
}
});
**/
View.OnClickListener rbClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioButton checked_rb = (RadioButton) v;
if (lastCheckedRB != null) {
lastCheckedRB.setChecked(false);
}
lastCheckedRB = checked_rb;
}
};
/** View.OnClickListener save =new View.OnClickListener() {
#Override public void onClick(View v) {
String date = dateView.getText().toString();
String mySelectedText = mySelectedRadioButton.getText().toString();
String a=getDataAdapter1.getName().toString();
String b=String.valueOf(getDataAdapter1.getId());
String type = "take";
BackgroundWorker_attendance_submit backgroundWorker = new BackgroundWorker_attendance_submit(context);
backgroundWorker.execute(type, a, b, mySelectedText, date);
}
**/
holder.P.setOnClickListener(rbClick);
holder.A.setOnClickListener(rbClick);
holder.L.setOnClickListener(rbClick);
holder.S.setOnClickListener(rbClick);
// holder.button0.setOnClickListener(save);
//CLICKED
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v, int pos) {
Snackbar.make(v, "Student " + getDataAdapter.get(pos).getName() + getDataAdapter.get(pos).getId() + " is selected", Snackbar.LENGTH_SHORT).show();
}
});
}
/**
cardView.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
Intent i = new Intent (view.getContext(), take_attendance.class);
i.putExtra("nn",NameTextView.getText().toString());
i.putExtra("ii",IdTextView.getText());
view.getContext().startActivity(i);
}
});
**/
#Override
public int getItemCount() {
return getDataAdapter.size();
}
}
package com.example.jains.attendencemanagementsystem;
/**
* Created by jains on 6/24/2017.
*/
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
/**
* Created by jains on 26//2017.
*/
public class BackgroundWorker_attendance_submit extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker_attendance_submit(Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://192.168.43.216/a_record_submit.php";
if(type.equals("take")) {
try {
int University_roll = Integer.parseInt(params[1]);
String student_name= params[2];
String status=params[3];
String date =params[4];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("University_roll","UTF-8")+"="+URLEncoder.encode(String.valueOf(University_roll),"UTF-8")+"&"
+URLEncoder.encode("student_name","UTF-8")+"="+URLEncoder.encode(student_name,"UTF-8")+"&"
+URLEncoder.encode("status","UTF-8")+"="+URLEncoder.encode(String.valueOf(status),"UTF-8")+"&"
+URLEncoder.encode("date","UTF-8")+"="+URLEncoder.encode(date,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!= null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Registration Status...");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}`package com.example.jains.attendencemanagementsystem;
/**
* Created by jains on 7/1/2017.
*/
import android.view.View;
/**
* Created by Hp on 3/18/2016.
*/
public interface ItemClickListener {
void onItemClick(View v,int pos);
}`package com.example.jains.attendencemanagementsystem;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
/**
* Created by jains on 7/2/2017.
*/
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ItemClickListener itemClickListener;
ButtonClickListener buttonClickListener;
static TextView IdTextView;
static TextView NameTextView;
static RadioButton P, A, L, S;
static Button button11;
RadioGroup myradiogroup;
RadioButton mySelectedRadioButton;
static CardView cardView;
public ViewHolder(View itemView) {
super(itemView);
IdTextView = (TextView) itemView.findViewById(R.id.textView2);
NameTextView = (TextView) itemView.findViewById(R.id.textView4);
itemView.setOnClickListener(this);
P = (RadioButton) itemView.findViewById(R.id.checkBoxP);
A = (RadioButton) itemView.findViewById(R.id.checkBoxA);
L = (RadioButton) itemView.findViewById(R.id.checkBoxL);
S = (RadioButton) itemView.findViewById(R.id.checkBoxS);
//this button is submit attendance button in card
button11 = (Button) itemView.findViewById(R.id.button11);
//these are the 4 radio button and radio group
myradiogroup = (RadioGroup) itemView.findViewById(R.id.myradiogroup);
int id = myradiogroup.getCheckedRadioButtonId();
mySelectedRadioButton = (RadioButton) itemView.findViewById(id);
cardView = (CardView)itemView.findViewById(R.id.cardview1);
}
#Override
public void onClick(View v) {
this.itemClickListener.onItemClick(v, getLayoutPosition());
}
public void setItemClickListener(ItemClickListener ic) {
this.itemClickListener = ic;
}
/** #Override
public void save(View view)
{
this.buttonClickListener.onButtonClick(view ,getLayoutPosition());
}
public void setButtonClickListener(ButtonClickListener bc)
{
this.buttonClickListener=bc;
}
**/
} /**
#Override
public void onClick(View v) {
**/
package com.example.jains.attendencemanagementsystem;
/**
* Created by jains on 6/28/2017.
*/
import android.content.Context;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import java.util.List;
import static com.example.jains.attendencemanagementsystem.ViewHolder.IdTextView;
import static com.example.jains.attendencemanagementsystem.ViewHolder.NameTextView;
/**
1. Created by JUNED on 6/16/2016.
*/
public class RecyclerViewAdapter extends RecyclerView.Adapter<ViewHolder> {
Context context;
RadioGroup myradiogroup;
RadioButton mySelectedRadioButton;
private RadioButton lastCheckedRB = null;
List<GetDataAdapter> getDataAdapter;
public RecyclerViewAdapter(List<GetDataAdapter> getDataAdapter, Context context){
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final GetDataAdapter getDataAdapter1 = getDataAdapter.get(position);
NameTextView.setText(getDataAdapter1.getName());
IdTextView.setText(String.valueOf(getDataAdapter1.getId()));
// holder.status.setText(String.valueOf());
/** holder.setButtonClickListener(new ButtonClickListener() {
#Override
public void onButtonClick(View v, int pos) {
Snackbar.make(v, "Student " + getDataAdapter.get(pos).getName() + getDataAdapter.get(pos).getId() + " is selected", Snackbar.LENGTH_SHORT).show();
}
});
**/
View.OnClickListener rbClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioButton checked_rb = (RadioButton) v;
if (lastCheckedRB != null) {
lastCheckedRB.setChecked(false);
}
lastCheckedRB = checked_rb;
}
};
/** View.OnClickListener save =new View.OnClickListener() {
#Override public void onClick(View v) {
String date = dateView.getText().toString();
String mySelectedText = mySelectedRadioButton.getText().toString();
String a=getDataAdapter1.getName().toString();
String b=String.valueOf(getDataAdapter1.getId());
String type = "take";
BackgroundWorker_attendance_submit backgroundWorker = new BackgroundWorker_attendance_submit(context);
backgroundWorker.execute(type, a, b, mySelectedText, date);
}
**/
holder.P.setOnClickListener(rbClick);
holder.A.setOnClickListener(rbClick);
holder.L.setOnClickListener(rbClick);
holder.S.setOnClickListener(rbClick);
// holder.button0.setOnClickListener(save);
//CLICKED
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v, int pos) {
Snackbar.make(v, "Student " + getDataAdapter.get(pos).getName() + getDataAdapter.get(pos).getId() + " is selected", Snackbar.LENGTH_SHORT).show();
}
});
}
/**
cardView.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
Intent i = new Intent (view.getContext(), take_attendance.class);
i.putExtra("nn",NameTextView.getText().toString());
i.putExtra("ii",IdTextView.getText());
view.getContext().startActivity(i);
}
});
**/
#Override
public int getItemCount() {
return getDataAdapter.size();
}
}
2. List item
package com.example.jains.attendencemanagementsystem;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class take_attendance extends AppCompatActivity {
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
ProgressBar progressBar;
TextView uni,name;
RadioButton radioButton_P,radioButton_A,radioButton_L,radioButton_S;
private DatePicker datePicker;
private Calendar calendar;
private TextView dateView;
private int year, month, day;
// SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
// String t_name= sharedPreferences.getString(Config.NAME_SHARED_PREF,"Not Available");
//TextView textView=(TextView)findViewById(R.id.showuser);
//
String GET_JSON_DATA_HTTP_URL = "http://192.168.43.216/fetch_stud.php?t_name=";
String JSON_STUDENT_NAME = "student_name";
String JSON_UNIVERSITY_ROLL = "University_roll";
Button button0;
JsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
RadioButton mySelectedRadioButton;
RadioGroup myradiogroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.take_attendance);
//uni=(TextView)findViewById(R.id.textView2);
//name=(TextView)findViewById(R.id.textView4);
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
button0 = (Button)findViewById(R.id.button0) ;
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
button0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//button0.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.VISIBLE);
JSON_DATA_WEB_CALL();
}
});
dateView = (TextView) findViewById(R.id.textView3);
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
showDate(year, month+1, day);
}
public void save(View view)
{
saving();
}
private void saving()
{
// I want to get Student name and University Roll grom the card content which button is clicked by the user
String a= ViewHolder.IdTextView.getText().toString();
String b= ViewHolder.NameTextView.getText().toString();
String date = dateView.getText().toString();
myradiogroup=(RadioGroup)findViewById(R.id.myradiogroup);
int id = myradiogroup.getCheckedRadioButtonId();
mySelectedRadioButton = (RadioButton) findViewById(id);
String mySelectedText = mySelectedRadioButton.getText().toString();
String type = "take";
BackgroundWorker_attendance_submit backgroundWorker = new BackgroundWorker_attendance_submit(this);
backgroundWorker.execute(type, a,b,mySelectedText,date);
//Intent y= new Intent(register_main.this,teacher.class);
//startActivity(y);
// Toast.makeText(register_main.this, "Successfully Registered...!!!", Toast.LENGTH_LONG).show();
}
public void JSON_DATA_WEB_CALL(){
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
final String aa= sharedPreferences.getString(Config.NAME_SHARED_PREF,"Not Available");
final String a= GET_JSON_DATA_HTTP_URL.concat(aa);
jsonArrayRequest = new JsonArrayRequest(a,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.GONE);
// button0.setVisibility(View.GONE);
Snackbar.make(recyclerView,"Note--> Take Attendance Of All Students ",1000000000).setDuration(1000000000).show();
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setId(json.getInt(JSON_UNIVERSITY_ROLL));
GetDataAdapter2.setName(json.getString(JSON_STUDENT_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
//DATE PICKER FUNCTIONS
#SuppressWarnings("deprecation")
public void setDate(View view) {
showDialog(999);
}
#Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this,
myDateListener, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener myDateListener = new
DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0,
int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
// arg1 = year
// arg2 = month
// arg3 = day
showDate(arg1, arg2+1, arg3);
}
};
private void showDate(int year, int month, int day) {
dateView.setText(new StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
}

How to use Checkbox in ListView with JSON data

I'm newbie Android developer. I want to someone help me.
Now, I can call JSON data to my ListView. I did to import checkbox in to ListView. But It's not work. When i am selected on some checkbox just will have other checkbox are selected such as below example event.
checkbox name
X A
_ B
_ C
_ D
_ E
_ F
__________________ << bottom screen
X G
_ H
_ I
When i am selected checkbox "A". Just will has another one checkbox was selected too (checkbox G).
I need to know how to resolve this case.
How to do if i want to show all checkbox are selected after click button submit.
Sorry for my bad English language skill.
Please help me sir.
SearchActivity.java
package com.example.rattapongt.rjp_b;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.rattapongt.rjp_b.Date.myCalendarView;
import com.example.rattapongt.rjp_b.Util.Config;
import com.example.rattapongt.rjp_b.Util.RequestHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
public class SearchActivity extends AppCompatActivity implements View.OnClickListener {
private ProgressDialog loading;
private String JSON_STRING;
ListView listView;
TextView tvDate, tvDateHide;
EditText editTextId, editTextId2;
ImageView ivSearch;
Button btnDate, btnReject;
private int mYear;
private int mMonth;
private int mDay;
private String mYearCheck;
static final int CALENDAR_VIEW_ID = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
listView = (ListView) findViewById(R.id.listView);
editTextId = (EditText) findViewById(R.id.editTextId);
editTextId2 = (EditText) findViewById(R.id.editTextId2);
ivSearch = (ImageView) findViewById(R.id.ivSearch);
tvDate = (TextView) findViewById(R.id.tvDate);
tvDateHide = (TextView) findViewById(R.id.tvDateHide);
btnDate = (Button) findViewById(R.id.btnDate);
btnReject = (Button) findViewById(R.id.btnReject);
ivSearch.setOnClickListener(this);
btnReject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Intent intent = new Intent(SearchActivity.this, RejectActivity.class);
//startActivity(intent);
}
});
editTextId.setText("1992");
editTextId2.setText("PCB116A731 ");
// add a click listener to the button
btnDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(SearchActivity.this, myCalendarView.class);
startActivityForResult(intent, CALENDAR_VIEW_ID);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case CALENDAR_VIEW_ID:
if (resultCode == RESULT_OK) {
Bundle bundle = data.getExtras();
tvDate.setText(bundle.getString("dateSelected1"));
tvDateHide.setText(bundle.getString("dateSelected"));
break;
}
}
}
private void getJSON() {
class GetJSON extends AsyncTask<Void, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(SearchActivity.this, "Fetching Data", "Wait...", false, false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
JSON_STRING = s;
showEmployee();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(Config.URL_GET_ALL);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
private void showEmployee() {
JSONObject jsonObject = null;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
for (int i = 0; i < result.length(); i++) {
JSONObject jo = result.getJSONObject(i);
String Ta = jo.getString(Config.TAG_A);
String Tb = jo.getString(Config.TAG_B);
String Tc = jo.getString(Config.TAG_C);
String Td = jo.getString(Config.TAG_D);
String Te = jo.getString(Config.TAG_E);
String Tf = jo.getString(Config.TAG_F);
String Tg = jo.getString(Config.TAG_G);
HashMap<String, String> employees = new HashMap<>();
employees.put(Config.TAG_A, Ta);
employees.put(Config.TAG_B, Tb);
employees.put(Config.TAG_C, Tc);
employees.put(Config.TAG_D, Td);
employees.put(Config.TAG_E, Te);
employees.put(Config.TAG_F, Tf);
employees.put(Config.TAG_G, Tg);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
SearchActivity.this, list, R.layout.item_list,
new String[]{Config.TAG_A, Config.TAG_B, Config.TAG_C, Config.TAG_D, Config.TAG_E, Config.TAG_F, Config.TAG_G},
new int[]{R.id.invoiceNo, R.id.code, R.id.name, R.id.itemNo, R.id.poNo, R.id.sq, R.id.qty});
listView.setAdapter(adapter);
}
private void getData() {
loading = ProgressDialog.show(this, "Please wait...", "Fetching...", false, false);
//String url = Config.DATA_URL + editTextId.getText().toString().trim();
String url = Config.DATA_URL + "&strKeyword=" + editTextId.getText().toString().trim()
+ "&strKeyword3=" + tvDateHide.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(SearchActivity.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
loading.dismiss();
lostConnection();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response) {
JSONObject jsonObject = null;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
try {
JSONObject jsonObjectSearch = new JSONObject(response);
JSONArray result = jsonObjectSearch.getJSONArray(Config.JSON_ARRAY);
//For map values for JSON to android
/*
JSONObject collegeData = result.getJSONObject(0);
name = collegeData.getString(Config.KEY_NAME);
address = collegeData.getString(Config.KEY_ADDRESS);
vc = collegeData.getString(Config.KEY_VC);
*/
for (int i = 0; i < result.length(); i++) {
JSONObject jo = result.getJSONObject(i);
String Ka = jo.getString(Config.TAG_A);
String Kb = jo.getString(Config.TAG_B);
String Kc = jo.getString(Config.TAG_C);
String Kd = jo.getString(Config.TAG_D);
String Ke = jo.getString(Config.TAG_E);
String Kf = jo.getString(Config.TAG_F);
String Kg = jo.getString(Config.TAG_G);
HashMap<String, String> employees = new HashMap<>();
employees.put(Config.TAG_A, Ka);
employees.put(Config.TAG_B, Kb);
employees.put(Config.TAG_C, Kc);
employees.put(Config.TAG_D, Kd);
employees.put(Config.TAG_E, Ke);
employees.put(Config.TAG_F, Kf);
employees.put(Config.TAG_G, Kg);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
//That will be show information to textView.
/*
if (!name.toString().equals("null")) {
//textViewResult.setText("Name:\t" + name + "\nDesignation:\t" + address + "\nSalary:\t" + vc);
Toast.makeText(this, response, Toast.LENGTH_LONG).show();
} else {
textViewResult.setText("Data not found!");
}
//textViewResult.setText("Name:\t" + name + "\nDesignation:\t" + address + "\nSalary:\t" + vc);
*/
ListAdapter adapter = new SimpleAdapter(
SearchActivity.this, list, R.layout.item_list,
new String[]{Config.KEY_A, Config.KEY_B, Config.KEY_C, Config.KEY_D, Config.KEY_E, Config.KEY_F, Config.KEY_G},
new int[]{R.id.invoiceNo, R.id.code, R.id.name, R.id.itemNo, R.id.poNo, R.id.sq, R.id.qty});
//Toast.makeText(this, response, Toast.LENGTH_LONG).show();
listView.setAdapter(adapter);
}
}
CustomAdapter.java
package com.example.rattapongt.rjp_b.Util;
/**
* Created by Rattapongt on 2/23/2017.
*/
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.rattapongt.rjp_b.R;
public class CustomAdapter extends BaseAdapter {
Context mContext;
String[] strName;
String[] strName1;
String[] strName2;
String[] strName3;
String[] strName4;
String[] strName5;
String[] strName6;
int[] resId;
public CustomAdapter(Context context, String[] strName, String[] strName1, String[] strName2, String[] strName3, String[] strName4, String[] strName5, String[] strName6) {
this.mContext = context;
this.strName = strName;
this.strName1 = strName1;
this.strName2 = strName2;
this.strName3 = strName3;
this.strName4 = strName4;
this.strName5 = strName5;
this.strName6 = strName6;
this.resId = resId;
}
public int getCount() {
return strName.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater mInflater =
(LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view = mInflater.inflate(R.layout.item_list, parent, false);
TextView textView = (TextView) view.findViewById(R.id.textView);
textView.setText(strName[position]);
TextView textView1 = (TextView) view.findViewById(R.id.textView1);
textView1.setText(strName1[position]);
TextView textView2 = (TextView) view.findViewById(R.id.textView2);
textView2.setText(strName2[position]);
TextView textView3 = (TextView) view.findViewById(R.id.textView3);
textView3.setText(strName3[position]);
TextView textView4 = (TextView) view.findViewById(R.id.textView4);
textView4.setText(strName4[position]);
TextView textView5 = (TextView) view.findViewById(R.id.textView5);
textView5.setText(strName5[position]);
TextView textView6 = (TextView) view.findViewById(R.id.textView6);
textView6.setText(strName6[position]);
return view;
}
}
Get the position of selected checkbox and store it in arraylist and then compare the position with the selected position list in getView method. If the list is having that position set the checkbox checked else make it uncheck.
I think removing if(view==null) will do the job.Try it , like in the code below:
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view=inflater.inflate(R.layout.grid_parent_cat_individual_items, null);
TextView textView = (TextView) view.findViewById(R.id.textView);
textView.setText(strName[position]);
TextView textView1 = (TextView) view.findViewById(R.id.textView1);
textView1.setText(strName1[position]);
TextView textView2 = (TextView) view.findViewById(R.id.textView2);
textView2.setText(strName2[position]);
TextView textView3 = (TextView) view.findViewById(R.id.textView3);
textView3.setText(strName3[position]);
TextView textView4 = (TextView) view.findViewById(R.id.textView4);
textView4.setText(strName4[position]);
TextView textView5 = (TextView) view.findViewById(R.id.textView5);
textView5.setText(strName5[position]);
TextView textView6 = (TextView) view.findViewById(R.id.textView6);
textView6.setText(strName6[position]);
return view;
}

How to refresh list view by calling notifyOnDatasetChanged with in base adapter

I am having the list view with buttons in my fragment class which was populated using the custom adapter.When the button which was present inside the list view was pressed i want to remove that item.Here i used the notifyDataSetChanged when ever the button clicks from my adapter class but it does not reflect any result.can any one tell me how to update the list view from adapter class
this is the code i had written inside my adapter class after clicking button
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
notifyDataSetChanged();
}
});
My complete adapter code
import java.util.List;
import java.util.Objects;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.lotus.com.androidmis.R;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.lotus.mis.modle.Complaints.Complaint;
import com.lotus.mis.modle.MyAppApplication;
import com.subtabs.complaints.Complaints_pending;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.w3c.dom.Text;
public class Support_ComplainAdapter extends BaseAdapter {
Context context;
List<Complaint> objects;
ProgressDialog progressdialog;
String UserID;
MyAppApplication mApp;
public Support_ComplainAdapter(Context context,int resource,List<Complaint> objects)
{
this.context = context;
this.objects = objects;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return objects.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return objects.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
// View POItemRow = inflater.inflate(R.layout.activity_poitem_listrow,parent,false);
View PurchaseOrderRow = LayoutInflater.from(context).inflate(R.layout.layout_complaint_adapter,null);
progressdialog = new ProgressDialog(context);
if (position % 2 == 1) {
PurchaseOrderRow.setBackgroundColor(Color.WHITE);
} else {
PurchaseOrderRow.setBackgroundColor(Color.LTGRAY);
}
mApp = ((MyAppApplication)context.getApplicationContext());
final Complaint TR = (Complaint)objects.get(position);
final String RequestNO = TR.getTicketNo();
final String reqID = TR.getComplaintID();
Complaint Complaintlist = (Complaint) objects.get(position);
//TextView txt_PONo = (TextView) PurchaseOrderRow.findViewById(R.id.txt_PONo);
//TextView txt_SuppName = (TextView) PurchaseOrderRow.findViewById(R.id.txt_SuppName);
TextView username = (TextView)PurchaseOrderRow.findViewById(R.id.txt_complaint_empname);
username.setText(mApp.getmGlobal_UserName());
TextView userid = (TextView)PurchaseOrderRow.findViewById(R.id.txt_complaint_userid);
userid.setText(mApp.getmGlobal_UserID());
TextView module_name = (TextView)PurchaseOrderRow.findViewById(R.id.txt_module_name);
module_name.setText(Complaintlist.getText2());
TextView Ref_no = (TextView)PurchaseOrderRow.findViewById(R.id.txt_ref_no);
Ref_no.setText(Complaintlist.getTicketNo());
TextView created_by = (TextView)PurchaseOrderRow.findViewById(R.id.txt_created_by_complaint);
created_by.setText(Complaintlist.getCreatedBy());
TextView created_Date= (TextView)PurchaseOrderRow.findViewById(R.id.txt_created_date_complaint);
created_Date.setText(Complaintlist.getCreatedDate());
TextView complaint_sub = (TextView)PurchaseOrderRow.findViewById(R.id.txt_complaint_sub);
complaint_sub.setText(Complaintlist.getComplaintName());
TextView complaint_body = (TextView)PurchaseOrderRow.findViewById(R.id.txt_complaint_body);
complaint_body.setText(Complaintlist.getText1());
final Button chat_support = (Button)PurchaseOrderRow.findViewById(R.id.btn_chat_support);
chat_support.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
final Button close_complaint = (Button)PurchaseOrderRow.findViewById(R.id.btn_close);
close_complaint.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new set_updateSupport().execute("UpdateValues", "1011",
reqID, "", "", "", "",
"", "","","","");
}
});
return PurchaseOrderRow;
}
class set_updateSupport extends AsyncTask<String, Integer, String> {
private static final String NAME_SPACE = "http://tempuri.org/";
private static final String URL = "http://192.168.1.106:99/Service.asmx";
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressdialog.setMessage("Adding Sales Request");
progressdialog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String TempMethod = params[0];
String Flag = params[1];
String value1 = params[2];
String value2 = params[3];
String value3 = params[4];
String value4 = params[5];
String value5 = params[6];
String value6 = params[7];
String value7 = params[8];
String value8 = params[9];
String value9 = params[10];
String value10 = params[11];
try {
SoapObject request = new SoapObject(NAME_SPACE, TempMethod);
request.addProperty("Flag", Flag);
request.addProperty("value1", value1);
request.addProperty("value2", value2);
request.addProperty("value3", value3);
request.addProperty("value4", value4);
request.addProperty("value5", value5);
request.addProperty("value6", value6);
request.addProperty("value7", value7);
request.addProperty("value8", value8);
request.addProperty("value9", value9);
request.addProperty("value10", value10);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE Android_HttpTransport = new HttpTransportSE(URL);
Android_HttpTransport.debug = true;
Android_HttpTransport.call(NAME_SPACE + TempMethod, envelope);
String responseXml = envelope.getResponse().toString();
// String responseXml = Android_HttpTransport.responseDump;
Log.i("RITESH", "responseXml" + responseXml);
return responseXml;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
// super.onPostExecute(result);
progressdialog.dismiss();
if (result == null) {
Toast.makeText(context, "Error while reading data",
Toast.LENGTH_SHORT).show();
} else if (result.equals("0")) {
Toast.makeText(context, "No record for Update",
Toast.LENGTH_SHORT).show();
} else if (result.equals("1")) {
Toast.makeText(context, "Complain/Support Close Successfully", Toast.LENGTH_SHORT)
.show();
notifyDataSetChanged();
} else {
Toast.makeText(context, "Not Updated result " + result,
Toast.LENGTH_SHORT).show();
}
}
}
}
I didn't find the code that changes the "List objects" content.
You can try this:
objects.clear();
objects.addAll(query(......));
mAdapter.notifyDataSetChanged();

NotifyDataSetChanged on gridview not working - Android

I am working with GridView. I want to update GridView on some basis. But notifyDataSetChanged() method is not working.
I am selecting tables on basis of section name. When I select section name very first time than I got tables of that section. But when I go to sections fragment again and select diff. section than I get previously selected tables only. That means notifyDataSetChanged() is not working.
What I have tried is like below.
TableScreenActivity.java
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import com.malaka.R;
import com.malaka.db.DBAdapter;
import com.malaka.helper.ActionItem;
import com.malaka.helper.AssignGetterSetter;
import com.malaka.helper.Attributes;
import com.malaka.helper.CategoryAdapter;
import com.malaka.helper.DialogAdapter;
import com.malaka.helper.JoinTableAdapter;
import com.malaka.helper.ListSwipeDetector;
import com.malaka.helper.Logout;
import com.malaka.helper.PopupWindows;
import com.malaka.helper.QuickAction;
import com.malaka.helper.QuickActionLocation;
import com.malaka.helper.ReplaceFragment;
import com.malaka.helper.async.AddNewCustomerAsync;
import com.malaka.helper.async.CustomerPhotoAsync;
import com.malaka.helper.async.GetValetNoAsync;
import com.malaka.helper.async.ReAssignTableAsync;
import com.malaka.helper.async.SetTableStatusAsync;
import com.malaka.helper.async.TableStatusAsync;
import com.malaka.helper.async.UnAttendedAsync;
import com.malaka.helper.async.ValetAsync;
import com.malaka.utils.CommanUtils;
import com.malaka.utils.PreferenceUtils;
public class TableScreenActivity extends Fragment {
final static String TAG = "TableScreenActivity";
Button btnBarCode, btnFeedBack, btnLogOut;
GridView gridView;
private TextView mDropdownTitle;
static DBAdapter dbAdapter;
TextView malaka, version;
ImageView refresh;
Animation rotation;
boolean isOpen = false;
RelativeLayout rl;
public static FragmentActivity activity;
LinearLayout mDropdownFoldOutNewCust;
TextView dropDownTextViewNewCust, alt0NewCust, alt1NewCust,
mDropdownTitleNewCust;
LinearLayout ll;
static Dialog dialogAddCust, joinDialog;
ListSwipeDetector detector;
static PreferenceUtils pref;
ArrayList<String> tableName, tableId, sectionId, tableDescriptionId,
tableDescription, custName, custId, custNo, parentId, isManager,
parentName;
ArrayList<String> isVale, isInquired;
ArrayList<Integer> tableColors;
Bundle bundle;
String name = "", no = "", custType = "", tableIds, tableDesc;
static String tableDescId;
static EditText edtName, edtNo;
int pos;
QuickAction quickAction;
QuickActionLocation quickActionLocation;
private static final int ID_TABLE = 1;
private static final int ID_TASK = 2;
private static final int ID_MANAGER = 3;
private static final int ID_RECIPE = 4;
private static final int ID_INSTRUCTION = 5;
private static final int ID_SEARCH = 6;
private static final int ID_HELP = 7;
private static final int ID_SETTING = 8;
private static final int ID_LOGOUT = 9;
private static final int ID_SECTIONS = 11;
private static final int ID_KP = 10;
private static final int ID_BANER = 20;
private static final int ID_CITY = 30;
static ArrayList<String> o_name, o_id, e_id, mTableIdList;
private CategoryAdapter categoryAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
System.out.println("TestTag: savedInstanceState " + savedInstanceState
+ " container: " + container);
System.out.println("TestTag: o_name " + o_name + " mTableIdList: "
+ mTableIdList);
View view = inflater.inflate(R.layout.table_screen, container, false);
init(view);
return view;
}
private void init(View view) {
System.out.println("TestTag: Time1: " + System.currentTimeMillis());
// getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
activity = getActivity();
o_id = new ArrayList<String>();
o_name = new ArrayList<String>();
e_id = new ArrayList<String>();
mTableIdList = new ArrayList<String>();
TextView textView = (TextView) view.findViewById(R.id.txt_table_status);
textView.setVisibility(View.GONE);
refresh = (ImageView) view.findViewById(R.id.img_refresh_table);
rotation = AnimationUtils.loadAnimation(getActivity(),
R.anim.refresh_dialog);
pref = new PreferenceUtils(getActivity());
version = (TextView) view.findViewById(R.id.table_version);
version.setText(pref.getVersion());
if (!pref.getTableStatus()) {
TableStatusAsync Async = new TableStatusAsync(getActivity());
HashMap<String, String> map = new HashMap<String, String>();
Log.e(TAG,
"user id : " + pref.getUserId() + "location : "
+ pref.getLocation() + "SectionId: "
+ pref.getSectionId());
map.put("UserId", pref.getUserId());
map.put("SectionId", pref.getSectionId());
map.put("Location", pref.getLocation());
Async.execute(map);
}
dbAdapter = new DBAdapter(getActivity());
dbAdapter.open();
tableId = dbAdapter.getTableId();
tableName = dbAdapter.getTableName();
sectionId = dbAdapter.getTableSectionId();
tableDescriptionId = dbAdapter.getTableDescriptionId();
tableDescription = dbAdapter.getTableDescription();
custName = dbAdapter.getTableCustName();
custId = dbAdapter.getTableCustID();
custNo = dbAdapter.getTableCustNo();
parentId = dbAdapter.getTableParentId();
parentName = dbAdapter.getTableParentName();
isVale = dbAdapter.getTableIsValeStatus();
isManager = dbAdapter.getTableIsManagerStatus();
isInquired = dbAdapter.getTableIsInquiredStatus();
dbAdapter.close();
Log.d(TAG, "Table length ==" + tableId.size());
tableColors = new ArrayList<Integer>();
for (int i = 0; i < tableDescriptionId.size(); i++) {
tableColors.add(Attributes.getColors(tableDescriptionId.get(i),
getActivity()));
}
ll = (LinearLayout) view.findViewById(R.id.table_ll);
rl = (RelativeLayout) view.findViewById(R.id.ll);
if (pref.getUserRole()) {
rl.setVisibility(View.VISIBLE);
} else {
rl.setVisibility(View.GONE);
}
rl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
quickActionLocation.show(arg0);
}
});
detector = new ListSwipeDetector();
malaka = (TextView) view.findViewById(R.id.txt_malaka_title_table);
malaka.setText(pref.getLocation());
gridView = (GridView) view.findViewById(R.id.gridView_table);
if (tableId.size() <= 0) {
gridView.setVisibility(View.GONE);
textView.setVisibility(View.VISIBLE);
} else {
gridView.setVisibility(View.VISIBLE);
textView.setVisibility(View.GONE);
}
dbAdapter = new DBAdapter(getActivity());
// CategoryAdapter categoryAdapter = new CategoryAdapter(getActivity(),
// 0,
// tableName, tableColors, isInquired, custName,
// tableDescriptionId, parentId, parentName, isManager);
// gridView.setAdapter(categoryAdapter);
// categoryAdapter.notifyDataSetChanged();
//tableName.clear();
//tableName = dbAdapter.getTableName();
categoryAdapter = new CategoryAdapter(getActivity(), 0, tableName,
tableColors, isInquired, custName, tableDescriptionId,
parentId, parentName, isManager);
gridView.setAdapter(categoryAdapter);
categoryAdapter.notifyDataSetChanged();
mDropdownTitle = ((TextView) view
.findViewById(R.id.dropdown_textview_table));
mDropdownTitle.setText(pref.getUserNameToGetManagerPage()
.substring(0, 1).toUpperCase()
+ pref.getUserNameToGetManagerPage().substring(1).toLowerCase()
+ " ");
final TextView dropDownTextView = (TextView) view
.findViewById(R.id.dropdown_textview_table);
dropDownTextView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (PopupWindows.mWindow.isShowing()) {
closeDropdown();
} else {
openDropdown();
}
quickAction.show(v);
}
});
gridView.setOnTouchListener(detector);
gridView.setOnItemLongClickListener(new OnItemLongClickListener() {
....
....
}
gridView.setOnItemClickListener(new OnItemClickListener() {
....
....
}
}// init() method closes
#Override
public void onAttach(Activity activity) {
Log.d(TAG, "TestTag::: onAttach()");
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "TestTag::: onCreate() savedInstanceState: "
+ savedInstanceState);
super.onCreate(savedInstanceState);
}
#Override
public void onStart() {
Log.d(TAG, "TestTag::: onStart()");
super.onStart();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.d(TAG, "TestTag::: onActivityCreated(): savedInstanceState "
+ savedInstanceState);
super.onActivityCreated(savedInstanceState);
}
#Override
public void onResume() {
Log.d(TAG, "TestTag::: onResume()");
super.onResume();
}
#Override
public void onPause() {
Log.d(TAG, "TestTag::: onPause()");
super.onPause();
}
#Override
public void onDestroyView() {
Log.d(TAG, "TestTag::: onDestroyView()");
super.onDestroyView();
}
#Override
public void onDestroy() {
Log.d(TAG, "TestTag::: onDestroy()");
super.onDestroy();
}
#Override
public void onStop() {
Log.d(TAG, "TestTag::: onStop()");
super.onStop();
}
#Override
public void onDetach() {
Log.d(TAG, "TestTag::: onDetach()");
super.onDetach();
}
}
Please, Help. I got stuck in. Thanks advance.
EDIT
TableStatusAsync.java
package com.malaka.helper.async;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.malaka.helper.AsyncAttributes;
import com.malaka.helper.ReplaceFragment;
import com.malaka.helper.TableStatusXmlParser;
import com.malaka.ui.TableScreenActivity;
import com.malaka.utils.CommanUtils;
import com.malaka.utils.NetworkUtils;
import com.malaka.utils.PreferenceUtils;
public class TableStatusAsync extends
AsyncTask<Map<String, String>, Void, Void> {
final static String TAG = "TableStatusAsync";
FragmentActivity context;
String xml;
PreferenceUtils pref;
int response;
boolean isConnected;
public TableStatusAsync(FragmentActivity context) {
this.context = context;
pref = new PreferenceUtils(context);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
CommanUtils.getDialogShow(context, "Please Wait...");
}
#Override
protected Void doInBackground(Map<String, String>... params) {
if (NetworkUtils.isConnectedToInternet(context)) {
isConnected = true;
HashMap<String, String> map = (HashMap<String, String>) params[0];
SoapObject request = new SoapObject(
AsyncAttributes.TableStatusNAMESPACE,
AsyncAttributes.TableStatusMETHOD_NAME);
Iterator<String> iterator = map.keySet().iterator();
// PropertyInfo pi1 = new PropertyInfo();
// pi1.setName("UserId");
// pi1.setValue(map.get("UserId"));
// pi1.setType(String.class);
//
// PropertyInfo pi2 = new PropertyInfo();
// pi2.setName("SectionId");
// pi2.setValue(map.get("SectionId"));
// pi2.setType(String.class);
//
// PropertyInfo pi3 = new PropertyInfo();
// pi3.setName("Location");
// pi3.setValue(map.get("Location"));
// pi3.setType(String.class);
//
// request.addProperty(pi1);
// request.addProperty(pi2);
// request.addProperty(pi3);
Log.e(TAG,
"user id : " + map.get("UserId") + "\nsection id : "
+ map.get("SectionId") + "\nlocation : "
+ map.get("Location"));
while (iterator.hasNext()) {
String key = iterator.next();
request.addProperty(key, map.get(key));
Log.d(TAG, "user id key: " + key + " value: " + map.get(key));
}
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(
AsyncAttributes.TableStatusURL);
try {
androidHttpTransport.call(
AsyncAttributes.TableStatusSOAP_ACTION, envelope);
SoapObject result = (SoapObject) envelope.bodyIn;
if (result
.toString()
.equals("GetTableStatusResponse{GetTableStatusResult=No Table available; }")) {
String xmltemp = String.valueOf(result).split("=")[1];
xml = xmltemp.split(";")[0];
} else {
String xmltemp = "<NewDataSet>\n"
+ String.valueOf(result).split("<NewDataSet>")[1];
xml = xmltemp.split("</NewDataSet>")[0] + "</NewDataSet>";
}
} catch (Exception e) {
e.printStackTrace();
}
if (xml == null) {
response = 1;
Log.d(TAG, "xml null");
} else if (xml.equals("No Table available")) {
response = 2;
} else {
response = 2;
Log.d(TAG, "Task 1 result " + xml);
TableStatusXmlParser.getTableStatusXmlParseData(xml, context);
}
} else {
isConnected = false;
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
CommanUtils.getDialogDismiss();
if (!isConnected) {
CommanUtils.showAlertDialog("Internet Is Required", context);
} else if (response == 1) {
CommanUtils.getToast("Server Error", context);
}
if (response == 2) {
pref.setTableStatus(true);
ReplaceFragment.getReplaceFragment(context,
new TableScreenActivity(), "");
}
}
}
EDIT - 2
CategoryAdapter.java
package com.malaka.helper;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.malaka.R;
import com.malaka.utils.PreferenceUtils;
public class CategoryAdapter extends ArrayAdapter<String> {
ArrayList<String> table, custName, isInquired, isManager, sectionId,
parentId, parentname;
ArrayList<Integer> tableColors;
FragmentActivity context;
ArrayList<Boolean> status;
View view;
PreferenceUtils pref;
int posision;
final static String TAG = "CategoryAdapter";
public CategoryAdapter(FragmentActivity context, int textViewResourceId,
List<String> objects, List<Integer> colors,
List<String> isInquired, List<String> custName,
List<String> sectionId, List<String> parentId,
List<String> parentname, List<String> ismanager) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
table = (ArrayList<String>) objects;
this.parentId = (ArrayList<String>) parentId;
this.parentname = (ArrayList<String>) parentname;
pref = new PreferenceUtils(context);
this.custName = (ArrayList<String>) custName;
tableColors = (ArrayList<Integer>) colors;
this.isManager = (ArrayList<String>) ismanager;
this.isInquired = (ArrayList<String>) isInquired;
this.sectionId = (ArrayList<String>) sectionId;
status = new ArrayList<Boolean>();
Log.i(TAG, "\nisInquired == " + isInquired);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
view = convertView;
ViewHolder holder = new ViewHolder();
if (convertView == null) {
Display display = context.getWindowManager().getDefaultDisplay();
int height = display.getHeight() / 8;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.table_screen_row, null);
holder.textView = (TextView) convertView
.findViewById(R.id.txt_category_seat);
holder.txtName = (TextView) convertView
.findViewById(R.id.txt_customer_name);
holder.imageViewManager = (ImageView) convertView
.findViewById(R.id.imageView_table_manager);
holder.textViewValet = (TextView) convertView
.findViewById(R.id.text_table_valley);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, height);
holder.rl = (RelativeLayout) convertView
.findViewById(R.id.category_seat);
holder.rl.setLayoutParams(params);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// if(isVale.get(position).equals("0")){
// holder.textViewValet.setText("");
// }else{
// if(parentId.get(position).equals("0")){
// holder.textViewValet.setText(isVale.get(position));
// }
// }
Log.d(TAG, "custName == " + custName.get(position) + "\nlength == "
+ custName.get(position).length());
if (custName.get(position).length() > 9) {
if (parentId.get(position).equals("0")) {
holder.txtName.setText(custName.get(position).substring(0, 8)
+ "...");
holder.textView.setText(table.get(position));
} else {
// we have to use parent table Name when Parent id is not 0
holder.txtName.setText(parentname.get(position));
holder.textView.setText("");
}
} else {
if (parentId.get(position).equals("0")) {
holder.txtName.setText(custName.get(position));
holder.textView.setText(table.get(position));
} else {
holder.txtName.setText(parentname.get(position));
holder.textView.setText("");
}
}
if (isManager.get(position).equals("true")) {
holder.imageViewManager
.setBackgroundResource(R.drawable.manager_icon);
} else {
holder.imageViewManager.setBackgroundResource(0);
}
holder.rl.setBackgroundColor(tableColors.get(position));
return convertView;
}
private class ViewHolder {
TextView textView, txtName;
ImageView imageViewManager;
TextView textViewValet;
RelativeLayout rl;
}
}
At last I got the solution.
I have done like below...
I was maintaining a FLAG called getTableStatus to get the tables of particular section. If the value of getTableStatus is FALSE than only TableStatusAsync is called. At first selection of section, tables are coming from web service and those tables are being inserted in DB.
On second time, selecting of SECTION, tables are coming from DB not from web service. And tables are coming from DB are of previously selected SECTION. So, there is nothing to do with notifyDataSetChanged().
I have just change the FLAG value to FALSE by calling pref.setTableStatus(false); on selection of SECTION. Now, TableStatusAsync is called every time when you change your selection of SECTION.
Modified Code...
TableScreenSectionwiseActivity.java
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
pref.setSectionId(view.getTag().toString());
pref.setTableStatus(false);
pref.setTableServiceStatus(false);
Fragment fragment = new TableScreenActivity();
ReplaceFragment.getReplaceFragment(getActivity(), fragment, "");
}

ListView not displayed with values in android

I have made a very simple, form with certain fields,In that i have put a ListView for country List,I am fetching all country names from a webservice,I got all data,But i am unable to set it in ListView,My ListView not visible,Please help me for it.thank you my code is as below:
RegistrationActivity.java
package com.epe.yehki.ui;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.epe.yehki.adapter.CountryAdapter;
import com.epe.yehki.adapter.ProductAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.backend.RegisterationAPI;
import com.epe.yehki.backend.ResponseListener;
import com.epe.yehki.uc.Menu;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Const.API_RESULT;
import com.example.yehki.R;
public class RegistrationActivity extends Activity {
public RegisterationAPI registartionAPI;
private EditText fName;
private EditText lName;
private EditText eMail;
private Button register;
private CountryAdapter countryContent;
private EditText contact;
private EditText password;
private ListView countrylist;
private ListView statelist;
public static ArrayList<String> countryArray;
private TextView country;
private TextView state;
JSONArray countries = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> countryList;
ArrayList<HashMap<String, String>> stateList;
public com.epe.yehki.uc.Menu regMenu;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_registration);
// FINDING IDS...
fName = (EditText) findViewById(R.id.et_fname);
lName = (EditText) findViewById(R.id.et_lname);
eMail = (EditText) findViewById(R.id.et_email);
contact = (EditText) findViewById(R.id.et_contact);
password = (EditText) findViewById(R.id.et_pwd);
country = (TextView) findViewById(R.id.et_country);
state = (TextView) findViewById(R.id.et_state);
regMenu = (Menu) findViewById(R.id.menuReg);
register = (Button) findViewById(R.id.btn_register);
countryList = new ArrayList<HashMap<String, String>>();
countrylist = (ListView) findViewById(R.id.country_list);
statelist = (ListView) findViewById(R.id.state_list);
countryArray = new ArrayList<String>();
regMenu.setSelectedTab(1);
// COUNTRY LIST CLICK EVENT...!!!
countrylist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
String countryname = ((TextView) view.findViewById(R.id.name)).getText().toString();
country.setText(countryname);
// countrylist.setVisibility(view.GONE);
}
});
// REGISTER BUTTOM CLICK EVENT.....!
register.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (!fName.getText().toString().equals("") && fName.getText().toString() != null) {
if ((!lName.getText().toString().equals("") && lName.getText().toString() != null)) {
if ((!country.getText().toString().equals("") && country.getText().toString() != null)) {
if ((!state.getText().toString().equals("") && state.getText().toString() != null)) {
if ((!eMail.getText().toString().equals("") && eMail.getText().toString() != null)) {
if ((!password.getText().toString().equals("") && password.getText().toString() != null)) {
if ((!contact.getText().toString().equals("") && contact.getText().toString() != null)) {
} else {// CONTACT NUMBER
validation(getResources().getString(R.string.valid_number));
password.requestFocus();
}
} else {// password...
validation(getResources().getString(R.string.valid_pwd));
password.requestFocus();
}
} else {// EMAIL
validation(getResources().getString(R.string.valid_mail));
eMail.requestFocus();
}
} else {// STATE
validation(getResources().getString(R.string.valid_state));
state.requestFocus();
}
} else {// COUNTRY
validation(getResources().getString(R.string.valid_country));
country.requestFocus();
}
} else {// LAST NAME
validation(getResources().getString(R.string.valid_lname));
lName.requestFocus();
}
} else {// FIRST NAME
validation(getResources().getString(R.string.valid_fname));
fName.requestFocus();
}
}
});
// COUINTRY LIST CLICK EVENT...!!!!
country.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
countrylist.setVisibility(View.VISIBLE);
new GetCountries().execute();
}
});
}
void validation(String msg) {
Toast.makeText(RegistrationActivity.this, msg, Toast.LENGTH_SHORT).show();
}
ResponseListener responseListener = new ResponseListener() {
#Override
public void onResponce(String api, API_RESULT result, Object obj) {
System.out.println("::::::::::::::inside response Listener::::::::");
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
if (api.equals(Const.API_LOGIN)) {
System.out.println("::::::::::::::inside response Listener::::::::1");
if (result == Const.API_RESULT.SUCCESS) {
registartionAPI = null;
// as
// doctor
System.out.println("success Login::::::::::>>>>>>>>>>>>>>>>>>" + result);
startActivity(new Intent(RegistrationActivity.this, HomeActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
} else {
System.out.println("failed Login::::::::::>>>>>>>>>>>>>>>>>>" + result);
}
}
}
};
// ASYNC TASK FOR GETTING COUNTRY LIST...!!!
private class GetCountries extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
/*
* pDialog = new ProgressDialog(CategoryActivity.this);
* pDialog.setMessage("Please wait...");
* pDialog.setCancelable(false); pDialog.show();
*/
System.out.println("==========inside preexecute===================");
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(Const.API_COUTRY, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
System.out.println("=============MY RESPONSE========== FOR COUNTRYlIST" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
if (jsonObj.has(Const.TAG_COUNTY_LIST)) {
// looping through All Contacts
countries = jsonObj.getJSONArray(Const.TAG_COUNTY_LIST);
for (int i = 0; i < countries.length(); i++) {
JSONObject c = countries.getJSONObject(i);
String cId = c.getString(Const.TAG_COUNTRY_ID);
String countryName = c.getString(Const.TAG_COUNTRY_NAME);
System.out.println("::::::::::::CountryId:::::::::::::" + countryName);
HashMap<String, String> country = new HashMap<String, String>();
country.put(Const.TAG_COUNTRY_ID, cId);
country.put(Const.TAG_COUNTRY_NAME, countryName);
countryList.add(country);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
countryContent = new CountryAdapter(RegistrationActivity.this, countryList);
countrylist.setAdapter(countryContent);
}
}
}
CountryAdapter.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.epe.yehki.util.Const;
import com.example.yehki.R;
public class CountryAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> countryArray;
private Context mContext;
public CountryAdapter(Context paramContext, ArrayList<HashMap<String, String>> cuntryList) {
this.mContext = paramContext;
this.countryArray = cuntryList;
}
public int getCount() {
return this.countryArray.size();
}
public Object getItem(int paramInt) {
return Integer.valueOf(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
#SuppressWarnings("static-access")
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
Viewholder localViewholder = null;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.list_item, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.countryid = ((TextView) paramView.findViewById(R.id.cat_id));
localViewholder.countryName = ((TextView) paramView.findViewById(R.id.name));
paramView.setTag(localViewholder);
} else {
localViewholder = new Viewholder();
localViewholder = (Viewholder) paramView.getTag();
}
System.out.println("::::::::::::::array indexes::::::::::::" + countryArray.get(paramInt));
localViewholder.countryName.setText(countryArray.get(paramInt).get(Const.TAG_COUNTRY_NAME));
localViewholder.countryid.setText(countryArray.get(paramInt).get(Const.TAG_COUNTRY_ID));
return paramView;
}
static class Viewholder {
TextView countryName;
TextView countryid;
}
}
It is display nothing because you do not fill up the dataset you want to display. You create the Adapter in onCreate but at the time the dataset is empty. Imo you should change the Adapter constructor from
public CountryAdapter(Context paramContext, ArrayList<String> paramArrayList) {
to
public CountryAdapter(Context paramContext, ArrayList<HashMap<String, String>> paramArrayList) {
and when onPostExecuted is called, you create a new CountryAdapter and submit it to the ListView. Of course you have to adjust your Adapter in order to reflect the changes of the Adapter's constructor

Categories

Resources