I know there are some identical questions but I just couldn't figure out what I'm doing wrong.
public class MainActivity extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
new JsonHandler().execute(this, collection, gridArray, customGridAdapter);
...
}
}
So in my main activity I need to query an API which gives back JSON and I have to process that to build my database.
Then in doInBackground() I call getAllCards() which gets the first JSON. Because the JSON includes URLs for more JSON requests, I have a few methods each querying a more detailed JSON.
public final class JsonHandler extends AsyncTask {
private final String urlCards = "https://api.gwentapi.com/v0/cards/";
private final String urlSpecificCard = "https://api.gwentapi.com/v0/cards/:id";
private Context context;
private Collection collection;
private ArrayList<Card> gridArray;
private CustomGridViewAdapter customGridAdapter;
public JsonHandler(Context context, Collection collection, ArrayList<Card> gridArray, CustomGridViewAdapter customGridAdapter){
this.context = context;
this.collection = collection;
this.gridArray = gridArray;
this.customGridAdapter = customGridAdapter;
}
public JsonHandler(){
this.context = null;
this.collection = null;
this.gridArray = null;
this.customGridAdapter = null;
}
private void getAllCards() throws RuntimeException {
JsonObjectRequest arrayRequest = new JsonObjectRequest(Request.Method.GET, urlCards, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
generateCollection(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError e) {
throw new RuntimeException(e.getMessage());
}
});
Volley.newRequestQueue(context).add(arrayRequest);
}
private void getSpecificCard(final String cardURL) throws RuntimeException {
JsonObjectRequest arrayRequest = new JsonObjectRequest(Request.Method.GET, cardURL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
processCard(response, collection);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError e) {
throw new RuntimeException(e.getMessage());
}
});
Volley.newRequestQueue(context).add(arrayRequest);
}
private void generateCollection(JSONObject response) throws RuntimeException {
try {
JSONArray array = response.getJSONArray("results");
for(int i = 0; i < array.length();i++){
JSONObject object = array.getJSONObject(i);
String cardURL = object.getString("href");
getSpecificCard(cardURL);
}
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
private void processCard(JSONObject response, Collection collection){
try {
String id = response.getString("id");
EnumFaction faction = EnumFaction.valueOf(response.getJSONObject("faction").getString("name").toUpperCase());
EnumType type = null;
EnumRarity rarity = null;
EnumLane lane = null;
EnumLoyalty loyalty = null;
String name = response.getString("name");
String text = response.getString("text");
String imagePath = "https://api.gwentapi.com/media/\" + id + \"_small.png";
URL url = new URL(imagePath);
InputStream inputStream = url.openConnection().getInputStream();
Bitmap image = BitmapFactory.decodeStream(inputStream);
Card card = new Card(id, faction, type, rarity, lane, loyalty, name, text, null, imagePath, 0);
collection.addCard(card);
gridArray.add(card);
customGridAdapter.notifyDataSetChanged();
} catch (Exception e){
throw new RuntimeException(e.getMessage());
}
}
#Override
protected Object doInBackground(Object[] params) {
context = (Context) params[0];
collection = (Collection) params[1];
gridArray = (ArrayList<Card>) params[2];
customGridAdapter = (CustomGridViewAdapter) params[3];
getAllCards();
return null;
}
}
So now on to the problem:
When the programm reaches processCard() when I've gathered enough information, I get a NetworkOnMainThreadException when I create the InputStream.
I've tried so many different methods to get a Bitmap from my URL and different methods to do an asynchronous task - all leading to the same result.
If you could show me how to resolve this issue, I'd be sooo happy.
Edit: Since it got marked as duplicate: I AM USING ASYNCTASK! I have looked at many questions and tried what they did there, it doesn't work!
Not really familiar with how volley works but onResponse but be on the main thread so you need to start a new thread to make that call too
Related
textView = findViewById(R.id.textVieww);
String url = "https://zenquotes.io/api/random";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
final String myResponse = response.body().string();
try {
JSONArray jsonarray = new JSONArray(myResponse);
for(int i=0; i<jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
Quote.this.runOnUiThread(() ->
textView.setText(myResponse));
}
}
});
}
This is the part im stuck on i think im on the right track but not sure where to go from here im trying to get the "q" information from the returned url and the "a" information but it just outputs everything any suggestions?
What was your problem
Even when you parsed JSON string, you were still using the myResponse string in your textView.setText() method.
Continuing your code snippet
your code snippet is quite short, but i do think i can quite understand what you mean.
So let's say that we have Activity, which is called MainActivity and in that activity we have two views, one TextView called that has an id of tv_author_and_quote and one Button which has a xml id btn_request_quote.
The button has an OnClickListener which calls method requestForQuote().
Our onCreate + the variables of Button and TextView looks like this:
TextView tvAuthorAndQuote;
Button btnRequestQuote;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvAuthorAndQuote = findViewById(R.id.tv_author_and_quote);
btnRequestQuote = findViewById(R.id.btn_request_quote);
btnRequestQuote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
requestForQuote();
}
});
}
And then we have a code itself for method requestForQuote():
public void requestForQuote() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(URL)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
if (response.isSuccessful()) {
final String myResponse = Objects.requireNonNull(response.body()).string();
String myFormattedQuote = "";
try {
JSONArray jsonarray = new JSONArray(myResponse);
for(int i=0; i<jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
String quote = obj.getString("q");
String author = obj.getString("a");
Log.d(TAG, "onResponse: quote:" + quote);
Log.d(TAG, "onResponse: author:" + author);
myFormattedQuote = author + ": " + quote;
}
} catch (JSONException e) {
e.printStackTrace();
}
final String myFinalQuote = myFormattedQuote;
MainActivity.this.runOnUiThread(() -> {
if (!myFinalQuote.equals("")) {
tvAuthorAndQuote.setText(myFinalQuote);
} else {
tvAuthorAndQuote.setText(myResponse);
}
});
}
}
});
}
The code above basically uses your existing solution, but instead of setting the text of textView with myResponse string, it parses the json array and gets a quote and an author from it. Then it just logs it (just for testing purposes), then it constructs the string which gets displayed to the if there is any, otherwise it prints the response. That it is.
Using Gson library
import it into your gradle dependecies
implementation 'com.google.code.gson:gson:2.8.7'
Write short "holder" class called Quote
public class Quote {
public Quote() {
}
String q;
String a;
String h;
public String getQ() {
return q;
}
public void setQ(String q) {
this.q = q;
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String getH() {
return h;
}
public void setH(String h) {
this.h = h;
}
#NonNull
#NotNull
#Override
public String toString() {
return a + ": " + q;
}
}
Then the requestForQuote() method could look something like this:
public void requestForQuoteWithGson() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(URL)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
if (response.isSuccessful()) {
final String myResponse = Objects.requireNonNull(response.body()).string();
Type listType = new TypeToken<ArrayList<Quote>>(){}.getType();
List<Quote> yourClassList = new Gson().fromJson(myResponse, listType);
if (yourClassList != null && yourClassList.size() > 0) {
final Quote quote = yourClassList.get(0);
if (quote != null) {
myQuotes.add(quote);
MainActivity.this.runOnUiThread(() ->
tvAuthorAndQuote.setText(quote.toString())
);
}
}
}
}
});
}
public class VolleyStringRequest {
String url;
String body;
String value;
public VolleyStringRequest(String url, String body){
this.url = url;
this.body = body;
value= "";
}
public StringRequest createStringRequest(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response
Log.e("Response", response);
try{
JSONObject o = new JSONObject(response);
JSONArray values=o.getJSONArray("response");
value += values.toString();
} catch (JSONException ex){}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
return body.getBytes();
};
#Override
public String getBodyContentType() {
return "application/json";
}
};
return stringRequest;
}
public String getValue() {
return value;
}
}
I wrote this code in a seperate class to prevent code repetition but when I run this inside a fragment like this:
RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
String url= "http://grwn.ddns.net:1337/results";
final String body = "{\"id\":1}";
VolleyStringRequest volleyStringRequest = new VolleyStringRequest(url, body);
rq.add(volleyStringRequest.createStringRequest());
volleyStringRequest.getValue();
And call the getValue() method. This method is always empty like: "". Does anyone know how I can enhance my class so this code will work? This issue is not because of a bad link or bad request. I can log the response and that does work (ofcourse inside VolleyStringRequest)
You run:
VolleyStringRequest volleyStringRequest = new VolleyStringRequest(url, body);
rq.add(volleyStringRequest.createStringRequest());
volleyStringRequest.getValue();
But remember createStringRequest is async method and value is populated after some delay a.e. inside public void onResponse(String response)
So when you call volleyStringRequest.getValue(); you get empty string
To make it work you can write some interface as:
public interface RequestHandlerInterface(){
void onResponse(String resp);
}
And pass it to VolleyStringRequest constructor:
RequestHandlerInterface rh = this; //Your main class should implement this method
RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
String url= "http://grwn.ddns.net:1337/results";
final String body = "{\"id\":1}";
VolleyStringRequest volleyStringRequest = new VolleyStringRequest(url, body, rh);
rq.add(volleyStringRequest.createStringRequest());
Next, change your VolleyStringRequest:
public class VolleyStringRequest {
String url;
String body;
String value;
public VolleyStringRequest(String url, String body, RequestHandlerInterface rh){
this.url = url;
this.body = body;
this.rh = rh;
value= "";
}
//...
}
And once you got response from POST, call the callback as:
#Override
public void onResponse(String response) {
// Do something with the response
Log.e("Response", response);
try{
JSONObject o = new JSONObject(response);
JSONArray values=o.getJSONArray("response");
value += values.toString();
if(this.rh != null){
this.rh.onResponse(value);
}
} catch (JSONException ex){}
}
So in bottom line instead to call volleyStringRequest.getValue();
you have:
#Override
void onResponse(String resp){
// here you go
}
that will be called when you get POST response
I try to return array of objects with this function:
public static JSONEvent[] invokeFunction(String funName, String requestContent) {
final String functionName = funName;
final String requestPayload = requestContent;
new AsyncTask<Void, Void, InvokeResult>() {
#Override
protected InvokeResult doInBackground(Void... params) {
try {
final ByteBuffer payload =
ENCODER.encode(CharBuffer.wrap(requestPayload));
final InvokeRequest invokeRequest =
new InvokeRequest()
.withFunctionName(functionName)
.withInvocationType(InvocationType.RequestResponse)
.withPayload(payload);
final InvokeResult invokeResult =
AWSMobileClient
.defaultMobileClient()
.getCloudFunctionClient()
.invoke(invokeRequest);
return invokeResult;
} catch (final Exception e) {
Log.e("LAMBDA", "AWS Lambda invocation failed : " + e.getMessage(), e);
final InvokeResult result = new InvokeResult();
result.setStatusCode(500);
result.setFunctionError(e.getMessage());
return result;
}
}
#Override
protected void onPostExecute(final InvokeResult invokeResult) {
try {
final int statusCode = invokeResult.getStatusCode();
final String functionError = invokeResult.getFunctionError();
final String logResult = invokeResult.getLogResult();
if (statusCode != 200) {
//showError(invokeResult.getFunctionError());
} else {
final ByteBuffer resultPayloadBuffer = invokeResult.getPayload();
//resultPayloadBuffer.rewind();
// while (resultPayloadBuffer.hasRemaining())
// Log.e("BUFFER",resultPayloadBuffer.position() + " -> " + resultPayloadBuffer.get());
// User a = new User(23, 24);
//
// User b = new User(58, 59);
// User[] ab = new User[] {a, b};
// User [] events = new User[3];
ObjectMapper mapper = new ObjectMapper();
final String resultPayload = DECODER.decode(resultPayloadBuffer).toString();
Log.e("LAMBDA-SUCCESS", resultPayload);
try {
// String s2 = getJson2(ab);
// Log.e("S2", s2);
//User[] user2 = mapper.readValue(resultPayload, User[].class);
events = mapper.readValue(resultPayload, JSONEvent[].class);
// for (JSONEvent u : events)
// Log.e("USER",u.getLocationLat()+"");
Log.e("ARRAY",Arrays.toString(events));
} catch (Exception e) {
e.printStackTrace();
}
//return resultPayload;
// mResultField.setText(resultPayload);
}
if (functionError != null) {
Log.e("LAMBDA", "AWS Lambda Function Error: " + functionError);
}
if (logResult != null) {
Log.d("LAMBDA", "AWS Lambda Log Result: " + logResult);
}
}
catch (final Exception e) {
Log.e("LAMBDA", "Unable to decode results. " + e.getMessage(), e);
//showError(e.getMessage());
}
}
}.execute();
return events;
}
The problem is that I call invokeFunction in diffrent activity and it returns null but in onPostExecute the array is not null. It seems that it returns array before calling OnPostExecute. How to solve that?
The problem is that the method invokeFunction is finishing before onPostExecute (asynchronous)
You could use an interface to communicate AsyncTask and activity.
Interface (pseudocode):
public interface AsyncCom {
public void sendUsers(User [] events);
}
Your asynFunction (pseucode):
public void invokeFunction(String funName, String requestContent, AsyncCom listener) {
...
And call the function of the listener in postExecute (pseudocode):
protected void onPostExecute(final InvokeResult invokeResult) {
...
listener.sendUsers(events);
}
Declare the interface in your activity and call your method with the listener (pseudocode):
public class MyActivity implements AsyncCom {
...
invokeFunction(funName, requestContent, this);
...
Finally, in your activity, implements the returned method (pseudocode):
public void sendUsers(User [] events){
// do wathever you want with users
}
But remeber that the response will bw asynchonous
private void invokeFunction(String funName, String requestContent{
YourTask task = new YourTask();
task.execute(new String[]{funName, requestContent});
}
static class YourTask extends AsyncTask<String, Void, InvokeResult> {
#Override
protected InvokeResult doInBackground(String... params) {
String funName = params[0];
String requestContent = params[1];
// ...
}
#Override
protected void onPostExecute(final InvokeResult invokeResult) {
/// . ..
doWhatYouNeedWithTheResult(result);
}
};
}
Hey everyone so I am just starting a part two for online training app and trying to adapt my async task to get movie reviews from the movie db. Having a totally different async task just for that seems like there should be a better way. Here is the current async task implementation that only gets the movie data.
The question is how do I add another async task to this in order to retrive the movie reviews as well from this url /movie/{id}/videos.
public FetchMovieData(Context context, GridView grid, boolean sortType, ITaskCompleteListener listener) {
mContext = context;
this.mMoviesGrid = grid;
this.mSortByMostPopular = sortType;
this.mTaskCompleteListener = listener;
}
#Override
protected Void doInBackground(String... params) {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
URL url;
if(mSortByMostPopular)
url = new URL(mContext.getString(R.string.picasso_url_popular_movies));
else
url = new URL(mContext.getString(R.string.picasso_url_highest_rated));
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
mMovieJsonStr = null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
mMovieJsonStr = null;
}
mMovieJsonStr = buffer.toString();
} catch (IOException e) {
Log.e("PlaceholderFragment", "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attempting
// to parse it.
mMovieJsonStr = null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PlaceholderFragment", "Error closing stream", e);
}
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(mMovieJsonStr != null)
Constants.mMovies = MovieDataParser.getMovieData(mMovieJsonStr);
mTaskCompleteListener.onTaskCompleted(); //Task completed alert UI that we have our data
}
So some one had suggested using Retrofit instead of having multiple async tasks. This seems like a good idea but I am having a lot of trouble understanding how it is supposed to work. Currently I have a WebService class an interface and am trying to use it to retrieve both movies and am going to add reviews then trailers. The issue is if I set the base url as "http://api.themoviedb.org" I get url must start with "/" in logcat.
Current code:
public class WebService {
public List<Movie> getMovies() {
RestAdapter retrofit = new RestAdapter.Builder()
.setEndpoint("http://api.themoviedb.org")
.build();
MovieDBService service = retrofit.create(MovieDBService.class);
return service.listMovies("movies");
}
}
public interface MovieDBService {
#GET("/3/discover/{switchterm}sort_by=popularity.desc&api_key=d273a1a1fb9390dab9 7ac0032b12366a")
List listMovies(#Path("switchterm") String switchterm);
}
//In code getting movies
WebService service = new WebService();
List movies = service.getMovies();
I think you have a lots of possibilities for doing this.You can follow this approach: add a second call to another AsyncTask when the first is finish, and pass to it a list of strings with the video ids:
public class FetchMovieData extends AsyncTask<Void, Void, Void> {
protected Boolean doInBackground() {
try {
String movieJSONString = getJSONMovies();
String[] ids = parseIdsFromJSON(movieJSONString);
if(ids.lenth != 0) {
FetchMovieReviews moviesReviewsAsyncTask = new FetchMovieReviews();
moviesReviewsAsyncTask.execute(ids);
} else {
return false;
}
return true;
} catch (Exception e) {
return false;
}
}
protected String getJSONMovies() {
//with the code you post, return the json string
}
protected String[] parseIdsFromJSON(String JSON) {
//parse the json and get the ids and return
//return {"1","2","3"}
}
}
public class FetchMovieReviews extends AsyncTask<String[], Void, Void> {
protected Void doInBackground(String[]... params) {
for(String id : params[0]) {
//call the web service and pass the id
}
return null;
}
}
You can put all the functionality for manage the calls to the web services in a MoviesRESTCalls class, and for manage the json in a MoviesJSONParser class or something like that, and the code is going to be much more clear.
So what I ended up with was this using the the Retrofit library for the web service. Thanks for the help everyone and let me know your thoughts.
public Context mContext;
private MovieJSON mMovieData;
private ReviewJSON mMovieReviews;
private VideoJSON mMovieVideos;
public boolean mSortByMostPopular;
ITaskCompleteListener mTaskCompleteListener;
public FetchMovieData(Context context, boolean sortType, ITaskCompleteListener listener) {
mContext = context;
this.mSortByMostPopular = sortType;
this.mTaskCompleteListener = listener;
}
public void getMovies() {
new FetchMovies().execute();
}
public void getReviews() {
new FetchReviews().execute();
}
public void getVideos() {
new FetchTrailers().execute();
}
private class FetchMovies extends AsyncTask<String, Void, Void > {
#Override
protected Void doInBackground(String... params) {
WebService service = new WebService();
//TODO Re-Implement sorting
mMovieData = service.getMovies();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(mMovieData != null)
Constants.mMovies = MovieDataParser.getMovieData(mMovieData);
mTaskCompleteListener.onTaskCompleted(); //Task completed alert UI that we have our data
}
}
private class FetchReviews extends AsyncTask<String, Void, Void > {
#Override
protected Void doInBackground(String... params) {
WebService service = new WebService();
mMovieReviews = service.getReviews();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(mMovieReviews != null)
Constants.mReviews = MovieDataParser.getReviewData(mMovieReviews);
mTaskCompleteListener.onTaskCompleted(); //Task completed alert UI that we have our data
}
}
private class FetchTrailers extends AsyncTask<String, Void, Void > {
#Override
protected Void doInBackground(String... params) {
WebService service = new WebService();
mMovieVideos = service.getVideos();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(mMovieVideos != null)
Constants.mTrailers = MovieDataParser.getVideoData(mMovieVideos);
mTaskCompleteListener.onTaskCompleted(); //Task completed alert UI that we have our data
}
}
//web service
public class WebService {
RestAdapter mRetrofit;
MovieDBService mService;
public WebService() {
mRetrofit = new RestAdapter.Builder()
.setEndpoint("http://api.themoviedb.org")
.build();
mService = mRetrofit.create(MovieDBService.class);
}
public MovieJSON getMovies() {
return mService.listMovies("");
}
public ReviewJSON getReviews() {
return mService.listReviews("76341");
}
public VideoJSON getVideos() {
return mService.listVideos("76341");
}
}
I'm using this code for sending data to server , but when i want to parser response data on volley onResponse method , my UI freezing .
JsonObjectRequest req = new JsonObjectRequest(Method.GET, url, null, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
parseFromJsonObject(response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
}
});
RequestHelper.getInstance().addToRequestQueue(req, this);
And it's parser method
public boolean parseFromJsonObject(JSONObject response)
{
boolean validResponse = super.isValidResponse(response);
try
{
if(response.has("keywords"))
{
JSONObject keywords = response.getJSONObject("keywords");
Iterator<?> langIterator = keywords.keys();
ArrayList<LanguagesStorage> languagesStorageArray = new ArrayList<LanguagesStorage>();
while(langIterator.hasNext())
{
String lang = (String) langIterator.next();
JSONObject langValues = keywords.getJSONObject(lang);
Iterator<?> valueIterator = langValues.keys();
while(valueIterator.hasNext())
{
String key = (String) valueIterator.next();
String value = (String) langValues.getString(key);
LanguagesStorage languagesStorage = new LanguagesStorage();
languagesStorage.setKey(key);
languagesStorage.setLang(lang);
languagesStorage.setValue(value);
languagesStorageArray.add(languagesStorage);
}
}
if(languagesStorageArray.size() > 0)
{
LanguageAdapter languageAdapter = new LanguageAdapter();
languageAdapter.insert(languagesStorageArray, true);
}
}
return lastParsingStatus = true;
}
catch (JSONException e)
{
RLog.error("Parsing error in keyword Parser " + e);
return lastParsingStatus = false;
}
}
What is the issue ? Why my UI thread freezing?
Volley onResponce work inside the UI thread
I recommend you to do parsing inside a separate thread.
In your parseFromJsonObject method, try to create a new Thread and inside that thread execute your parsing data.