Hello my code makes a simple http request and returns a json. My Code works fine but when i try to extend AppCompatActivity (because i want to show the json on device screen) it gaves me multiple errors my code is below
package com.vogella.java.library.okhttp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.IOException;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import org.json.JSONException;
import org.json.JSONObject;
public class TestMain extends AppCompatActivity {
OkHttpClient client = new OkHttpClient();
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
String doPostRequest(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
public static void main(String[] args) throws IOException, JSONException {
String username = "test";
String password = "123";
TestMain example = new TestMain();
String json = "";
String postResponse = example.doPostRequest("http://86.145.89.53:8080/authentication_service-dev/authenticate?username=" + username + "&password=" + password, json);
int counter = postResponse.length();
if (counter == 14) {
System.out.println("Your username or password is invalid!!");
}
if (counter > 1000) {
System.out.println("HTTP Status 401 – Unauthhorized");
}
if (counter < 1000 && counter > 14) {
System.out.println("Welcome!!");
}
}}
the errors are :
Exception in thread "main" java.lang.RuntimeException: Stub!
at android.content.Context.<init>(Context.java:20)
at android.content.ContextWrapper.<init>(ContextWrapper.java:21)
at android.view.ContextThemeWrapper.<init>(ContextThemeWrapper.java:21)
at android.app.Activity.<init>(Activity.java:22)
at android.support.v4.app.SupportActivity.<init>(SupportActivity.java:31)
at android.support.v4.app.BaseFragmentActivityGingerbread.<init>(BaseFragmentActivityGingerbread.java:37)
at android.support.v4.app.BaseFragmentActivityHoneycomb.<init>(BaseFragmentActivityHoneycomb.java:29)
at android.support.v4.app.BaseFragmentActivityJB.<init>(BaseFragmentActivityJB.java:30)
at android.support.v4.app.FragmentActivity.<init>(FragmentActivity.java:79)
at android.support.v7.app.AppCompatActivity.<init>(AppCompatActivity.java:61)
at com.vogella.java.library.okhttp.TestMain.<init>(TestMain.java:18)
at com.vogella.java.library.okhttp.TestMain.main(TestMain.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
You don't use public static void main in Android dev. In the activity, you use onCreate:
#Override
public void onCreate(Bundle sis){
super.onCreate(sis);
//Move the contents of "public static void main" here
}
And delete public static void main when you have moved the code.
Android activities must have onCreate() method, when you extend any class with AppCompactAcitvity it must implement some methods
Change your code, remove main method, add onCreate() and do stuff there.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_acremote);
}
Have a look at activities life cycle Link.
Related
I am having a problem with the API that I have implemented to my website that is connected to an activity in the Android application that I am developing. According to the Logcat of my Android Studio,
that line 118 of the ForgotPassword.java of my Android application
is throwing the java.lang.AssertionError. I have studied the problem again, then learned that the response of the API that is implemented on my website is being read by my Android application as null, thus with the aforementioned error.
I have also tried to solve the problem by doing the following:
Created a separate response class called ForgotPassRP with the same variables, because the DataRP response class is being used by other classes.
Updated the version of the retrofit that is implemented in my
build.grade(:app) from 2.7.2 to 2.9.0 and the retrofit2:converter-gson from 2.5.0 to 2.9.0.
Currently, I am still finding a solution by digging more about REST APIs on websites and Retrofit on Android, and I will implement anything new that I can learn from these. So am I missing something on my website, and Android code, or are there variables that are missing, while I am trying to do a POST method to the API that I have implemented to my website?
These are the following body of codes that I have analyzed so far that are connected to the problem (java.lang.AssertionError) that I am encountering on my Android application
The screenshot of the actual error that is being shown in the Logcat of my Android Studio:
Website:
1. APIS.php
//This is where the #POST method from my Android application API interface of the "ForgotPassword.java" is communicating with
public function forgot_password_post()
{
$response = array();
$user_info = $this->common_model->check_email($this->get_param['email'])[0];
if (!empty($user_info))
{
$this->load->helper("rendomPassword");
$info['new_password'] = get_random_password();
$updateData = array(
'user_password' => md5($info['new_password'])
);
$data_arr = array(
'email' => $user_info->user_email,
'password' => $info['new_password']
);
if ($this->common_model->update($updateData, $user_info->id, 'tbl_users')) {
$subject = $this->app_name . ' - ' . $this->lang->line('forgot_password_lbl');
$body = $this->load->view('admin/emails/forgot_password.php', $data_arr, TRUE);
if (send_email($user_info->user_email, $user_info->user_name, $subject, $body))
{
$row_info = array('success' => '1', 'msg' => $this->lang->line('password_sent_mail'));
}
else
{
$row_info = array('success' => '0', $this->lang->line('email_not_sent'));
}
}
}
else
{
$row_info = array('success' => '0', 'msg' => $this->lang->line('email_not_found'));
}
$this->set_response($row_info, REST_Controller::HTTP_OK);
}
Android Application
1. ForgotPassword.java
package com.example.mototecxecommerceapp.activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.mototecxecommerceapp.R;
import com.example.mototecxecommerceapp.response.DataRP;
import com.example.mototecxecommerceapp.response.ForgotPassRP;
import com.example.mototecxecommerceapp.rest.ApiClient;
import com.example.mototecxecommerceapp.rest.ApiInterface;
import com.example.mototecxecommerceapp.util.API;
import com.example.mototecxecommerceapp.util.ConstantApi;
import com.example.mototecxecommerceapp.util.Method;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.jetbrains.annotations.NotNull;
import io.github.inflationx.viewpump.ViewPumpContextWrapper;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class ForgetPassword extends AppCompatActivity {
private Method method;
private TextInputEditText editText;
private ProgressDialog progressDialog;
private InputMethodManager imm;
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(ViewPumpContextWrapper.wrap(newBase));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fp);
method = new Method(ForgetPassword.this);
method.forceRTLIfSupported();
progressDialog = new ProgressDialog(ForgetPassword.this);
imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
MaterialToolbar toolbar = findViewById(R.id.toolbar_fp);
toolbar.setTitle(getResources().getString(R.string.forget_password));
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
editText = findViewById(R.id.editText_fp);
MaterialButton button = findViewById(R.id.button_fp);
button.setOnClickListener(v -> {
String string_fp = editText.getText().toString();
editText.setError(null);
if (!isValidMail(string_fp) || string_fp.isEmpty()) {
editText.requestFocus();
editText.setError(getResources().getString(R.string.please_enter_email));
} else {
editText.clearFocus();
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
if (method.isNetworkAvailable()) {
forgetPassword(string_fp);
} else {
method.alertBox(getResources().getString(R.string.internet_connection));
}
}
});
}
private boolean isValidMail(String email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
public void forgetPassword(String sendEmail) {
progressDialog.show();
progressDialog.setMessage(getResources().getString(R.string.loading));
progressDialog.setCancelable(false);
JsonObject jsObj = (JsonObject) new Gson().toJsonTree(new API(ForgetPassword.this));
jsObj.addProperty("email", sendEmail);
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<DataRP> call = apiService.getForgotPass(API.toBase64(jsObj.toString()));
call.enqueue(new Callback<DataRP>() {
#Override
public void onResponse(#NotNull Call<DataRP> call, #NotNull Response<DataRP> response) {
try {
DataRP dataRP = response.body();
assert dataRP != null; //This is the part of the code where the java.lang.AssertionError is being thrown.
if (dataRP.getStatus().equals("1")) {
if (dataRP.getSuccess().equals("1")) {
editText.setText("");
}
method.alertBox(dataRP.getMsg());
} else {
method.alertBox(dataRP.getMessage());
}
} catch (Exception e) {
Log.d(ConstantApi.exceptionError, e.toString());
method.alertBox(getResources().getString(R.string.failed_response));
}
progressDialog.dismiss();
}
#Override
public void onFailure(#NotNull Call<DataRP> call, #NotNull Throwable t) {
// Log error here since request failed
Log.e(ConstantApi.failApi, t.toString());
progressDialog.dismiss();
method.alertBox(getResources().getString(R.string.failed_response));
}
});
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
2. ApiInterface.java
//This is the post method that is being sent to the forgot password API of my website.
#POST("apis/forgot_password")
#FormUrlEncoded
Call<DataRP> getForgotPass(#Field("data") String data);
3. DataRP.java
package com.example.mototecxecommerceapp.response;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
//This is the response from the #POST method.
public class DataRP implements Serializable {
#SerializedName("status")
private String status;
#SerializedName("message")
private String message;
#SerializedName("success")
private String success;
#SerializedName("msg")
private String msg;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
I am also including the screenshot of the API logs that are being stored in the database that I have integrated into my website. This part is what seems to be the response of the "apis/forgot_password", whenever a post method that is thrown by my Android application is executed.
The SQL database of my website showing the logs related to "apis/forgotpassword"
This is also my first time asking a question in StackOverflow. So please bear with any "rookie mistakes" with the format/structure of the question that I have posted :)
In the android application development most used Retrofit2 Retrofit2 Documention
Then Generate Response Model Class (Call API using Postman). Create a Response Model with JSON
Source type:> JSON. Annotation style:>Gson.
Use this code in the "onResponse" method section.
if (response.isSuccessful()) {
if (response.body() != null) {
DataRP dataRp=response.body();
//code statement... } }
I am making a Discord JDA bot that can when a user sends the message: Prefix("$") + hastebin + their code, the bot will create a request to hastebin and paste their code, after that he will take the paste URL and print it to the console(I will send it as a message after I solve the problem).
This is my HastebinCommand class:
package events;
import main.Hastebin;
import Info.Info;
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
import java.lang.*;
public class HastebinCommand extends ListenerAdapter
{
Info info;
Hastebin hastebin;
#Override
public void onGuildMessageReceived(GuildMessageReceivedEvent event)
{
String[] message = event.getMessage().getContentRaw().split(" ");
if (message[0].equalsIgnoreCase(info.prefix + "hastebin") || message[0].equalsIgnoreCase(info.prefix + "haste"))
{
if (message.length == 1)
{
//Send an error message
}
else
{
String code = "";
for (int i = 1; i < message.length; i++)
{
code = code + "" + message[i];
}
System.out.println(hastebin.paste(code));
}
}
}
}
This is my Hastebin request class:
package main;
import org.json.JSONObject;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Hastebin
{
public static String paste(String content) throws Exception{
final HttpClient client = HttpClient.newHttpClient();
final HttpRequest request = HttpRequest.newBuilder(URI.create("https://hastebin.com/documents"))
.POST(HttpRequest.BodyPublishers.ofString(content)).build();
final HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
final String responseContent = response.body();
final JSONObject responseJson = new JSONObject(responseContent);
final String key = responseJson.getString("key");
return "https://hastebin.com/" + key;
}
}
My error:
C:\Users\user\Documents\Java\Java Projects\DiscordJDA\SpoonfeedingBot\src\events\HastebinCommand.java
Error:(32, 50) java: unreported exception java.lang.Exception; must be caught or declared to be thrown
I would really appreciate getting help after trying to solve my problem for so long.
Some function you're using is throwing an exception that must be dealt with (checked exception). Whenever you have a problem with an exception you should google the exception first. For example, in this case, you could paste "unreported exception java.lang.Exception; must be caught or declared to be thrown" in google search engine and you'd get your explanation.
Here's a tutorial on Exceptions: https://www.tutorialspoint.com/java/java_exceptions.htm
Also, your StackOverflow post should be about the error itself, in other words "unreported exception java.lang.Exception".
I am trying to query an API to get the JSON response and store the response in an ArrayList.
This ArrayList will be later used for setting up a RecyclerView.
I am getting the response if I Log in the OnResponse() method from OkHttp. But when I am receiving the response in my Fragment as a String via the return in the OkhttpHandler then the string value is being received as null
Here's the code
OkHttpHelper.Java
package com.execube.genesis.utils;
import android.util.Log;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by Prateek Phoenix on 4/24/2016.
*/
public class OkHttpHandler {
private String queryUrl;
private String jsonData;
private static final String TAG = "CustomTAG1";
public OkHttpHandler(String Url) {
this.queryUrl = Url;
}
public String fetchData() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(queryUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.v(TAG, "Exception: ", e);
}
#Override
public void onResponse(Call call, Response response) throws IOException {
Log.v(TAG, response.body().string());
if (response.isSuccessful()) {
jsonData = response.body().string();
}
}
});
return jsonData; //Even this is null when I check via Debugger
}
}
PopularMoviesFragment.java
package com.execube.genesis.views;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import com.execube.genesis.R;
import com.execube.genesis.model.Movie;
import com.execube.genesis.utils.API;
import com.execube.genesis.utils.OkHttpHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by Prateek Phoenix on 4/24/2016.
*/
public class PopularMoviesFragment extends Fragment {
private static final String TAG = "CustomTAG";
private ArrayList<Movie> mMovies;
private String jsonResponse;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
mMovies=new ArrayList<>();
String url= API.BASE_URL+API.API_KEY+API.SORT_POPULARITY;
OkHttpHandler handler= new OkHttpHandler(url);
jsonResponse=handler.fetchData();
try {
mMovies= parseItems(jsonResponse);
} catch (JSONException e) {
Log.v(TAG,"Exception caught: ",e);
}
super.onCreate(savedInstanceState);
}
private ArrayList<Movie> parseItems( String jsonResponse) throws JSONException{
JSONObject jsonData= new JSONObject(jsonResponse);
JSONArray moviesJSONArray= jsonData.getJSONArray("results");
ArrayList<Movie> Movies= new ArrayList<>();
for (int i = 0; i <moviesJSONArray.length() ; i++) {
Movie movie= new Movie();
JSONObject movieJson= moviesJSONArray.getJSONObject(i);
movie.setId(movieJson.getInt("id"));
Log.v(TAG,"TITLE IS "+movieJson.getString("title"));
movie.setOriginalTitle(movieJson.getString("original_title"));
movie.setOverview(movieJson.getString("overview"));
movie.setPosterPath(movieJson.getString("poster_path"));
movie.setVoteAverage((float) movieJson.getDouble("vote_average"));
movie.setTitle(movieJson.getString("title"));
Movies.add(movie);
}
return Movies;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_popular_movies,container,false);
return view;
}
}
API.java for building the url
package com.execube.genesis.utils;
/**
* Created by Prateek Phoenix on 4/24/2016.
*/
public class API {
public static String BASE_URL = "http://api.themoviedb.org/3/discover/movie?";
public static String MOVIE_BASE_URL = "http://api.themoviedb.org/3/movie/";
public static String API_KEY = "api_key=a98debe57ccd9b42fe6b99b9014c80e3";
public static String SORT_POPULARITY = "&sort_by=popularity.desc";
public static String SORT_R_RATED = "&certification_country=US&certification=R&sort_by=vote_average.desc&vote_count.gte=250";
public static String IMAGE_URL = "http://image.tmdb.org/t/p/";
public static String IMAGE_SIZE_185 = "w500";
}
Here's the URL that I am querying http://api.themoviedb.org/3/discover/movie?api_key=a98debe57ccd9b42fe6b99b9014c80e3&sort_by=popularity.desc
Call#enqueue is OkHttp's asynchronous API. This means the request will be handled on a background thread and the calling thread will continue to run with OR without running the callback.
To use the data you either need to use some form of Future (Guava's ListenableFuture or RxJava might work) to respond to the eventual availability of the data or use Call#execute() instead of Call#enqueue to do the call in a synchronous way.
The thing is, you're accessing the variable jsonData before the network operation can finish and put something in it.
Which is very unlikely to happen.
Use something like an Event Bus (I like Green Robot's), and post an event when the jsonData has something, right after the line jsonData = response.body().string();
And listen to this event in your UI fragment, and populate data once you receive this event.
Till then, keep showing the progress dialog/UI.
This way your code will remain async and you'll get this done as well
Ive been doing this tutorial using Android Studio IDE.
The problem I have is that the tutorial was done with older libraries of gson and retrofit 1.8.0...
I was following along well with retrofit2.0-beta3 until I came upon this error that I cant seem to resolve..
It has something to do with this line...(this line is in my MainActivity.Java under onCreate())
SCService scService = SoundCloud.getService();
scService.getRecentTracks(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()), new Callback<List<Track>>() {
#Override
public void onResponse(Response<List<Track>> tracks) {
Log.d("TAG", "ONRESPONSE() - -- - some else wrong");
// response.isSuccess() is true if the response code is 2xx
if (tracks.isSuccess()) {
Log.d("TAG", "ONRESPONSE()_isSuccess? - -- - some else wrong");
List<Track> track = tracks.body();
loadTracks(track);
} else {
Log.d("TAG", "some else wrong");
}
}
#Override
public void onFailure(Throwable t) {
// handle execution failures like no internet connectivity
Log.d("Error", t.getMessage());
}
});
so I think that the problem starts with scService Interface..
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.http.GET;
import retrofit2.http.Query;
interface SCService {
#GET("tracks?client_id=" + Config.CLIENT_ID)
public void getRecentTracks(#Query("created_at[from]") String date, Callback<List<Track>> cb);
}
Here is my Soundcloud class....
import retrofit2.Retrofit;
import retrofit2.Retrofit;
public class SoundCloud {
private static final Retrofit REST_ADAPTER = new Retrofit.Builder().baseUrl(Config.API_URL).build();
private static final SCService SERVICE = REST_ADAPTER.create(SCService.class);
public static SCService getService() {
return SERVICE;
}
}
This is the Config class didnt think it would be needed...
public class Config {
public static final String CLIENT_ID = "c85f6828ae5eaf5981937ead09ef1b45";
public static final String API_URL = "https://api.soundcloud.com/";
}
I have been at this the whole day, Any help would be much appreciated..
It could be few things, but most likely the problem is that Gson converter is no longer automatically registered with retrofit and thus your code doesn't know how to get you object from Json. I.e. in retrofit2 you need to register Gson like:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://api.nuuneoi.com/base/")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
Take a look at this article: Retrofit 2 changes, Custom Gson Object (in the middle of the page)
I'm using Volley in an Android App to fetch data from the Misfit API (http://build.misfit.com). I tried to construct an intermittent activity, after someone logged in, to get all the data from the API. In that activity, I perform a JsonObject GET request, that should give me some information about the user of the app. Here's the code so far:
package com.iss_fitness.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import learn2crack.weboauth2.R;
public class LoadingScreenActivity extends Activity {
//Introduce an delay
private final int WAIT_TIME = 500;
private static final String QUERY_URL = "https://api.misfitwearables.com/move/resource/v1/user/me/profile";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
System.out.println("LoadingScreenActivity screen started");
setContentView(R.layout.loading_screen);
findViewById(R.id.mainSpinner1).setVisibility(View.VISIBLE);
// Instantiate the RequestQueue.
final RequestQueue queue = Volley.newRequestQueue(this);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
executeJson();
System.out.println("Going to Profile Data");
/* Create an Intent that will start the ProfileData-Activity. */
Intent mainIntent = new Intent(LoadingScreenActivity.this, DataView.class);
LoadingScreenActivity.this.startActivity(mainIntent);
LoadingScreenActivity.this.finish();
}
}, WAIT_TIME);
}
private Response.ErrorListener createRequestErrorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
};
}
private void executeJson() {
SharedPreferences prefs = this.getSharedPreferences("AppPref", MODE_PRIVATE);
final String token = prefs.getString("token", null);
RequestQueue queue = Volley.newRequestQueue(this);
Map<String, String> params = new HashMap<String, String>();
System.out.println(token);
params.put("access_token", token);
CustomRequest jsonRequest = new CustomRequest(Request.Method.GET, QUERY_URL, params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response);
}
}, this.createRequestErrorListener());
System.out.println(jsonRequest);
queue.add(jsonRequest);
}
}
I'm quite new to Android development, so please bear with me, I'll try to describe the code. I've implemented a help class as suggested for JsonObjectRequest, as, as I understood, you can't override the getparams method when defining a request locally. the executeJson() method is the interesting one: I get the user access token from my SharedPreferences (Where it's correctly stored), put that in a String Map and give that to the CustomRequest, where, inside the help class, it gets thrown into a getparams method that simply returns the params. The responselistener sadly never gets called, as the errorlistener reports the following:
com.android.volley.NoConnectionError: java.io.IOException: No authentication challenges found
According to the API reference of Misfit, that should work.
Now, I know that a GET request requires "headers" and not "params" but does that make any difference?
Okay, I found a solution. The helper class contained an overriding getparams method, but no getheaders method. GET request requires getheaders, post requires getparams.