Asynctask JSON error handling using try and catch android - android

Im having a problem on my application, when my application refreshes or loading in slow internet connection.. the activity always destroys, or "Unfortunately (Name) is Stopped" how can i prevent the Force Close on my activity. I'm using Asynctask and JSON file to get my data out of PHP. and this is my code:
package com.example.this;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class Frontpane extends Activity {
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ( keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onBackPressed() {
return;
}
Button Loginbutton;
Button exitButton;
EditText username=null;
EditText password=null;
EditText checker;
String Username1;
String Password1;
/** For database connection**/
private static String url = "http://1.1.1.1/radarMonitoring/api/retrieveacc.php";
private static final String TAG_REGISTEREDACCOUNTS = "RegisteredAccounts";
private static final String TAG_ACCNUM = "Acc_Num";
private static final String TAG_USEREG = "User_NameReg";
private static final String TAG_PASSREG = "Pass_WordReg";
JSONArray accnt = null;
String cntb;
String cnta;
String can;
String cbn;
int usncnt;
int pswcnt;
ArrayList<HashMap<String, String>> accntList;
/** For database connection**/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.front);
Toast.makeText(Frontpane.this, "Please Login to Continue.", Toast.LENGTH_SHORT).show();
exitButton = (Button) findViewById(R.id.button);
username=(EditText)findViewById(R.id.username);
password=(EditText)findViewById(R.id.password);
// checker=(EditText)findViewById(R.id.editText1);
exitButton.setOnClickListener(button);
addButtonListener();
/**array of usernames and pw **/
accntList = new ArrayList<HashMap<String, String>>();
/**array of usernames and pw **/
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
accnt = jsonObj.getJSONArray(TAG_REGISTEREDACCOUNTS);
// looping through All Contacts
for (int i = 0; i < accnt.length(); i++) {
int l;
JSONObject c = accnt.getJSONObject(i);
// String an = c.getString(TAG_ACCNUM);
String unr = c.getString(TAG_USEREG);
// String pwr = c.getString(TAG_PASSREG);
// tmp hashmap for single contac
HashMap<String, String> acc = new HashMap<String, String>();
// adding each child node to HashMap key => value
// acc.put(TAG_ACCNUM, an);
acc.put(TAG_USEREG, unr);
// acc.put(TAG_PASSREG, pwr);
if(unr.equals(Username1)){
usncnt = i;
can = unr;
}
// adding contact to contact list
accntList.add(acc);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
Toast.makeText(Frontpane.this,"Please Check Your Internet Connection", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
/**
* Updating parsed JSON data into ListView
* */
cnta = can;
if(Username1.isEmpty()==false){
if(Password1.isEmpty()){
Toast.makeText(Frontpane.this, "Please Enter Password!", Toast.LENGTH_SHORT).show();
username.setText(null, null);
password.setText(null, null);
}
else{
if(cnta!=null){
new GetPAss().execute();
}
else{
Toast.makeText(Frontpane.this, "Not Registered or Check your Internet Connection..", Toast.LENGTH_SHORT).show();
username.setText(null, null);
password.setText(null, null);
}
}
}
else{
Toast.makeText(Frontpane.this, "Please Enter Username!", Toast.LENGTH_SHORT).show();
username.setText(null, null);
password.setText(null, null);
}
}
}
private class GetPAss extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
accnt = jsonObj.getJSONArray(TAG_REGISTEREDACCOUNTS);
// looping through All Contacts
for (int i = 0; i < accnt.length(); i++) {
int l;
JSONObject c = accnt.getJSONObject(i);
// String an = c.getString(TAG_ACCNUM);
//String unr = c.getString(TAG_USEREG);
String pwr = c.getString(TAG_PASSREG);
// tmp hashmap for single contac
HashMap<String, String> acc = new HashMap<String, String>();
// adding each child node to HashMap key => value
// acc.put(TAG_ACCNUM, an);
// acc.put(TAG_USEREG, unr);
acc.put(TAG_PASSREG, pwr);
if(pwr.equals(Password1)){
pswcnt = i;
cbn = pwr;
}
// adding contact to contact list
accntList.add(acc);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
Toast.makeText(Frontpane.this,"Please Check Your Internet Connection", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
/**
* Updating parsed JSON data into ListView
* */
cntb = cbn;
if(Username1.isEmpty()){
Toast.makeText(Frontpane.this, "Please Enter Username!", Toast.LENGTH_SHORT).show();
username.setText(null, null);
password.setText(null, null);
}
else{
/* Toast.makeText(Frontpane.this, "meron", Toast.LENGTH_SHORT).show();
username.setText(null, null);
password.setText(null, null); */
if(cntb!=null){
if((pswcnt>=0)&&(usncnt>=0)){
if(pswcnt==usncnt){
Intent intent = new Intent(Frontpane.this,MyActivity.class);
startActivity(intent);
Toast.makeText(Frontpane.this, "Login Successful!", Toast.LENGTH_SHORT).show();
username.setText(null, null);
password.setText(null, null);
}
else{
Toast.makeText(Frontpane.this, "Username and Password does not match, Please Try Again! ", Toast.LENGTH_SHORT).show();
username.setText(null, null);
password.setText(null, null);
}
}
}
else{
Toast.makeText(Frontpane.this, "Wrong Password, Please Try Again! ", Toast.LENGTH_SHORT).show();
username.setText(null, null);
password.setText(null, null);
}
}
}
}
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.killBackgroundProcesses("com.example.RadarOperationMonitoringSystem");
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
// Method 2
System.exit(0);
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
public void addButtonListener() {
Loginbutton = (Button) findViewById(R.id.buttonLogin);
Loginbutton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Username1 = username.getText().toString();
Password1 = password.getText().toString();
new GetContacts().execute();
Toast.makeText(Frontpane.this, "Please Wait.. Verifying User Log-in. ", Toast.LENGTH_SHORT).show();
}
});
}
OnClickListener button = new OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(Frontpane.this);
builder.setMessage("Are you sure want to exit?").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
};
}

do this in post execute, by returning proper value from doInBackground method. All UI related code should run in ui thread.
Toast.makeText(Frontpane.this,"Please Check Your Internet Connection", Toast.LENGTH_SHORT).show();
Update
you have to do some thing like this
private class GetContacts extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
accnt = jsonObj.getJSONArray(TAG_REGISTEREDACCOUNTS);
// looping through All Contacts
for (int i = 0; i < accnt.length(); i++) {
int l;
JSONObject c = accnt.getJSONObject(i);
// String an = c.getString(TAG_ACCNUM);
String unr = c.getString(TAG_USEREG);
// String pwr = c.getString(TAG_PASSREG);
// tmp hashmap for single contac
HashMap<String, String> acc = new HashMap<String, String>();
// adding each child node to HashMap key => value
// acc.put(TAG_ACCNUM, an);
acc.put(TAG_USEREG, unr);
// acc.put(TAG_PASSREG, pwr);
if(unr.equals(Username1)){
usncnt = i;
can = unr;
}
// adding contact to contact list
accntList.add(acc);
}
} catch (JSONException e) {
e.printStackTrace();
return false;
}
return true;
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
///Toast.makeText(Frontpane.this,"Please Check Your Internet Connection", Toast.LENGTH_SHORT).show();
return false;
}
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
// Dismiss the progress dialog
/**
* Updating parsed JSON data into ListView
* */
if(!result)
{
// add here your message
Toast.makeText(Frontpane.this,"Please Check Your Internet Connection", Toast.LENGTH_SHORT).show();
return;
}
cnta = can;
if(Username1.isEmpty()==false){
if(Password1.isEmpty()){
Toast.makeText(Frontpane.this, "Please Enter Password!", Toast.LENGTH_SHORT).show();
username.setText(null, null);
password.setText(null, null);
}
else{
if(cnta!=null){
new GetPAss().execute();
}
else{
Toast.makeText(Frontpane.this, "Not Registered or Check your Internet Connection..", Toast.LENGTH_SHORT).show();
username.setText(null, null);
password.setText(null, null);
}
}
}
else{
Toast.makeText(Frontpane.this, "Please Enter Username!", Toast.LENGTH_SHORT).show();
username.setText(null, null);
password.setText(null, null);
}
}

The workflow for executing asynctask is as follows
onPreExecute()
doInBackground(Params...)
onProgressUpdate(Progress...)
onPostExecute(Result)
It is possible to invoke UI code on these methods except doInBackground(Params...). The UI work should be deferred to onPostExecute(Result).
It seems that the toast message in doInbackground is triggered following an exception in the code.

Related

Activity not opening after signing in

I'm currently creating an application that allows the user to login using a web api. While checking response of the API , i'm not getting any error.
{"error":0,"data":[{"id":"2","driver_name":"Test Driver","driver_lat":"","driver_long":"","driver_mobile_no":"9164618545","driver_password":"202cb962ac59075b964b07152d234b70","driver_token":"bef1032495ef4b2c891795fce1fa16c2","driver_image":"","is_active":"1","on_duty":"0","t_drivers":"0","created_at":"2017-07-04 06:38:22","last_activity_at":"2017-07-04 09:19:08"}],"msg":"Login Successfully."}
But while using the app, it does not go to the mainActivity.
This is the login class:-
public class login extends AppCompatActivity {
private Button login1;
Session session;
private ConstraintLayout mRootLayout;
boolean doubleBackToExitPressedOnce = false;
boolean status = false;
EditText mEdtEmail , mEdtPassword ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Answers(), new Crashlytics());
setContentView(R.layout.activity_login);
login1 = (Button) findViewById(R.id.button);
mEdtEmail = (EditText) findViewById(R.id.phone_number);
mEdtPassword = (EditText) findViewById(R.id.password);
session = new Session(login.this);
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(login.this, MainActivity.class);
startActivity(intent);
finish();
}
// sign_in();
login1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String mobile = mEdtEmail.getText().toString().trim();
String password = mEdtPassword.getText().toString().trim();
status = checkInternetConnection();
if (status) {
if (mobile.length() == 0) {
mEdtEmail.setError("Required");
} else if (mobile.length() < 10) {
mEdtEmail.setError("Mobile no must be 10 char. long");
} else if (password.length() == 0) {
mEdtPassword.setError("Required");
} else {
new UserLoginTask(mobile, password, login.this).execute();
}
}
else
{
Snackbar.make(mRootLayout, "You don't have Internet connection!", Snackbar.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), "You don't have Internet connection", Toast.LENGTH_LONG).show();
}
}
});
}
private class UserLoginTask extends AsyncTask<String, Void, String> {
private String mUserName;
private String mPassword;
String msg ;
ProgressDialog progressDialog;
Boolean loginStatus = false;
private Activity activity;
public static final String MyPREFERENCES = "MyPrefs" ;
SharedPreferences sharedpreferences;
UserLoginTask(String userName, String password, Activity activity) {
mUserName = userName;
mPassword = password;
this.activity = activity;
}
#Override
protected void onPreExecute() {
progressDialog= ProgressDialog.show(login.this, "Loading. . .","Please Wait. . .", true);
Toast.makeText(login.this,"toast 1",Toast.LENGTH_SHORT).show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
String result= WebService.postHttpResponse(mUserName, mPassword, activity);
JSONObject jsonObject = new JSONObject(result);
// Log.d("Json Array", "doInBackground: "+jsonObject);
String status = jsonObject.optString("error");
// msg = jsonObject.optString("msg");
// Toast.makeText(login.this,"toast 2",Toast.LENGTH_SHORT).show();
if(status.equals("0")){
loginStatus = true ;
session.setLogin(true);
JSONArray jsonarray = jsonObject.getJSONArray("data");
JSONObject jsonObject1=jsonarray.getJSONObject(0);
status = jsonObject1.getString("msg");
Log.e("DRIVER NAME -----" ,jsonObject1.getString("driver_name"));
Driver driver = new Driver();
driver.setId(jsonObject1.getString("id"));
driver.setDriver_name(jsonObject1.getString("driver_name"));
driver.setDriver_lat(jsonObject1.getString("driver_lat"));
driver.setDriver_long(jsonObject1.getString("driver_long"));
driver.setDriver_mobile_no(jsonObject1.getString("driver_mobile_no"));
driver.setDriver_token(jsonObject1.getString("driver_token"));
driver.setCreated_at(jsonObject1.getString("created_at"));
driver.setLast_activity_at(jsonObject1.getString("last_activity_at"));
sharedpreferences = activity.getSharedPreferences("MY" , Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("driver_name",jsonObject1.getString("driver_name"));
editor.putString("driver_mobile_no", jsonObject1.getString("driver_mobile_no"));
editor.putString("id", jsonObject1.getString("id"));
editor.putString("driver_token", jsonObject1.getString("driver_token"));
editor.putString("driver_image", jsonObject1.getString("driver_image"));
editor.putString("current_order_no", "");
editor.commit();
startActivity(intent);
activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));
overridePendingTransition(R.anim.right_in, R.anim.left_out);
finish();
}
else {
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return msg ;
}
#Override
protected void onPostExecute(String msg) {
super.onPostExecute(msg);
progressDialog.dismiss();
Toast.makeText(activity , msg , Toast.LENGTH_LONG).show();
}
}
/*public void sign_in(){
login1=(Button)findViewById(R.id.button);
login1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(login.this,"Welcome!", Toast.LENGTH_SHORT).show();
startActivity(intent);
}
});
}*/
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce){
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true ;
Toast.makeText(this , "Please click BACK again to exit" , Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false ;
}
}, 2000);
/*Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
System.exit(0);*/
}
public boolean checkInternetConnection()
{
ConnectivityManager connectivity = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] inf = connectivity.getAllNetworkInfo();
if (inf != null)
for (int i = 0; i < inf.length; i++)
if (inf[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
Please Help!
Thanks!!
EDIT 1: Thanks a lot! I've gotten the solution for this. It was a really small error on my part!
Your jsonObject1.getString("msg"); don't have any msg
{"error":0,"data":[{"id":"2",.....}],"msg":"Login Successfully."}
// ` ^^^^^ part of jsonObject`
|_____________|
| first json object which has no msg key/value pair
|________________|
| jsonarray
|_______________________________________________________________|
|
JSONObject jsonObject = new JSONObject(result);
// response object
String status = jsonObject.optString("error");
// response json contains error , so far so good
..
..
JSONArray jsonarray = jsonObject.getJSONArray("data");
// get the jsonarray
JSONObject jsonObject1=jsonarray.getJSONObject(0);
// get first object
status = jsonObject1.getString("msg");
// there is no msg string in jsonObject1 hence error
so use
jsonObject.optString("msg");
Note : Apparently you are starting your MainActivity twice so remove one and from doInBackground which works on background thread so don't do this
Intent intent = new Intent("oodi_design.driver4.Activity.MainActivity");
startActivity(intent);
activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));
Start your activity from onPostExecute
Here you are getting JSONObject in response from server.
This object contains three values:
error
data
msg
error contains error code in integer format.
data contains JSONArray which contain the details of the driver.
msg contains the message in String format.
So you need to write
JSONObject jsonObject = new JSONObject(result);
int code = jsonObject.getString("error");
if (code == 0) {
JSONArray jsonarray = jsonObject.getJSONArray("data");
JSONObject data = jsonarray.getJSONObject(0);
String msg = jsonObject.getString("msg");
driver = new Driver();
...
}
and remove this from doInBackground method
Intent intent = new Intent("oodi_design.driver4.Activity.MainActivity");
startActivity(intent);
activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));
overridePendingTransition(R.anim.right_in, R.anim.left_out);
finish();
and write this code in onPostExecute method after displaying Toast
...
activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));
overridePendingTransition(R.anim.right_in, R.anim.left_out);
finish();
...
You need to declare Driver in UserLoginTask after ProgressDialog like
...
ProgressDialog progressDialog;
Driver driver;
From your attached JSONObject, its seems that JSONObject contains two string (error and msg) and one JSONArray named data.
So you have to parse this JSON data as below:
.........
..............
String result = WebService.postHttpResponse(mUserName, mPassword, activity);
JSONObject jsonObject = new JSONObject(result);
// ERROR & STATUS
String status = jsonObject.optString("error");
String msg = jsonObject.optString("msg");
// DATA
JSONArray jsonArrayData = jsonObject.getJSONArray("data");
// First DATA JSONObject
JSONObject jsonObject1 = jsonArrayData.getJSONObject(0);
........
..............
To start MainActivity, use below code in onPostExecute() :
#Override
protected void onPostExecute() {
Intent intent = new Intent(login.this, MainActivity.class);
intent.putExtra("driver_obj" , driver); // driver should be declared as global in `UserLoginTask` class.
activity.startActivity(intent);
overridePendingTransition(R.anim.right_in, R.anim.left_out);
finish();
}
Hope this will help~

Wait for Database to finish inserting data before continuing to next activity Android

I have an activity that calls JSON data from a foreign database.
Below is my ideal case for my app:
The JSON data is parsed and inserted into an SQLite database on Android
Next activity is started and the newly inserted data is read from the SQLite database
What actually happens:
The JSON data is parsed and inserted into an SQLite database on Android
The next activity is started while data is still being inserted and returns zero when reading from the desired databse for my ListArray in that activity.
How do I force Android to wait until database insertion is completed before starting the next activity?
EDIT
My doInBackground looks as follows:
#Override
protected String doInBackground(String... params) {
StringRequest strReq = new StringRequest(Request.Method.GET,
str, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
JSONArray jObjInside = jObj.getJSONArray("service_prov_services");
for (int i = 0; i < jObjInside.length(); i++) {
// Now store the user in SQLite
try {
// JSONObject user = jObj.getJSONObject("user");
String service_prov_type = jObj.getString("service_prov_type");
String service_prov_name = jObj.getString("service_prov_name");
String addr_street = jObj.getString("addr_street");
String addr_num = jObj.getString("addr_number");
String addr_plz = jObj.getString("addr_plz");
String addr_city = jObj.getString("addr_city");
JSONObject elem = jObjInside.getJSONObject(i);
if(elem != null){
String service_id = elem.getString("service_id");
String service_type = elem.getString("service_type");
String service_measure = elem.getString("service_measure");
// Inserting row in userServiceProvServices table
db.addUserServiceProvServices(service_id, service_prov_type,
service_prov_name, addr_street, addr_num, addr_plz, addr_city, service_type, service_measure);
Log.d("post_url for service", addr_plz );
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(), "Json error: " +
e.getMessage(), Toast.LENGTH_LONG).show();
}
}
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getActivity().getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(), "Json error: " +
e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
});
Log.d("test string to appcntr",strReq.toString());
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
return params[0];
}
onPostExecute looks as follows:
#Override
protected void onPostExecute(String Result) {
//super.onPostExecute(Result);
pdLoading.dismiss();
//this method will be running on UI thread
Log.d(TAG, "Stamp: " + Result);
Bundle args = new Bundle();
args.putString("stampID", Result);
ProviderServiceListFragment frag = new ProviderServiceListFragment();
frag.setArguments(args);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame,
frag)
.commit();
}
With the way I am doing it now, my next Fragment is already called, although the data has not finished being entered into the database. This means the ListArray in the follwoing Fragment is empty because of the missing database data.
I worked on this for a month and finally figured it out for myself (stupid nube I am..) So here is a piece of code inserting a record to sqlite.
On the chosen event ("onClick actionbutton1") a new AsyncTask is created with doInBackground, onPreExecute and onPostExecute.
onPreExecute will setMessage() and show() the progressDialog which will start spinning
onPostExecute will handle the new/next Activity
READ BELOW FOR doInBackground!!
actionButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog progressDialog = new ProgressDialog(AddUpdateEvf.this);
new AsyncTask<Void, Void, Boolean>() {
protected Boolean doInBackground(Void... params) {
doOneThing();
return null;
}
#Override
protected void onPreExecute() {
progressDialog.setMessage("Processing...");
progressDialog.show();
}
protected void onPostExecute(Boolean result) {
evaluationFormOps.close();
progressDialog.dismiss();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(AddUpdateEvf.this);
alertDialogBuilder.setMessage("Added to Database...")
.setCancelable(false)
.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
i = new Intent(AddUpdateEvf.this, ViewProduct.class);
i.putExtra(EXTRA_ADD_UPDATE, "View");
i.putExtra(EXTRA_PRODUCT_ID, hiddenTextId.getText().toString());
i.putExtra(EXTRA_PRODUCT_NO, productNo_tv.toString());
startActivity(i);
dialog.dismiss();
finish();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
private void doOneThing() {
makeDbRequest();
do {
evfId = newEvf.getEvfId();
}
while (evfId<1);
}
}.execute();
}
});
Note this snippet in the above code called in doInBackground():
private void doOneThing() {
makeDbRequest();
do {
evfId = newEvf.getEvfId();
}
while (evfId<1);
}
Note: The makeDbRequest() handles the insert to sqlite by setting the values and then passing it to another class which handles the cursor and puts the values etc.
Heres a small snippet of relevant code in that class (which you should already have mastered...):
public Evf addEvf(Evf evf, String dBsuccess){
ContentValues values = new ContentValues();
values.put(TableHelper.PRODUCT_IDE,evf.getPRODUCTId());
values.put(TableHelper.CSCORE,evf.getcScore());
values.put(TableHelper.FSCORE,evf.getfScore());
values.put(TableHelper.TSCORE,evf.gettScore());
values.put(TableHelper.WEIGHT,evf.getWeight());
values.put(TableHelper.TEMP,evf.getTemp());
values.put(TableHelper.STATUS,evf.getStatus());
values.put(TableHelper.TIMESTAMP, String.valueOf(evf.getTimeStamp()));
values.put(TableHelper.LOADED, dBsuccess);
long insertid = database.insert(TableHelper.TABLE_EVFS,null,values);
evf.setEvfId((int) insertid);
return evf;
}
So above you can see the Id of, in my case evaluationform(Evf), being set to the insert id. This happens after the insert and you can set any value in your object class (the one with getters and setters...Evf())
Finally, use the do...while statement above to "listen" for the value being set in the object class
This can obviously only happen if the insert was finished and the onPosteExecute takes care of the rest
Hope it helps, crit is welcome, PEACHES!!
Use AsyncTask to process the Database insertion process & then use the onPostExecute method to move away from the current activity.
private class ProcessDatabase extends AsyncTask<String, String, String> {
String sampleData;
#Override
protected String doInBackground(String... params) {
//Call your Database Insert method here.
//In this example, I am inserting sampleData to the DB
return null;
}
#Override
protected void onPostExecute(String result) {
//This gets triggered when the process is complete
}
}
You can start the AsyncTask by adding the following code in your onCreate or where ever you want to start the DB Insertion process:
//in this case I am just passing a string, You can create your own
//custom class & send that as well
ProcessDatabase.execute(myData);
Refer this link for more information. Good luck!
The StringRequest is an Asynchronous request, so upon the executing the those lines onPostExecute will called immediately, so there is no guarantee that the sql update will complete before the next activity is launched.
Call the nextActivity at the end of the onResponse callback method of the StringRequest which way you can guarantee to insert the data to db first and then call the nextActivity.
private void makeJsonRequest(String str) {
StringRequest strReq = new StringRequest(Request.Method.GET,
str, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
JSONArray jObjInside = jObj.getJSONArray("service_prov_services");
for (int i = 0; i < jObjInside.length(); i++) {
// Now store the user in SQLite
try {
// JSONObject user = jObj.getJSONObject("user");
String service_prov_type = jObj.getString("service_prov_type");
String service_prov_name = jObj.getString("service_prov_name");
String addr_street = jObj.getString("addr_street");
String addr_num = jObj.getString("addr_number");
String addr_plz = jObj.getString("addr_plz");
String addr_city = jObj.getString("addr_city");
JSONObject elem = jObjInside.getJSONObject(i);
if (elem != null) {
String service_id = elem.getString("service_id");
String service_type = elem.getString("service_type");
String service_measure = elem.getString("service_measure");
// Inserting row in userServiceProvServices table
db.addUserServiceProvServices(service_id, service_prov_type,
service_prov_name, addr_street, addr_num, addr_plz, addr_city, service_type, service_measure);
Log.d("post_url for service", addr_plz);
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(), "Json error: " +
e.getMessage(), Toast.LENGTH_LONG).show();
}
}
goNextActivity();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getActivity().getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(), "Json error: " +
e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
});
Log.d("test string to appcntr", strReq.toString());
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void goNextActivity(){
//this method will be running on UI thread
ProviderServiceListFragment frag = new ProviderServiceListFragment();
frag.setArguments(args);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame,
frag)
.commit();
}

after click back button in main activity it going to back to login ,HOW TO STOP TO GO LOGIN AGAIN

i am very new to android ,my login activity was working fine but my problem is after login in to my app sucessesfully go to main activity,after enter into my main activity when i press back button it will go to again login page please any one help me how to solve that
login.class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sharedpreferences = getSharedPreferences(mypreference, Context.MODE_PRIVATE);
String checkemail=sharedpreferences.getString("Email", "");
String checkuid =sharedpreferences.getString("Uid", "");
if (checkemail.length()>0 && checkuid.length()>0){
Intent main = new Intent(getApplicationContext(),MainActivity.class);
startActivity(main);
}
username =(EditText)findViewById(R.id.input_email);
password =(EditText)findViewById(R.id.input_password);
login =(Button)findViewById(R.id.btn_login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkvalid();
}
});
signup_link=(TextView)findViewById(R.id.link_signup);
signup_link.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent signup= new Intent(getApplicationContext(),SignUp.class);
startActivity(signup);
}
});
}
private void checkvalid()
{
uname =username.getText().toString();
upassword=password.getText().toString();
new AttemptLogin().execute();
if (username.length()==0 || password.length()==0)
{
Toast.makeText(getApplicationContext(), "Please enter all fields", Toast.LENGTH_LONG).show();
} else
{
uname =username.getText().toString();
upassword=password.getText().toString();
new AttemptLogin().execute();
}
}
class AttemptLogin extends AsyncTask<String, String, String>
{
/** * Before starting background thread Show Progress Dialog * */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args)
{
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("email",uname));
postParameters.add(new BasicNameValuePair("password",upassword));
System.out.println("?????????" + postParameters);
String response = null;
try
{
response = SimpleHttpClient.executeHttpPost(LOGIN_URL,postParameters).toString();
System.out.println("#################"+response);
}
catch (Exception e)
{
e.printStackTrace();
String errorMsg = e.getMessage();
}
return response;
} /** * Once the background process is done we need to Dismiss the progress dialog asap * **/
protected void onPostExecute(String response)
{
pDialog.dismiss();
try {
JSONObject jsonobject = new JSONObject(response);
status = jsonobject.getString("Status");
message = jsonobject.getString("Message");
if (message.equalsIgnoreCase("OK")){
JSONArray childArray = jsonobject.optJSONArray("Result");
if (childArray != null && childArray.length() > 0) {
for (int k = 0; k < childArray.length(); k++) {
JSONObject objj = childArray.optJSONObject(k);
uid = objj.getString("id");
user_name = objj.getString("user_name");
user_email = objj.getString("user_email");
user_status = objj.getString("status");
user_mobile = objj.getString("mobile_number");
System.out.println("AAAAAAAAAAAAAAAAAA"+user_name+user_email+user_mobile);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("Email", user_email);
editor.putString("Uid", uid);
editor.putString("Uname", user_name);
editor.putString("Status", user_status);
editor.putString("Mobile", user_mobile);
editor.commit();
Intent login= new Intent(getApplicationContext(),MainActivity.class);
startActivity(login);
}
}
else{
Toast.makeText(Login.this, "Registration Failed", Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
}
}
Whenever you don't want to load the previous activity on back press you should call finish() method after launching the new activity.
You need to finish() the login activity when login is successful.
Add
finish();
at the end of method startActivity();
You might have to add any condition as per your requirement.

Transaction ID set correctly, but displayed only a submit later

My code gives correct response and sets transaction ID correctly. But on screen, the ID is missing the first time I submit, and when I go back and submit again, then the ID on screen is the ID of the first transaction.
On the first submit, this is rendered:
MOBILE NUMBER: 9129992929
OPERATOR: AIRTEL
AMOUNT: 344
TRANSACTION ID:
On the second submit, this is rendered:
MOBILE NUMBER: 9129992929
OPERATOR: AIRTEL
AMOUNT: 344
TRANSACTION ID: NUFEC37WD537K5K2P9WX
I want to see the second screen the first time I submit.
Response to the first submit:
D/TID IS: ====>NUFEC37WD537K5K2P9WX D/UID IS:
====>27W3NDW71XRUR83S7RN3 D/Response-------: ------>{"tid":"NUFEC37WD537K5K2P9WX","uid":"27W3NDW71XRUR83S7RN3","status":"ok"}
Response to the second submit:
D/TID IS: ====>18R6YXM82345655ZL3E2 D/UID IS:
====>27W3NDW71XRUR83S7RN3 D/Response-------: ------>{"tid":"18R6YXM82345655ZL3E2","uid":"27W3NDW71XRUR83S7RN3","status":"ok"}
The code generating the response:
public class Prepaid extends Fragment implements View.OnClickListener {
Button submit_recharge;
Activity context;
RadioGroup _RadioGroup;
public EditText number, amount;
JSONObject jsonobject;
JSONArray jsonarray;
ArrayList<String> datalist, oprList;
ArrayList<Json_Data> json_data;
TextView output, output1;
String loginURL = "http://www.www.example.com/operator_details.php";
ArrayList<String> listItems = new ArrayList<>();
ArrayAdapter<String> adapter;
String data = "";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootview = inflater.inflate(R.layout.prepaid, container, false);
submit_recharge = (Button) rootview.findViewById(R.id.prepaid_submit);
number = (EditText) rootview.findViewById(R.id.prenumber);
amount = (EditText) rootview.findViewById(R.id.rechergpre);
submit_recharge.setOnClickListener(this);
context = getActivity();
new DownloadJSON().execute();
return rootview;
}
public void onClick(View v) {
MyApplication myRecharge = (MyApplication) getActivity().getApplicationContext();
final String prepaid_Number = number.getText().toString();
String number_set = myRecharge.setNumber(prepaid_Number);
final String pre_Amount = amount.getText().toString();
String amount_set = myRecharge.setAmount(pre_Amount);
Log.d("amount", "is" + amount_set);
Log.d("number", "is" + number_set);
switch (v.getId()) {
case R.id.prepaid_submit:
if (prepaid_Number.equalsIgnoreCase("") || pre_Amount.equalsIgnoreCase("")) {
number.setError("Enter the number please");
amount.setError("Enter amount please");
} else {
int net_amount_pre = Integer.parseInt(amount.getText().toString().trim());
String ph_number_pre = number.getText().toString();
if (ph_number_pre.length() != 10) {
number.setError("Please Enter valid the number");
} else {
if (net_amount_pre < 10 || net_amount_pre > 2000) {
amount.setError("Amount valid 10 to 2000");
} else {
AsyncTaskPost runner = new AsyncTaskPost(); // for running AsyncTaskPost class
runner.execute();
Intent intent = new Intent(getActivity(), Confirm_Payment.class);
startActivity(intent);
}
}
}
}
}
}
/*
*
* http://pastie.org/10618261
*
*/
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
MyApplication myOpt = (MyApplication) getActivity().getApplicationContext();
protected Void doInBackground(Void... params) {
json_data = new ArrayList<Json_Data>();
datalist = new ArrayList<String>();
// made a new array to store operator ID
oprList = new ArrayList<String>();
jsonobject = JSONfunctions
.getJSONfromURL(http://www.www.example.com/operator_details.php");
Log.d("Response: ", "> " + jsonobject);
try {
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Json_Data opt_code = new Json_Data();
opt_code.setName(jsonobject.optString("name"));
opt_code.setId(jsonobject.optString("ID"));
json_data.add(opt_code);
datalist.add(jsonobject.optString("name"));
oprList.add(jsonobject.getString("ID"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void args) {
final Spinner mySpinner = (Spinner) getView().findViewById(R.id.operator_spinner);
mySpinner
.setAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item,
datalist));
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
String opt_code = oprList.get(position);
String selectedItem = arg0.getItemAtPosition(position).toString();
Log.d("Selected operator is==", "======>" + selectedItem);
Log.d("Selected Value is======", "========>" + position);
Log.d("Selected ID is======", "========>" + opt_code);
if (opt_code == "8" || opt_code == "14" || opt_code == "35" || opt_code == "36" || opt_code == "41" || opt_code == "43") // new code
{
_RadioGroup = (RadioGroup) getView().findViewById(R.id.radioGroup);
_RadioGroup.setVisibility(View.VISIBLE);
int selectedId = _RadioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
final RadioButton _RadioSex = (RadioButton) getView().findViewById(selectedId);
_RadioSex.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (null != _RadioSex && isChecked == false) {
Toast.makeText(getActivity(), _RadioSex.getText(), Toast.LENGTH_LONG).show();
}
Toast.makeText(getActivity(), "Checked In button", Toast.LENGTH_LONG).show();
Log.d("Checked In Button", "===>" + isChecked);
}
});
}
String user1 = myOpt.setOperator(opt_code);
String opt_name = myOpt.setOpt_provider(selectedItem);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
private class AsyncTaskPost extends AsyncTask<String, Void, Void> {
MyApplication mytid = (MyApplication)getActivity().getApplicationContext();
String prepaid_Number = number.getText().toString();
String pre_Amount = amount.getText().toString();
protected Void doInBackground(String... params) {
String url = "http://www.example.com/android-initiate-recharge.php";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
public void onResponse(String response) {
try {
JSONObject json_Response = new JSONObject(response);
String _TID = json_Response.getString("tid");
String _uid = json_Response.getString("uid");
String _status = json_Response.getString("status");
String tid_m =mytid.setTransaction(_TID);
Log.d("TID IS","====>"+tid_m);
Log.d("UID IS", "====>" + _uid);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response-------", "------>" + response);
}
},
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
Log.e("Responce error==","===>"+error);
error.printStackTrace();
}
}
) {
MyApplication uid = (MyApplication) getActivity().getApplicationContext();
final String user = uid.getuser();
MyApplication operator = (MyApplication) getActivity().getApplicationContext();
final String optcode = operator.getOperator();
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
// the POST parameters:
params.put("preNumber", prepaid_Number);
params.put("preAmount", pre_Amount);
params.put("key", "XXXXXXXXXX");
params.put("whattodo", "prepaidmobile");
params.put("userid", user);
params.put("category", optcode);
Log.d("Value is ----------", ">" + params);
return params;
}
};
Volley.newRequestQueue(getActivity()).add(postRequest);
return null;
}
protected void onPostExecute(Void args) {
}
}
class Application
private String _TId;
public String getTId_name() {
return _TId;
}
public String setTId_name(String myt_ID) {
this._TId = myt_ID;
Log.d("Application set TID", "====>" + myt_ID);
return myt_ID;
}
class Confirm_pay
This is where the ID is set.
MyApplication _Rechargedetail =(MyApplication)getApplicationContext();
confirm_tId =(TextView)findViewById(R.id._Tid);
String _tid =_Rechargedetail.getTId_name();
confirm_tId.setText(_tid);
Because you have used Volley library which is already asynchronous, you don't have to use AsyncTask anymore.
Your code can be updated as the following (not inside AsyncTask, direct inside onCreate for example), pay attention to // update TextViews here...:
...
String url = "http://www.example.com/index.php";
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject json_Response = new JSONObject(response);
String _TID = json_Response.getString("tid");
String _uid = json_Response.getString("uid");
String _status = json_Response.getString("status");
String tid_m =mytid.setTId_name(_TID);
Log.d("TID IS","====>"+tid_m);
Log.d("UID IS","====>"+_uid);
// update TextViews here...
txtTransId.setText(_TID);
txtStatus.setText(_status);
...
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response-------", "------>" + response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Responce error==","===>"+error);
error.printStackTrace();
}
}
requestQueue.add(postRequest);
...
P/S: since the reponse data is a JSONObject, so I suggest you use JsonObjectRequest instead of StringRequest. You can read more at Google's documentation.
Hope it helps!
Your line of code should be executed after complete execution of network operation and control comes in onPostExecute(); of your AsyncTask.
confirm_tId.setText(_tid);

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) {
}

Categories

Resources