Related
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);
}
}
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 trying to call Async task in some other activity from a fragment. I tried to call various way but none of it worked. I just want to know whats the best way to call static AsyncTask .Here is my Async task:
static class MyAsync extends AsyncTask<Void, Void, Void> {
Context context;
String username, password;
private MyAsync(Context context, String username, String password) {
this.context = context;
this.username = username;
this.password = password;
}
ProgressDialog dialog;
private String response;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(context, "Connecting to Server","Getting Credentials"
, true);
}
#Override
protected Void doInBackground(Void... arg0) {
try {
ContentDownload download = new ContentDownload();
response = download.loginApi(agentId, password);
if(response.contains("Success")){
if(SettingHelper.getFirstCall(context)){
ContentDownload.CallApi(context);
SettingHelper.setFirstCall(context, false);
}
if(SettingHelper.getFirstLaunch(context)){
ContentDownload load = new ContentDownload();
load.callItemApi(context);
load.callActionApi(context);
SettingHelper.setFirstLaunch(context, false);
}
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(response.contains("Success")){
context.startActivity(new Intent(context, AllActivity.class));
}else{
Toast.makeText(context, "Got back", Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
}}
I am trying to call it this way:
LoginActivity.new MyAsync(getActivity).execute();
but its giving error
It you want to use this class from your Fragment, give it public visibility, also a public constructor and then you can call it:
new LoginActivity.MyAsync(getActivity())
i have search and not found the answer. I want to call startActvity(newintent), but the page not change.
This my code:
public class MainActivity extends Activity {
private TextView IdPeserta, Password;
//private ArrayList<NameValuePair> authentication;
#SuppressWarnings("unused")
//private String temp, _nama = "";
//private readURL rL;
public static String username = "";
public static String password = "";
public static String status = "FALSE";
public void setPassword(String password){
MainActivity.password = password;
}
public void setUsername(String username){
MainActivity.username = username;
}
public void setStatus(String status){
MainActivity.status = status;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
IdPeserta = (TextView) findViewById(R.id.idPeserta);
Password = (TextView) findViewById(R.id.password);
}
public void Login(View view){
setUsername(IdPeserta.getText().toString());
setPassword(Password.getText().toString());
if((IdPeserta.getText().length() > 0 && Password.getText().length() > 0)){
RestTask task = new RestTask();
task.applicationContext = MainActivity.this;
task.execute();
}else{
Toast.makeText(this,"fill Id Peserta and Password 1", 0).show();
}
}
public void authenticate(){
if(status.equals("TRUE")){
Intent i = new Intent(MainActivity.this, Home.class);
//PendingIntent pending = PendingIntent.getActivity(this, 0, i, 0);
startActivity(i);
finish();
}else if(status.equals("FALSE")){
Log.d("gagal", "coba lagi");
}
}
public static String getService() {
String responseString = null;
String baseurlString = "http://10.0.2.2:8080/UjianServices/authentikasi.php";
RestClient client = new RestClient(baseurlString);
client.AddParam("id_peserta", MainActivity.username);
client.AddParam("password", MainActivity.password);
try {
client.Execute(RequestMethod.POST);
} catch (Exception e) {
Log.d("error", e.getMessage());
//e.printStackTrace();
}
responseString = client.getResponse();
return responseString;
}
public class RestTask extends AsyncTask<Object, Object, Object>{
private ProgressDialog dialog;
protected Context applicationContext;
#Override
protected void onPreExecute() {
this.dialog = ProgressDialog.show(applicationContext, "Calling", "Time Service...", true);
}
#Override
protected void onPostExecute(Object result) {
this.dialog.cancel();
String status = result.toString();
setStatus(status);
authenticate();
}
#Override
protected Object doInBackground(Object... arg0) {
return MainActivity.getService();
}
}
}
When i did not using the RestTask it can change the page. How i change my activity?
because applicationContext is null you have not initialize applicationContext before using it for showing ProgressDialog from onPreExecute .
you need to initialize applicationContext before using for showing ProgressDialog or just use MainActivity.this as :
#Override
protected void onPreExecute() {
applicationContext=MainActivity.this; //<<< initialize context here
this.dialog = ProgressDialog.show(applicationContext,
"Calling", "Time Service...", true);
}
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.