how to set progress bar - android

package com.example.tabactivity;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ActivityGroup;
import android.app.ProgressDialog;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class circularlistparsing extends ActivityGroup {
public int currentPage = 1;
public ListView lisView1;
static final String KEY_ITEM = "docdetails";
static final String KEY_ITEM2 = "info";
static final String KEY_NAME1 = "";
static final String KEY_NAME = "heading";
static final String KEY_DATE = "date";
public Button btnNext;
public Button btnPre;
public static String url = "http://dev.taxmann.com/TaxmannService/TaxmannService.asmx/GetCircularList";
TextView txtreord;
TextView totalpage;
TextView pagenumber;
ProgressDialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtreord = (TextView) findViewById(R.id.recored);
totalpage = (TextView) findViewById(R.id.totalpage);
pagenumber = (TextView) findViewById(R.id.pagenumber);
// listView1
lisView1 = (ListView) findViewById(R.id.listView1);
// new YourTask().execute();
// Next
btnNext = (Button) findViewById(R.id.btnNext);
// Perform action on click
btnNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
currentPage = currentPage + 1;
// new YourTask().execute();
ShowData();
pagenumber.setText("Of" + currentPage+"]");
}
});
// Previous
btnPre = (Button) findViewById(R.id.btnPre);
// Perform action on click
btnPre.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
currentPage = currentPage - 1;
// new YourTask().execute();
ShowData();
pagenumber.setText("Of" + currentPage+"]");
}
});
// new YourTask().execute();
ShowData();
}
public void ShowData() {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(url); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
NodeList n2 = doc.getElementsByTagName(KEY_ITEM2);
int displayPerPage = 10; // Per Page
int TotalRows = nl.getLength();
txtreord.setText( TotalRows+"Records|"); // number of records
int indexRowStart = ((displayPerPage * currentPage) - displayPerPage);
int TotalPage = 0;
if (TotalRows <= displayPerPage) {
TotalPage = 1;
} else if ((TotalRows % displayPerPage) == 0) {
TotalPage = (TotalRows / displayPerPage);
} else {
TotalPage = (TotalRows / displayPerPage) + 1; // 7
TotalPage = (int) TotalPage; // 7
}
totalpage.setText("Page[" + TotalPage);
int indexRowEnd = displayPerPage * currentPage; // 5
if (indexRowEnd > TotalRows) {
indexRowEnd = TotalRows;
}
// Disabled Button Next
if (currentPage >= TotalPage) {
btnNext.setEnabled(false);
} else {
btnNext.setEnabled(true);
}
// Disabled Button Previos
if (currentPage <= 1) {
btnPre.setEnabled(false);
} else {
btnPre.setEnabled(true);
}
// Load Data from Index
int RowID = 1;
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
// RowID
if (currentPage > 1) {
RowID = (displayPerPage * (currentPage - 1)) + 1;
}
for (int i = indexRowStart; i < indexRowEnd; i++) {
Element e = (Element) nl.item(i);
Element e2 = (Element) n2.item(i);
String date = e2.getAttribute(KEY_DATE);
// adding each child node to HashMap key => value
map = new HashMap<String, String>();
map.put("RowID", String.valueOf(RowID));
map.put(KEY_DATE, date);
// String Heading = parser.getValue(e, KEY_NAME).replace("|", "|\n")
// .replace("|", "");
//
String mytime = date;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmdd");
Date myDate = null;
try {
myDate = dateFormat.parse(mytime);
} catch (ParseException t) {
t.printStackTrace();
} catch (java.text.ParseException t) {
// TODO Auto-generated catch block
t.printStackTrace();
}
SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd");
String finalDate = timeFormat.format(myDate);
// System.out.println("rrrrrrrrrrrrr"+finalDate);
String Heading = parser.getValue(e, KEY_NAME);
int a = Heading.indexOf("|");
String beforeSubString = Heading.substring(0, a);
String afterSubString = Heading.substring(a, Heading.length())
.replace("|", "") + "[" + finalDate + "]";
// String
// final1="<b>"+beforeSubString+"<b>"+"|"+afterSubString.replace("|",
// "|\n")
// .replace("|", "");
// String k=Html.fromHtml(final1).toString();
//
// Html.fromHtml(final1);
map.put(KEY_NAME, beforeSubString);
map.put(KEY_NAME1, afterSubString);
// adding HashList to ArrayList
menuItems.add(map);
RowID = RowID + 1;
}
SimpleAdapter sAdap;
sAdap = new SimpleAdapter(circularlistparsing.this, menuItems,
R.layout.list_item,
new String[] { "RowID", KEY_NAME1, KEY_NAME }, new int[] {
R.id.ColRowID, R.id.ColName, R.id.textView1 });
lisView1.setAdapter(sAdap);
lisView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Intent i = new Intent(circularlistparsing.this, detail.class);
// sending data to new activity
// i.putExtra("product", product);
startActivity(i);
}
});
}
class YourTask extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
dialog = ProgressDialog.show(circularlistparsing.this, "", "Please wait..");
}
protected Void doInBackground(Void... unused) {
try {
// doSomethingHeavy();
// publishProgress(...);
ShowData();
} catch(Exception e) {
//...
}
return null;
}
protected void onProgressUpdate(Void... unused) {
}
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
}
}
Hii please this code show data function is for displaying data when i m using new YourTask().execute(); in place of show data then its showing Progress bar but not displaying data but able to read data while when we user showdata() function den it display data please tell me how to implement progress bar .

private class YourTask extends AsyncTask<Object, Integer, Object> {
ProgressDialog dialog = new ProgressDialog(Currentactivity.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.show();
this.dialog.setCancelable(false);
super.onPreExecute();
}
#Override
protected Object doInBackground(Object... params) {
//do hard work here
return params;
}
#Override
protected void onProgressUpdate(Integer... values) {
progress.getProgress();
}
#Override
protected void onPostExecute(Object result) {
progressBar.dismiss();
super.onPostExecute(result);
}
}

implement this code
private class YourTask extends AsyncTask<Object, Integer, Object> {
#Override
protected void onPreExecute() {
ProgressDialog dialog = ProgressDialog.show(Activity.this, "",
"Loading...");
super.onPreExecute();
}
#Override
protected Object doInBackground(Object... params) {
try {
// doSomethingHeavy();
// publishProgress(...);
ShowData();
} catch(Exception e) {
//...
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
dialog .getProgress();
}
#Override
protected void onPostExecute(Object result) {
dialog .dismiss();
super.onPostExecute(result);
}
}

Related

How to send mobile number to Send activity?

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

how to display dynamic spinner values in android

In the code below, I took two spinners. One is for brand and other for model. But data is not being displaying in spinner. It is not showing any errors but dropdown is also not shown.
Can any one help me?
What is the mistake in the code?
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;
private RelativeLayout mRel_Ownview,mRel_publicview;
private LinearLayout mLin_Stock,mLin_Contact;
private TextView mTxt_OwnView,mTxt_PublicView;
private Map<String, String> BrandMap = new HashMap<String, String>();
private RangeSeekBar<Integer> seekBar;
private RangeSeekBar<Integer> seekBar1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ActionBar actionBar=getActivity().getActionBar();
actionBar.setTitle("DEVINE MECHINES");
SharedPreferences userPreference = getActivity().getSharedPreferences("UserDate", Context.MODE_PRIVATE);
userId=userPreference.getString("MYID", null);
companyId=userPreference.getString("companyId",null);
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>();
seekBar = new RangeSeekBar<Integer>(5000, 50000,getActivity());
seekBar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener<Integer>() {
#Override
public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) {
// handle changed range values
//Log.i(TAG, "User selected new range values: MIN=" + minValue + ", MAX=" + maxValue);
TextView seekMin = (TextView) getView().findViewById(R.id.textSeekMin);
TextView seekMax = (TextView) getView().findViewById(R.id.textSeekMax);
seekMin.setText(minValue.toString());
seekMax.setText(maxValue.toString());
}
});
seekBar1 = new RangeSeekBar<Integer>(5000, 50000,getActivity());
seekBar1.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener<Integer>() {
#Override
public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) {
// handle changed range values
//Log.i(TAG, "User selected new range values: MIN=" + minValue + ", MAX=" + maxValue);
TextView seekMin = (TextView) getView().findViewById(R.id.textSeekMin1);
TextView seekMax = (TextView) getView().findViewById(R.id.textSeekMax1);
seekMin.setText(minValue.toString());
seekMax.setText(maxValue.toString());
}
});
mTxt_OwnView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRel_publicview.setVisibility(View.GONE);
mTxt_OwnView.setBackgroundColor(getResources().getColor(R.color.light_blue));
mTxt_PublicView.setBackgroundColor(getResources().getColor(R.color.dark_blue));
mTxt_OwnView.setTextColor(getResources().getColor(R.color.text_white));
mTxt_PublicView.setTextColor(getResources().getColor(R.color.light_blue));
mRel_Ownview.setVisibility(View.VISIBLE);
}
});
mTxt_PublicView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRel_Ownview.setVisibility(View.GONE);
mTxt_PublicView.setBackgroundColor(getResources().getColor(R.color.light_blue));
mTxt_OwnView.setBackgroundColor(getResources().getColor(R.color.dark_blue));
mTxt_OwnView.setTextColor(getResources().getColor(R.color.light_blue));
mTxt_PublicView.setTextColor(getResources().getColor(R.color.text_white));
mRel_publicview.setVisibility(View.VISIBLE);
}
});
String selectedBrandId = BrandMap.get(String.valueOf(spinner1.getSelectedItem()));
// System.out.print(url);
mLin_Stock=(LinearLayout)rootView.findViewById(R.id.stock);
mLin_Stock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragment =new StockFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
}
});
mLin_Contact =(LinearLayout)rootView.findViewById(R.id.contacts);
mLin_Contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// getLead();
fragment = new ContactFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
getLead();
}
});
// add RangeSeekBar to pre-defined layout
ViewGroup layout = (ViewGroup) rootView.findViewById(R.id.layout_seek);
layout.addView(seekBar);
ViewGroup layout1 = (ViewGroup) rootView.findViewById(R.id.layout_seek1);
layout1.addView(seekBar1);
getBrands();
getModels();
return rootView;
}
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.i("Brand_result","Now" + Brand_result);
if(Brand_result.equals("SUCCESS"))
{
listBrands =brandresult_object.getBRANDS();
Log.i("listbrands", "List Brands" + listBrands);
/* for(int i = 0; i < listBrands.size(); i++){
listBrands_String.add(listBrands.get(i).toString());
Log.d("string is",""+ listBrands_String);
}*/
spinner_fn();
// 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);
Log.i("Result","Brand Result"+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() {
/*ArrayAdapter<String> dataAdapter = ArrayAdapter.createFromResource(getActivity().getBaseContext(),
listBrands_String, android.R.layout.simple_spinner_item);*/
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) {
}
});
}
private void getLead()
{
String url = URLBuilder.getLeadUrl();
String json = JSONBuilder.getJSONLead(userId, companyId);
SendToServerTask task = new SendToServerTask(getActivity());
task.execute(url, json);
}
private void setLead(String json)
{
ObjectMapper objectMapper = new ObjectMapper();
try
{
LeadResult result_object = objectMapper.readValue(json, LeadResult.class);
String lead_result = result_object.getRESULT();
Log.d("lead_result","" + lead_result);
if (lead_result.equals("SUCCESS"))
{
list=result_object.getUSERS();
// 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 SendToServerTask extends AsyncTask<String, String, String>
{
private Context mContext = null;
private ProgressDialog mProgressDialog;
public SendToServerTask(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);
setLead(result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}

ProgressDialog remains open in android activity

I have made an activity in that I am making an api call by using AsyncTak,I have shown a progressDialog In DoBackground method ,and want to dismiss that progressDialog in postExecute i have done this way but its not working,My progressDialog remains, open after the operations too..My code is as below,can anybuddy help me to dissmiss it.
main.java
package com.epe.yehki.ui;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Paint.Join;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewDebug.FlagToString;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.backend.FavoriteAPI;
import com.epe.yehki.backend.ResponseListener;
import com.epe.yehki.uc.Menu;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Const.API_RESULT;
import com.epe.yehki.util.Pref;
import com.epe.yehki.util.Utils;
import com.example.yehki.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
public class WholesaleProductDetailActivity extends Activity {
public ImageView productImage;
private ImageLoader imageLoader;
private DisplayImageOptions options;
private ProgressDialog pDialog;
JSONArray proDetails = null;
private Menu menu;
Intent i1;
private FavoriteAPI favApi;
private int isFavourite;
private ProgressDialog progressDialog;
// CONTROLLS FOR WHOLESALE RETAILS.........!!!
TextView retailPrice;
TextView tv_moqW;
TextView tv_moqR;
TextView tv_shipping_cost;
TextView EscrowPayment;
TextView ProcessigPeriod;
LinearLayout llQuantity;
EditText quantity;
LinearLayout llbotm;
TextView tv_escrow_payment;
TextView tv_procesiing_period;
Button contactSuplier, addToCart, buyNOw;
LinearLayout ll_botom1;
// ************************
// strings.......!!!
String pro_id;
String name;
String retail_price;
String price_wholesale;
String keywords;
String supplier_id;
String supplier_name;
String listing_description;
String image;
String Specifications;
String date_added;
String status;
int flag = 0;
String port;
String customer_name;
String customer_id;
String cId;
String min_order_qty_retail;
String min_order_qty_wholesale;
String countyId;
String supply_amount;
String msg;
String supply_unit_id;
String supply_unit_name;
String supply_time;
String payment_terms;
String min_order_qty;
String min_order_qty_unit;
String min_order_qty_unit_name;
String delivery_time;
String company_name;
String country_id;
String state_id;
String procesPeriod;
// COMPANY DETAILS....
String companyDetail;
String companyDetailName;
String companyDetailAddress;
String companyDetailPhoto;
String companyDetailMainProduct;
String companyDetailotherProduct;
String cartNo;
// PRODUCT QUICK DETAILS...
// TextViews.............!!!
public TextView productName;
public TextView wholeSalePrice;
public TextView minOrder;
public TextView shippingCost;
public TextView escrowPayment;
public TextView processingPeriod;
public TextView compnyName;
public TextView countryName;
public TextView bussinessType;
public TextView mainProduct;
public TextView productDetails;
public String pid;
// Buttons of placeOrder and contact supplier..
private Button contactSupplier;
private ImageView iv_back;
private TextView cart;
private ImageView iv_fav;
public Intent i;
//
// Hashmap for ListView
ArrayList<HashMap<String, String>> ProductDetailList;
// URL to get contacts JSON
// API_PRODUCT?product_id=29
private static String productUrl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_detail);
initializeViews();
cId = Pref.getValue(WholesaleProductDetailActivity.this, Const.PREF_CUSTOMER_ID, "");
ll_botom1 = (LinearLayout) findViewById(R.id.ll_botom1);
ll_botom1.setVisibility(View.VISIBLE);
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(WholesaleProductDetailActivity.this));
options = new DisplayImageOptions.Builder().cacheOnDisc(true).showImageOnFail(R.drawable.logo).build();
new AddToCart().execute();
// get extras..............!!!!
i = getIntent();
i.getStringExtra(Const.TAG_PRODUCT_NAME);
i.getStringExtra(Const.TAG_PRODUCT_IMG);
pid = i.getStringExtra(Const.TAG_PRODUCT_ID);
favApi = new FavoriteAPI(WholesaleProductDetailActivity.this, responseListener, pid, Pref.getValue(WholesaleProductDetailActivity.this, Const.PREF_CUSTOMER_ID, ""));
favApi.callApi();
// bACK BUTTON.......!
iv_back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
finish();
}
});
// DO FAVOURITE YOUR PRODUCT..........!!!
iv_fav.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// CHECKING IS USER lOGIN...!
if (Pref.getValue(WholesaleProductDetailActivity.this, Const.PREF_CUSTOMER_ID, "") != null
&& !Pref.getValue(WholesaleProductDetailActivity.this, Const.PREF_CUSTOMER_ID, "").equals("")) {
// FAVOURITE API CALL..........!!!
if (iv_fav.isSelected()) {
isFavourite = 0;
iv_fav.setImageResource(R.drawable.star);
iv_fav.setSelected(false);
} else {
isFavourite = 1;
iv_fav.setImageResource(R.drawable.star_filled);
iv_fav.setSelected(true);
}
if (Utils.isOnline(WholesaleProductDetailActivity.this)) {
progressDialog = new ProgressDialog(WholesaleProductDetailActivity.this);
progressDialog.setMessage(getString(R.string.process_progress_msg));
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
favApi = new FavoriteAPI(WholesaleProductDetailActivity.this, responseListener, pid, Pref.getValue(WholesaleProductDetailActivity.this, Const.PREF_CUSTOMER_ID, ""));
favApi.callApi();
} else {
Toast.makeText(WholesaleProductDetailActivity.this, "Please check your interenet connection", Toast.LENGTH_SHORT).show();
}
} else {
i = new Intent(WholesaleProductDetailActivity.this, LoginActivity.class);
startActivity(i);
}
}
});
productUrl = Const.API_WHOLESALE_PRODUCT_DETAIL + "?" + Const.TAG_PRODUCT_ID + "=" + pid;
System.out.println(":::::::::::PRODUCT URL:::::::::::::::" + productUrl);
productName.setText(i.getStringExtra(Const.TAG_PRODUCT_NAME));
try {
imageLoader.displayImage(i.getStringExtra(Const.TAG_PRODUCT_IMG), productImage, options);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
productImage.setBackgroundResource(R.drawable.logo);
}
new GetProductDetails().execute();
buyNOw.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (quantity.getText().toString() != null && !quantity.getText().toString().equals("")) {
if (Double.parseDouble(quantity.getText().toString()) < (Double.parseDouble(min_order_qty_retail))) {
Utils.showCustomeAlertValidation(WholesaleProductDetailActivity.this, "Please Enter Quantity greater than min. retail quamtity", "Yehki", "Ok");
} else {
i1 = new Intent(WholesaleProductDetailActivity.this, WholesalePlaceOrderActivity.class);
i1.putExtra(Const.TAG_PRODUCT_NAME, name);
i1.putExtra(Const.TAG_PRODUCT_ID, pid);
i1.putExtra("QTY_RETAIL", min_order_qty_retail);
i1.putExtra("QTY_WHOLESALE", min_order_qty_wholesale);
i1.putExtra(Const.TAG_PRODUCT_SUPPLEY_UNIT_ID, supply_unit_id);
i1.putExtra(Const.TAG_PRODUCT_SUPPLY_UNIT_NAME, supply_unit_name);
i1.putExtra(Const.TAG_PRODUCT_MAX_PRICE, price_wholesale);
i1.putExtra(Const.TAG_PRODUCT_MIN_PRICE, retail_price);
i1.putExtra("takenQTY", quantity.getText().toString());
if (Double.parseDouble(quantity.getText().toString()) > (Double.parseDouble(min_order_qty_retail))
&& Double.parseDouble(quantity.getText().toString()) < (Double.parseDouble(min_order_qty_wholesale))) {
i1.putExtra("price", retail_price);
startActivity(i1);
} else if (Double.parseDouble(quantity.getText().toString()) > (Double.parseDouble(min_order_qty_wholesale))) {
i1.putExtra("price", price_wholesale);
startActivity(i1);
}
}
} else {
Utils.showCustomeAlertValidation(WholesaleProductDetailActivity.this, "Please Enter Quantity", "Yehki", "Ok");
}
}
});
contactSuplier.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(WholesaleProductDetailActivity.this, ContactSupplierActivity.class);
i.putExtra(Const.TAG_SUPPLIER_ID, supplier_id);
System.out.println("::::::::::::::::;my supplier id>>>>>>>>>>>>>>+++++++++++++++++" + supplier_id);
i.putExtra(Const.TAG_PRODUCT_ID, pid);
startActivity(i);
}
});
addToCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!quantity.getText().toString().equals("") && quantity.getText().toString() != null) {
new AddToCart().execute();
} else {
Utils.showCustomeAlertValidation(WholesaleProductDetailActivity.this, "Please enter quanitity", "Yehki", "Ok");
}
}
});
}
// ****INITIALIZING THE VIEWS.....!!!!!!!!!!!!!!!
private void initializeViews() {
productImage = (ImageView) findViewById(R.id.iv_product);
productName = (TextView) findViewById(R.id.tv_product_name);
buyNOw = (Button) findViewById(R.id.tv_place_order);
contactSupplier = (Button) findViewById(R.id.tv_contact_suplier);
wholeSalePrice = (TextView) findViewById(R.id.tv_price_range);
minOrder = (TextView) findViewById(R.id.tv_min_order);
shippingCost = (TextView) findViewById(R.id.tv_sply);
escrowPayment = (TextView) findViewById(R.id.tv_payment_terms);
processingPeriod = (TextView) findViewById(R.id.tv_port);
compnyName = (TextView) findViewById(R.id.tv_company_name);
countryName = (TextView) findViewById(R.id.tv_contry);
bussinessType = (TextView) findViewById(R.id.tv_bussiness_type);
mainProduct = (TextView) findViewById(R.id.tv_main_products);
productDetails = (TextView) findViewById(R.id.tv_pro_detail);
menu = (Menu) findViewById(R.id.menuProduct);
iv_back = (ImageView) findViewById(R.id.iv_back);
iv_fav = (ImageView) findViewById(R.id.iv_fvrt);
cart = (TextView) findViewById(R.id.tv_cart);
retailPrice = (TextView) findViewById(R.id.tv_retail_price);
tv_moqW = (TextView) findViewById(R.id.tv_moqw);
tv_moqR = (TextView) findViewById(R.id.tv_min_order);
tv_shipping_cost = (TextView) findViewById(R.id.tv_shipping_cost);
tv_escrow_payment = (TextView) findViewById(R.id.tv_escrow_payment);
tv_procesiing_period = (TextView) findViewById(R.id.tv_procesiing_period);
quantity = (EditText) findViewById(R.id.et_qty);
llQuantity = (LinearLayout) findViewById(R.id.ll_btm);
llQuantity.setVisibility(View.VISIBLE);
llbotm = (LinearLayout) findViewById(R.id.ll_botom1);
llbotm.setVisibility(View.VISIBLE);
tv_shipping_cost.setText("Shipping Cost:");
tv_escrow_payment.setText("Escrow Payment:");
tv_procesiing_period.setText("Processing Period:");
contactSuplier = (Button) findViewById(R.id.tv_contc_sup);
addToCart = (Button) findViewById(R.id.btn_add_cart);
buyNOw = (Button) findViewById(R.id.btn_buy);
retailPrice.setVisibility(View.VISIBLE);
menu.setSelectedTab(1);
}
private class GetProductDetails extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(WholesaleProductDetailActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
System.out.println("==========inside preexecute===================");
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(productUrl, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
System.out.println("=============MY RESPONSE==========" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
if (jsonObj.has(Const.TAG_PRODUCT_DETAIL)) {
// yes
proDetails = jsonObj.getJSONArray(Const.TAG_PRODUCT_DETAIL);
System.out.println("==========inside doIn background===================");
// looping through All Contacts
for (int i = 0; i < proDetails.length(); i++) {
JSONObject c = proDetails.getJSONObject(i);
name = c.getString(Const.TAG_PRODUCT_NAME);
keywords = c.getString(Const.TAG_PRODUCT_KEYWORDS);
supplier_id = c.getString(Const.TAG_PRODUCT_SUPPLIER_ID);
supplier_name = c.getString(Const.TAG_PRODUCT_SUPPLIER_NAME);
listing_description = c.getString(Const.TAG_PRODUCT_LISTING_DESCRIPTION);
image = c.getString(Const.TAG_PRODUCT_IMG);
Specifications = c.getString(Const.TAG_PRODUCT_SPECIFICATION);
date_added = c.getString(Const.TAG_PRODUCT_DATE_ADDED);
customer_name = c.getString(Const.TAG_PRODUCT_CUSTMER_NAME);
customer_id = c.getString(Const.TAG_PRODUCT_CUSTOMER_ID);
retail_price = c.getString(Const.TAG_PRICE_RETAIL);
price_wholesale = c.getString(Const.TAG_PRICE_WHOLESALE);
System.out.println(":::::::::::::My wholesale price:::::::::>>>>>>>" + price_wholesale);
min_order_qty_retail = c.getString(Const.TAG_MIN_ORDER_QTY_RETAIL);
System.out.println(":::::::::::::My wholesale price:::::::::>>>>>>>" + min_order_qty_retail);
min_order_qty_wholesale = c.getString(Const.TAG_MIN_ORDER_QTY_WHOLESALE);
System.out.println(":::::::::::::My wholesale price:::::::::>>>>>>>" + min_order_qty_wholesale);
countyId = c.getString(Const.TAG_COUNTRY_ID);
state_id = c.getString(Const.TAG_STATE_WHOLESALE_ID);
supply_unit_id = c.getString(Const.TAG_PRODUCT_SUPPLEY_UNIT_ID);
supply_unit_name = c.getString(Const.TAG_PRODUCT_SUPPLY_UNIT_NAME);
System.out.println("::::::::::::::::mY supply unit name::::::::::::::");
supply_time = c.getString(Const.TAG_PRODUCT_SUPPLY_TIME);
delivery_time = c.getString(Const.TAG_DELIVERY_TIME_WHOLESALE);
System.out.println(":::::::::::::::supply unit name:::::::::::::::::::" + delivery_time);
company_name = c.getString(Const.TAG_PRODUCT_COMPANY_NAME);
System.out.println(":::::::::::::::supply unit name:::::::::::::::::::" + company_name);
// GETTING COMPANY DETAILS..........!!!
JSONObject companyDetails = c.getJSONObject(Const.TAG_PRODUCT_COMPANY_DETAILS);
companyDetailName = companyDetails.getString(Const.TAG_PRODUCTDETAIL_COMPANY_NAME);
companyDetailAddress = companyDetails.getString(Const.TAG_PRODUCTDETAIL_COMPANY_ADDRESS);
companyDetailMainProduct = companyDetails.getString(Const.TAG_PRODUCTDETAIL_COMPANY_MAIN_PRODUCT);
companyDetailotherProduct = companyDetails.getString(Const.TAG_PRODUCTDETAIL_COMPANY_OTHER_PRODUCT);
companyDetailPhoto = companyDetails.getString(Const.TAG_PRODUCTDETAIL_PHOTO);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog != null) {
pDialog.dismiss();
}
productName.setText(name);
wholeSalePrice.setText("WholeSale Price:" + " " + price_wholesale);
retailPrice.setText("Retail Price:" + " " + retail_price);
tv_moqW.setText("MoqW:" + min_order_qty_wholesale);
minOrder.setText("MoqR:" + min_order_qty_retail);
shippingCost.setText("");
escrowPayment.setText(payment_terms);
compnyName.setText(company_name);
countryName.setText(country_id);
mainProduct.setText(companyDetailMainProduct);
processingPeriod.setText(delivery_time);
}
}
// RESPONSE lISTENER FOR THE FAVOURITE......!!
ResponseListener responseListener = new ResponseListener() {
#Override
public void onResponce(String api, API_RESULT result, Object obj) {
if (progressDialog != null) {
progressDialog.dismiss();
}
if (api.equals(Const.API_DO_FAVOURITE)) {
if (result == Const.API_RESULT.SUCCESS) {
System.out.println("::::::::::::::::;INSIDE SUCCESS ACTIVITY OF FAVORITE:::::::::;");
}
}
}
};
// *********************ADD TO CART CALL...
// *******************
private class AddToCart extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(WholesaleProductDetailActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
System.out.println("==========inside preexecute===================");
}
#Override
protected Void doInBackground(Void... arg0) {
String addToCArt = Const.API_ADD_TO_CART + "?customer_id=" + cId + "&product_id=" + pid + "&quantity=" + quantity.getText().toString() + "&unit_id=" + supply_unit_id; // Creating
// service
// handler
// class
// instance
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::MY add to cart url:::::::::::;" + addToCArt);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(addToCArt, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
System.out.println("=============MY RESPONSE==========" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_STATUS)) {
status = jsonObj.getString(Const.TAG_STATUS);
if (status.equalsIgnoreCase("success")) {
flag = 1;
msg = jsonObj.getString(Const.TAG_MESSAGE);
cartNo = jsonObj.getString(Const.TAG_TOTAL_CART_PRODUCTS);
} else {
flag = 2;
msg = jsonObj.getString(Const.TAG_MESSAGE);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog != null) {
pDialog.dismiss();
}
if (flag == 1) {
Toast.makeText(WholesaleProductDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
quantity.setText("");
cart.setText(cartNo);
Pref.setValue(WholesaleProductDetailActivity.this, Const.PREF_CART_NO, cartNo);
} else {
Toast.makeText(WholesaleProductDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
}
}
}
}
replace your GetProductDetails AsyncTask code with this. and do same for other
// My AsyncTask start...
class GetProductDetails extends AsyncTask<Void, Void, Void> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(WholesaleProductDetailActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(productUrl, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
System.out.println("=============MY RESPONSE==========" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
if (jsonObj.has(Const.TAG_PRODUCT_DETAIL)) {
// yes
proDetails = jsonObj.getJSONArray(Const.TAG_PRODUCT_DETAIL);
System.out.println("==========inside doIn background===================");
// looping through All Contacts
for (int i = 0; i < proDetails.length(); i++) {
JSONObject c = proDetails.getJSONObject(i);
name = c.getString(Const.TAG_PRODUCT_NAME);
keywords = c.getString(Const.TAG_PRODUCT_KEYWORDS);
supplier_id = c.getString(Const.TAG_PRODUCT_SUPPLIER_ID);
supplier_name = c.getString(Const.TAG_PRODUCT_SUPPLIER_NAME);
listing_description = c.getString(Const.TAG_PRODUCT_LISTING_DESCRIPTION);
image = c.getString(Const.TAG_PRODUCT_IMG);
Specifications = c.getString(Const.TAG_PRODUCT_SPECIFICATION);
date_added = c.getString(Const.TAG_PRODUCT_DATE_ADDED);
customer_name = c.getString(Const.TAG_PRODUCT_CUSTMER_NAME);
customer_id = c.getString(Const.TAG_PRODUCT_CUSTOMER_ID);
retail_price = c.getString(Const.TAG_PRICE_RETAIL);
price_wholesale = c.getString(Const.TAG_PRICE_WHOLESALE);
System.out.println(":::::::::::::My wholesale price:::::::::>>>>>>>" + price_wholesale);
min_order_qty_retail = c.getString(Const.TAG_MIN_ORDER_QTY_RETAIL);
System.out.println(":::::::::::::My wholesale price:::::::::>>>>>>>" + min_order_qty_retail);
min_order_qty_wholesale = c.getString(Const.TAG_MIN_ORDER_QTY_WHOLESALE);
System.out.println(":::::::::::::My wholesale price:::::::::>>>>>>>" + min_order_qty_wholesale);
countyId = c.getString(Const.TAG_COUNTRY_ID);
state_id = c.getString(Const.TAG_STATE_WHOLESALE_ID);
supply_unit_id = c.getString(Const.TAG_PRODUCT_SUPPLEY_UNIT_ID);
supply_unit_name = c.getString(Const.TAG_PRODUCT_SUPPLY_UNIT_NAME);
System.out.println("::::::::::::::::mY supply unit name::::::::::::::");
supply_time = c.getString(Const.TAG_PRODUCT_SUPPLY_TIME);
delivery_time = c.getString(Const.TAG_DELIVERY_TIME_WHOLESALE);
System.out.println(":::::::::::::::supply unit name:::::::::::::::::::" + delivery_time);
company_name = c.getString(Const.TAG_PRODUCT_COMPANY_NAME);
System.out.println(":::::::::::::::supply unit name:::::::::::::::::::" + company_name);
// GETTING COMPANY DETAILS..........!!!
JSONObject companyDetails = c.getJSONObject(Const.TAG_PRODUCT_COMPANY_DETAILS);
companyDetailName = companyDetails.getString(Const.TAG_PRODUCTDETAIL_COMPANY_NAME);
companyDetailAddress = companyDetails.getString(Const.TAG_PRODUCTDETAIL_COMPANY_ADDRESS);
companyDetailMainProduct = companyDetails.getString(Const.TAG_PRODUCTDETAIL_COMPANY_MAIN_PRODUCT);
companyDetailotherProduct = companyDetails.getString(Const.TAG_PRODUCTDETAIL_COMPANY_OTHER_PRODUCT);
companyDetailPhoto = companyDetails.getString(Const.TAG_PRODUCTDETAIL_PHOTO);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
productName.setText(name);
wholeSalePrice.setText("WholeSale Price:" + " " + price_wholesale);
retailPrice.setText("Retail Price:" + " " + retail_price);
tv_moqW.setText("MoqW:" + min_order_qty_wholesale);
minOrder.setText("MoqR:" + min_order_qty_retail);
shippingCost.setText("");
escrowPayment.setText(payment_terms);
compnyName.setText(company_name);
countryName.setText(country_id);
mainProduct.setText(companyDetailMainProduct);
processingPeriod.setText(delivery_time);
// Dismiss the progress dialog
pDialog.dismiss();
}
}
}
Remove
if (pDialog.isShowing())
and
use if (pDialog != null)
may this help you
You should remove super.onPostExecute(result); as you have your implementation of onPostExecute(), so you may not want framework to handle it.
Since you have definitely showed the Progress Dialog in onPreExecute(), then you can also omit check for isShowing(), but i will recommend you to keep this check as it causes no harm and adds little more security.
In your onPostExecute() block you are calling super.onPostExecute(result);
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Your code
}
However as you are overriding the onPostExecute() there is no need to call super.onPostExecute(result);
If you take a look at the AsyncTask source, you will see that the super class does nothing:
#SuppressWarnings({"UnusedDeclaration"})
protected void onPostExecute(Result result) {
}

AsynTask with Endless Listview Scroll in android

I am creating an application where in i need to have endless scrolling listview. I dnt want to use any library in my application. I have seen some examples on line that help in achieving such listview,but my doubt is how can i have an endless listview when my data are coming from server and are getting parsed in the Asynctask. How can i load 10 items at a time from my asynctask on scroll? I want to know to implement a endless listview on asyntask.
Do i call my asynctask in the onScroll() or not???
public class EndlessScrollExample extends ListActivity {
public JSONArray jsonarray,jsondatearray;
public String url;
public String selectedvalue;
public String TAG = "TAG Event Display";
public String SuggestCity;
public String SuggestState;
public String suggestCountry;
public String event_id,address;
String lat;
String lng;
public String event_name;
public String dateKey;
public String datetime,timenew;
Calendar cal;
public SharedPreferences prefs;
public Editor editor;
public String access_token,id,username;
public static ArrayList<EventsBean> arrayEventsBeans = new ArrayList<EventsBean>();
ArrayList<DateBean> sortArray = new ArrayList<DateBean>();
public SAmpleAdapter adapter;
public ImageView img_menu,img_calender;
public ListView listview;
public EventsBean eventsbean;
int counter = 0;
int currentPage = 0;
FetchEventValues fetchValues;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setTheme(android.R.style.Theme);
setContentView(R.layout.sample_endless);
listview = (ListView)findViewById(android.R.id.list);
try {
// Preferences values fetched from the preference of FBConnection class.
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
access_token = prefs.getString("access_token", null);
id = prefs.getString("uid", null);
username = prefs.getString("username", null);
if(access_token == null && id == null && username == null)
{
Toast.makeText(getApplicationContext(), "FaceBook Login was not successful" +
"/nPlease Relogin.", Toast.LENGTH_SHORT).show();
}
else
{
Log.i(TAG, "VALUES::" + access_token+ " " + id + " " +username);
url = "my Url";
}
} catch (NullPointerException e) {
Log.i(TAG, "User Not Logged IN " + e.getMessage());
// TODO Auto-generated catch block
e.printStackTrace();
}
fetchValues = new FetchEventValues();
fetchValues.execute();
listview = getListView();
listview.setOnScrollListener(new EndlessScrollListener());
}
// AsyncTask Class called in the OnCreate() when the activity is first started.
public class FetchEventValues extends AsyncTask<Integer, Integer, Integer>
{
ProgressDialog progressdialog = new ProgressDialog(EndlessScrollExample.this);
#SuppressLint("SimpleDateFormat")
#SuppressWarnings("unchecked")
#Override
protected Integer doInBackground(Integer... params) {
currentPage++;
// Creating JSON Parser instance
JsonParser jParser = new JsonParser();
// getting JSON string from URL
//arrayEventsBeans.clear();
JSONObject jsonobj = jParser.getJSONFromUrl(url);
Log.i(TAG, "URL VALUES:" + url);
try{
// Code to get the auto complete values Autocomplete Values
JSONArray jsonAarray = jsonobj.getJSONArray(Constants.LOCATIONS);
eventsbean = new EventsBean();
Log.e(TAG, "Location Array Size:" + jsonAarray.length());
for(int j = 0 ; j < jsonAarray.length() ; j++)
{
if(!jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_CITY) && !jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_STATE) && !jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_COUNTRY))
{
JSONObject job = jsonAarray.getJSONObject(j);
if(job.has(Constants.LOCATION_STATE))
{
SuggestCity = job.getString(Constants.LOCATION_CITY);
eventsbean.setLocation_city(job.getString(Constants.LOCATION_CITY));
SuggestState = job.getString(Constants.LOCATION_STATE);
eventsbean.setLocation_state(job.getString(Constants.LOCATION_STATE));
suggestCountry = job.getString(Constants.LOCATION_COUNTRY);
eventsbean.setLocation_country(job.getString(Constants.LOCATION_COUNTRY));
}
}
}
// JSON object to fetch the events in datewise format
JSONObject eventobject = jsonobj.getJSONObject("events");
arrayEventsBeans = new ArrayList<EventsBean>();
// #SuppressWarnings("unchecked")
Iterator<Object> keys = eventobject.keys();
while (keys.hasNext()) {
String datestring = String.valueOf(keys.next());
if (datestring.trim().length() > 0) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = formatter.parse(datestring);
DateBean dateBean = new DateBean(date);
sortArray.add(dateBean);
}
// JSONArray jsonArray = eventobject.getJSONArray(datestring);
//System.out.println(" --"+jsonArray);
}
System.out.println("size:"+sortArray.size());
System.out.println("==========sorting array======");
Collections.sort(sortArray,new CompareDate());
//reverse order
//Collections.reverse(sortArray);
for(DateBean d : sortArray){
dateKey = new SimpleDateFormat("yyyy-MM-dd").format(d.getDate());
System.out.println(dateKey);
Date today = new Date();
Date alldates = d.getDate();
/// Calendar alldates1 = Calendar.getInstance();
JSONArray jsonArray = eventobject.getJSONArray(dateKey);
System.out.println(" --"+jsonArray);
for (int i = 0 ; i < jsonArray.length() ; i++)
{
if ((today.compareTo(alldates) < 0 || (today.compareTo(alldates)== 0)))
// if (alldates1 > cal) alldates.getTime() >= today.getTime()
{
String currentTimeStr = "7:04 PM";
Date userDate = new Date();
String userDateWithoutTime = new SimpleDateFormat("yyyyMMdd").format(userDate);
String currentDateStr = userDateWithoutTime + " " + currentTimeStr;
Date currentDate = new SimpleDateFormat("yyyyMMdd h:mm a").parse(currentDateStr);
if (userDate.compareTo(currentDate) >= 0) {
System.out.println(userDate + " is greater than or equal to " + currentDate);
} else {
System.out.println(userDate + " is less than " + currentDate);
}
JSONObject jsonobjname = jsonArray.getJSONObject(i);
EventsBean eventsbean = new EventsBean();
JSONObject jobjectpicture = jsonobjname.getJSONObject(Constants.PICTURE);
JSONObject jobjeventpicture = jobjectpicture.getJSONObject(Constants.DATA);
eventsbean.setUrl(jobjeventpicture.getString(Constants.URL));
if(jsonobjname.has(Constants.OWNER))
{
JSONObject owner_obj = jsonobjname.getJSONObject(Constants.OWNER);
eventsbean.setOwner_id(owner_obj.getString(Constants.OWNER_ID));
eventsbean.setOwner_name(owner_obj.getString(Constants.OWNER_NAME));
String owner_name = owner_obj.getString(Constants.OWNER_NAME);
Log.i(TAG, "Owner:" + owner_name);
}
if(!jsonobjname.isNull(Constants.COVER))
{
JSONObject objectcover = jsonobjname.getJSONObject(Constants.COVER);
eventsbean.setCover_id(objectcover.getString(Constants.COVER_ID));
eventsbean.setSource(objectcover.getString(Constants.SOURCE));
String cover_url = objectcover.getString(Constants.SOURCE);
Log.i(TAG, "Cover Url:" + cover_url);
eventsbean.setOffset_y(objectcover.getString(Constants.OFFSET_Y));
eventsbean.setOffset_x(objectcover.getString(Constants.OFFSET_X));
}
eventsbean.setName(jsonobjname.getString(Constants.NAME));
eventsbean.setEvent_id(jsonobjname.getString(Constants.EVENT_ID));
eventsbean.setStart_time(jsonobjname.getString(Constants.START_TIME));
eventsbean.setDescription(jsonobjname.getString(Constants.DESCRIPTION));
eventsbean.setLocation(jsonobjname.getString(Constants.LOCATION));
if(!jsonobjname.isNull(Constants.IS_SILHOUETTE))
{
eventsbean.setIs_silhouette(jsonobjname.getString(Constants.IS_SILHOUETTE));
}
eventsbean.setPrivacy(jsonobjname.getString(Constants.PRIVACY));
datetime = jsonobjname.getString(Constants.START_TIME);
if(!jsonobjname.isNull(Constants.VENUE))
{
JSONObject objectvenue = jsonobjname.getJSONObject(Constants.VENUE);
if(objectvenue.has(Constants.VENUE_NAME))
{
eventsbean.setVenue_name(objectvenue.getString(Constants.VENUE_NAME));
event_name = objectvenue.getString(Constants.VENUE_NAME);
Log.i(TAG, "Event Venue Name:" + event_name);
}
else
{
eventsbean.setLatitude(objectvenue.getString(Constants.LATITUDE));
eventsbean.setLongitude(objectvenue.getString(Constants.LONGITUDE));
eventsbean.setCity(objectvenue.getString(Constants.CITY));
eventsbean.setState(objectvenue.getString(Constants.STATE));
eventsbean.setCountry(objectvenue.getString(Constants.COUNTRY));
eventsbean.setVenue_id(objectvenue.getString(Constants.VENUE_ID));
eventsbean.setStreet(objectvenue.getString(Constants.STREET));
address = objectvenue.getString(Constants.STREET);
eventsbean.setZip(objectvenue.getString(Constants.ZIP));
}
}
arrayEventsBeans.add(eventsbean);
Log.i(TAG, "arry list values:" + arrayEventsBeans.size());
}
}
}
}catch(Exception e){
Log.e(TAG , "Exception Occured:" + e.getMessage());
}
return null;
}
class CompareDate implements Comparator<DateBean>{
#Override
public int compare(DateBean d1, DateBean d2) {
return d1.getDate().compareTo(d2.getDate());
}
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Integer result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
if(this.progressdialog.isShowing())
{
this.progressdialog.dismiss();
}
if(adapter == null)
{
adapter = new SAmpleAdapter(EndlessScrollExample.this, 0, arrayEventsBeans);
listview.setAdapter(adapter);
}
else
{
adapter.notifyDataSetChanged();
}
//currentPage++;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
this.progressdialog.setMessage("Loading....");
this.progressdialog.setCanceledOnTouchOutside(false);
this.progressdialog.show();
}
public int setPage(int currentPage) {
return currentPage;
// TODO Auto-generated method stub
}
}
public class EndlessScrollListener implements OnScrollListener {
private int visibleThreshold = 0;
private int currentPage = 0;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == SCROLL_STATE_IDLE) {
if (listview.getLastVisiblePosition() >= listview.getCount() - visibleThreshold) {
currentPage++;
fetchValues.setPage(currentPage);
fetchValues.execute();
}
}
}
}
}
Thanks in advance.
ListView already supports OnScrollListener, so you have to override it and check the condition(in onScroll()), whether it is reached to the end of the list or not.If yes, then add a footer(optional) and fire the async task. After reciving the result notify the adapter. You could check solution on this link, it works on the same concept.
here are few examples of what you are looking for:
http://mobile.dzone.com/news/android-tutorial-dynamicaly
https://github.com/johannilsson/android-pulltorefresh

Handling Activity stack through application programmatically

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.

Categories

Resources