Android - Arraylist size always zero - java

i try to make a application. i use facebook sdk and i can login with facebook. App is getting movies with user likes. i can do this with graph api and i can add all name of movie into arraylist. Everything is OK so far. but when i try to access in onCreate method that arraylist always null. When i am use debug i can see the json value. How can i solve this. i know my english is not good i am trying to explain my issue. i could hope :)
public class list extends AppCompatActivity {
ArrayList<String> movieList = new ArrayList<String>();
public void getInfo(){
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
JSONObject jsonObject = response.getJSONObject();
try {
JSONObject movies = jsonObject.getJSONObject("movies");
JSONArray data = movies.getJSONArray("data");
for (int i = 0; i<data.length();i++){
JSONObject objectData = data.getJSONObject(i);
String movieName = objectData.getString("name");
movieList.add(movieName);
}
}catch (JSONException e){
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "movies");
request.setParameters(parameters);
request.executeAsync();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
getInfo();
this.setTitle(movieList.get(0));
}
}

it's empty cause the request is async and it hasn't end when you try to access the array... try accessing it at onCompleted

Related

I have been making an News API project in android studio but have volley got error in it. Error- com.android.volley.AuthFailureError. Using json

public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(this);
List<news_Objects> newsList = new ArrayList<>();
//url for News API
String url="https://newsapi.org/v2/everything?q=apple&from=2021-08-31&to=2021-08-31&sortBy=popularity&apiKey=ca3d6c89eff24db2a8ef78868f0af555";
//making json object request
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArr = response.getJSONArray("articles");
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject newsDetail = jsonArr.getJSONObject(i);
//class name news_Objects created
news_Objects news = new news_Objects();
String imtUrl = newsDetail.getString("urlToImage");
String title = newsDetail.getString("title");
String detail = newsDetail.getString("description");
String newsUrl = newsDetail.getString("url");
String content = newsDetail.getString("content");
news.setNewsImageUrl(imtUrl);
news.setNewsTitle(title);
news.setNewsDetail(detail);
news.setNewsUrl(newsUrl);
news.setContent(content);
newsList.add(news);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("fine", "Something Wrong"+error);
Toast.makeText(MainActivity.this, "Something Wrong "+error, Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
requestQueue.add(request);
}
}
Your API Key is Invalid please check your API key. Getting this response:
{"status":"error","code":"apiKeyInvalid","message":"Your API key is invalid or incorrect. Check your key, or go to https://newsapi.org to create a free API key."}
Maybe Your API key is not live, please check your API key status than again hit the api.

Android Studio - Parsing JSON from Google Places Details API Phone Number giving null on first run

Bit of a strange issue here. Currently I have an activity which gets the names and place ids of all the taxi companies using Google Places Search API and places them into a list view. Then when the item is clicked it will take the place id and run the Places Details API to fetch the phone number.
Currently I am running into the issue where the first time the item is clicked in the list view the JSON parser will return a NULL and the phone will dial a number like 6855 or 685-5. If you go back and click on the same item or another item then the phone number will fetch correctly.
In the activity I am running 2 JSON parsers however they run at different times.
onCreate:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_taxi);
mQueue = Volley.newRequestQueue(this);
pQueue = Volley.newRequestQueue(this);
listItem = new ArrayList<>();
placeid = new ArrayList<>();
police = findViewById(R.id.textView11);
userlist = findViewById(R.id.users_list);
jsonParse();
userlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String phone = jsonParseNumber(position);
}
});
}
jsonParse (Gets the names of the taxi companies locally)
private void jsonParse() {
String url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=51.6232817,0.2919483&radius=1000&type=taxi%20service&keyword=taxi&key=APIKEY";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++){
JSONObject result = jsonArray.getJSONObject(i);
String name = result.getString("name");
String id = result.getString("place_id");
placeid.add(id);
listItem.add(name);
}
adapter = new ArrayAdapter(Taxi.this, R.layout.row, listItem);
userlist.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
jsonParseNumber (gets the number and calls it - This is the code which is returning NULL when it is first ran)
private String jsonParseNumber(int pos) {
String id = placeid.get(pos);
String url = "https://maps.googleapis.com/maps/api/place/details/json?placeid="+id+"&key=APIKEY";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonArray = response.getJSONObject("result");
for (int i = 0; i < jsonArray.length(); i++){
number = jsonArray.getString("formatted_phone_number");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
pQueue.add(request);
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel: " + number));
startActivity(intent);
return number;
}
At first I thought it could be that the Dial Action is being called before the Parser finished so I moved it to the end of jsonParseNumber to make sure but it still does the same.
Quick notes:
2 JSON Parsers in Activity
1st Parser gets JSON from GOOGLE PLACES SEARCH API to get names and place id of taxi companies in the area
2nd Parser uses the place id to get a JSON from GOOGLE PLACES DETAILS to get the phone number
When the 2nd Parser is ran it will return a NULL on the first run however if called again it will return the return the intended phone number and dial it.
It is because, your number is null by the time you return "number". You are not waiting until the api call is complete. It is better you implement a callback when you get the response to perform specific action.

Volley onResponse android not work

MainActivity:
RequestQueue requestQueue;
String url = "http://andriodtest.eb2a.com/show.php";
TextView textView;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.TextView);
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(MainActivity.this, response.toString(), Toast.LENGTH_LONG).show();
try {
JSONArray jsonArray = response.getJSONArray("users");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject respons = jsonArray.getJSONObject(i);
String id = respons.getString("id");
String info = respons.getString("name");
textView.append(id);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue.add(jsonObjectRequest);
When run app no data called
And file config is work 100%.
example
And if set Textview= "text" not work.
I think the problem is public void onResponse.
Please help me important
Your code seems fine, however it looks like your server's response is not returning a json object but instead a javascript file for setting a cookie (you can try hitting your url with Postman to look at the javascript response I'm mentioning).
Volley expects to receive a json response and that may be the reason why your app is currently not working as expected.
I would probably try to change the way the server responds. The following link has some suggestions in order to solve that issue:
Why I can't retrieve data from my webserver as json but i can when i test it on localhost

Parsing simple json to spinner entries

I've been trying to get into android/java programming and I've been having issues understanding how to properly get the value of this json and parse it into the options to select in a spinner.
My json is like:
["Result1","Result2","Result3"]
My current code is like:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://example.com/jsonfile.json";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Do something with response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.toString());
}
});
queue.add(stringRequest);
}
What would be the easiest way to get these values (Result1, Result2, Result3, etc.) into the spinner.entries?
Thanks in advance
Try this:
myString.replace("\"]","");
myString.replace("[\"","");
List<String> myList = new ArrayList<String>(Arrays.asList(s.split("\",\"")));
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, myList);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down vieww
mySpinner.setAdapter(spinnerArrayAdapter);
As per my knowledge you are sending json data in the wrong way.
If you want to send an array you have to place a jsonArray object in response with name to access that jsonArray.
Example
"cars":[ "Ford", "BMW", "Fiat" ]
Here, we are sending 3 car name in JsonArray of name "cars".
For accessing those entries:-
for (i in myObj.cars) {
carsArray += myObj.cars[i];
}
You need to make an assync call to get json data. Please refer the following tutorial
Android assync task example
and for parsing json data use Android json parsing example
#Override
public void onResponse(String response) {
//Do something with response
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
array.put(jsonArray.getString(i));
}
}
add this on your activity's OnCreate() metod
ArrayAdapter<CharSequence> adapter =
ArrayAdapter.createFromResource(this, array,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
and put it
ArrayList<String> array = new ArrayList<String>();
Hello Try this if it may help
public class MainActivity extends AppCompatActivity {
Button btnCall;
final List<String> reviewList = new ArrayList<>();
List<String>resultList=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCall=(Button)findViewById(R.id.btnCall);
final String jArrStr="[\"Result1\",\"Result2\",\"Result3\"]";
btnCall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
JSONArray jArry=new JSONArray(jArrStr);
for (int i = 0; i < jArry.length(); i++) {
String strArr=jArry.getString(0);
resultList.add(jArry.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}

Android JSON Parsing volley library?

I have been struggling to understand the logic of the Android JSON Parsing with volley libraries.I am trying to get JSON Array and parse with Volley Libraries.I understand how JSON data is extracted from PHP file but I have big problems. makeJsonArrayRequest() function runs correctly and parse JSON Array from get_data.php file and add users ArrayList from User class in each iteration.I called this function in onCreate and userLogin function individually.Size of users ArrayList equals to 0 when I call makeJsonArrayRequest() function in onCreate method .However,Size of users ArrayList equals to nonzero number when I call makeJsonArrayRequest() function in userLogin method(This method called when clicked on Login Button).This is my problem.Why makeJsonArrayRequest() doesn't run on Create() method ?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ET_NAME = (EditText) findViewById(R.id.user_name);
ET_PASS = (EditText) findViewById(R.id.user_pass);
pDialog = new ProgressDialog(this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
makeJsonArrayRequest();
Toast.makeText(getApplicationContext(),"Size:" + users.size(),Toast.LENGTH_LONG).show();
}
public void userLogin(View view) {
login_name = ET_NAME.getText().toString();
login_pass = ET_PASS.getText().toString();
String method = "login";
String status = "1";
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute(method, login_name, login_pass, status);
Intent i = new Intent(this,MapsActivity.class);
i.putExtra("username",login_name);
i.putExtra("userpass", login_pass);
makeJsonArrayRequest();
startActivity(i);
Toast.makeText(getApplicationContext(),"Size:" + users.size(),Toast.LENGTH_LONG).show();
}
private void makeJsonArrayRequest() {
showpDialog();
JsonArrayRequest req = new JsonArrayRequest(JSON_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
jsonResponse ="";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String name = person.getString("name");
String username = person.getString("username");
String password = person.getString("password");
double latitude = Double.parseDouble(person.getString("latitude"));
double longitude = Double.parseDouble(person.getString("longitude"));
String status = person.getString("status");
User user = new User(name,username,password,latitude,longitude,status);
users.add(user);
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
If what you're saying is :
I run the request in onCreate() and check - it's empty.
and then:
I run it again LATER, and Check - it's full.
then have you considered the request latency? it takes time (albeit - not much time) for the request to return, you might be checking before it does
EDIT:
Run what you want inside the onResponse(), that's only called when the request returns.
Hope this helps.

Categories