Android AsyncTask Error with Facebook SDK - java

I used Facebook SDK in Android App for Login. I can login with Facebook. I want to insert AccessToken and Email to my database. I solved get Email but I can get email from user with Async. Then I use AsyncTask For Insert data to database. When I used AsyncTask with Facebook SDK, I got exception.
AsyncTask #5 java.lang.RuntimeException: An error occured while executing doInBackground()
And My Code
private JSONParser jParser = new JSONParser();
private String AccessToken;
public String Email;
private LoginAPI api = new LoginAPI();
#Override
protected void onCreate(Bundle savedInstanceState) {
FacebookSdk.sdkInitialize(getApplicationContext());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginButton = (LoginButton)findViewById(R.id.login_button);
if(Profile.getCurrentProfile()!=null){
user = Profile.getCurrentProfile();
new LoginAPI().execute();
}
loginButton.setReadPermissions("public_profile");
loginButton.setReadPermissions("email");
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
user = Profile.getCurrentProfile();
AccessToken = loginResult.getAccessToken().getToken();
GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject user, GraphResponse graphResponse) {
Email = user.optString("email");
api.execute();
}
}).executeAsync();
}
#Override
public void onCancel() {
AlertDialog alertMessage = new AlertDialog.Builder(Login.this).create();
alertMessage.setMessage("Iptal");
alertMessage.show();
}
#Override
public void onError(FacebookException exception) {
AlertDialog alertMessage = new AlertDialog.Builder(Login.this).create();
alertMessage.setMessage(exception.toString());
alertMessage.show();
}
});
}
class LoginAPI extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(final String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new NameValuePair() {
#Override
public String getName() {
return "Email";
}
#Override
public String getValue() {
return Email;
}
});
params.add(new NameValuePair() {
#Override
public String getName() {
return "AccessToken";
}
#Override
public String getValue() {
return AccessToken;
}
});
JSONObject json = jParser.makeHttpRequest("WebServiceURL", "POST", params); //Exception Line
try {
if (json != null) {
Sonuc = json.getBoolean("Result");
Mesaj = json.getString("Message");
JSONObject _uye = json.getJSONObject("Data");
if(_uye!=null){
localUser = new User(_uye.getInt("UserID"),
_uye.getString("FacebookID"),
_uye.getString("NameSurname"),
_uye.getString("Email"),
_uye.getString("ProfileImage"));
}
else{
localUser = new User(1,"","","","");
}
}
} catch (JSONException e) {
return e.getMessage().toString();
}
return null;
}
protected void onPostExecute(String file_url) {
runOnUiThread(new Runnable() {
public void run() {
if(Sonuc){
Intent welcomeAct = new Intent(getBaseContext(), Welcome.class);
welcomeAct.putExtra("User",localUser);
Login.this.startActivity(welcomeAct);
}
else{
AlertDialog alertMessage = new AlertDialog.Builder(Login.this).create();
alertMessage.setMessage(Mesaj);
alertMessage.show();
}
}
});
}
}

I solved this problem. I wrote AsyncTask code in OnActivityResult event. When Authenticate process finished, I call AsyncTask.

Related

AsyncTask already finished [duplicate]

This question already has answers here:
How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?
(17 answers)
Closed 5 years ago.
How to catch moment when AsyncTask is finished?
I have ProfileUpdate class which extends AsyncTask, and from another activity I calling this method and after I need update my data. How to know that asynctask finished? My asynctask method in another class and not in activity class!!!
this is my onRefresh method in the activity:
#Override
public void onRefresh() {
if (!AlertView.isInternetAvailable(getContext())) {
swipeLayout.setRefreshing(false);
Toast.makeText(getContext(), Messages.CONNECTION_ERROR + ": " + Messages.NO_INTERNET, Toast.LENGTH_SHORT).show();
} else {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
new UpdateProfile(getActivity(), swipeLayout, sharedPreferences.getString(Constants.TOKEN, ""), user.getIin()).execute(Urls.GET_USER);
}
});
profileDefaults();
}
}
and here my AsyncTask method:
public class UpdateProfile extends AsyncTask <String, Void, String> {
private Activity activity;
private SwipeRefreshLayout swipeRefreshLayout;
private String token;
private String userIin;
private SharedPreferences sharedPreferences;
public UpdateProfile(Activity activity, SwipeRefreshLayout swipeRefreshLayout, String token, String userIin) {
this.activity = activity;
this.swipeRefreshLayout = swipeRefreshLayout;
this.token = token;
this.userIin = userIin;
sharedPreferences = this.activity.getSharedPreferences(Constants.PROJECT, Context.MODE_PRIVATE);
}
#Override
protected String doInBackground(String... params) {
URL url = null;
try {
url = new URL(params[0]);
try {
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("iin", userIin)
.build();
Request request = new Request.Builder()
.url(url)
.addHeader(Constants.AUTH_TOKEN, token)
.post(body)
.build();
Response responses = null;
try {
responses = okHttpClient.newCall(request).execute();
} catch (Exception e) {
AlertView.showAlertView(activity, Messages.CONNECTION_ERROR, Messages.NO_INTERNET, Messages.OK);
}
assert responses != null;
return responses.body().string();
} catch (Exception e) {
AlertView.showAlertView(activity, Messages.CONNECTION_ERROR, Messages.NO_INTERNET, Messages.OK);
}
} catch (Exception e) {
AlertView.showAlertView(activity, Messages.CONNECTION_ERROR, Messages.NO_INTERNET, Messages.OK);
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
int code = Integer.valueOf(jsonObject.getString(Constants.CODE));
if (code == Codes.OK) {
Toast.makeText(activity, "Данные обновлены", Toast.LENGTH_SHORT).show();
String userHeader = jsonObject.getString("user");
JSONObject userInfo = new JSONObject(userHeader);
String mobilePhone = userInfo.getString(SingletonConstants.MOBILE_PHONE);
Boolean isActive = userInfo.getBoolean(SingletonConstants.IS_ACTIVE);
Boolean signedAgreement = userInfo.getBoolean(SingletonConstants.SIGNED_AGREEMENT);
Boolean esfEntered = userInfo.getBoolean(SingletonConstants.ESF_ENTERED);
String address = userInfo.getString(SingletonConstants.ADDRESS);
String iin = userInfo.getString(SingletonConstants.IIN);
String certExpDate = userInfo.getString(SingletonConstants.CERT_EXP_DATE);
String firstName = userInfo.getString(SingletonConstants.FIRST_NAME);
String middleName = userInfo.getString(SingletonConstants.MIDDLE_NAME);
String workPhone = userInfo.getString(SingletonConstants.WORK_PHONE);
String secondName = userInfo.getString(SingletonConstants.SECOND_NAME);
String avatarUrl = userInfo.getString(SingletonConstants.AVATAR_URL);;
String secondEmail = userInfo.getString(SingletonConstants.SECOND_EMAIL);
String email = userInfo.getString(SingletonConstants.EMAIL);
User newUser = new User(mobilePhone, isActive, signedAgreement, esfEntered, address, iin, certExpDate, firstName, middleName, workPhone, secondName, avatarUrl, secondEmail, email);
Gson gson = new Gson ();
String userGson = gson.toJson (newUser);
sharedPreferences.edit().putString(SingletonConstants.USER, userGson).apply();
swipeRefreshLayout.setRefreshing(false);
} else {
AlertView.showAlertView(activity, Messages.ERROR, jsonObject.getString(Constants.MESSAGE), Messages.OK);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
How I can call profileDefaults()? It's into my activity. And I need to call it after onPostExecute!
A cleaner way to do it is to use interfaces as listeners.
Create this interface:
public interface OnAsyncFinished{
void onAsyncFinished(Object o);
}
Add the interface as a parameter in your AsyncTaskClass constructor:
private OnAsyncFinished onAsyncFinished;
public UpdateProfile(..., OnAsyncFinished onAsyncFinished) {
...
this.onAsyncFinished = onAsyncFinished;
}
...
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
onAsyncFinished.onAsyncFinished(s); //This will notifiy the method on main activity, and you can now resume the work there
...
}
Implement the interface in your main activity:
public MainActivity extends Activity implements OnAsyncFinished {
#Override
public void onAsyncFinished(Object o) {
//This will get called after onPostExecute, do what u want with the object you got from onPostExecute, json or string in ur example
profileDefaults(); //call ur function
}
}
EDIT:
When creating the async task in your main activity pass this in the constructor likeso:
#Override
public void run() {
new UpdateProfile(..., this).execute(Urls.GET_USER);
}

getting email address from facebook SDK For Android

I have integrated Facebook login in my application .i get other profile information but can't get the email from the sdk.is it possible?
public void getProfileInformation_fb() {
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
String json = response;
try {
JSONObject profile = new JSONObject(json);
// getting name of the user
final String name = profile.getString("name");
// getting email of the user
final String email = profile.getString("email");
final String id = profile.getString("id");
Log.i("ID , Name", ""+id+ ""+name);
Log.i("Email", ""+email);
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.i("Face Book", "" + email);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
This code id working for me.
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
accessToken = loginResult.getAccessToken();
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
try {
String name = object.getString("name");
String birthday = object.getString("birthday");
String gender = object.getString("gender");
String email = object.getString("email");
String picture = object.getString("picture");
} catch (Exception e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,birthday,first_name,gender,last_name,location,email,picture.type(large)");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// App code
Log.e("fb", "cancel ");
LoginManager.getInstance().logOut();
}
#Override
public void onError(FacebookException exception) {
// App code
Log.e("fb", "error " + exception);
LoginManager.getInstance().logOut();
}
});
public class FbLogin extends Activity{
CallbackManager callbackManager;
private static final String NAME = "name";
private static final String ID = "id";
private static final String PICTURE = "picture.type(large)";
private static final String EMAIL = "email";
private static final String FIELDS = "fields";
private static final String REQUEST_FIELDS =
TextUtils.join(",", new String[]{ID, NAME, EMAIL, PICTURE});
Bitmap mIcon1 = null;
String imgUrl = "";
String id = "";
String name = "";
String email = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_type);
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
fetchUserInfo();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
});
btnFb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
LoginManager.getInstance().logInWithReadPermissions(Activity_LoginType.this, Arrays.asList("public_profile", "user_friends","email"));
}
});
}
private void fetchUserInfo() {
final String PERMISSION = "publish_actions";
final AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (accessToken != null) {
GraphRequest request = GraphRequest.newMeRequest(
accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object,
GraphResponse response) {
// TODO Auto-generated method stub
parseUserInfo(object);
}
});
Bundle parameters = new Bundle();
parameters.putString(FIELDS, REQUEST_FIELDS);
request.setParameters(parameters);
GraphRequest.executeBatchAsync(request);
LoginManager.getInstance().logInWithPublishPermissions(
this,
Arrays.asList(PERMISSION));
} else {
}
}
private void parseUserInfo(JSONObject me) {
try {
id = me.getString("id");
name = me.getString("name");
email = me.getString("email");
imgUrl = me.getJSONObject("picture").getJSONObject("data").getString("url");
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
callbackManager.onActivityResult(requestCode, resultCode, data);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and add
FacebookSdk.sdkInitialize(getApplicationContext());
in application class.
and add below code in manifest file
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/fb_id" />
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name"
android:theme="#android:style/Theme.Translucent.NoTitleBar" />

Use HttpClient for login authentication

I am trying to send a POST request to a php file and when the user is asked for login information, if wrong, it prints the json message from the php file and if right, it allows user to login. However, my application crashes, giving a NetworkOnThreadMainException pointing errors to three lines.
HttpResponse response=httpClient.execute(httpPost);
public class LoginActivity extends ActionBarActivity {
login();
So how can i make this possible?
This is some part of the code I have written:
public class LoginActivity extends ActionBarActivity {
EditText et, et2;
ImageButton ib5;
String name,pwd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
et = (EditText) findViewById(R.id.editText);
et2 = (EditText) findViewById(R.id.editText2);
ib5 = (ImageButton) findViewById(R.id.imageButton5);
name=et.getText().toString();
pwd=et2.getText().toString();
final LoginActivity loginActivity=null;
ib5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//login();
new DownloadFilesTask(loginActivity,name,pwd).doInBackground();
}
});
}
public void login() {
new LoginTask(this, et.getText().toString(), et2.getText().toString());
}
private class LoginTask {
public LoginTask(LoginActivity loginActivity, String name, String pwd) {
}
}
void navigatetoMainActivity() {
Intent homeIntent = new Intent(getApplicationContext(), MainActivity.class);
homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
}
void InvalidToast(){
Toast.makeText(getApplicationContext(), "Please enter valid name and password", Toast.LENGTH_LONG).show();
}
void EmptyToast(){
Toast.makeText(getApplicationContext(), "Please fill the form, don't leave any field blank", Toast.LENGTH_LONG).show();
}
}
DownloadFilesTask.java
public class DownloadFilesTask extends AsyncTask<String, String, String> {
private String name, pwd;
private LoginActivity loginActivity;
public DownloadFilesTask(LoginActivity loginActivity,String name, String pwd){
this.loginActivity=loginActivity;
this.name=name;
this.pwd=pwd;
}
#Override
protected String doInBackground(String... strings) {
HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost("login.php");
List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(2);
String result=null;
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("password", pwd));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpResponse response= null;
try {
response = httpClient.execute(httpPost); //error is given here
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity entity=response.getEntity();
InputStream instream= null;
try {
instream = entity.getContent();
} catch (IOException e) {
e.printStackTrace();
}
result=convertStreamToString(instream);
try {
instream.close();
} catch (IOException e) {
e.printStackTrace();
}
if (Utility.isNotNull(name) && Utility.isNotNull(pwd)) {
RequestParams params = new RequestParams();
if (Utility.validate(name, pwd)) {
params.put("username", name);
params.put("password", pwd);
onPostExecute();
} else {
loginActivity.InvalidToast();
}
} else {
loginActivity.EmptyToast();
}
return result;
}
private String convertStreamToString(InputStream instream) {
BufferedReader reader=new BufferedReader(new InputStreamReader(instream));
StringBuilder sb=new StringBuilder();
String line=null;
try {
while ((line=reader.readLine())!=null){
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
instream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
protected void onPostExecute(){
loginActivity.navigatetoMainActivity();
}
private static class Utility {
static Pattern pattern;
static Matcher matcher;
static Pattern pattern1;
static Matcher matcher1;
static String NAME_PATTERN="SuperBoise";
static String PWD_PATTERN="qwerty";
public static boolean validate(String name,String pwd){
pattern=Pattern.compile(NAME_PATTERN);
pattern1=Pattern.compile(PWD_PATTERN);
matcher=pattern.matcher(name);
matcher1=pattern1.matcher(pwd);
return matcher.matches()&& matcher1.matches();
}
public static boolean isNotNull(String name) {
return name!=null && name.trim().length()>0 ? true: false;
}
}
}
Your application has 1 main thread running all the time when it is not paused which is called the UI Thread.
As of the latest versions of Android, you are not permitted to make any network related actions on the UI Thread because it is time-consuming and it blocks the main thread which is responsible for drawing all the UI and registering the clicks, etc. (there is a way to bypass this but it is HIGHLY NOT RECOMMENDED)
An easy way to perform network related actions such as logging in, is the AsyncTask class implemented by Android.
The class runs on a very simple principle, it has 2 methods which run on the UI Thread: the onPreExecute() and the onPostExecute() methods.
And it has a method that runs on a Background Thread which is called the doInBackground() (this is where you should do all your network related actions
Here is a very basic example of an AsyncTask class:
public class DownloadFilesTask extends AsyncTask<void, void, void> {
public DownloadFilesTask(){
// Here you can pass data to the task
// if you want to pass more than 1 type of data
}
protected void onPreExecute(){
// this is executed on the UI Thread
// so you can modify elements inside the UI Thread
// this is called after execute() is called and
// before doInBackground() is called
}
protected void doInBackground(Void... params) {
//here you do all your network related stuff
return null;
}
protected void onPostExecute(Void result) {
// here you can work on the UI Thread
// this is executed after the AsyncTask's execute() is finished
// (after doInBackground() is done)
}
}
And to use this task you can just simply call it from the UI Thread like this:
new DownloadFilesTask().execute();
This is the AsyncTask documentation page on the developer.android.com: AsyncTask
You could pass a reference to your LoginActivity through the constructor of the task and if the login is valid then you can call the navigatetoMainActivity() method from your onPostExecute() inside the task
Edit1: How your LoginActivity should look:
public class LoginActivity extends ActionBarActivity {
EditText et, et2;
ImageButton ib5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
et = (EditText) findViewById(R.id.editText);
et2 = (EditText) findViewById(R.id.editText2);
ib5 = (ImageButton) findViewById(R.id.imageButton5);
ib5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
}
});
}
public void login(){
new LoginTask(this, et.getText().toString(), et2.getText.toString()).execute();
}
}
Edit2: This is how your task should look like:
public class LoginTask extends AsyncTask<void , void, void> {
private String user, password;
private LoginActivity loginActivity;
public LoginTask(LoginActivity loginActivity, String user, String password){
this.loginActivity = loginActivity;
this.user = user;
this.password = password;
}
#Override
protected String doInBackground(Void... params) {
//do all the networking here
}
protected void onPostExecute(Void results){
super.onPostExecute(results);
loginActivity.navigatetoMainActivity();
}
}

How to set progressbar while fetching data from server on click? [duplicate]

This question already has answers here:
Updating progress dialog in Activity from AsyncTask
(2 answers)
How to use AsyncTask to show a ProgressDialog while doing background work in Android? [duplicate]
(2 answers)
Closed 8 years ago.
I want to add progressbar while new activity is not opened.
on next activity I am also fetching data so I want to add a progress bar on next activity also.
Here is my code.
login=(Button)dialog.findViewById(R.id.buttonLogin);
login.setOnClickListener(new OnClickListener() {
#SuppressLint("DefaultLocale")
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(LoginUsername.getText()==null||LoginUsername.getText().toString().equals(""))
{
LoginUsername.setHint("Enter Username");
LoginUsername.setHintTextColor(Color.RED);
}
else if(LoginPassword.getText()==null||LoginPassword.getText().toString().equals("")||LoginPassword.getText().toString().length()<6)
{
LoginPassword.setText("");
LoginPassword.setHint("Enter Password");
LoginPassword.setHintTextColor(Color.RED);
}
else
{
String username=LoginUsername.getText().toString();
String password=LoginPassword.getText().toString();
username1=username.toLowerCase();
// fetch the Password form database for respective user name
//String loginentries=database.getSingleEntry(username1);
//type=database.getType(username1);
try{
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost("http://www.universal-cinemas.com/android/login.php");
JSONObject jobj=new JSONObject();
jobj.put("username",username1);
jobj.put("password", password);
post.setEntity(new StringEntity(jobj.toString()));
Log.i("Info", "Sending request");
HttpResponse res=client.execute(post);
Log.i("Info", "Executed");
InputStream inp=res.getEntity().getContent();
BufferedReader bf = new BufferedReader(new InputStreamReader(inp));
StringBuilder sb= new StringBuilder();
sb.append(bf.readLine()+"\n");
String tmp="0";
while((tmp=bf.readLine())!=null)
{
sb.append(tmp+"\n");
}
String result= sb.toString();
JSONArray jarray=new JSONArray(result);
for(int i=0;i<jarray.length();i++)
{
a=1;
JSONObject job=jarray.getJSONObject(i);
type=job.getString("type");
currency=job.getString("currency");
}
}
catch(Exception e)
{
e.printStackTrace();
}
if(a==1)
{
i=new Intent(getApplicationContext(),User_MainOptions_List.class);
startActivity(i);
finish();
Toast.makeText(getApplicationContext(), "Welcome "+username, Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "Username and Password is not correct", Toast.LENGTH_SHORT).show();
}
}
}
});
dialog.show();
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes(); // retrieves the windows attributes
lp.dimAmount=0.7f;// sets the dimming amount to zero
dialog.getWindow().setAttributes(lp); // sets the updated windows attributes
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND); // adds the flag to blur bg
}
});
class MyLodingAsycTask extends AsyncTask<Void, Void, Void>{
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
runOnUiThread(new Runnable() {
public void run() {
progressDialog = new ProgressDialog(CameraActivity.this);
progressDialog.setMessage("Loding...");
progressDialog.setCancelable(false);
progressDialog.show();
}
});
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
runOnUiThread(new Runnable() {
public void run() {
if(progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
#Override
protected Void doInBackground(Void... params) {
//call HTTP service
return null;
}
}
try this
private class MyAsync extends AsyncTask {
ProgressDialog PD;
#Override
protected void onPreExecute() {
super.onPreExecute();
PD = new ProgressDialog(MainActivity.this);
PD.setTitle("Please Wait..");
PD.setMessage("Loading...");
PD.setCancelable(false);
PD.show();
}
#Override
protected Void doInBackground(Void... params) {
//do what u want
return result;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
PD.dismiss();
}
}
}

Get Android Volley response in another class

I'm trying to use Volley as a DBA layer to call a webservice that hadles JSON objects. Because this layer is below the activity and another service layer, it doesn't seem to be working properly. I'll try to explain my setup:
MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ProductService productService = new ProductService();
productService.getProduct();
}
ProductService.java:
public void getProduct() {
JsonObjectRequest req = new JsonObjectRequest("http://echo.jsontest.com/name/Milk/price/1.23/", null, createMyReqSuccessListener(), createMyReqErrorListener());
ApplicationController.getInstance().addToRequestQueue(req);
}
private Response.Listener<JSONObject> createMyReqSuccessListener() {
return new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.v("response", response.toString());
}
};
}
private Response.ErrorListener createMyReqErrorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
return;
}
};
}
I hope that is clear enough.
In the end, I would like to use the ProductService::getProduct() from an activity and the the actual JSON response from the webservice in a variable which I can later use.
However, at the moment, the line
Log.v("response", response.toString());
doesn't even execute. What am I doing wrong?
What I would try is this:
Declare getProduct as
public void getProduct(Response.Listener<JSONObject> listener,
Response.ErrorListener errlsn) {
JsonObjectRequest req = new JsonObjectRequest("http://echo.jsontest.com/name/Milk/price/1.23/",null, listener, errlsn);
ApplicationController.getInstance().addToRequestQueue(req);
}
And than call in your activity like this:
productService.getProduct(
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
variableFromActivity = response;
//Or call a function from the activity, or whatever...
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Show error or whatever...
}
});
Create an abstract class AppActivity
import androidx.appcompat.app.AppCompatActivity;
public abstract class AppActivity extends AppCompatActivity
{
abstract void callback(String data);
}
Extend all your Activities using AppActivity
public class MainActivity extends AppActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url = "Your URL";
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("Title", "Android Volley Demo");
jsonBody.put("Author", "BNK");
}
catch (JSONException e) {
System.out.println(e);
}
final String requestBody = jsonBody.toString();
Messenger messenger = new Messenger(MainActivity.this);
messenger.sendMessage(this, url, requestBody);
}
public void callback(String data)
{
System.out.println(data);
}
}
Create Messenger class as below:
public class Messenger
{
private AppActivity myActivity;
public Messenger(AppActivity activity)
{
myActivity = activity;
}
public void sendMessage(Context context, String url, final String requestBody)
{
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(context);
// Request a string response from the provided URL.
StringRequest stringRequest =
new StringRequest(
Request.Method.POST,
url,
null,
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
}
) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
}
catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response)
{
myActivity.callback(new String(response.data));
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
queue.add(stringRequest);
}
}
Hope it helps.

Categories