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);
}
}
Related
I am having problem with AsyncTask class inside ViewPager's Fragment.
I have added code like below inside ViewPager's 3rd Fragment:
private View.OnClickListener finishClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
UserIdAsyncTask userIdAsyncTask = new UserIdAsyncTask( getActivity(), "URL", "Test", "Value" );
userIdAsyncTask.execute();
Her is my UserIdAsyncTask class:
private class UserIdAsyncTask extends AsyncTask<Void, Void, String> {
String url = "";
String oldpass = "";
String newpass = "";
private Context mContext = null;
private ProgressDialog dialog;
public UserIdAsyncTask( Context context, String url, String oldPass, String newPass ) {
this.mContext = context;
this.url = url;
this.oldpass = oldPass;
this.newpass = newPass;
}
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(this.mContext, "", "Please wait...");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
String str = "";
try {
return str;
} catch (Exception e) {
Log.e(ThirdFrag.class.toString(), e.getMessage(), e);
}
return str;
}
#Override
protected void onPostExecute(String response) {
dialog.dismiss();
Intent i = new Intent(getActivity(), ABC.class);
startActivity(i);
getActivity().finish();
}
}
In the given code, onPreExecute() called but doInBackground() never called.
Any ideas anyone? I'm really struggling with this one.
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.
I have four activities in my application A-->B-->C-->D.
I write a My own class MyActivity which extends Activity class. I write this class to handle activity stack.This class has two methods addActivitiyTostack() and getActivityFromStack()
I used a stack for storing activities.
All other activities are extends this class.
When I moved from one activity to other using intent it added to stack.
And when I moved backword activity gets popped up.
I can correctly add activities to stack, But I have problem in popping the activities.
also I have Logout Button on all activities, OnClick of this button I want to close the application how to implement it? Anybody know how to handle activity stack in Android.
This is my code.
package com.example.iprotect;
import java.util.Enumeration;
import java.util.Stack;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MyActivity extends Activity {
private static Stack<Activity> stack = new Stack<Activity>();
static int top=0;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addActivityToStack(this);
}
public static void addActivityToStack(MyActivity myActivity) {
// TODO Auto-generated method stub
stack.push(myActivity);
for (int i =0; i< stack.size() ; i++) {
Activity act=stack.get(i);
Log.i("Element in stack", ""+act);
}
}
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
//getActivityFromStack();
//logoutFromApplication();
}
public static void logoutFromApplication() {
// TODO Auto-generated method stub
Enumeration<Activity> enm=stack.elements();
while(enm.hasMoreElements())
{
Activity act=enm.nextElement();
stack.pop();
}
}
public static Activity getActivityFromStack() {
return stack.pop();
}
}
A-->
public class WebServiceActivity extends MyActivity{
EditText editText1, editText2;
Button button;
String response = "";
String email, password;
public final Pattern EMAIL_ADDRESS_PATTERN = Pattern
.compile(".+#.+\\.[a-z]+");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText1 = (EditText) findViewById(R.id.etEmail);
final EditText editText2 = (EditText) findViewById(R.id.etPassword);
button = (Button) findViewById(R.id.loginButton);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(editText1.getText().toString())) {
Toast.makeText(getApplicationContext(),
"please enter email id", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(editText2.getText().toString())) {
Toast.makeText(getApplicationContext(),
"please enter passwod", Toast.LENGTH_SHORT).show();
} else {
Boolean bool = EMAIL_ADDRESS_PATTERN.matcher(
editText1.getText().toString()).matches();
if (bool == true) {
} else {
Toast.makeText(getApplicationContext(),
"Invalid email id", Toast.LENGTH_SHORT).show();
}
email = editText1.getText().toString();
password = editText2.getText().toString();
// final ProgressDialog pd = ProgressDialog.show(
// WebServiceActivity.this, "Calling webservice...",
// "Please wait...", true, false);
final ProgressBar bar = (ProgressBar) findViewById(R.id.progressBar2);
bar.setVisibility(View.VISIBLE);
new AsyncTask<Void, Void, Void>() {
String r;
protected void onPreExecute() {
};
#Override
protected Void doInBackground(Void... params) {
r = invokeWebService();
return null;
};
protected void onPostExecute(Void result) {
bar.setVisibility(View.VISIBLE);
};
}.execute();
}
}
private String invokeWebService() {
String response = "";
try {
WebService webService = new WebService(
"http://sphinx-solution.com/iProtect/api.php?");
Map<String, String> params = new HashMap<String, String>();
params.put("action", "auth");
params.put("email", email);
params.put("password", password);
response = webService.WebGet("auth", params);
JSONObject jsonObject = new JSONObject(response);
String rr = jsonObject.optString("status");
if (TextUtils.equals(rr, "success")) {
Log.e("MSG", "status==success");
Intent intent = new Intent(WebServiceActivity.this,
SecondActivity.class);
//MyActivity.addActivityToStack(WebServiceActivity.this);
intent.putExtra("email", email);
intent.putExtra("password", password);
WebServiceActivity.this.startActivity(intent);
finish();
} else {
Log.e("MSG", "status ==failed");
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
});
}
}
B-->
public class SecondActivity extends MyActivity {
ListView listView;
String email1, password1;
ArrayList<JSONStructure> arrayList = new ArrayList<JSONStructure>();
String r;
String r1;
String tablename;
String rows;
JSONObject jsonObject;
String tablename2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_layout);
Intent intent = getIntent();
email1 = intent.getExtras().getString("email");
password1 = intent.getExtras().getString("password");
Button btn1 = (Button) findViewById(R.id.refreshbutton);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog pd = ProgressDialog.show(
SecondActivity.this, "Refresh List...",
"Please wait...", true, false);
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
pd.dismiss();
r = invokeWebService();
return null;
}
protected void onPostExecute(Void result) {
};
}.execute();
}
});
Button btn = (Button) findViewById(R.id.logoutbutton);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog pd = ProgressDialog.show(
SecondActivity.this, "Calling webservice...",
"Please wait...", true, false);
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
pd.dismiss();
return null;
}
#Override
protected void onPostExecute(Void result) {
Intent intent = new Intent(SecondActivity.this,
WebServiceActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
SecondActivity.this.startActivity(intent);
}
}.execute();
}
});
listView = (ListView) findViewById(R.id.listview1);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long id) {
JSONStructure jsonstructure = (JSONStructure) listView
.getAdapter().getItem(position);
final String tablename1 = jsonstructure.getTableName()
.toString();
Intent intent = new Intent(SecondActivity.this,
ProgressBarActivity.class);
//MyActivity.addActivityToStack(SecondActivity.this);
intent.putExtra("tablename", tablename1);
intent.putExtra("Rows", rows);
intent.putExtra("email", email1);
intent.putExtra("password", password1);
SecondActivity.this.startActivity(intent);
}
});
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
r = invokeWebService();
try {
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject(r);
jsonArray = jsonObject.getJSONArray("Records");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
tablename = c.optString("TABLE NAME");
rows = c.optString("Rows");
JSONStructure jsonStructure = new JSONStructure();
jsonStructure.setTableName(tablename);
jsonStructure.setRows(rows);
arrayList.add(jsonStructure);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (arrayList != null && arrayList.size() > 0) {
MyAdapter adapter = new MyAdapter(SecondActivity.this,
arrayList);
listView.setAdapter(adapter);
}
}
}.execute();
}
private String invokeWebService() {
String response = "";
try {
WebService webService = new WebService(
"http://sphinx-solution.com/iProtect/api.php?");
Map<String, String> params = new HashMap<String, String>();
params.put("action", "getTables");
params.put("email", email1);
params.put("password", password1);
response = webService.WebGet("getTables", params);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
C-->
public class ThirdActivity extends MyActivity {
String tablename1, row1, json1;
ArrayList<JSONStructure> arrayList = new ArrayList<JSONStructure>();
JSONArray jsonArray, jsonArray2;
JSONObject jsonObject;
String row;
String email1, password1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.third_layout);
ListView listView = (ListView) findViewById(R.id.listview2);
TextView textView = (TextView) findViewById(R.id.title_textview);
Intent intent = getIntent();
tablename1 = intent.getExtras().getString("tablename");
row = intent.getExtras().getString("Rows");
textView.setText(tablename1);
json1 = intent.getExtras().getString("Json");
email1 = intent.getExtras().getString("email");
password1 = intent.getExtras().getString("password");
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
Button button = (Button) findViewById(R.id.goback);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ThirdActivity.this,
SecondActivity.class);
MyActivity.getActivityFromStack();
intent.putExtra("email", email1);
intent.putExtra("password", password1);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
ThirdActivity.this.startActivity(intent);
}
});
}
}.execute();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
final int position, long id) {
final ProgressDialog pd = ProgressDialog.show(
ThirdActivity.this, "Calling webservice...",
"Please wait...", true, false);
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... paramArrayOfParams) {
pd.dismiss();
try {
jsonObject = new JSONObject(json1);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Intent intent = new Intent(ThirdActivity.this,
FinalActivity.class);
//MyActivity.addActivityToStack(ThirdActivity.this);
intent.putExtra("tablename", tablename1);
intent.putExtra("Json", jsonObject.toString());
intent.putExtra("Row", position);
intent.putExtra("email", email1);
intent.putExtra("password", password1);
ThirdActivity.this.startActivity(intent);
}
}.execute();
}
});
try {
JSONObject jsonObject = new JSONObject(json1);
JSONArray jsonArray = new JSONArray();
jsonArray = jsonObject.getJSONArray("FirstThree");
jsonArray2 = jsonObject.getJSONArray("Color");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String one = c.optString("One");
String two = c.optString("Two");
String three = c.optString("Three");
JSONObject c1 = jsonArray2.getJSONObject(i);
String color = c1.optString("color");
JSONStructure jsonStructure = new JSONStructure();
jsonStructure.column1 = one;
jsonStructure.column2 = two;
jsonStructure.column3 = three;
jsonStructure.setColumn1(one);
jsonStructure.setColumn2(two);
jsonStructure.setColumn3(three);
jsonStructure.setColor(color);
arrayList.add(jsonStructure);
Log.e("one", c.optString("One"));
Log.e("two", c.optString("Two"));
Log.e("three", c.optString("Three"));
Log.e("color", c1.optString("color"));
}
} catch (Exception e) {
e.printStackTrace();
}
if (arrayList != null && arrayList.size() > 0) {
MyAdapter1 adapter1 = new MyAdapter1(ThirdActivity.this, arrayList);
listView.setAdapter(adapter1);
}
Button btn = (Button) findViewById(R.id.logoutbutton);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog pd = ProgressDialog.show(
ThirdActivity.this, "Calling webservice...",
"Please wait...", true, false);
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
pd.dismiss();
return null;
}
#Override
protected void onPostExecute(Void result) {
Intent intent = new Intent(ThirdActivity.this,
WebServiceActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
ThirdActivity.this.startActivity(intent);
super.onPostExecute(result);
}
}.execute();
}
});
}
}
Assuming you need this stack solely for the logout function, there are better ways. Use a broadcast instead. Register a BroadcastReceiver in MyActivity.onCreate. The receiver should just call the activity's finish(). Send the broadcast from the button's click listener (btn1? What does that button do? Couldn't guess from the name; better names required ;) ). That's it.