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));
}
?>`
Related
I currently have two activities doing HTTP requests.
The first activity contains a CustomList class extends BaseAdapter.
On the second, there is a previous button allowing me to return to the first activity.
Returning to the first activity, I would like to be able to recover the state in which I left it. That is to say to be able to find the information which also come from an HTTP request. I would like to find the data "infos_user" which is in the first activity and all the data in the BaseAdapter.
My architecture is as follows: Activity 0 (HTTP request) -> Activity 1 (with BaseAdapter and HTTP request) -> Activity 2 (HTTP request)
I put all the code because I really don't know how can I do this :/
First activity:
public class GetChildrenList extends AppCompatActivity implements View.OnClickListener {
private ArrayList<Child> childrenImeList = new ArrayList<Child>();
private Button btn_previous;
private ListView itemsListView;
private TextView tv_signin_success;
int id = 0;
String infos_user;
String email;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_children_list);
infos_user = (String) getIntent().getSerializableExtra("infos_user");
Intent intent = new Intent(GetChildrenList.this , GetLearningGoalsList.class);
intent.putExtra("username", infos_user);
btn_previous = (Button) findViewById(R.id.btn_previous);
btn_previous.setOnClickListener(this);
tv_signin_success = (TextView) findViewById(R.id.tv_signin_success);
tv_signin_success.setText("Bonjour " + infos_user + "!");
itemsListView = (ListView)findViewById(R.id.list_view_children);
new GetChildrenAsync().execute();
}
class GetChildrenAsync extends AsyncTask<String, Void, ArrayList<Child>> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(GetChildrenList.this, "Please wait", "Loading...");
}
#Override
protected ArrayList<Child> doInBackground(String... params) {
int age = 0;
email = (String) getIntent().getSerializableExtra("email");
password = (String) getIntent().getSerializableExtra("password");
String first_name = null;
String last_name = null;
try {
SendRequest sr = new SendRequest();
String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/childrenime/list", "GET", true, email, password);
String jsonResult = "{ \"children\":" + result + "}";
Log.d("result1", jsonResult);
//Manage JSON result
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray childrenArray = jsonObject.getJSONArray("children");
for (int i = 0; i < childrenArray.length(); ++i) {
JSONObject child = childrenArray.getJSONObject(i);
id = child.getInt("id");
first_name = child.getString("first_name");
last_name = child.getString("last_name");
age = child.getInt("age");
String name = first_name + " " + last_name;
childrenImeList.add(new Child(id,name,age));
}
} catch (JSONException e) {
e.printStackTrace();
}
return childrenImeList;
}
#Override
protected void onPostExecute(final ArrayList<Child> childrenListInformation) {
loadingDialog.dismiss();
if(childrenListInformation.size() > 0) {
CustomListChildrenAdapter adapter = new CustomListChildrenAdapter(GetChildrenList.this, childrenListInformation);
itemsListView.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des enfants", Toast.LENGTH_LONG).show();
}
}
}
}
BaseAdapter:
public class CustomListChildrenAdapter extends BaseAdapter implements View.OnClickListener {
private Context context;
private ArrayList<Child> children;
private Button btnChoose;
private TextView childrenName;
private TextView childrenAge;
public CustomListChildrenAdapter(Context context, ArrayList<Child> children) {
this.context = context;
this.children = children;
}
#Override
public int getCount() {
return children.size(); //returns total item in the list
}
#Override
public Object getItem(int position) {
return children.get(position); //returns the item at the specified position
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout_list_view_children,null);
childrenName = (TextView)view.findViewById(R.id.tv_childrenName);
childrenAge = (TextView) view.findViewById(R.id.tv_childrenAge);
btnChoose = (Button) view.findViewById(R.id.btn_choose);
btnChoose.setOnClickListener(this);
} else {
view = convertView;
}
btnChoose.setTag(position);
Child currentItem = (Child) getItem(position);
childrenName.setText(currentItem.getChildName());
childrenAge.setText(currentItem.getChildAge() + "");
return view;
}
#Override
public void onClick(View v) {
Integer position = (Integer) v.getTag();
Child item = (Child) getItem(position);
String email = (String) ((Activity) context).getIntent().getSerializableExtra("email");
String password = (String) ((Activity) context).getIntent().getSerializableExtra("password");
Intent intent = new Intent(context, GetLearningGoalsList.class);
intent.putExtra("idChild",item.getId());
intent.putExtra("email",email);
intent.putExtra("password",password);
context.startActivity(intent);
}
}
Second Activity:
public class GetLearningGoalsList extends AppCompatActivity implements View.OnClickListener {
private ArrayList<LearningGoal> childrenLearningList = new ArrayList<LearningGoal>();
private Button btn_previous;
private ListView itemsListView;
String email;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_learning_goals_list);
btn_previous = (Button) findViewById(R.id.btn_previous);
btn_previous.setOnClickListener(this);
itemsListView = (ListView)findViewById(R.id.list_view_learning_goals);
new GetLearningGoalsAsync().execute();
}
#Override
public void onClick(View v) {
Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
return;
}
class GetLearningGoalsAsync extends AsyncTask<String, Void, ArrayList<LearningGoal>> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(GetLearningGoalsList.this, "Please wait", "Loading...");
}
#Override
protected ArrayList<LearningGoal> doInBackground(String... params) {
int id = 0;
email = (String) getIntent().getSerializableExtra("email");
password = (String) getIntent().getSerializableExtra("password");
int idChild = (int) getIntent().getSerializableExtra("idChild");
String name = null;
String start_date = null;
String end_date = null;
try {
List<BasicNameValuePair> parameters = new LinkedList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("idchild", Integer.toString(idChild)));
SendRequest sr = new SendRequest();
String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/learningchild/list"+ "?"+ URLEncodedUtils.format(parameters, "utf-8"), "POST", true, email, password);
String jsonResult = "{ \"learningGoals\":" + result + "}";
Log.d("result1", jsonResult);
//Manage JSON result
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray learningGoalsArray = jsonObject.getJSONArray("learningGoals");
for (int i = 0; i < learningGoalsArray.length(); ++i) {
JSONObject learningGoal = learningGoalsArray.getJSONObject(i);
id = learningGoal.getInt("id");
name = learningGoal.getString("name");
start_date = learningGoal.getString("start_date");
end_date = learningGoal.getString("end_date");
childrenLearningList.add(new LearningGoal(id,name,start_date,end_date));
}
} catch (JSONException e) {
e.printStackTrace();
}
return childrenLearningList;
}
#Override
protected void onPostExecute(final ArrayList<LearningGoal> learningListInformation) {
loadingDialog.dismiss();
if(learningListInformation.size() > 0) {
CustomListLearningGoalAdapter adapter = new CustomListLearningGoalAdapter(GetLearningGoalsList.this, learningListInformation);
itemsListView.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des scénarios de cet enfant", Toast.LENGTH_LONG).show();
}
}
}
}
Thanks for your help.
if you want to maintain GetChildrenList state as it is then just call finish() rather than new intent on previous button click as follow
replace in GetLearningGoalsList
#Override
public void onClick(View v) {
Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
return;
}
with
#Override
public void onClick(View v) {
finish();
}
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);
}
}
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
}
});
Hi in the below code I am displaying two spinner one is for displaying brand name and another for displaying model name.
I am getting the response from server like this:
{"RESULT":"SUCCESS","BRANDS":[{"BRANDID":"14","BRANDNAME":"471"},{"BRANDID":"3","BRANDNAME":"ACE"},{"BRANDID":"4","BRANDNAME":"ADLER"},{"BRANDID":"5","BRANDNAME":"ALIEN"},{"BRANDID":"6","BRANDNAME":"ARTISAN-TORO"},{"BRANDID":"7","BRANDNAME":"ASSOCIATED PACIFIC"},{"BRANDID":"8","BRANDNAME":"ASTEX"},{"BRANDID":"9","BRANDNAME":"BERNINA"},{"BRANDID":"10","BRANDNAME":"BONIS"},{"BRANDID":"11","BRANDNAME":"BROTHER"},{"BRANDID":"12","BRANDNAME":"BROTHER "},{"BRANDID":"13","BRANDNAME":"CHANDLER"},{"BRANDID":"15","BRANDNAME":"CINCINNATI"},{"BRANDID":"16","BRANDNAME":"CONSEW"},{"BRANDID":"17","BRANDNAME":"CONSEW\/SEIKO"},{"BRANDID":"18","BRANDNAME":"DENNISON"},{"BRANDID":"19","BRANDNAME":"DURKOPP ADLER"},{"BRANDID":"20","BRANDNAME":"EAGLE"},{"BRANDID":"21","BRANDNAME":"EASTMAN"},{"BRANDID":"22","BRANDNAME":"EASTMAN CARDINAL"},{"BRANDID":"23","BRANDNAME":"ECONOSEW"},{"BRANDID":"1","BRANDNAME":"usha"}]}
Model Response:
{"RESULT":"SUCCESS","MODELS":[{"MODELNAME":"150","MODELID":"2"},{"MODELNAME":"C150WS","MODELID":"3"},{"MODELNAME":"HC720A","MODELID":"4"}
Based on the brand i want to display model names.
java
public class HomeFragment extends Fragment {
public HomeFragment(){}
Fragment fragment = null;
String userId,companyId;
private String brandid = "3";
public static List<LeadResult.Users> list;
public static List<BrandResult.Brands> listBrands;
public static List<ModelResult.Models> listModels;
public static ArrayList<String> listBrands_String;
// public static List<BrandResult.Brands> list1;
String[] brand_name;
Spinner spinner1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ActionBar actionBar=getActivity().getActionBar();
final View rootView = inflater.inflate(R.layout.layout_ownview, container, false);
spinner1=(Spinner)rootView.findViewById(R.id.brand1);
mTxt_OwnView=(TextView) rootView.findViewById(R.id.txt_OwnView);
mTxt_PublicView =(TextView) rootView.findViewById(R.id.txt_PublicView);
mRel_Ownview=(RelativeLayout)rootView.findViewById(R.id.ownview);
mRel_publicview =(RelativeLayout)rootView.findViewById(R.id.publicview);
listBrands = new ArrayList<BrandResult.Brands>();
listBrands_String = new ArrayList<String>();
listModels = new ArrayList<ModelResult.Models>();
private void getBrands() {
String brandjson = JSONBuilder.getJSONBrand();
String brandurl = URLBuilder.getBrandUrl();
Log.d("url","" + brandurl);
SendToServerTaskBrand taskBrand = new SendToServerTaskBrand(getActivity());
taskBrand.execute(brandurl, brandjson);
Log.d("brandjson", "" + brandjson);
}
private void setBrand(String brandjson)
{
ObjectMapper objectMapper_brand = new ObjectMapper();
try
{
BrandResult brandresult_object = objectMapper_brand.readValue(brandjson, BrandResult.class);
String Brand_result = brandresult_object.getRESULT();
Log.d("Brand_result","" + Brand_result);
if(Brand_result.equals("SUCCESS"))
{
listBrands =brandresult_object.getBRANDS();
spinner_fn();
Log.i("listbrands", " " + listBrands);
// startActivity(new Intent(getActivity().getApplicationContext(), Contact_Activity.class));
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Unable to load data please try again", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
// return eNames;
}
public class SendToServerTaskBrand extends AsyncTask<String, String, String>
{
private Context mContext = null;
private ProgressDialog mProgressDialog;
public SendToServerTaskBrand(Context context)
{
mContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
}
#Override
protected String doInBackground(String... params)
{
String Burl = params[0];
String Bjson = params[1];
String Bresult = UrlRequester.post(mContext, Burl, Bjson);
return Bresult;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
setBrand(result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
private void getModels() {
String model_url = URLBuilder.getModelUrl();
String model_json = JSONBuilder.getJSONModel(brandid);
Log.d("model_json", "" + model_json);
SendToServerTaskModel taskModel = new SendToServerTaskModel(getActivity());
taskModel.execute(model_url, model_json);
}
private void setModel(String json)
{
ObjectMapper objectMapperModel = new ObjectMapper();
try
{
ModelResult modelresult_object = objectMapperModel.readValue(json, ModelResult.class);
String model_result = modelresult_object.getRESULT();
Log.d("model_result","" + model_result);
if (model_result.equals("SUCCESS"))
{
listModels =modelresult_object.getMODELS();
Log.i("listmodels", " " + listModels);
// startActivity(new Intent(getActivity().getApplicationContext(), Contact_Activity.class));
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Unable to load data please try again", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
// return eNames;
}
public class SendToServerTaskModel extends AsyncTask<String, String, String>
{
private Context mContext = null;
private ProgressDialog mProgressDialog;
public SendToServerTaskModel(Context context)
{
mContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
}
#Override
protected String doInBackground(String... params)
{
String url = params[0];
String json = params[1];
String result = UrlRequester.post(mContext, url, json);
return result;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
setModel(result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
private void spinner_fn() {
for(int i = 0; i < listBrands.size(); i++){
listBrands_String.add(listBrands.get(i).toString());
Log.d("string is",""+ listBrands_String);
}
//ArrayAdapter<String> dataAdapter = ArrayAdapter.createFromResource(getActivity().getApplicationContext()
// ,android.R.layout.simple_spinner_item,listBrands_String);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext()
,android.R.layout.simple_spinner_item, listBrands_String);
// ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.category_array, android.R.layout.simple_spinner_item);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
Log.e("Position new",""+ listBrands_String.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
I am new to android. I write a code for JSON parsing. In this code i need to call JSON Web service repeatedly .How I can do that. Please help me
code:
public class MainActivity extends Activity implements OnItemClickListener {
private static final String rssFeed = "https://www.dropbox.com/s/rhk01nqlyj5gixl/jsonparsing.txt?dl=1";
private static final String ARRAY_NAME = "student";
private static final String ID = "id";
private static final String NAME = "name";
private static final String CITY = "city";
private static final String GENDER = "Gender";
private static final String AGE = "age";
private static final String BIRTH_DATE = "birthdate";
List<Item> arrayOfList;
ListView listView;
NewsRowAdapter objAdapter;
private static final String TAG = "Your Service";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.listview);
listView.setOnItemClickListener(this);
arrayOfList = new ArrayList<Item>();
if (Utils.isNetworkAvailable(MainActivity.this)) {
new MyTask().execute(rssFeed);
} else {
//showToast("No Network Connection!!!");
}
}
// My AsyncTask start...
class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
return Utils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
if (null == result || result.length() == 0) {
showToast("No data found from web!!!");
MainActivity.this.finish();
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(ARRAY_NAME);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject objJson = jsonArray.getJSONObject(i);
Item objItem = new Item();
objItem.setId(objJson.getInt(ID));
objItem.setName(objJson.getString(NAME));
objItem.setCity(objJson.getString(CITY));
objItem.setGender(objJson.getString(GENDER));
objItem.setAge(objJson.getInt(AGE));
objItem.setBirthdate(objJson.getString(BIRTH_DATE));
arrayOfList.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
Collections.sort(arrayOfList, new Comparator<Item>() {
#Override
public int compare(Item lhs, Item rhs) {
return (lhs.getAge() - rhs.getAge());
}
});
setAdapterToListview();
}
}
}
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
showDeleteDialog(position);
}
private void showDeleteDialog(final int position) {
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this)
.create();
alertDialog.setTitle("Delete ??");
alertDialog.setMessage("Are you sure want to Delete it??");
alertDialog.setButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.setButton2("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
arrayOfList.remove(position);
objAdapter.notifyDataSetChanged();
}
});
alertDialog.show();
}
public void setAdapterToListview() {
objAdapter = new NewsRowAdapter(MainActivity.this, R.layout.row,
arrayOfList);
listView.setAdapter(objAdapter);
}
public void showToast(String msg) {
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
}
}
You can use alarm manager and call the webservice at a particular interval of time. You can chekc using alarm manager here
You can use the java class TimerTask for repeated execution of a method.
See also: Timer, which uses TimerTask to schedule tasks.