I am working on a project that has a custom listview containing dynamic data. What I want is to fetch that data in an arraylist then pass it to the php file for further processing. I am able to do this for single values but for multiple values I don't have any idea.
This is my adapter class:
public class ListAdapter extends ArrayAdapter {
//static String get_empcode,get_empname,get_app_date,get_nod,get_from,get_to,get_lv_type,get_reason,get_remark,get_status;
static List list=new ArrayList();
static String[] get_empcode,get_empname,get_app_date,get_nod,get_from,get_to,get_lv_type,get_reason,get_remark,get_status;
static String sting_length;
int i;
public ListAdapter(Context context, int resource) {
super(context, resource);
}
public void add(Details object) {
super.add(object);
list.add(object);
}
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row=convertView;
final DetailsHolder detailsHolder;
if(row==null)
{
LayoutInflater layoutInflater=(LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=layoutInflater.inflate(R.layout.list_layout_approval, parent, false);
detailsHolder=new DetailsHolder();
detailsHolder.empcode=(TextView) row.findViewById(R.id.empcode1);
detailsHolder.empname=(TextView) row.findViewById(R.id.empname1);
detailsHolder.appdate=(TextView) row.findViewById(R.id.appdate1);
detailsHolder.lv_type=(TextView) row.findViewById(R.id.lv_type1);
detailsHolder.from=(TextView) row.findViewById(R.id.from1);
detailsHolder.to=(TextView) row.findViewById(R.id.to1);
detailsHolder.nod=(TextView) row.findViewById(R.id.nod1);
detailsHolder.reason=(TextView) row.findViewById(R.id.reason1);
detailsHolder.status=(TextView) row.findViewById(R.id.status1);
detailsHolder.cb2=(CheckBox) row.findViewById(R.id.cb2);
// Leave_approval la=new Leave_approval();
/*
if( Leave_approval.cb_status==true){
detailsHolder.cb2.setChecked(true);
}
else
{
detailsHolder.cb2.setChecked(false);
}
*/
DetailsHolder.cb2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(DetailsHolder.cb2.isChecked())
{
get_empcode=(String) detailsHolder.empcode.getText();
get_from=(String) detailsHolder.from.getText();
get_to=(String) detailsHolder.to.getText();
get_lv_type=(String) detailsHolder.lv_type.getText();
get_nod=(String) detailsHolder.nod.getText();
get_status=(String) detailsHolder.status.getText();
}
}
});
row.setTag(detailsHolder);
}
else{
detailsHolder=(DetailsHolder) row.getTag();
}
Details details=(Details)this.getItem(position);
detailsHolder.empcode.setText(details.getEmpcode());
detailsHolder.empname.setText(details.getEmpname());
detailsHolder.appdate.setText(details.getApplyDate());
detailsHolder.lv_type.setText(details.getLeave_type());
detailsHolder.from.setText(details.getFrom());
detailsHolder.to.setText(details.getTo());
detailsHolder.nod.setText(details.getNod());
detailsHolder.reason.setText(details.getReason());
detailsHolder.status.setText(details.getStatus());
return row;
}
here is my Activity file from where I am passing data to php using async task
public class Leave_approval extends Activity {
String JSON_STRING,php_result,LeaveType,empcode,FullName,ApplyDate,From,To,NOD,Reason,Status;
//String empcode_val="",lv_type_val="",nod_value="",status_val="",from_value="",to_value="";
String[] empcode_val,lv_type_val,nod_value,status_val,from_value,to_value;
JSONObject jsonObject;
JSONArray jsonArray;
String[] date_list;
ArrayList<HashMap<String, String>> personList;
TextView head;
ListAdapter listAdapter;
ListView listView;
CheckBox cb1;
static Boolean cb_status;
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.leave_approval);
listView=(ListView) findViewById(R.id.list);
cb1=(CheckBox) findViewById(R.id.cb1);
listAdapter=new ListAdapter(this, R.layout.list_layout_approval);
listView.setAdapter(listAdapter);
head=(TextView) findViewById(R.id.head);
Bundle b = getIntent().getExtras();
php_result=b.getString("json_data");
//Toast.makeText(getBaseContext(), php_result, Toast.LENGTH_SHORT).show();
cb1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
try {
jsonObject=new JSONObject(php_result);
jsonArray=jsonObject.getJSONArray("server_response");
for(int i=0;i<jsonArray.length();i++){
JSONObject c = jsonArray.getJSONObject(i);
LeaveType=c.getString("LeaveType");
empcode=c.getString("empcode");
FullName=c.getString("FullName");
ApplyDate=c.getString("ApplyDate");
From=c.getString("From");
To=c.getString("To");
NOD=c.getString("NOD");
Reason=c.getString("Reason");
Status=c.getString("Status");
String[] from_array=From.split("-");
String[] to_array=To.split("-");
String[] apply_array=ApplyDate.split("-");
String from_date,to_date,appdate;
if(from_array[1].equals("01"))
from_array[1]="jan";
if(from_array[1].equals("02"))
from_array[1]="Feb";
if(from_array[1].equals("03"))
from_array[1]="Mar";
if(from_array[1].equals("04"))
from_array[1]="Apr";
if(from_array[1].equals("05"))
from_array[1]="May";
if(from_array[1].equals("06"))
from_array[1]="Jun";
if(from_array[1].equals("07"))
from_array[1]="Jul";
if(from_array[1].equals("08"))
from_array[1]="Aug";
if(from_array[1].equals("09"))
from_array[1]="Sep";
if(from_array[1].equals("10"))
from_array[1]="Oct";
if(from_array[1].equals("11"))
from_array[1]="Nov";
if(from_array[1].equals("12"))
from_array[1]="Dec";
if(to_array[1].equals("01"))
to_array[1]="jan";
if(to_array[1].equals("02"))
from_array[1]="Feb";
if(to_array[1].equals("03"))
to_array[1]="Mar";
if(to_array[1].equals("04"))
to_array[1]="Apr";
if(to_array[1].equals("05"))
to_array[1]="May";
if(to_array[1].equals("06"))
to_array[1]="Jun";
if(to_array[1].equals("07"))
to_array[1]="Jul";
if(to_array[1].equals("08"))
to_array[1]="Aug";
if(to_array[1].equals("09"))
to_array[1]="Sep";
if(to_array[1].equals("10"))
to_array[1]="Oct";
if(to_array[1].equals("11"))
to_array[1]="Nov";
if(to_array[1].equals("12"))
to_array[1]="Dec";
if(apply_array[1].equals("01"))
apply_array[1]="jan";
if(apply_array[1].equals("02"))
apply_array[1]="Feb";
if(apply_array[1].equals("03"))
apply_array[1]="Mar";
if(apply_array[1].equals("04"))
apply_array[1]="Apr";
if(apply_array[1].equals("05"))
apply_array[1]="May";
if(apply_array[1].equals("06"))
apply_array[1]="Jun";
if(apply_array[1].equals("07"))
apply_array[1]="Jul";
if(apply_array[1].equals("08"))
apply_array[1]="Aug";
if(apply_array[1].equals("09"))
apply_array[1]="Sep";
if(apply_array[1].equals("10"))
apply_array[1]="Oct";
if(apply_array[1].equals("11"))
apply_array[1]="Nov";
if(apply_array[1].equals("12"))
apply_array[1]="Dec";
from_date=from_array[2]+"-"+from_array[1]+"-"+from_array[0];
to_date=to_array[2]+"-"+to_array[1]+"-"+to_array[0];
appdate=apply_array[2]+"-"+apply_array[1]+"-"+apply_array[0];
Details details=new Details(empcode,FullName,appdate,LeaveType,from_date,to_date,NOD,Reason,Status);
listAdapter.add(details);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void approve(View view){
String empcode_val="",lv_type_val="",nod_value="",status_val="",from_value="",to_value="";
empcode_val=ListAdapter.get_empcode;
lv_type_val=ListAdapter.get_lv_type;
nod_value=ListAdapter.get_nod;
status_val="Approved";
from_value=ListAdapter.get_from;
to_value=ListAdapter.get_to;
if(empcode_val.equals("")&&lv_type_val.equals("")&&nod_value.equals("")&&status_val.equals("")&&from_value.equals("")
&&to_value.equals("")){
Toast.makeText(getBaseContext(), "Please make some selections",Toast.LENGTH_SHORT).show();
}
else{
BackgroundTask backgroundTask = new BackgroundTask(getApplicationContext());
backgroundTask.execute(empcode_val,lv_type_val,nod_value,status_val,from_value,to_value);
}
}
public class BackgroundTask extends AsyncTask {
AsyncResponse delegate = null;
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx =ctx;
}
#Override
protected void onPreExecute() {
}
protected String doInBackground(String... params) {
String login_url = "http://10.0.2.2/neha/leave_approval_update.php";
String empcode = params[0];
String leave_type=params[1];
String nod=params[2];
String status=params[3];
String from=params[4];
String to=params[5];
try {
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 data = URLEncoder.encode("empcode","UTF-8")+"="+URLEncoder.encode(empcode,"UTF-8")+"&"+
URLEncoder.encode("leave_type","UTF-8")+"="+URLEncoder.encode(leave_type,"UTF-8")+"&"+
URLEncoder.encode("nod","UTF-8")+"="+URLEncoder.encode(nod,"UTF-8")+"&"+
URLEncoder.encode("status","UTF-8")+"="+URLEncoder.encode(status,"UTF-8")+"&"+
URLEncoder.encode("from","UTF-8")+"="+URLEncoder.encode(from,"UTF-8")+"&"+
URLEncoder.encode("to","UTF-8")+"="+URLEncoder.encode(to,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine())!=null)
{
response+= line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// }
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx, result, Toast.LENGTH_SHORT).show();
}
}
}
Ok, I got solved my problem by creating array list for all my data then I parse then into json array and passed it as a string to php.
This is how I did:
these are my arraylist
public void approve(View view){
ArrayList<String> emplist=new ArrayList<>();
ArrayList<String> fromlist=new ArrayList<>();
ArrayList<String> tolist=new ArrayList<>();
ArrayList<String> lv_typelist=new ArrayList<>();
ArrayList<String> nodlist=new ArrayList<>();
ArrayList<String> status=new ArrayList<>();
// getting data from ListAdapter class and and adding it to arraylist
emplist=ListAdapter.getemplist();
fromlist=ListAdapter.getfromlist();
tolist=ListAdapter.gettolist();
lv_typelist=ListAdapter.getlv_typelist();
nodlist=ListAdapter.getnodlist();
status.add("Approved");
JSONArray jArr1= new JSONArray();
for(String data:emplist)
{
jArr1.put(data);
}
JSONArray jArr2= new JSONArray();
for(String data:fromlist)
{
jArr2.put(data);
}
JSONArray jArr3= new JSONArray();
for(String data:tolist)
{
jArr3.put(data);
}
JSONArray jArr4= new JSONArray();
for(String data:lv_typelist)
{
jArr4.put(data);
}
JSONArray jArr5= new JSONArray();
for(String data:status)
{
jArr5.put(data);
}
JSONArray jArraySet = new JSONArray();
jArraySet.put(jArr1);
jArraySet.put(jArr2);
jArraySet.put(jArr3);
jArraySet.put(jArr4);
jArraySet.put(jArr5);
BackgroundTask backgroundTask = new BackgroundTask(getApplicationContext());
backgroundTask.execute(json_string);
}
Related
I cannot figure why I getting null listview from it as i tried my url with postman. I think my Android part has some problem with it but i have no idea where the problem.
View Order Activity
public class ViewOrderActivity extends AppCompatActivity {
private ListView listView3;
private CustomAdapter2 listAdapter2;
ArrayList<Order> orderlist = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_order);
User user = SharedPrefManager.getInstance(this).getUser();
String str_oid=String.valueOf(user.getId());
String type="cancel";
BackgroundWorker backgroundWorker=new BackgroundWorker(this);
backgroundWorker.execute(type,str_oid);
listView3 = (ListView) findViewById(R.id.listView3);
getJSON("http://192.168.28.1/restaurant/getorder.php");
}
private void getJSON(final String urlWebService) {
class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}
private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
orderlist.add(new Order(obj.getInt("orderid"), obj.getInt("pickuptime"), obj.getInt("pickupdate")));
}
listAdapter2 = new CustomAdapter2(this, orderlist);
listView3.setAdapter(listAdapter2);
}
}
This is custom adapter where the listview is structured.
Custom Adapter
class CustomAdapter2 extends BaseAdapter {
public ArrayList<Order> ordlists;
private Context context;
CustomAdapter2(Context context, ArrayList<Order> ordlists) {
//super(context, R.layout.item_food, strilist);
this.context = context;
this.ordlists = ordlists;
}
#Override
public int getCount(){
return ordlists.size();
}
#Override
public Order getItem(int position){
return ordlists.get(position);
}
#Override
public long getItemId(int position){
return 0;
}
#NonNull
#Override
public View getView(final int position, View convertView, #NonNull ViewGroup parent) {
final ListViewHolder2 listViewHolder2;
View customView2;
if(convertView == null)
{
LayoutInflater menuInflater2 = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// LayoutInflater menuInflater = LayoutInflater.from(getContext());
customView2 = menuInflater2.inflate(R.layout.item_order, parent, false);
listViewHolder2 = new ListViewHolder2();
listViewHolder2.tvorderid = (TextView) customView2.findViewById(R.id.tvorderid );
listViewHolder2.tvtime = (TextView) customView2.findViewById(R.id.tvtime);
listViewHolder2.tvdate = (TextView) customView2.findViewById(R.id.tvdate);
listViewHolder2.btncancel = (Button) customView2.findViewById(R.id.btncancel);
customView2.setTag(listViewHolder2);
}
else
{
customView2=convertView;
listViewHolder2= (ListViewHolder2) customView2.getTag();
}
final Order order=getItem(position);
//Typeface customfont= Typeface.createFromAsset(parent.getContext().getAssets(),"fonts");
listViewHolder2.tvorderid.setText(String.valueOf(order.getOrderid()));
listViewHolder2.tvorderid.setTextColor(Color.YELLOW);
listViewHolder2.tvorderid.setTextSize(10);
listViewHolder2.tvtime.setText(String.valueOf(order.getPickuptime()));
listViewHolder2.tvtime.setTextColor(Color.YELLOW);
listViewHolder2.tvtime.setTextSize(10);
listViewHolder2.tvdate.setText(String.valueOf(order.getPickupdate()));
listViewHolder2.tvdate.setTextColor(Color.YELLOW);
listViewHolder2.tvdate.setTextSize(10);
listViewHolder2.btncancel.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
}
});
return customView2;
}
Background Worker for cancel type
else if (type.equals("cancel")){
try{
String id=params[1];
URL url=new URL(cancel_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("id","UTF-8")+"="+URLEncoder.encode(id,"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();
}
}
This is my code for url getorder.php
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$database = "y77";
$conn = new mysqli($hostname, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$orders = array();
session_start();
$id=$_POST["id"];
$stmt =$conn->prepare("SELECT `orderid`, `pickuptime`, `pickupdate` FROM `order` WHERE `id`=$id");
$stmt->execute();
$stmt->bind_result($orderid, $pickuptime, $pickupdate);
while($stmt->fetch()){
$temp = [
'orderid'=>$orderid,
'pickuptime'=>$pickuptime,
'pickupdate'=>$pickupdate
];
array_push($orders, $temp);
}
echo json_encode($orders);
?>
I am new to android. I need to pass values from the spinner to asynctask as an parameter and till now I am successful in showing the results in spinner successfully. Now i need to pass the selected value from the spinner to another activity on a button click (as an parameter to asynctask). Below is the code. Thanks in advance.
BackgroundFetchWorker.java:
public class BackgroundFetchWorker extends AsyncTask<String,Void,String> {
String json_string;
ProgressDialog progressDialog;
Context context;
BackgroundFetchWorker(Context ctx)
{
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type2 = params[0];
String student_fetch_url = "http://pseudoattendance.pe.hu/studentFetch.php";
if (type2.equals("fetchSubject")) {
try {
String semester = params[1];
String stream = params[2];
URL url = new URL(student_fetch_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("semester", "UTF-8") + "=" + URLEncoder.encode(semester, "UTF-8")
+ URLEncoder.encode("stream","UTF-8")+"="+URLEncoder.encode(stream,"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 (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Fetching Data....");
progressDialog.setMessage("This may take a while..");
progressDialog.show();
}
#Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
String s = result.trim();
if(s.equals("{\"result\":[]}")){
Toast.makeText(context, "ERROR OCCURED", Toast.LENGTH_SHORT).show();
}
else {
json_string = result;
Intent i = new Intent(context, TakeAttendanceActivity.class);
i.putExtra("studentdata", json_string);
context.startActivity(i);
Toast.makeText(context, "Success", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
FacultyWelcomeActivity.java:
public class FacultyWelcomeActivity extends AppCompatActivity implements Spinner.OnItemSelectedListener{
String JSON_STRING;
JSONObject jsonObject;
JSONArray jsonArray;
ContactAdapter contactAdapter;
ListView listView;
//Declaring an Spinner
private Spinner spinner;
private Spinner spinner1;
//An ArrayList for Spinner Items
private ArrayList<String> students;
private ArrayList<String> stream;
//JSON Array
private JSONArray result;
private JSONArray result1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_faculty_welcome);
//Initializing the ArrayList
students = new ArrayList<String>();
stream = new ArrayList<String>();
//Initializing Spinner
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String semesters= parent.getItemAtPosition(position).toString();
String stream= parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinner1 = (Spinner) findViewById(R.id.spinner1);
//Adding an Item Selected Listener to our Spinner
//As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener
getData();
getData1();
listView = (ListView) findViewById(R.id.lectureList);
contactAdapter = new ContactAdapter(this, R.layout.rowlayout);
listView.setAdapter(contactAdapter);
JSON_STRING = getIntent().getExtras().getString("JSON Data");
try {
jsonObject = new JSONObject(JSON_STRING);
jsonArray = jsonObject.getJSONArray("result");
int count = 0;
String sub1, sub2, sub3, sub4;
while (count < jsonArray.length()) {
JSONObject JO = jsonArray.getJSONObject(count);
sub1 = JO.getString("fname");
sub2 = JO.getString("lname");
sub3 = JO.getString("id");
sub4 = JO.getString("email");
Contacts contacts = new Contacts(sub1, sub2, sub3, sub4);
contactAdapter.add(contacts);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void fetchSubject(View view) {
String type2 = "fetchSubject";
String spinnerdata = spinner.getSelectedItem().toString();
String spinner1data = spinner1.getSelectedItem().toString();
BackgroundFetchWorker background = new BackgroundFetchWorker(this);
background.execute(type2,spinnerdata,spinner1data);
}
private void getData1(){
StringRequest stringRequest = new StringRequest(Config2.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result1 = j.getJSONArray(Config2.JSON_ARRAY);
getStudents1(result1);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void getData(){
StringRequest stringRequest = new StringRequest(Config.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
result = j.getJSONArray(Config.JSON_ARRAY);
getStudents(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void getStudents(JSONArray j){
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
students.add(json.getString(Config.TAG_SEMESTER));
} catch (JSONException e) {
e.printStackTrace();
}
}
spinner.setAdapter(new ArrayAdapter<String>(FacultyWelcomeActivity.this, android.R.layout.simple_spinner_dropdown_item, students));
}
private void getStudents1(JSONArray j){
//Traversing through all the items in the json array
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
stream.add(json.getString(Config2.TAG_STREAM));
} catch (JSONException e) {
e.printStackTrace();
}
}
spinner1.setAdapter(new ArrayAdapter<String>(FacultyWelcomeActivity.this, android.R.layout.simple_spinner_dropdown_item, stream));
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//check which spinner triggered the listener
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}}
You are passing parameters to doInBackground() this way:
background.execute("your string");
Now the string "your string" will be the parameter within doInBackground() callback:
#Override
protected String doInBackground(String... params) {
String type2 = params[0]; // type2 == "your string"
...
}
See docs for more info.
public class MainActivity extends AppCompatActivity {
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView)findViewById(R.id.list_id);
new JsonTask().execute("https://www.dropbox.com/s/o8yqrfm08wfdh48/Hotels.txt?dl=0");
}
class JsonTask extends AsyncTask<String,String ,List<MovieModels>>{
#Override
protected List<MovieModels> doInBackground(String...Params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(Params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream= connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer =new StringBuffer();
String line="";
while ((line=reader.readLine())!=null){
buffer.append(line);
}
String finaljson = buffer.toString();
JSONObject parentObject = new JSONObject(finaljson);
JSONArray parentArray =parentObject.getJSONArray("Hotels");
List<MovieModels> modelsList=new ArrayList<>();
for (int i=0; i<parentArray.length();i++) {
JSONObject finalobject = parentArray.getJSONObject(i);
MovieModels models= new MovieModels();
models.setImage(finalobject.getString("Image"));
models.setHotel_Name(finalobject.getString("Hotel_Name"));
modelsList.add(models);
}
return modelsList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<MovieModels> result) {
super.onPostExecute(result);
Adapter adapter=new Adapter(getApplicationContext(),R.layout.row,result);
lv.setAdapter(adapter);
//to do set the data into list
}
}
public class Adapter extends ArrayAdapter{
private List<MovieModels> modelsList;
private int resource;
private LayoutInflater inflater;
public Adapter(Context context, int resource, List<MovieModels> objects) {
super(context, resource, objects);
modelsList= objects;
this.resource=resource;
inflater=(LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView==null){
convertView=inflater.inflate(R.layout.row,null);
}
ImageView imageView;
TextView textView;
imageView=(ImageView)convertView.findViewById(R.id.image_id);
textView=(TextView)convertView.findViewById(R.id.text_id);
ImageLoader.getInstance().displayImage(modelsList.get(position).getImage(),imageView);
textView.setText("Hotel_Name-"+modelsList.get(position).getHotel_Name());
return convertView;
}
}}
I have an error in the set adapter class, could anyone advise?
Create a class for your MovieModels like this:
public class MovieModels(){
private String imagePath, hotelName;
public MovieModels(String imagePath, String hotelName){
this.imagePath = imagePath;
this.hotelName = hotelName;
}
public String getImagePath(){
return imagePath;
}
public String getHotelName(){
return hotelName;
}
public void setImagePath(String imagePath){
this.imagePath = imagePath;
}
public void setHotelName(String hotelName){
this.hotelName = hotelName;
}
}
and then modify your doInBackground() method like this:
#Override
protected List<MovieModels> doInBackground(String...Params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
List<MovieModels> modelsList=new ArrayList<>();
try {
URL url = new URL(Params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream= connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer =new StringBuffer();
String line="";
while ((line=reader.readLine())!=null){
buffer.append(line);
}
String finaljson = buffer.toString();
JSONObject parentObject = new JSONObject(finaljson);
JSONArray parentArray =parentObject.getJSONArray("Hotels");
for (int i=0; i<parentArray.length();i++) {
JSONObject finalobject = parentArray.getJSONObject(i);
String image = finalobject.getString("Image");
String hotelName = finalobject.getString("Hotel_Name");
modelsList.add(new MovieModels(image, hotelName));
}
return modelsList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
and your postExecute() like this:
#Override
protected void onPostExecute(List<MovieModels> result) {
super.onPostExecute(result);
if (result == null) {
Log.e("MY APPLICATION", "No result to display");
}
Adapter adapter=new Adapter(getApplicationContext(),R.layout.row,result);
lv.setAdapter(adapter);
//to do set the data into list
}
Hope it helps!!!
You return null in your doInBackground and then sets it to the adapter.
You have 2 options to solve it:
Return an empty Array e.g return new ArrayList<>(); instead of return null
or
Check don't set the adapter in case its null. e.g:
#Override
protected void onPostExecute(List<MovieModels> result) {
super.onPostExecute(result);
if (result == null) {
//todo handle no result
return;
}
Adapter adapter=new Adapter(getApplicationContext(),R.layout.row,result);
lv.setAdapter(adapter);
//to do set the data into list
}
}
Edit:
In addition, as said in the comments, your JSON Key you are trying to get ("Hotel_Name") is not like the one of the JSON itself (its "Hotel Name" in the JSON). After you fix that you will see the list, though its still important to solve the exception first.
I've currently got an application that pulls data from a mysql database and displays it in raw JSON format. I'm currently working on pushing this data into a String variable and displaying it on a Listview on a specific activity.
Problem is, when trying to display this data, my Listview is not populating; I'm sure the variable is not empty as the if statement would have captured this.
Here is snippet of MainActivity code:
//Methods to grab information from abhandym_DB database
public void getJSON(View view){
new BackgroundTask().execute();
}
public void parseJSON(View view){
if(JSON_String==null){
Toast.makeText(getApplicationContext(), "First Get Json", Toast.LENGTH_LONG).show();
}else{
Intent intent = new Intent(this,Test.class);
intent.putExtra("JSON_Data",JSON_String);
startActivity(intent);
}
}
class BackgroundTask extends AsyncTask<Void,Void,String>{
String json_url;
#Override
protected void onPreExecute() {
json_url = "http://abhandyman.x10host.com/json_get_data.php";
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputSteam = httpURLConnection.getInputStream();
BufferedReader buffereredReader = new BufferedReader(new InputStreamReader(inputSteam));
StringBuilder stringBuilder = new StringBuilder();
while((JSON_String = buffereredReader.readLine())!=null){
stringBuilder.append(JSON_String+"\n");
}
buffereredReader.close();
inputSteam.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
TextView textView = (TextView)findViewById(R.id.fragment1_textview_JSONAPPEAR);
textView.setText(result);
JSON_String = result;
}
}
Here is the code for my Test.java
public class Test extends AppCompatActivity {
String JSON_String;
JSONObject jsonObject;
JSONArray jsonArray;
DataAdapter dataAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
listView = (ListView)findViewById(R.id.test_listView);
dataAdapter = new DataAdapter(this, R.layout.row_layout);
listView.setAdapter(dataAdapter);
JSON_String = getIntent().getExtras().getString("JSON_Data");
try {
jsonObject = new JSONObject(JSON_String);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String jobid,problem,resolution;
while(count<jsonObject.length()){
JSONObject JO = jsonArray.getJSONObject(count);
jobid = JO.getString("jobid");
problem = JO.getString("problem");
resolution = JO.getString("resolution");
Data data = new Data(jobid,problem,resolution);
dataAdapter.add(data);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here is the code for my DataAdapter:
public class DataAdapter extends ArrayAdapter{
List list = new ArrayList();
public DataAdapter(Context context, int resource) {
super(context, resource);
}
public void add(Data object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
DataHolder dataHolder;
if(row == null){
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
dataHolder = new DataHolder();
dataHolder.tx_jobid = (TextView) row.findViewById(R.id.tx_jobid);
dataHolder.tx_problem = (TextView) row.findViewById(R.id.tx_problem);
dataHolder.tx_resolution = (TextView) row.findViewById(R.id.tx_resolution);
row.setTag(dataHolder);
}else{
dataHolder = (DataHolder)row.getTag();
}
Data data = (Data)this.getItem(position);
dataHolder.tx_jobid.setText(data.getJobid());
dataHolder.tx_problem.setText(data.getProblem());
dataHolder.tx_resolution.setText(data.getResolution());
return row;
}
static class DataHolder{
TextView tx_jobid,tx_problem,tx_resolution;
}
}
and here is what it displays when clicking on "Parse JSON" button.
listView empty after population
Any help or advise on why its not displaying would be much appreciated!
Thanks in advance!
your problem seems to be here :
while(count<jsonObject.length()){
you're not looping using the number of array elements but using the number of mapped key:value object which is one (the "server_response") , you have to change this line to :
while(count<jsonArray.length()){
,
you have just the first element showing because jsonObject.length() will return 1 since it have just one element.
from the doc, JSONObject, length() method:
Returns the number of name/value mappings in this object.
and in your case you have just one name/value mapped ("server_response":[array items...])
Check in Test.java. I think You are setting the adapter to the listview before adding data to it
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
listView = (ListView)findViewById(R.id.test_listView);
dataAdapter = new DataAdapter(this, R.layout.row_layout);
JSON_String = getIntent().getExtras().getString("JSON_Data");
try {
jsonObject = new JSONObject(JSON_String);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String jobid,problem,resolution;
while(count<jsonObject.length()){
JSONObject JO = jsonArray.getJSONObject(count);
jobid = JO.getString("jobid");
problem = JO.getString("problem");
resolution = JO.getString("resolution");
Data data = new Data(jobid,problem,resolution);
dataAdapter.add(data);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
listView.setAdapter(dataAdapter); //change effected
}
I have one spinner and I want to to populate the custom listview with the the data according to spinner selection. Data is coming from mysql database. Currently I am able to get the data from different spinner selection but the problem is when I try to add the data in listview it doesn't remove previous data from listview.
I tried listAdapter.notifyDataSetChanged() but this didn,t worked for me. Even I created 2 adapters for different spinner selections and tried to add them to list according to spinner selection but this gives me blank list.
I saw multiple solutions for my problem but nothing worked for me.
So please give me some suitable idea for adding different data to listview according to spinner selection.
Thanks in advance
this is my adapter class
public class ListAdapter extends ArrayAdapter {
//static String get_empcode,get_empname,get_app_date,get_nod,get_from,get_to,get_lv_type,get_reason,get_remark,get_status;
static List list=new ArrayList();
static String[] get_empcode,get_empname,get_app_date,get_nod,get_from,get_to,get_lv_type,get_reason,get_remark,get_status;
static ArrayList<String> empcode = new ArrayList<String>();
static ArrayList<String> from = new ArrayList<String>();
static ArrayList<String> to = new ArrayList<String>();
static ArrayList<String> lv_type = new ArrayList<String>();
static ArrayList<String> nod = new ArrayList<String>();
static int count=0;
int i;
static int arr_length;
public ListAdapter(Context context, int resource) {
super(context, resource);
}
public void add(Details object) {
super.add(object);
list.add(object);
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
super.registerDataSetObserver(observer);
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
super.unregisterDataSetObserver(observer);
}
public int getCount() {
return list.size();
}
#Override
public Details getItem(int position) {
return (Details) list.get(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row;
row=convertView;
final DetailsHolder detailsHolder;
if(row==null)
{
LayoutInflater layoutInflater=(LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=layoutInflater.inflate(R.layout.list_layout_approval, parent, false);
detailsHolder=new DetailsHolder();
detailsHolder.empcode=(TextView) row.findViewById(R.id.empcode1);
detailsHolder.empname=(TextView) row.findViewById(R.id.empname1);
detailsHolder.appdate=(TextView) row.findViewById(R.id.appdate1);
detailsHolder.lv_type=(TextView) row.findViewById(R.id.lv_type1);
detailsHolder.from=(TextView) row.findViewById(R.id.from1);
detailsHolder.to=(TextView) row.findViewById(R.id.to1);
detailsHolder.nod=(TextView) row.findViewById(R.id.nod1);
detailsHolder.reason=(TextView) row.findViewById(R.id.reason1);
detailsHolder.status=(TextView) row.findViewById(R.id.status1);
DetailsHolder.cb2=(CheckBox) row.findViewById(R.id.cb2);
DetailsHolder.cb2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
{
count=count+1;
empcode.add((String) detailsHolder.empcode.getText());
from.add((String) detailsHolder.from.getText());
to.add((String) detailsHolder.to.getText());
lv_type.add((String) detailsHolder.lv_type.getText());
nod.add((String) detailsHolder.nod.getText());
}
else{
count=count-1;
empcode.remove(position);
from.remove(position);
to.remove(position);
lv_type.remove(position);
nod.remove(position);
}
arr_length=empcode.size()+from.size()+to.size()+lv_type.size()+nod.size();
}
});
row.setTag(detailsHolder);
}
else{
detailsHolder=(DetailsHolder) row.getTag();
}
Details details=(Details)this.getItem(position);
detailsHolder.empcode.setText(details.getEmpcode());
detailsHolder.empname.setText(details.getEmpname());
detailsHolder.appdate.setText(details.getApplyDate());
detailsHolder.lv_type.setText(details.getLeave_type());
detailsHolder.from.setText(details.getFrom());
detailsHolder.to.setText(details.getTo());
detailsHolder.nod.setText(details.getNod());
detailsHolder.reason.setText(details.getReason());
detailsHolder.status.setText(details.getStatus());
return row;
}
static class DetailsHolder
{
TextView empcode,empname,appdate,lv_type,from,to,nod,reason,status;
EditText remark;
static CheckBox cb2;
}
}
below is details class:-
public class Details {
private String empcode,empname,applyDate,leave_type,from,to,nod,reason,remark,status;
public Details(String empcode,String empname,String applyDate,String leave_type,String from,
String to,String nod,String reason,String status){
this.setEmpcode(empcode);
this.setEmpname(empname);
this.setApplyDate(applyDate);
this.setLeave_type(leave_type);
this.setFrom(from);
this.setTo(to);
this.setNod(nod);
this.setReason(reason);
this.setStatus(status);
}
public String getEmpcode() {
return empcode;
}
public void setEmpcode(String empcode) {
this.empcode = empcode;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public String getApplyDate() {
return applyDate;
}
public void setApplyDate(String applyDate) {
this.applyDate = applyDate;
}
public String getLeave_type() {
return leave_type;
}
public void setLeave_type(String leave_type) {
this.leave_type = leave_type;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getNod() {
return nod;
}
public void setNod(String nod) {
this.nod = nod;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
And in mainActivity I am passing data as follows:
public class Leave_approval extends Activity {
String JSON_STRING,php_result,LeaveType,empcode,FullName,ApplyDate,From,To,NOD,Reason,Status,bundle_id,approve_bkg_result;
String from_date,to_date,appdate;
String LeaveType1,empcode1,FullName1,ApplyDate1,From1,To1,NOD1,Reason1,Status1,bundle_id1,from_date1,to_date1,appdate1;
String[] status_data;
String[] empcode_val,lv_type_val,nod_value,status_val,from_value,to_value;
JSONObject jsonObject;
JSONArray jsonArray;
String[] date_list;
Details details;
TextView head;
ListAdapter listAdapter;
Approve_List_adapter approve_adapter;
ListView listView;
CheckBox cb1;
static Boolean cb_status;
int i;
Spinner status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.leave_approval);
listView=(ListView) findViewById(R.id.list);
cb1=(CheckBox) findViewById(R.id.cb1);
status=(Spinner) findViewById(R.id.status);
listAdapter=new ListAdapter(this, R.layout.list_layout_approval);
// approve_adapter=new Approve_List_adapter(this, R.layout.approve_list_adapter);
listView.setAdapter(listAdapter);
//listView.setAdapter(approve_adapter);
head=(TextView) findViewById(R.id.head);
Bundle b = getIntent().getExtras();
php_result=b.getString("json_data");
bundle_id = b.getString("string");
status_data=getResources().getStringArray(R.array.status);
ArrayAdapter<String> adapter=new ArrayAdapter<>(this, android.R.layout.simple_spinner_item,status_data);
status.setAdapter(adapter);
status.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
String status_changed=arg0.getItemAtPosition(arg2).toString();
if(status_changed.equals("Approved"))
{
LeaveApprovedStatus bkg=new LeaveApprovedStatus(getApplicationContext());
bkg.execute(bundle_id);
}
else{
//Toast.makeText(getApplicationContext(), status_changed, Toast.LENGTH_SHORT).show();
try {
jsonObject=new JSONObject(php_result);
jsonArray=jsonObject.getJSONArray("server_response");
for(int i=0;i<jsonArray.length();i++){
JSONObject c = jsonArray.getJSONObject(i);
LeaveType=c.getString("LeaveType");
empcode=c.getString("empcode");
FullName=c.getString("FullName");
ApplyDate=c.getString("ApplyDate");
From=c.getString("From");
To=c.getString("To");
NOD=c.getString("NOD");
Reason=c.getString("Reason");
Status=c.getString("Status");
String[] from_array=From.split("-");
String[] to_array=To.split("-");
String[] apply_array=ApplyDate.split("-");
String from_date,to_date,appdate;
if(from_array[1].equals("01"))
from_array[1]="jan";
if(from_array[1].equals("02"))
from_array[1]="Feb";
if(from_array[1].equals("03"))
from_array[1]="Mar";
if(from_array[1].equals("04"))
from_array[1]="Apr";
if(from_array[1].equals("05"))
from_array[1]="May";
if(from_array[1].equals("06"))
from_array[1]="Jun";
if(from_array[1].equals("07"))
from_array[1]="Jul";
if(from_array[1].equals("08"))
from_array[1]="Aug";
if(from_array[1].equals("09"))
from_array[1]="Sep";
if(from_array[1].equals("10"))
from_array[1]="Oct";
if(from_array[1].equals("11"))
from_array[1]="Nov";
if(from_array[1].equals("12"))
from_array[1]="Dec";
if(to_array[1].equals("01"))
to_array[1]="jan";
if(to_array[1].equals("02"))
from_array[1]="Feb";
if(to_array[1].equals("03"))
to_array[1]="Mar";
if(to_array[1].equals("04"))
to_array[1]="Apr";
if(to_array[1].equals("05"))
to_array[1]="May";
if(to_array[1].equals("06"))
to_array[1]="Jun";
if(to_array[1].equals("07"))
to_array[1]="Jul";
if(to_array[1].equals("08"))
to_array[1]="Aug";
if(to_array[1].equals("09"))
to_array[1]="Sep";
if(to_array[1].equals("10"))
to_array[1]="Oct";
if(to_array[1].equals("11"))
to_array[1]="Nov";
if(to_array[1].equals("12"))
to_array[1]="Dec";
if(apply_array[1].equals("01"))
apply_array[1]="jan";
if(apply_array[1].equals("02"))
apply_array[1]="Feb";
if(apply_array[1].equals("03"))
apply_array[1]="Mar";
if(apply_array[1].equals("04"))
apply_array[1]="Apr";
if(apply_array[1].equals("05"))
apply_array[1]="May";
if(apply_array[1].equals("06"))
apply_array[1]="Jun";
if(apply_array[1].equals("07"))
apply_array[1]="Jul";
if(apply_array[1].equals("08"))
apply_array[1]="Aug";
if(apply_array[1].equals("09"))
apply_array[1]="Sep";
if(apply_array[1].equals("10"))
apply_array[1]="Oct";
if(apply_array[1].equals("11"))
apply_array[1]="Nov";
if(apply_array[1].equals("12"))
apply_array[1]="Dec";
from_date=from_array[2]+"-"+from_array[1]+"-"+from_array[0];
to_date=to_array[2]+"-"+to_array[1]+"-"+to_array[0];
appdate=apply_array[2]+"-"+apply_array[1]+"-"+apply_array[0];
details=new Details(empcode,FullName,appdate,LeaveType,from_date,to_date,NOD,Reason,Status);
listAdapter.add(details);
//listView.invalidate();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {}
});
}
public void approve(View view){
//Toast.makeText(getApplicationContext(), String.valueOf(ListAdapter.count), Toast.LENGTH_SHORT).show();
ArrayList<String> emplist=new ArrayList<>();
ArrayList<String> fromlist=new ArrayList<>();
ArrayList<String> tolist=new ArrayList<>();
ArrayList<String> lv_typelist=new ArrayList<>();
ArrayList<String> nodlist=new ArrayList<>();
ArrayList<String> status=new ArrayList<>();
emplist=ListAdapter.getemplist();
fromlist=ListAdapter.getfromlist();
tolist=ListAdapter.gettolist();
lv_typelist=ListAdapter.getlv_typelist();
nodlist=ListAdapter.getnodlist();
status.add("Approved");
JSONArray jArr1= new JSONArray();
for(String data:emplist)
{
jArr1.put(data);
}
JSONArray jArr2= new JSONArray();
for(String data:fromlist)
{
jArr2.put(data);
}
JSONArray jArr3= new JSONArray();
for(String data:tolist)
{
jArr3.put(data);
}
JSONArray jArr4= new JSONArray();
for(String data:lv_typelist)
{
jArr4.put(data);
}
JSONArray jArr5= new JSONArray();
for(String data:status)
{
jArr5.put(data);
}
JSONArray jArraySet = new JSONArray();
jArraySet.put(jArr1);
jArraySet.put(jArr2);
jArraySet.put(jArr3);
jArraySet.put(jArr4);
jArraySet.put(jArr5);
String json_string=String.valueOf(jArraySet);
// Toast.makeText(getApplicationContext(), json_string, Toast.LENGTH_LONG).show();
BackgroundTask backgroundTask = new BackgroundTask(getApplicationContext());
backgroundTask.execute(json_string);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
listView.onWindowFocusChanged(true);
listView.invalidate();
listView.invalidateViews();
}
}
public void reject(View view){
ArrayList<String> emplist=new ArrayList<>();
ArrayList<String> fromlist=new ArrayList<>();
ArrayList<String> tolist=new ArrayList<>();
ArrayList<String> lv_typelist=new ArrayList<>();
ArrayList<String> nodlist=new ArrayList<>();
ArrayList<String> status=new ArrayList<>();
emplist=ListAdapter.getemplist();
fromlist=ListAdapter.getfromlist();
tolist=ListAdapter.gettolist();
lv_typelist=ListAdapter.getlv_typelist();
nodlist=ListAdapter.getnodlist();
status.add("Rejected");
JSONArray jArr1= new JSONArray();
for(String data:emplist)
{
jArr1.put(data);
}
JSONArray jArr2= new JSONArray();
for(String data:fromlist)
{
jArr2.put(data);
}
JSONArray jArr3= new JSONArray();
for(String data:tolist)
{
jArr3.put(data);
}
JSONArray jArr4= new JSONArray();
for(String data:lv_typelist)
{
jArr4.put(data);
}
JSONArray jArr5= new JSONArray();
for(String data:status)
{
jArr5.put(data);
}
JSONArray jArraySet = new JSONArray();
jArraySet.put(jArr1);
jArraySet.put(jArr2);
jArraySet.put(jArr3);
jArraySet.put(jArr4);
jArraySet.put(jArr5);
String json_string=String.valueOf(jArraySet);
//Toast.makeText(getApplicationContext(), json_string, Toast.LENGTH_LONG).show();
BackgroundTask backgroundTask = new BackgroundTask(getApplicationContext());
backgroundTask.execute(json_string);
}
public class BackgroundTask extends AsyncTask<String,Void,String> {
AsyncResponse delegate = null;
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx =ctx;
}
#Override
protected void onPreExecute() {
}
protected String doInBackground(String... params) {
String login_url = "http://10.0.2.2/neha/leave_approval_json.php";
String json_data = params[0];
try {
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 data = URLEncoder.encode("json_data","UTF-8")+"="+URLEncoder.encode(json_data,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine())!=null)
{
response+= line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// }
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx, result, Toast.LENGTH_SHORT).show();
}
}
class LeaveApprovedStatus extends AsyncTask<String, Void, String>
{
String json_url;
Context ctx;
LeaveApprovedStatus(Context ctx)
{
this.ctx =ctx;
}
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
json_url = "http://10.0.2.2/neha/leave_approval_approvedStatus.php";
final String empcode = params[0];
try {
URL url = new URL(json_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 data = URLEncoder.encode("empcode","UTF-8")+"="+URLEncoder.encode(empcode,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
StringBuilder stringBuilder1=new StringBuilder();
while((JSON_STRING=bufferedReader.readLine())!=null)
{
stringBuilder1.append(JSON_STRING+"\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder1.toString().trim();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
approve_bkg_result=result;
Details details1=new Details (empcode1,FullName1,appdate1,LeaveType1,from_date1,to_date1,NOD1,Reason1,Status1);
listAdapter.add(details1);
listAdapter.notifyDataSetChanged();
listView.invalidate();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
So supposing you store your data in an ArrayList:
private ArrayList<VideoPreview> dataList = new ArrayList<>();
You can populate it in the spinner onItemSelectedListener:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position != currentPosition) {
dataList.clear();
dataList = myData[position];
dataListView.getAdapter().notifyOnDataSetChanged();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Without knowing anything else of your problem and code, I cannot give you a more specific solution.
Your declaration of the adapter should look similar to this:
final DataAdapter adapter = new DataAdapter(getContext(), dataList);
dataListView.setAdapter(adapter);
If the data object you are passing is ArrayList<MyObject>
just make your custom adapter extend ArrayAdapter<MyObject> instead of BaseAdapter. Implement the required methods (leave default) and you should be fine.