Update ListView periodically - android

In my code, I want to update ListView periodically say after every 10 seconds. As ListView is custom and data in ListView are populated from database, I need to refresh ListView periodically so that any changes in database can be reflected in ListView. I tried using Handler concept but it didn't help me. Below is my code. What needs to be done?
public class GetFriendDeviceId extends ListActivity {
String data = "";
String title;
ListView list;
CustomDeviceId adapter;
ArrayList<String> useridarr;
ArrayList<String> namearr;
ArrayList<String> regidarr;
ArrayList<String> statusarr;
String id;
String userid, name, regid;
private static final String USERID = "user_id";
private static final String NAME = "user_name";
private static final String REGID = "regId";
DBController contoller = new DBController(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.getfriend_deviceid);
useridarr = new ArrayList<String>();
namearr = new ArrayList<String>();
regidarr = new ArrayList<String>();
statusarr = new ArrayList<String>();
// get user_id using sharedpreference
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
id = preferences.getString("ID", "");
new GetContent().execute();
}
// asynctask to get content for selected title
public class GetContent extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(GetFriendDeviceId.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
useridarr.clear();
namearr.clear();
regidarr.clear();
statusarr.clear();
pdLoading.setMessage("\tPlease wait...");
pdLoading.show();
}
#Override
protected Void doInBackground(Void... params) {
final GetDeviceId getdb = new GetDeviceId();
new Thread(new Runnable() {
public void run() {
data = getdb.getDataFromDB(id);
System.out.println(data);
runOnUiThread(new Runnable() {
#Override
public void run() {
ArrayList<User_DeviceId> users = parseJSON(data);
addData(users);
}
});
}
}).start();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pdLoading.dismiss();
}
}
public ArrayList<User_DeviceId> parseJSON(String result) {
ArrayList<User_DeviceId> users = new ArrayList<User_DeviceId>();
try
{
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++)
{
JSONObject json_data = jArray.getJSONObject(i);
User_DeviceId user = new User_DeviceId();
user.setUser_id(json_data.getString(USERID));
user.setUser_name(json_data.getString(NAME));
user.setRegId(json_data.getString(REGID));
users.add(user);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return users;
}
#SuppressWarnings({ "rawtypes" })
public void addData(ArrayList<User_DeviceId> users) {
for (Iterator i = users.iterator(); i.hasNext();) {
User_DeviceId p = (User_DeviceId) i.next();
useridarr.add(p.getUser_id());
namearr.add(p.getUser_name());
regidarr.add(p.getRegId());
}
DBController.statusArray = statusarr;
contoller.getStatus(id, useridarr, 0);
adapter = new CustomDeviceId(GetFriendDeviceId.this, namearr, useridarr, statusarr);
list.setAdapter(adapter);
}
I tried this code
final Handler handler_new = new Handler();
handler_new.postDelayed( new Runnable() {
#Override
public void run() {
DBController.statusArray = MainActivity.result;
contoller.Status("100003818200590", "100007144268382", 0);
MainActivity.adapter.notifyDataSetChanged();
handler_new.postDelayed( this, 1000);
}
}, 1000);
But didn't work...

I just Edit your code hope this helps you
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.ListView;
public class GetFriendDeviceId extends ListActivity {
String data = "";
String title;
ListView list;
CustomDeviceId adapter;
ArrayList<String> useridarr;
ArrayList<String> namearr;
ArrayList<String> regidarr;
ArrayList<String> statusarr;
String id;
String userid, name, regid;
private static final String USERID = "user_id";
private static final String NAME = "user_name";
private static final String REGID = "regId";
DBController contoller;
Timer timer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.getfriend_deviceid);
contoller = new DBController(this);
useridarr = new ArrayList<String>();
namearr = new ArrayList<String>();
regidarr = new ArrayList<String>();
statusarr = new ArrayList<String>();
// get user_id using sharedpreference
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
id = preferences.getString("ID", "");
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
new GetContent().execute();
}
});
}
}, 0, 10000);
}
// asynctask to get content for selected title
public class GetContent extends AsyncTask<Void, Void, ArrayList<User_DeviceId>> {
ProgressDialog pdLoading = new ProgressDialog(GetFriendDeviceId.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
useridarr.clear();
namearr.clear();
regidarr.clear();
statusarr.clear();
pdLoading.setMessage("\tPlease wait...");
pdLoading.show();
}
#Override
protected ArrayList<User_DeviceId> doInBackground(Void... params) {
final GetDeviceId getdb = new GetDeviceId();
data = getdb.getDataFromDB(id);
ArrayList<User_DeviceId> users = parseJSON(data);
return users;
}
#Override
protected void onPostExecute(ArrayList<User_DeviceId> result) {
super.onPostExecute(result);
addData(result);
pdLoading.dismiss();
}
}
public ArrayList<User_DeviceId> parseJSON(String result) {
ArrayList<User_DeviceId> users = new ArrayList<User_DeviceId>();
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
User_DeviceId user = new User_DeviceId();
user.setUser_id(json_data.getString(USERID));
user.setUser_name(json_data.getString(NAME));
user.setRegId(json_data.getString(REGID));
users.add(user);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return users;
}
#SuppressWarnings({ "rawtypes" })
public void addData(ArrayList<User_DeviceId> users) {
for (Iterator i = users.iterator(); i.hasNext();) {
User_DeviceId p = (User_DeviceId) i.next();
useridarr.add(p.getUser_id());
namearr.add(p.getUser_name());
regidarr.add(p.getRegId());
}
DBController.statusArray = statusarr;
contoller.getStatus(id, useridarr, 0);
adapter = new CustomDeviceId(GetFriendDeviceId.this, namearr, useridarr, statusarr);
list.setAdapter(adapter);
}
}

Constantly/Periodically polling for a change is not a good idea in general.
You should implement some thing like push notification when DB is updated for better performance. When a piece of code changes the content of DB, it should invoke all subscriber of listener/ or broadcast a message.
Your activity/fragment should implement that listener, and refresh the listview. This way your listview will be refreshed only when some changes occur in DB instead of looking for a change in DB and refresh itself.
A listview can be refreshed by modifying the backing datasource of listview.
namearr = newnamearr;
...
newnamearr is new contents for listview.
and then calling notifyDataSetChanged().
This piece of code is working but their could be better approach available.
import java.util.ArrayList;
public class ListenerTest {
public static void main(String[] args) {
// simulation for activities.
A a = new A();
a.simulateOnCreate();
B b = new B();
b.simulateOnCreate();
DBChanger obj = new DBChanger();
obj.changeDBContent();
}
}
// this is class where all DB changes will occur.
class DBChanger{
public void changeDBContent(){
// some piece of Code that change the DB code.
ArrayList<Listenable> subcribers = ListnerManager.getInstance().getSubscribersList();
for(Listenable l: subcribers){
l.onUpadateAvailable();
}
}
}
// This class should corresponds to Activity/Fragment in Android which will implement the listener
class A implements Listenable {
public void simulateOnCreate(){
ListnerManager maneger = ListnerManager.getInstance();
maneger.setOnListenable(this);
}
#Override
public void onUpadateAvailable() {
System.out.println("A---> onUpadateAvailable");
}
}
// This class is manager of listener.
class ListnerManager {
public static ListnerManager instance = new ListnerManager();
public static ListnerManager getInstance(){
if(instance == null){
instance = new ListnerManager();
}
return instance;
}
ArrayList<Listenable> subscriberlist = new ArrayList<Listenable>();
public void setOnListenable(Listenable subcsriber) {
subscriberlist.add(subcsriber);
}
public ArrayList<Listenable> getSubscribersList() {
return subscriberlist;
}
}
// Same as class A
class B implements Listenable {
public void simulateOnCreate(){
ListnerManager maneger = ListnerManager.getInstance();
maneger.setOnListenable(this);
}
#Override
public void onUpadateAvailable() {
// TODO Auto-generated method stub
System.out.println("B---> onUpadateAvailable");
}
}
interface Listenable {
public void onUpadateAvailable();
}
Output i received on my console:
A---> onUpadateAvailable
B---> onUpadateAvailable

I agree with #GauravGupta. The best way is to implement a push notification when there is changes in the database.
But regarding your problem you can try to run this asynctask:
class refreshList extends AsyncTask<String, String, String> {
Context context
public refreshList(Context context){
this.context=context;
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method sstub
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
//Since you cant invoke notify notifyDataSetChanged() inside the doInBackground. So we will use this code:
((MainActivity) context).runOnUiThread(new Runnable() {
public void run() {
//Do your code here like refreshing your adapter
MainActivity.adapter.notifyDataSetChanged();
//
}
});
}
}, 1000, 10000);
//1000= interval delay;
//10000= run every 10secs
return null;
}
}
Remember to pass your activity's context when running the asynctask.
new refreshList(this).execute();

Related

After pressing back button, previous activity (listview) is emtpty

In my android project i have a listview with items loaded from an online database. When i click on an item i go to another class where i can delete or update it. My problem is that when i press the back button, my listview is empty. I tried onBackPressed with intent to go to previous activity but it is empty again. I want to reload my listview when from a clicked item i press the back button. Below is my code.
The listview:
public class AllStudents extends AppCompatActivity {
ListView StudentListView;
ProgressBar progressBar;
String HttpUrl = "http://sissy-nickels.000webhostapp.com/AllStudentData.php";
List<String> IdList = new ArrayList<>();
String LessonName;
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
String FinalJSonObject;
HashMap<String,String> ResultHash = new HashMap<>();
String ParseResult ;
List<Student> studentList;
EditText search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_allstudents);
StudentListView = (ListView)findViewById(R.id.listview2);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
LessonName = getIntent().getStringExtra("Lesson");
HttpWebCall(LessonName);
//Adding ListView Item click Listener.
StudentListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Intent intent = new Intent(AllStudents.this,SingleStudent.class);
// Sending ListView clicked value using intent.
intent.putExtra("ListViewValue", IdList.get(position).toString());
startActivity(intent);
//Finishing current activity after open next activity.
//finish();
}
});
search = (EditText)findViewById(R.id.search);
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged (CharSequence s, int start, int count, int after) {
}
// when text is entered in search box, filter list by search text
#Override
public void onTextChanged(CharSequence cs, int start, int before, int count) {
filterStudents(cs);
}
#Override
public void afterTextChanged(Editable s) {
}
});
// check student's name whether contain text entered in search box
}
public void HttpWebCall(final String LessonName){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(AllStudents.this,"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new GetHttpResponse(AllStudents.this).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("LessonName",params[0]);
ParseResult = httpParse.postRequest(ResultHash, HttpUrl);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(LessonName);
}
// JSON parse class started from here.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
Student student;
studentList = new ArrayList<Student>();
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
student = new Student();
// Adding Student Id TO IdList Array.
IdList.add(jsonObject.getString("id").toString());
//Adding Student Name.
student.StudentName = jsonObject.getString("Regnum").toString();
studentList.add(student);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
StudentListView.setVisibility(View.VISIBLE);
ListAdapter adapter = new ListAdapter(studentList, context);
StudentListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
private void filterStudents (CharSequence cs) {
List<Student> filteredList = new ArrayList<>();
if (TextUtils.isEmpty(cs)) {
// no text is entered for search, do nothing
return;
}
// build new student list which filtered by search text.
for (Student student : studentList) {
if (student.StudentName.contains(cs)) {
filteredList.add(student);
}
}
// show filtered list in listview
ListAdapter adapter = new ListAdapter(filteredList, this);
StudentListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}}
And the code from item click:
public class SingleStudent extends AppCompatActivity {
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
// Http Url For Filter Student Data from Id Sent from previous activity.
String HttpURL = "http://sissy-nickels.000webhostapp.com/FilterStudentData.php";
// Http URL for delete Already Open Student Record.
String HttpUrlDeleteRecord = "http://sissy-nickels.000webhostapp.com/DeleteStudent.php";
String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
TextView NAME,SURNAME,DEPT,REGNUM,GRADE;
String NameHolder, SurnameHolder, DeptHolder, RegnumHolder, GradeHolder;
Button UpdateButton, DeleteButton;
String TempItem;
ProgressDialog progressDialog2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singlestudent);
NAME = (TextView)findViewById(R.id.name);
SURNAME = (TextView)findViewById(R.id.surname);
DEPT = (TextView)findViewById(R.id.dept);
REGNUM = (TextView)findViewById(R.id.regnum);
GRADE = (TextView)findViewById(R.id.grade);
UpdateButton = (Button)findViewById(R.id.BDel);
DeleteButton = (Button)findViewById(R.id.BUp);
//Receiving the ListView Clicked item value send by previous activity.
TempItem = getIntent().getStringExtra("ListViewValue");
//Calling method to filter Student Record and open selected record.
HttpWebCall(TempItem);
UpdateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(SingleStudent.this,StudentUpdate.class);
// Sending Student Id, Name, Number and Class to next UpdateActivity.
intent.putExtra("Id", TempItem);
intent.putExtra("name", NameHolder);
intent.putExtra("surname", SurnameHolder);
intent.putExtra("dept", DeptHolder);
intent.putExtra("regnum", RegnumHolder);
intent.putExtra("grade", GradeHolder);
startActivity(intent);
// Finishing current activity after opening next activity.
finish();
}
});
// Add Click listener on Delete button.
DeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Calling Student delete method to delete current record using Student ID.
StudentDelete(TempItem);
}
});
}
// Method to Delete Student Record
public void StudentDelete(final String StudentID) {
class StudentDeleteClass extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog2 = ProgressDialog.show(SingleStudent.this, "Φόρτωση", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
progressDialog2.dismiss();
Toast.makeText(SingleStudent.this, httpResponseMsg.toString(), Toast.LENGTH_LONG).show();
finish();
}
#Override
protected String doInBackground(String... params) {
// Sending STUDENT id.
hashMap.put("StudentID", params[0]);
finalResult = httpParse.postRequest(hashMap, HttpUrlDeleteRecord);
return finalResult;
}
}
StudentDeleteClass studentDeleteClass = new StudentDeleteClass();
studentDeleteClass.execute(StudentID);
}
//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(SingleStudent.this,"Φόρτωση",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new GetHttpResponse(SingleStudent.this).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("StudentID",params[0]);
ParseResult = httpParse.postRequest(ResultHash, HttpURL);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(PreviousListViewClickedItem);
}
// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
// Storing Student Name, Phone Number, Class into Variables.
NameHolder = jsonObject.getString("Name").toString() ;
SurnameHolder = jsonObject.getString("Surname").toString() ;
DeptHolder = jsonObject.getString("Dept").toString() ;
RegnumHolder = jsonObject.getString("Regnum").toString() ;
GradeHolder = jsonObject.getString("Grade").toString() ;
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
// Setting Student Name, Phone Number, Class into TextView after done all process .
NAME.setText(NameHolder);
SURNAME.setText(SurnameHolder);
DEPT.setText(DeptHolder);
REGNUM.setText(RegnumHolder);
GRADE.setText(GradeHolder);
}
}}
Than you in advance!
try this on AllStudents activity
#Override
protected void onResume() {
super.onResume();
if (studentList != null && studentList.size()>0) {
ListAdapter adapter = new ListAdapter(studentList, this);
StudentListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
*Note
when you make a search you run the filterStudents() method
and replace the current list in the adapter
ListAdapter adapter = new ListAdapter(filteredList, this);
but make sure that if you search for nothing .. return the original list
ListAdapter adapter = new ListAdapter(studentList, this);
or you will get an empty list view
You should not recreate from secondActivity. You just finish it when your work is done in secondActivity. Which means, simply you have to do the below in your secondActivity.
#Override
public void onBackPressed() {
super.onBackPressed();
}

Thread exiting with uncaught exception on a specific function

Im developing an android app that performs add, update, and delete operations on data on a localhosted MySQL Database. Everything is working fine except for the update part. It happens on the activity ViewFeedingSched when im trying to update the data. The app crashes when the update button is pressed or simply when the function for updating is called. The logcat is giving a message: threadid=1: thread exiting with uncaught exception (group=0x41640c80) . I've seen several solutions and they're mostly about not initializing some objects or having null values. I can't seem to find where I have not initialized something. It was working before and I don't know what I've changed with the program. Below is the codes of the ViewFeedingSched class.
EDIT
I've added the codes for the class that goes before the ViewFeedingSched class which is the FeedingSchedList class. It's layout contains a ListView with the data being listed, and an onItemClick method that opens the ViewFeedingSched class whenever an item (data) is clicked.
public class ViewFeedingSched extends AppCompatActivity implements View.OnClickListener {
private EditText editTextSchedNo;
private EditText editTextFeedTime;
private EditText editTextFeedAmt;
private TextView textViewCurrentTimeSet;
private TextView textViewIDSelected;
//private TextView textViewCurrentAmtSet;
private NumberPicker numPickerHr;
private NumberPicker numPickerMin;
//private Spinner spinnerFeedAmt;
ArrayAdapter<CharSequence> adapter;
private Button buttonUpdate;
private Button buttonDelete;
private String id;
private String ftime;
// private String famt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_feeding_sched);
Intent intent = getIntent();
id = intent.getStringExtra(Config.SCHED_ID);
ftime = intent.getStringExtra(Config.FEEDTIME);
//famt = intent.getStringExtra(Config.FEEDAMT);
editTextSchedNo = (EditText) findViewById(R.id.ET_SchedNo);
editTextFeedTime = (EditText) findViewById(R.id.ET_FeedTime);
//editTextFeedAmt = (EditText) findViewById(R.id.ET_FeedAmt);
textViewCurrentTimeSet = (TextView) findViewById(R.id.TV_CurrentTimeSet);
textViewIDSelected = (TextView) findViewById(R.id.TV_PickedSchedID);
//textViewCurrentAmtSet = (TextView) findViewById(R.id.TV_CurrentAmountSet);
buttonUpdate = (Button) findViewById(R.id.BT_UpdateSched);
buttonDelete = (Button) findViewById(R.id.BT_DeleteSched);
buttonUpdate.setOnClickListener(this);
buttonDelete.setOnClickListener(this);
textViewIDSelected.setText(id);
textViewCurrentTimeSet.setText(ftime);
//textViewCurrentAmtSet.setText(famt);
numPickerHr = (NumberPicker) findViewById(R.id.NP_Hour);
numPickerHr.setMinValue(0);
numPickerHr.setMaxValue(23);
numPickerHr.setWrapSelectorWheel(true);
numPickerMin = (NumberPicker) findViewById(R.id.NP_Min);
numPickerMin.setMinValue(0);
numPickerMin.setMaxValue(59);
numPickerMin.setWrapSelectorWheel(true);
//spinnerFeedAmt = (Spinner) findViewById(R.id.SP_FeedAmt);
//adapter = ArrayAdapter.createFromResource(this,R.array.FeedAmt,android.R.layout.simple_spinner_item);
//spinnerFeedAmt.setAdapter(adapter);
getSchedule();
}
private void getSchedule(){
class GetSchedule extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ViewFeedingSched.this,"Fetching...","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
showSchedule(s);
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequestParam(Config.URL_GET_SCHED,id);
return s;
}
}
GetSchedule ge = new GetSchedule();
ge.execute();
}
private void showSchedule(String json){
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
JSONObject c = result.getJSONObject(0);
String feedtime = c.getString(Config.TAG_FEEDTIME);
String feedamt = c.getString(Config.TAG_FEEDAMT);
//editTextFeedTime.setText(feedtime);
// editTextFeedAmt.setText(feedamt);
textViewCurrentTimeSet.setText(feedtime);
// String spinnerVal = String.valueOf(spinnerFeedAmt.getSelectedItem().toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
private void updateSchedule(){
final String feedtime = editTextFeedTime.getText().toString().trim();
final String feedamt = editTextFeedAmt.getText().toString().trim();
final String NP_FeedTime_HR = String.valueOf(numPickerHr.getValue()).trim();
final String NP_FeedTime_MIN = String.valueOf(numPickerMin.getValue()).trim();
//final String SP_FeedAmt = spinnerFeedAmt.getSelectedItem().toString().trim();
class UpdateSchedule extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ViewFeedingSched.this,"Updating...","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(ViewFeedingSched.this,s,Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Void... params) {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put(Config.KEY_SCHED_ID,id);
hashMap.put(Config.KEY_FEED_TIME,NP_FeedTime_HR+":"+NP_FeedTime_MIN+":00");
hashMap.put(Config.KEY_FEED_AMT,feedamt);
RequestHandler rh = new RequestHandler();
String s = rh.sendPostRequest(Config.URL_UPDATE_SCHED,hashMap);
return s;
}
}
UpdateSchedule ue = new UpdateSchedule();
ue.execute();
}
private void deleteSchedule(){
class DeleteSchedule extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ViewFeedingSched.this, "Updating...", "Wait...", false, false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(ViewFeedingSched.this, s, Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequestParam(Config.URL_DELETE_SCHED, id);
return s;
}
}
DeleteSchedule de = new DeleteSchedule();
de.execute();
}
private void confirmDeleteSchedule(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure you want to delete this schedule?");
alertDialogBuilder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
deleteSchedule();
startActivity(new Intent(ViewFeedingSched.this,FeedingScheduleList.class));
}
});
alertDialogBuilder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
public void onClick(View v) {
if(v == buttonUpdate){
updateSchedule();
}
if(v == buttonDelete){
confirmDeleteSchedule();
}
}
}
FeedingSchedList class
public class FeedingScheduleList extends AppCompatActivity implements ListView.OnItemClickListener{
private ListView listView;
private String JSON_STRING;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.feeding_schedule_list);
listView = (ListView) findViewById(R.id.FeedSchedListView);
listView.setOnItemClickListener(this);
getJSON();
}
private void showFeedSched(){
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 id = jo.getString(Config.TAG_ID);
String feedtime = jo.getString(Config.TAG_FEEDTIME);
String feedamt = jo.getString(Config.TAG_FEEDAMT);
HashMap<String,String> schedules = new HashMap<>();
schedules.put(Config.TAG_ID,id+" ");
schedules.put(Config.TAG_FEEDTIME,feedtime+" ");
schedules.put(Config.TAG_FEEDAMT,feedamt+" ");
list.add(schedules);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
FeedingScheduleList.this, list, R.layout.list_item,
new String[]{Config.TAG_ID,Config.TAG_FEEDTIME,Config.TAG_FEEDAMT},
new int[]{R.id.SchedID, R.id.FeedSchedTime,R.id.FeedAmt});
listView.setAdapter(adapter);
}
private void getJSON() {
class GetJSON extends AsyncTask<Void, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(FeedingScheduleList.this, "Fetching Data", "Wait...", false, false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
JSON_STRING = s;
showFeedSched();
}
#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();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this, ViewFeedingSched.class);
HashMap<String,String> map =(HashMap)parent.getItemAtPosition(position);
String schedID = map.get(Config.TAG_ID).toString();
String feedTime = map.get(Config.TAG_FEEDTIME).toString();
//String feedAmt = map.get(Config.TAG_FEEDAMT).toString();
intent.putExtra(Config.SCHED_ID,schedID);
intent.putExtra(Config.FEEDTIME,feedTime);
//intent.putExtra(Config.FEEDAMT,feedAmt);
startActivity(intent);
}
}

how to show only selected data when spinner value is selected in android?

I have got 3 spinner where data is coming from server, if we click the search button without selecting any spinner then on next activity , it should show all list(all product without condition), but if we select according to 3 spinner then it should show only related item.I am getting all item when clicking search button without selecting anything but i am not getting selected item in next activity .
here is my Search Activity:
public class PMSearchActivity extends AppCompatActivity {
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
private ImageButton mtoolbar,pmplus;
private Button mpigeonSearchbtn;
private Spinner pmcountry;
private Spinner pmstrain;
private Spinner pmdistance;
private TextView error_text;
// distance part
ArrayList<String> listItems = new ArrayList<>();
ArrayAdapter<String> adapter;
ArrayList<String> listItems2 = new ArrayList<>();
ArrayAdapter<String> adapter2;
// distance part
ArrayList<String> listItems3 = new ArrayList<>();
ArrayAdapter<String> adapter3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pmsearch);
getSupportActionBar().hide();
pmplus = (ImageButton) findViewById(R.id.plus);
pmplus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(PMSearchActivity.this, PMAddPigeonActivity.class);
startActivity(intent);
finish();
}
}) ;
mtoolbar = (ImageButton) findViewById(R.id.toolbar_new);
mtoolbar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Intent intent = new Intent(PMSearchActivity.this, PMDashboardActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish(); //
return false;
}
});
mpigeonSearchbtn = (Button) findViewById(R.id.pmaddcompanybtn);
mpigeonSearchbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
pmcountry = (Spinner) findViewById(R.id.sname);
pmstrain = (Spinner) findViewById(R.id.fbcountry);
pmdistance = (Spinner) findViewById(R.id.pstrain);
error_text = (TextView) findViewById(R.id.error_text);
adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.txt, listItems);
pmstrain.setAdapter(adapter);
ListDistanceTask distanceTask = new ListDistanceTask();
distanceTask.execute();
adapter2 = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.txt, listItems2);
pmdistance.setAdapter(adapter2);
ListStrainTask strainTask = new ListStrainTask();
strainTask.execute();
adapter3 = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.txt, listItems3);
pmcountry.setAdapter(adapter3);
ListCountryTask listCountryTask = new ListCountryTask();
listCountryTask.execute();
}
private void attemptLogin() {
// Reset errors.
// mEmailView.setError(null);
//mPasswordView.setError(null);
// Store values at the time of the login attempt.
String PMcountry = pmcountry.getSelectedItem().toString();
String PMstrains = pmstrain.getSelectedItem().toString();
String PMdistance = pmdistance.getSelectedItem().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
}
Intent intent = new Intent(PMSearchActivity.this, PMPigeonListingActivity.class);
intent.putExtra("Country_name", PMcountry);
intent.putExtra("Strain_name", PMstrains);
intent.putExtra("Distance_name", PMdistance);
startActivity(intent);
}
public class ListStrainTask extends AsyncTask<Void, Void, Void> {
ArrayList<String> list;
protected ProgressDialog progressDialog;
;
ListStrainTask() {
}
#Override
protected Void doInBackground(Void... params) {
String result = "";
try {
list.add("-Select Strain-");
// Json coding
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(PMSearchActivity.this, "Please wait...", "Fetching data", true, false);
list = new ArrayList<>();
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
listItems.addAll(list);
adapter.notifyDataSetChanged();
}
#Override
protected void onCancelled() {
// ml = null;
progressDialog.dismiss();
}
}
// listdistancetask
public class ListDistanceTask extends AsyncTask<Void, Void, Void> {
ArrayList<String> list;
protected ProgressDialog progressDialog;
;
ListDistanceTask() {
}
// Json coding
}
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(PMSearchActivity.this, "Please wait...", "Fetching data", true, false);
list = new ArrayList<>();
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
listItems2.addAll(list);
adapter2.notifyDataSetChanged();
}
#Override
protected void onCancelled() {
// ml = null;
progressDialog.dismiss();
}
}
public class ListCountryTask extends AsyncTask<Void, Void, Void> {
ArrayList<String> list;
protected ProgressDialog progressDialog;
;
ListCountryTask() {
}
#Override
protected Void doInBackground(Void... params) {
String result = "";
try {
list.add("-Select Country-");
// Json coding
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(PMSearchActivity.this, "Please wait...", "Fetching data", true, false);
list = new ArrayList<>();
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
listItems3.addAll(list);
adapter3.notifyDataSetChanged();
}
#Override
protected void onCancelled() {
// ml = null;
progressDialog.dismiss();
}
}
}
here in PiegonListing activity:
public class PMPigeonListingActivity extends AppCompatActivity {
private Button mpigeonListBtn;
private ImageView mimg3;
private ImageButton mtoolbar;
private String PostCountry;
private String PostStrain;
private String PostDistance;
private Button listpigeonbutton;
private Spinner lsDistance;
private Spinner lsStrain;
private Spinner lsCountry;
private Button lssearchbutton;
private TextView listallbtn;
//Web api url
// distance part
ArrayList<String> listItems = new ArrayList<>();
ArrayAdapter<String> adapter;
ArrayList<String> listItems2 = new ArrayList<>();
ArrayAdapter<String> adapter2;
// distance part
ArrayList<String> listItems3 = new ArrayList<>();
ArrayAdapter<String> adapter3;
//Tag values to read from json
public static final String TAG_IMAGE_URL = "pimage";
public static final String TAG_NAME = "pprice";
public static final String TAG_PID = "pid";
public static final String TAG_PNAME = "pname";
public static final String TAG_PDETAILS = "pdetails";
public static final String TAG_MOBILE = "pmobile";
public static final String TAG_EMAIL = "pemail";
//GridView Object
private GridView gridView;
private GridView gridView2;
//ArrayList for Storing image urls and titles
private ArrayList<String> images;
private ArrayList<String> names;
private ArrayList<Integer> pid;
private ArrayList<String> pname;
private ArrayList<String> pdetails;
private ArrayList<String> pimage;
private ArrayList<String> pmobile;
private ArrayList<String> pemail;
//for inline search
private ArrayList<String> images2;
private ArrayList<String> names2;
private ArrayList<Integer> pid2;
private ArrayList<String> pname2;
private ArrayList<String> pdetails2;
private ArrayList<String> pimage2;
private ArrayList<String> pmobile2;
private ArrayList<String> pemail2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pmpigeon_listing);
getSupportActionBar().hide();
gridView = (GridView) findViewById(R.id.gridView);
gridView2 = (GridView) findViewById(R.id.gridView);
Bundle extras = getIntent().getExtras();
if (extras != null) {
PostCountry = extras.getString("Country_name");
PostStrain = extras.getString("Strain_name");
PostDistance = extras.getString("Distance_name");
}
images = new ArrayList<>();
names = new ArrayList<>();
pid = new ArrayList<>();
pname = new ArrayList<>();
pdetails = new ArrayList<>();
pmobile = new ArrayList<>();
pemail = new ArrayList<>();
images2 = new ArrayList<>();
names2 = new ArrayList<>();
pid2 = new ArrayList<>();
pname2 = new ArrayList<>();
pdetails2 = new ArrayList<>();
pmobile2 = new ArrayList<>();
pemail2 = new ArrayList<>();
lsStrain = (Spinner) findViewById(R.id.lsStrain);
lsDistance = (Spinner) findViewById(R.id.lsDistance);
lsCountry = (Spinner) findViewById(R.id.lsCountry);
lssearchbutton = (Button) findViewById(R.id.lssearchbutton);
listallbtn = (TextView) findViewById(R.id.listallbtn);
if (PostCountry.equals("Select Country") && PostStrain.equals("Select Strain") && PostDistance.equals("Select Distance")) {
listallbtn.setVisibility(View.GONE);
} else {
listallbtn.setVisibility(View.VISIBLE);
}
//Calling the getData method
getData();
mtoolbar = (ImageButton) findViewById(R.id.toolbar_new);
mtoolbar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Intent intent = new Intent(PMPigeonListingActivity.this, PMDashboardActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish(); //
return false;
}
});
lssearchbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (lsCountry.getSelectedItemPosition() != 0 || lsStrain.getSelectedItemPosition() != 0 || lsDistance.getSelectedItemPosition() != 0) {
listallbtn.setVisibility(View.VISIBLE);
} else {
listallbtn.setVisibility(View.GONE);
}
images2.clear();
names2.clear();
pid2.clear();
pname2.clear();
pdetails2.clear();
pmobile2.clear();
pemail2.clear();
filter();
}
});
listallbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (lsCountry.getSelectedItemPosition() != 0 || lsStrain.getSelectedItemPosition() != 0 || lsDistance.getSelectedItemPosition() != 0) {
listallbtn.setVisibility(View.VISIBLE);
} else {
listallbtn.setVisibility(View.GONE);
}
lsCountry.setSelection(0);
lsStrain.setSelection(0);
lsDistance.setSelection(0);
images2.clear();
names2.clear();
pid2.clear();
pname2.clear();
pdetails2.clear();
pmobile2.clear();
pemail2.clear();
filter();
}
});
// button list
listpigeonbutton = (Button) findViewById(R.id.listpigeonbutton);
listpigeonbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(PMPigeonListingActivity.this, PMAddPigeonActivity.class);
startActivity(intent);
}
});
adapter = new ArrayAdapter<String>(this, R.layout.spinner_small, R.id.txt, listItems);
lsStrain.setAdapter(adapter);
ListDistanceTask distanceTask = new ListDistanceTask();
distanceTask.execute();
adapter2 = new ArrayAdapter<String>(this, R.layout.spinner_small, R.id.txt, listItems2);
lsDistance.setAdapter(adapter2);
ListStrainTask strainTask = new ListStrainTask();
strainTask.execute();
adapter3 = new ArrayAdapter<String>(this, R.layout.spinner_small, R.id.txt, listItems3);
lsCountry.setAdapter(adapter3);
ListCountryTask listCountryTask = new ListCountryTask();
listCountryTask.execute();
}
private void getData() {
//Showing a progress dialog while our app fetches the data from url
final ProgressDialog loading = ProgressDialog.show(this, "Please wait...", "Fetching data...", false, false);
String DATA_URL = "http://......searchPigeonList";
StringRequest stringRequest = new StringRequest(Request.Method.POST, DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(PMPigeonListingActivity.this,response,Toast.LENGTH_LONG).show();
loading.dismiss();
try {
JSONArray json = new JSONObject(response).getJSONArray("pigeon_list");
for (int i = 0; i < json.length(); i++) {
JSONObject obj = null;
try {
obj = json.getJSONObject(i);
pid.add(obj.getInt("id"));
pname.add(obj.getString("pigeon_name"));
pdetails.add(obj.getString("pigeon_details"));
pmobile.add(obj.getString("usr_mobile"));
pemail.add(obj.getString("usr_email"));
images.add(obj.getString("image"));
names.add(obj.getString("pigeon_price"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(JSONException je){
je.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
Log.d("Test",response);
//Creating GridViewAdapter Object
PMPigeonListAdapter pmpigeonlistadapter = new PMPigeonListAdapter(getApplicationContext(), images, names, pid, pdetails, pmobile, pemail, pname);
//Adding adapter to gridview
gridView.setAdapter(pmpigeonlistadapter);
pmpigeonlistadapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(PMPigeonListingActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("country", PostCountry);
params.put("strain", PostStrain);
params.put("distance", PostDistance);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void filter() {
//Showing a progress dialog while our app fetches the data from url
final ProgressDialog loading = ProgressDialog.show(this, "Please wait...", "Fetching data...", false, false);
String DATA_URL = "http://......hPigeonList";
final String lstrain = lsStrain.getSelectedItem().toString();
final String ldistance = lsDistance.getSelectedItem().toString();
final String lcountry = lsCountry.getSelectedItem().toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(PMPigeonListingActivity.this,response,Toast.LENGTH_LONG).show();
loading.dismiss();
try {
JSONArray json = new JSONObject(response).getJSONArray("pigeon_list");
for (int i = 0; i < json.length(); i++) {
JSONObject obj = null;
try {
obj = json.getJSONObject(i);
pid2.add(obj.getInt("id"));
pname2.add(obj.getString("pigeon_name"));
pdetails2.add(obj.getString("pigeon_details"));
pmobile2.add(obj.getString("usr_mobile"));
pemail2.add(obj.getString("usr_email"));
images2.add(obj.getString("image"));
names2.add(obj.getString("pigeon_price"));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
//Creating GridViewAdapter Object
PMPigeonSearchInlineAdapter pmPigeonSearchInlineAdapter = new PMPigeonSearchInlineAdapter(getApplicationContext(), images2, names2, pid2, pdetails2, pmobile2, pemail2, pname2);
//Adding adapter to gridview
pmPigeonSearchInlineAdapter.notifyDataSetChanged();
gridView2.setAdapter(pmPigeonSearchInlineAdapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(PMPigeonListingActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params2 = new HashMap<String, String>();
params2.put("country", lcountry);
params2.put("strain", lstrain);
params2.put("distance", ldistance);
return params2;
}
};
RequestQueue requestQueue2 = Volley.newRequestQueue(this);
gridView2.setAdapter(null);
requestQueue2.add(stringRequest);
}
public class ListStrainTask extends AsyncTask<Void, Void, Void> {
// some coding
}
// listdistancetask
public class ListDistanceTask extends AsyncTask<Void, Void, Void> {
// some coding
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
listItems2.addAll(list);
adapter2.notifyDataSetChanged();
ArrayAdapter<String> array_spinner = (ArrayAdapter<String>) lsDistance.getAdapter();
lsDistance.setSelection(array_spinner.getPosition(PostDistance));
}
#Override
protected void onCancelled() {
// ml = null;
progressDialog.dismiss();
}
}
public class ListCountryTask extends AsyncTask<Void, Void, Void> {
ArrayList<String> list;
protected ProgressDialog progressDialog;
;
ListCountryTask() {
}
#Override
protected Void doInBackground(Void... params) {
String result = "";
try {
list.add("Select Country");
// some coding
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(PMPigeonListingActivity.this, "Please wait...", "Fetching data", true, false);
list = new ArrayList<>();
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
listItems3.addAll(list);
adapter3.notifyDataSetChanged();
ArrayAdapter<String> array_spinner = (ArrayAdapter<String>) lsCountry.getAdapter();
lsCountry.setSelection(array_spinner.getPosition(PostCountry));
}
#Override
protected void onCancelled() {
// ml = null;
progressDialog.dismiss();
}
}
}
In Pigeon listing activity there is 1 option like search activity where user can search without selecting any item just like in search activity.
Set listeners for each of your spinners
setOnItemSelectedListener
In onItemSelected method , get the selected value in a variable and pass on these values to next activity.
E.g.
yourSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
String yourValue = yourSpinner.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});

How can i print arraylist from class AsyncTask?

I want to print an ArrayList. I have receive value arraylist from class AsyncTask, in MainActivity, I have value ArrayList, but when I print ArrayList, my app is not working. Please help me!
MainActivity
{
executeLoadProduct();
arraylistgroup = new ArrayList<String>();
arraylistgroup=TaskLoadProductGroup.getvaluearraylist();
String[] mStringArray = new String[arraylistgroup.size()];
mStringArray = arraylistgroup.toArray(mStringArray);
for (int i = 0; i < mStringArray.length; i++) {
System.out.println("string is2" + (String) mStringArray[i]);
}
executeLoadProduct
private void executeLoadProduct() {
// execute task load product
loadProductGroup = new TaskLoadProductGroup(MainActivity.this);
loadProductGroup.execute();
}
AsyncTask
public class TaskLoadProductGroup extends AsyncTask<String, Void, ArrayList<String>> {
private ActionBarActivity actionBarActivity;
private Context context;
private static ArrayList<String> arrayListgroup;
public TaskLoadProductGroup(ActionBarActivity actionBarActivity) {
this.actionBarActivity = actionBarActivity;
this.context = actionBarActivity.getApplicationContext();
}
#Override
protected void onPreExecute() {
///show progress loading
super.onPreExecute();
}
#Override
protected ArrayList<String> doInBackground(String... url) {
ArrayList<String> listProductgroup = null;
try {
Server server = new Server();
ResListProduct resListProduct = server.getListProducts(context);
//init list item for listview home product
listProductgroup = initItemProduct(resListProduct);
} catch (Exception e) {
}
return listProductgroup;
}
public static ArrayList<String> initItemProduct(ResListProduct rsProduct) {
List<GroupProduct> groups = rsProduct.getGroups();
arrayListgroup = new ArrayList<String>();
for (GroupProduct group : groups) {
// add header group
String s = group.getName();
arrayListgroup.add(s);
}
getvaluearraylist();
// getVarialty();
return arrayListgroup;
}
public static ArrayList<String> getvaluearraylist()
{
return arrayListgroup;
}
#Override
protected void onPostExecute(ArrayList<String> listProductgroup) {
super.onPostExecute(listProductgroup);
}
}
I couldn't identify why are you doing so complex code to print the ArrayList. You can just print that inside onPostExecute method like this,
#Override
protected void onPostExecute(ArrayList<String> listProductgroup) {
super.onPostExecute(listProductgroup);
for (String value : listProductgroup){
Log.d("myTag", value);
}
}
OR
Use loadProductGroup.execute().get() method, but remember this will freeze your UI.

How to send mobile number to Send activity?

Request_Viewer Activity
public class Request_Viewer extends ListActivity {
private ProgressDialog pDialog;
private static final String REQUEST_VIEWER_URL = "http://192.168.43.84/taxiservice/request_view.php";
private static final String TAG_POSTS = "posts";
private static final String TAG_REQUEST_ID = "request_id";
private static final String TAG_CUSTOMER_CITY = "currentcity";
private static final String TAG_CUSTOMER_NAME = "customername";
private static final String TAG_CUSTOMER_MOBILE = "customermobile";
private static final String TAG_STARTING_LOCATION = "starting_location";
private static final String TAG_DISTINATION = "destination";
private static final String TAG_WHENDATE = "whendate";
private static final String TAG_WHENTIME = "whentime";
private JSONArray cRequest = null;
private ArrayList<HashMap<String, String>> cRequestList;
Handler mHandler;
TextView TextViewMobile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.request_viewer);
this.mHandler = new Handler();
m_Runnable.run();
}
private final Runnable m_Runnable = new Runnable()
{
public void run()
{
Request_Viewer.this.mHandler.postDelayed(m_Runnable,200);
}
};
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
new LoadRequests().execute();
}
public void addrefresh(View v) {
new LoadRequests().execute();
}
public void addYes(View v) {
Intent i = new Intent(getApplicationContext(),Send.class);
startActivity(i);
}
public void updateJSONdata() {
cRequestList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(REQUEST_VIEWER_URL);
try {
cRequest = json.getJSONArray(TAG_POSTS);
for (int i = cRequest.length()-1; i > 0; i--) {
JSONObject c = cRequest.getJSONObject(i);
String request_id = c.getString(TAG_REQUEST_ID);
String current_city = c.getString(TAG_CUSTOMER_CITY);
String customer_name = c.getString(TAG_CUSTOMER_NAME);
String customer_mobile = c.getString(TAG_CUSTOMER_MOBILE);
String starting_location = c.getString(TAG_STARTING_LOCATION);
String distination = c.getString(TAG_DISTINATION);
String whendate = c.getString(TAG_WHENDATE);
String customer_time = c.getString(TAG_WHENTIME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_REQUEST_ID, request_id);
map.put(TAG_CUSTOMER_CITY, current_city);
map.put(TAG_CUSTOMER_NAME, customer_name);
map.put(TAG_CUSTOMER_MOBILE, customer_mobile);
map.put(TAG_STARTING_LOCATION, starting_location);
map.put(TAG_DISTINATION, distination);
map.put(TAG_WHENDATE, whendate);
map.put(TAG_WHENTIME, customer_time);
cRequestList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, cRequestList,
R.layout.single_view, new String[] { TAG_REQUEST_ID,TAG_CUSTOMER_CITY,TAG_CUSTOMER_NAME,TAG_CUSTOMER_MOBILE,TAG_STARTING_LOCATION,TAG_DISTINATION, TAG_WHENDATE,
TAG_WHENTIME }, new int[] { R.id.request_id,R.id.current_city,R.id.customer_name,R.id.customer_mobile, R.id.starting_location,
R.id.distination,R.id.whendate,R.id.customer_time });
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextViewMobile=(TextView)findViewById(R.id.customer_mobile);
final String CustomerMobile=TextViewMobile.getText().toString();
Intent intent = new Intent(Request_Viewer.this, Send.class);
intent.putExtra("customermobile",CustomerMobile);
startActivity(intent);
}
});
}
public class LoadRequests extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Request_Viewer.this);
pDialog.setMessage("Loading Requests...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
**Send Activity**
package com.example.king.driverapptaxiexpress;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Send extends Activity {
EditText AnswerYes;
TextView Phone;
Button DriverSend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send);
AnswerYes = (EditText) findViewById(R.id.editYes);
Phone=(TextView)findViewById(R.id.editView1);
DriverSend = (Button) findViewById(R.id.button1);
//int index = data.getIntExtra("songIndex", 0);
Phone.setText(getIntent().getExtras().getString("customermobile",null));
DriverSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String phoneNumber = ((TextView)findViewById(R.id.editView1)).getText().toString();
String yes=AnswerYes.getText().toString();
try {
SmsManager.getDefault().sendTextMessage(phoneNumber, null,yes, null, null);
Toast.makeText(getApplicationContext(), "Sent Successfully", Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "sending fail", Toast.LENGTH_SHORT).show();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Send.this);
AlertDialog dialog = alertDialogBuilder.create();
dialog.setMessage(e.getMessage());
dialog.show();
}
}
});
}
}
My Php Script is
<?php
$query_params=null;
require("config.inc.php");
$query = "Select * FROM req_spec";
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
$rows = $stmt->fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Available Requests";
$response["posts"] = array();
foreach ($rows as $row) {
$post = array();
$post["request_id"] = $row["request_id"];
$post["currentcity"] = $row["currentcity"];
$post["customername"] = $row["customername"];
$post["customermobile"] = $row["customermobile"];
$post["starting_location"] = $row["starting_location"];
$post["destination"] = $row["destination"];
$post["whendate"] = $row["whendate"];
$post["whentime"] = $row["whentime"];
//update our repsonse JSON data
array_push($response["posts"], $post);
}
// echoing JSON response
echo json_encode($response);
}
else {
$response["success"] = 0;
$response["message"] = "No Requests Available";
die(json_encode($response));
}
?>`

Categories

Resources