I am just creating a simple signup module. I have written the following code it inserts data but the progress dialog keeps on spinning and it never stops but if I check my database the data is there inserted correctly. I am using volley framework. I am a beginner on Android volley please tell me where I am going wrong.
registration.java
public class registration extends AppCompatActivity {
EditText Name,Email,Username,Password;
ProgressDialog dialog;
ProgressBar progressBar;
String Reg_url="------";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
Name=(EditText)findViewById(R.id.nametext);
Email=(EditText)findViewById(R.id.email);
Username=(EditText)findViewById(R.id.Username);
Password=(EditText)findViewById(R.id.pass);
dialog=new ProgressDialog(this);
dialog.setTitle("Loading");
dialog.setMessage("Please Wait a Momment");
dialog.setCancelable(false);
}
public void SignUp(View view)
{
if(TextUtils.isEmpty(Name.getText().toString()))
{
Name.setError("At least 5 charachters");
}
else if(TextUtils.isEmpty(Email.getText().toString()))
{
Email.setError("Enter a Valid Email");
}
else if(TextUtils.isEmpty(Username.getText().toString()))
{
Username.setError("At least 5 charachters");
}
else if(TextUtils.isEmpty(Password.getText().toString()))
{
Password.setError("At least 5 charachters");
}
else
{
dialog.show();
StringRequest stringRequest=new StringRequest(Request.Method.POST, Reg_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray=new JSONArray(response);
JSONObject jsonObject=jsonArray.getJSONObject(0);
dialog.dismiss();
finish();
startActivity(new Intent(registration.this,MainActivity.class));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(registration.this,"Connection Failed",Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map=new HashMap<String, String>();
map.put("name",Name.getText().toString());
map.put("email",Email.getText().toString());
map.put("user_name",Username.getText().toString());
map.put("password",Password.getText().toString());
return map;
}
};
int socketTimeout= 30000;
RetryPolicy policy=new DefaultRetryPolicy(socketTimeout,DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
}
I have added user permission for internet in the manifest file.
I have volley framework dependency volley 1.1.0.
It shows the onerrorresponse correctly but in response if i apply a toast that won't show either but data is inserted.
My php code is:
<?php
require "connect.php";
$name = $_POST["name"];
$email =$_POST["email"];
$user_name =$_POST["user_name"];
$password =$_POST["password"];
$sql = "INSERT INTO `user_info`(`name`, `email`, `user_name`, `password`) VALUES ('$name','$email','$user_name','$password')";
$result = mysqli_query($con,$sql);
mysqli_close($con);
?>
Change your response block like this
#Override
public void onResponse(String response) {
Toast.makeText(registration.this,"Response :"+response,Toast.LENGTH_SHORT).show();
try {
JSONArray jsonArray=new JSONArray(response);
dialog.dismiss();
finish();
startActivity(new Intent(registration.this,MainActivity.class));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
EDIT : Configure your php code in such a way that it returns a response during a network call. And then parse the response in the app side. Currently your try block is not getting executed due to no response from backend(even if the backend query is executed)
PHP code
<?php
require "connect.php";
$name = $_POST["name"];
$email =$_POST["email"];
$user_name =$_POST["user_name"];
$password =$_POST["password"];
$sql = "INSERT INTO `user_info`(`name`, `email`, `user_name`, `password`) VALUES ('$name','$email','$user_name','$password')";
$result = mysqli_query($con,$sql);
$myArray = array();
if($result){
$myArray = array("status" => "success", 'code' => "200")
} else{
$myArray = array("status" => "failure", 'code' => "400")
}
echo json_encode($myArray);
mysqli_close($con);
?>
Your try/catch block is likely failing. Test to make sure this is the case by a) setting a breakpoint on the try/catch block and running it line by line through the debugger until you find which line is causing the error to be thrown, or b) adding a log statement to the catch block that includes e.getLocalizedMessage() so you can see the error output, or c) just putting dialog.dismiss() in the catch black and see if it goes away. If you get the error message and don't know what it means post it and we'll get to the bottom of it.
Related
I'm creating my splash screen for app. While loading it executes 4 methods. First one checks if Internet permission is granted, second one sends request to API to check if it is Online, third one is getting Token from Firebase and the fourth one is checking if user is already logged-in. I'm doing it using 4 threads. Each method in case of error sets the flag as false. Then when all the threads end their work (I used .join()) The last method checks the state of flag and launch new activity or just display Error and try everything once again.
The problem I have is that I'm getting the view after all the threads finish their work. For example I have black screen, then message ("Error occured") and only after that I can see UI. But on Error the UI is refreshed, so one more time I have black screen, then result and UI for 1sec until another restart.
My question is, can I in some way stop these Threads until my UI is ready ?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
setContentView(R.layout.activity_splash);
checkProgress = findViewById(R.id.checkProgressText);
auth = FirebaseAuth.getInstance();
tokenUtils = new TokenUtils();
requestQueue = Volley.newRequestQueue(getApplicationContext());
animatedCircleLoadingView = findViewById(R.id.circle_loading_view);
//starting the animation
startLoading();
Thread[] checkers = new Thread[4];
checkers[0] = new Thread(this::checkInternetPermissions);
checkers[1] = new Thread(this::checkConnection);
checkers[2] = new Thread(this::getUserAuth);
checkers[3] = new Thread(this::getUserToken);
for (Thread t : checkers) {
try {
t.start();
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
changeActivity();
}
Check internet permission method:
private void checkInternetPermissions() {
checkProgress.setText(getString(R.string.check_internet_permissions_text));
if (ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET)
!= PackageManager.PERMISSION_GRANTED)
requestPermissions(new String[]{Manifest.permission.INTERNET}, 1);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode != 1) {
connectionFlag = false;
}
}
Check connection method:
private void checkConnection() {
checkProgress.setText(getString(R.string.checking_api_connection));
RequestFuture<String> requestFuture = RequestFuture.newFuture();
StringRequest request = new StringRequest
(Request.Method.GET, API_CHECK,
requestFuture,
requestFuture);
requestQueue.add(request);
String response = null;
try {
response = requestFuture.get(5, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
this.connectionFlag = false;
}
if (!Objects.equals(response, "ok"))
this.connectionFlag = false;
}
Get user token method:
private void getUserToken() {
checkProgress.setText(getString(R.string.getting_user_auth_token));
String token = null;
try {
token = tokenUtils.getFirebaseToken();
} catch (ExecutionException | InterruptedException e) {
this.connectionFlag = false;
}
if (Objects.isNull(token) || Objects.requireNonNull(token).isEmpty())
this.connectionFlag = false;
}
And finally get user auth method:
private void getUserAuth() {
checkProgress.setText(getString(R.string.checking_user_auth));
authStateListener = firebaseAuth -> {
firebaseUser = firebaseAuth.getCurrentUser();
if (Objects.isNull(firebaseUser) || Objects.requireNonNull(firebaseUser.getEmail()).isEmpty()) {
this.authFlag = false;
}
};
}
Last method which handle the states of flags:
private void changeActivity() {
checkProgress.setText(getString(R.string.finalizing_text_progress));
if (connectionFlag && authFlag) {
startActivity(new Intent(SplashActivity.this, MapActivity.class));
} else if (!connectionFlag) {
Toast.makeText(getApplicationContext(), "Error occurred.", Toast.LENGTH_LONG).show();
finish();
startActivity(getIntent());
} else {
startActivity(new Intent(SplashActivity.this, LoginActivity.class));
}
}
Yes, You can try it with handler thread with some delay then it will work fine or you can start your thread on onResume() method at the time of onResume your view will have been created
I think, your way wrong. Because, API request working on asynchronous. Your app should run like this;
Check Internet connection.
API Request.
Get token in API Request onSuccess method.
Get User Auth.
I think, you shouldn't use Thread.
In my app, when I press a button, a buffered reader should read a line of a text from a text file online.
As a test, if the text is read correctly, I want a toast to appear saying "success". If the read fails, such as because the phone has no connection to the internet, I want a toast to appear saying "failed".
However, if I turn on airplane mode, and then press the button, it simply seems to "hang" forever, and the "failed" toast never appears -- or it just crashes the app entirely.
This is the code I am using:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new NotePadFileFromServer().execute();
}
});
public class NotePadFileFromServer extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
try {
url = new URL(TextFileURL);
bufferReader = new BufferedReader(new InputStreamReader(url.openStream()));
TextHolder = bufferReader.readLine();
bufferReader.close();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Fail!", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(Void finalTextHolder) {
Toast.makeText(MainActivity.this, "Success!", Toast.LENGTH_SHORT).show();
super.onPostExecute(finalTextHolder);
}
}
I tried adding in a pre-check using ConnectivityManager to test if there is an internet connection as per this code: https://stackoverflow.com/a/58146646/4250107, but that only works if the phone user has specifically turned off the internet, and the crashes occur again if the wifi function is turned on, but there is no internet. I then tried checking the internet connection, as per this code: https://stackoverflow.com/a/58146896/4250107, but this also crashes the app, as apparently (?) attempting to ping a server does not work on Samsung phones.
EDIT: Final fixed code.
public class NotePadFileFromServer extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... params) {
try {
URLConnection url = new URL(TextFileURL).openConnection());
url.setConnectTimeout(1000);
url.setReadTimeout(1000);
bufferReader = new BufferedReader(new InputStreamReader(url.getInputStream()));
TextHolder = bufferReader.readLine();
bufferReader.close();
return "Success!";
} catch (Exception e) {
return "Fail!";
}
}
#Override
protected void onPostExecute(String success) {
Toast.makeText(MainActivity.this, success, Toast.LENGTH_SHORT).show();
super.onPostExecute(success);
}
}
The app is crashing because you are trying to perform UI related task in the Background Thread when there is an exception. So, the following is responsible for the crash,
catch (Exception e) {
Toast.makeText(MainActivity.this, "Fail!", Toast.LENGTH_SHORT).show();
}
So, you can avoid the crash by refactoring you code in the following way,
public class NotePadFileFromServer extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... params) {
try {
url = new URL(TextFileURL);
bufferReader = new BufferedReader(new InputStreamReader(url.openStream()));
TextHolder = bufferReader.readLine();
bufferReader.close();
return "Success!";
} catch (Exception e) {
return "Fail!";
}
}
#Override
protected void onPostExecute(String finalTextHolder) {
Toast.makeText(MainActivity.this, finalTextHolder, Toast.LENGTH_SHORT).show();
super.onPostExecute(finalTextHolder);
}
}
And in case of timeout issue which you described here as hang, I would recommend you to use openConnection() (which returns a UrlConnection) instead of openStream(). So that you can set shorter connection and read timeout.
Yes, as you say ConnectivityManager will not help you because if you have wifi but no internet it will crash.
However, it is possible to check internet connection. I couldn't do it with ping (same as you), but i could when i try to open a socket to some of the opened ports (80 or 443). Here is a code using rxjava but you can adapt it to what you are using.
fun isOnline(context: Context?): Single<Boolean> {
return Single.fromCallable {
try {
// Connect to Google DNS to check for connection
val timeoutMs = 2500
val socket = Socket()
val address = InetAddress.getByName("www.google.com")
val socketAddress = InetSocketAddress(address, 443)
socket.connect(socketAddress, timeoutMs)
socket.close()
true
} catch (e: Exception) {
false
}
}.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
In my case i opened the socket with my backend so also i can check if it is working. I put www.google.com in case you don't have a backend.
The way to use it is:
isOnline(context).subscribe { hasInternet ->
//Conditional check
}
im new to android and php languages. I want to add point for students upon clicking a button in android. My database table is 'user' and my column that i want it to be updated is 'point'.
I tried to use this code for point.php that will be activate in onclick button in android.
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$point = $_POST['point_add'];
$myVar = $point;
var_dump($myVar);
$myVar= $myVar += 1;
var_dump($myVar);
//importing database connection script
require "init.php";
//Creating sql query
$sql = "UPDATE user SET point = '$point' WHERE id = $id;";
//Updating database table
if(mysqli_query($con,$sql)){
echo 'Data Updated Successfully';
}else{
echo 'Could Not Update Data Try Again';
}
//closing connection
mysqli_close($con);
}
?>
this is my init.php
<?php
error_reporting(0);
$db_name = "mymerit";
$mysql_user = "root";
$mysql_pass = "root";
$server_name = "localhost";
$con = mysqli_connect($server_name, $mysql_user, $mysql_pass, $db_name);
if(!$con){
echo '{"message":"Unable to connect to the database."}';
}
?>
and this is my point.java in android
public class Point extends Activity implements View.OnClickListener{
String Err;
TextView err;
Button badd;
Context ctx=this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.point);
badd = (Button) findViewById(R.id.point_add);
err = (TextView) findViewById(R.id.err);
Err = getIntent().getStringExtra("err");
badd.setOnClickListener(this);
err.setText(Err);
}
public void onClick(View v){
BackGround b = new BackGround();
Intent intent = new Intent(this, Thanks.class);
startActivity(intent);
}
class BackGround extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String point = params[0];
String data="";
int tmp;
try {
URL url = new URL("http://192.168.1.12/android/point.php");
String urlParams = "point="+point;
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(urlParams.getBytes());
os.flush();
os.close();
InputStream is = httpURLConnection.getInputStream();
while((tmp=is.read())!=-1){
data+= (char)tmp;
}
is.close();
httpURLConnection.disconnect();
return data;
} catch (MalformedURLException e) {
e.printStackTrace();
return "Exception: "+e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "Exception: "+e.getMessage();
}
}
#Override
protected void onPostExecute(String s) {
if(s.equals("")){
s="Data saved successfully.";
}
Toast.makeText(ctx, s, Toast.LENGTH_LONG).show();
}
}
}
There's no error and the android's working fine. but my point is not updated to 1. Is my code wrong somewhere?
Is the point.php the actual file? Because there is a lot wrong there. You defined the variable $sql 3 times, first two don't have any effect on the code. I assume it's a snipped because you used variables that haven't been defined in the files, could you please clean up point.php? If this is actually the entire file try removing that error_reporting(0) and work your way through the errors.
If i've understood properly, you want to add counter each click of button and push it into the database. So you could use sharedPref or simple do this, int counter =0,
OnClick of button counter += 1;
then you can push counter value in the database, Same you can try with string :)
I'm trying to make a register page for my android app.
I have managed to create a login page and I'm now trying to get the register page to work.
I've managed to get the data I'm sending via the register page into the database. I'm using a php script to transfer the data into my mysql database.
But every time I register, it sends the data and gives the echo back saying that the username/mail already exists.
It also shows this error in Java: Invalid use of SingleClientConnManager: connection still allocated.
I've been trying to fix this for hours but can't find anything that helps.
This is my database:
id - primary key AI
mail - unique
password
username - unique
This is my php script
<?php
$hostname_memolink = "localhost";
$database_memolink = "memolink";
$username_memolink = "android";
$password_memolink ="f3.W2TmM}8yO";
$memolink = mysql_connect($hostname_memolink, $username_memolink, $password_memolink) or trigger_error(mysql_error(), E_USER_ERROR);
mysql_select_db($database_memolink, $memolink);
$mail = $_POST['mail'];
$password = $_POST['password'];
$username = $_POST['username'];
if (trim($password) == "" or trim($username) == "" or trim($mail) == "")
{
echo "variables are null";
exit;
}
else
{
$resultUsername = mysql_query("SELECT * FROM tbl_user WHERE username='$username'");
$resultMail = mysql_query("SELECT * FROM tbl_user WHERE mail='$mail'");
$num_rows_username = mysql_num_rows($resultUsername);
$num_rows_mail = mysql_num_rows($resultMail);
if ($num_rows_username >= 1 && $num_rows_mail >= 1) {
echo "username or email already exists";
die();
}
else
{
mysql_query("INSERT INTO tbl_user (id, mail, password, username) VALUES('', '$mail', '$password', '$username')") or die(mysql_error());
echo "registration complete";
}
}
?>
This is my Java method which sends the data to my php file:
HttpPost httpPost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpClient;
List<NameValuePair> registerData;
public void register(){
try{
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://www.memo-link.be/php/register.php");
registerData = new ArrayList<NameValuePair>(2);
EditText mailBox = (EditText) findViewById(R.id.mail_box);
EditText userBox = (EditText) findViewById(R.id.username_box);
EditText passBox = (EditText) findViewById(R.id.password_box);
String mail = mailBox.getText().toString();
String username = userBox.getText().toString();
String password = passBox.getText().toString();
registerData.add(new BasicNameValuePair("mail", mail));
registerData.add(new BasicNameValuePair("username", username));
registerData.add(new BasicNameValuePair("password", password));
httpPost.setEntity(new UrlEncodedFormEntity(registerData));
response = httpClient.execute(httpPost); //send data to Internet
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpClient.execute(httpPost, responseHandler);
System.out.println("Response : " + response.toString());
if (response.equalsIgnoreCase("username or email already exists")){
runOnUiThread(new Runnable(){
public void run(){
dialog.dismiss();
}
});
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(250);
Toast toast = Toast.makeText(RegisterActivity.this, "Username already exists!", Toast.LENGTH_SHORT);
toast.show();
}else if(response.toString().equalsIgnoreCase("username or email already exists")){
runOnUiThread(new Runnable(){
public void run(){
dialog.dismiss();
}
});
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(250);
Toast toast = Toast.makeText(RegisterActivity.this, "Mail address already in use!", Toast.LENGTH_SHORT);
toast.show();
}else if(response.toString().equalsIgnoreCase("registration complete")){
runOnUiThread(new Runnable(){
public void run(){
Toast toast = Toast.makeText(RegisterActivity.this, "Registration Succesfull", Toast.LENGTH_SHORT);
toast.show();
}
});
startActivity(new Intent(RegisterActivity.this, DashboardActivity.class));
}
runOnUiThread(new Runnable(){
public void run(){
dialog.dismiss();
}
});
}catch (Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
Thanks in advance
Please see this, if this might help you. Let us know if you need more help.
Android: Invalid use of SingleClientConnManager: connection still allocated
Also, in your code, you are executing the query twice, which on the first time executes normally and as soon as it gets second query (as your data is already inserted), this satisfies the condition and prints the error message. Hope this will help.
I am writing an android application to get the Facebook user albums and photos and display in my Android application.
I have created a Facebook App with APP_ID 281846961912565.
While creating the Facebook instance, I am passing this id as follows
facebook = new Facebook(APP_ID);
Using this instance, I am able to login to my FB account post on messages on facebook wall programatically.
After logging in, I get an access_token.
I'm using the access token to get the album ids using facebook.request("https://graph.facebook.com/me/albums?access_token="+facebook.getAccessToken());
Now I get {"error":{"message":"Malformed access token ACCESSTOKENACCESSTOKEN?access_token=ACCESSTOKENACCESSTOKEN","type":"OAuthException","code":190}}
Can any of you please help me resolve this issue and point out what i am doing wrong.
My code is as follows:
private static final String[] PERMISSIONS = new String[] { "publish_stream","user_photos" };
public boolean saveCredentials(Facebook facebook) {
Editor editor = getApplicationContext().getSharedPreferences(KEY,
Context.MODE_PRIVATE).edit();
editor.putString(TOKEN, facebook.getAccessToken());
editor.putLong(EXPIRES, facebook.getAccessExpires());
return editor.commit();
}
public boolean restoreCredentials(Facebook facebook) {
SharedPreferences sharedPreferences = getApplicationContext()
.getSharedPreferences(KEY, Context.MODE_PRIVATE);
facebook.setAccessToken(sharedPreferences.getString(TOKEN, null));
facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0));
return facebook.isSessionValid();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
facebook = new Facebook(APP_ID);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.facebook_dialog);
String facebookMessage = getIntent().getStringExtra("facebookMessage");
if (facebookMessage == null) {
facebookMessage = "Test wall post";
}
messageToPost = facebookMessage;
}
R.layout.facebook_dialog is the dialog which pops up asking if a message should be shared on facebook or not. If yes the following method is called.
public void share(View button) {
if (!facebook.isSessionValid()) {
loginAndPostToWall();
} else {
postToWall(messageToPost);
}
}
public void loginAndPostToWall() {
facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH,
new LoginDialogListener());
}
class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
saveCredentials(facebook);
if (messageToPost != null) {
postToWall(messageToPost);
}
}
public void onFacebookError(FacebookError error) {
showToast("Authentication with Facebook failed!");
finish();
}
public void onError(DialogError error) {
showToast("Authentication with Facebook failed!");
finish();
}
public void onCancel() {
showToast("Authentication with Facebook cancelled!");
finish();
}
}
public void postToWall(String message) {
Bundle parameters = new Bundle();
parameters.putString("message", message);
parameters.putString("description", "topic share");
try {
facebook.request("me");
String response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("")
|| response.equals("false")) {
showToast("Blank response.");
} else {
showToast("Message posted to your facebook wall!");
}
getImagesFromUserAlbum();
finish();
} catch (Exception e) {
showToast("Failed to post to wall!");
e.printStackTrace();
finish();
}
}
Later when I do a `private void getImagesFromUserAlbum() {
facebook.getAccessToken();
JSONArray albumss = null;
String response = null;
try {
response = facebook.request("me/albums");
// `
I get the error
{"error":{"message":"Malformed access token ACCESSTOKEN?access_token=ACCESSTOKEN","type":"OAuthException","code":190}}
Thanks for your help.
The code above is now the working copy. Thanks to Bartek.
If you look at the Errors page in the documentation you will see that when you get error 190 you should authorise/reauthorise the user.
I suspect that this happened to you because you first logged in, then added the permissions to access the albums to your application BUT did not log out and log back in. Hence, you need to obtain a new access token which will grant the new permissions to your application.
Please check is there &expires in your access token if yes then remove it because it is not part of access_token and try after that.