Hello guys i have now searched for the error or how to do it correct for some time and yes alot of questions in here have helped me closer i think.
but i got an API where i get a JSONArray and i want to show this data in a listview. So far i get my data in my log, and now i just try to show the name from each object to start with(then i can add the rest of data later) but im not sure if im on the right spot maybe someone can help me out here and show what im doing wrong?
Thanks alot
Listview name: AllBirds
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_observation);
mAuth = FirebaseAuth.getInstance();
String URL="myAPI";
RequestQueue requestQueue= Volley.newRequestQueue(this);
JsonArrayRequest objectRequest = new JsonArrayRequest (Request.Method.GET, URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("Rest Response",response.toString());
try{
for(int i=0; i<response.length();i++){
JSONObject jresponse = response.getJSONObject(i);
String NameDanish = jresponse.getString("NameDanish");
Log.d("NameDanish", NameDanish);
}
}catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Rest Response",error.toString());
}
});
requestQueue.add(objectRequest);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_all_observation, NameDanish);
ListView list = (ListView) findViewById(R.id.AllBirds);
list.setAdapter(adapter);
}
Create ArrayList in your class
ArrayList arrayList = new ArrayList<>();
change your above code with
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_observation);
mAuth = FirebaseAuth.getInstance();
String URL = "myAPI";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonArrayRequest objectRequest = new JsonArrayRequest(Request.Method.GET, URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("Rest Response", response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jresponse = response.getJSONObject(i);
String NameDanish = jresponse.getString("NameDanish");
arrayList.add(NameDanish);
Log.d("NameDanish", NameDanish);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Rest Response", error.toString());
}
});
requestQueue.add(objectRequest);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_all_observation, arrayList);
ListView list = (ListView) findViewById(R.id.AllBirds);
list.setAdapter(adapter);
}
Create a string arraylist globally like this
ArrayList<String> name_array=new ArrayList<>();
then add
try{
for(int i=0; i<response.length();i++){
JSONObject jresponse = response.getJSONObject(i);
String NameDanish = jresponse.getString("NameDanish");
name_array.add(NameDanish);
Log.d("NameDanish", NameDanish);
}
then pass this arraylist to your adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_all_observation, name_array);
Create listView, adapter, array as member variable and use notifyDataUpdate from responseHandler to update data.
ListView mList;
ArrayAdapter<String> mAdapter
ArrayList<String> mData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_observation);
mData=new ArrayList<>();
mList = (ListView) findViewById(R.id.AllBirds);
mAdapter = new ArrayAdapter<String>(this, R.layout.activity_all_observation, mData);
list.setAdapter(adapter);
mAuth = FirebaseAuth.getInstance();
String URL="myAPI";
RequestQueue requestQueue= Volley.newRequestQueue(this);
JsonArrayRequest objectRequest = new JsonArrayRequest (Request.Method.GET, URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("Rest Response",response.toString());
try{
for(int i=0; i<response.length();i++){
JSONObject jresponse = response.getJSONObject(i);
String NameDanish = jresponse.getString("NameDanish");
mData.add(NameDanish);
Log.d("NameDanish", NameDanish);
}
mAdapter.notifyDataSetChanged();
}catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Rest Response",error.toString());
}
});
requestQueue.add(objectRequest);
}
I have now changed the code to this as Toyj said, i have posted my xml to.
i dont get any data out only all the names are showed in the log?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_observation);
mAuth = FirebaseAuth.getInstance();
final ArrayList arrayList = new ArrayList<>()
String URL="MYAPI";
RequestQueue requestQueue= Volley.newRequestQueue(this);
JsonArrayRequest objectRequest = new JsonArrayRequest (Request.Method.GET, URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("Rest Response",response.toString());
try{
//JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<response.length();i++){
JSONObject jresponse = response.getJSONObject(i);
String NameDanish = jresponse.getString("NameDanish");
arrayList.add(NameDanish);
Log.d("NameDanish", NameDanish);
}
}catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Rest Response",error.toString());
}
});
requestQueue.add(objectRequest);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_all_observation, arrayList);
ListView list = (ListView) findViewById(R.id.AllBirds);
list.setAdapter(adapter);
}
JSON data looks like this where i just take NameDanish to start with
{
"BirdId": 1,
"Comment": null,
"Created": "/Date(1523836800000+0000)/",
"Id": 132,
"Latitude": 55.6886037,
"Longitude": 12.5310135,
"Placename": "K",
"Population": 0,
"UserId": "user1",
"NameDanish": "solsort",
"NameEnglish": "blackbird"
}
XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="net.simplifiedlearning.firebaseauth.all_observationActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/AllBirds">
</ListView>
</LinearLayout>
Related
In my android app I want to fetch JSON data from a website.
I created it to fetch data with this structure:
[{"id":"1","name":"a"},{"id":"2","name":"a"},{"id":"3","name":"a"},{"id":"4","name":"a"}]
It works perfectly like it should. Now I tried to manipulate the code a little to fetch other JSON data.it has this structure:
{"ok":true,"license":"xx","data":"zz","status":"ok","stations":
[{"id":"474","name":"ABC","street":"MARGARETE-STR."},
{"id":"442","name":"XYZ","street":"ABCSTR"}]}
I don‘t get any results for it, I thought it might be because the data that should be fetched lays in an array, but I thought as well that I am getting it anyway. Am I fetching it the wrong way?
My code:
public class MainActivity extends AppCompatActivity {
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
ProgressBar progressBar;
String GET_JSON_DATA_HTTP_URL = "xx.com";
String JSON_ID = "id";
String JSON_NAME = "name";
String JSON_SUBJECT = "email";
String JSON_STREET = "street";
Button button;
JsonArrayRequest jsonArrayRequest;
com.android.volley.RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
button = (Button) findViewById(R.id.button);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
JSON_DATA_WEB_CALL();
}
});
}
public void JSON_DATA_WEB_CALL() {
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.GONE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setId(json.getInt(JSON_ID));
GetDataAdapter2.setName(json.getString(JSON_NAME));
GetDataAdapter2.setStreet(json.getString(JSON_STREET));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}
The second JSON sample is not a JSON array; it is a JSON object. You should use a JsonObjectRequest instead of a JsonArrayRequest to obtain this data.
I'm trying to parse the value in this JSON url using Volley, however I'm getting a null returned from the response: http://free.currencyconverterapi.com/api/v3/convert?q=CAD_USD&compact=ultra
{"CAD_USD":0.78246}
All I am trying to do is display the value of the JSON in my textview.
The error I get:
java.lang.NullPointerException: Attempt to invoke virtual method 'double java.lang.Double.doubleValue()' on a null object reference
I'm not sure if I'm fetching the JSON data correctly.
What I have so far:
public class MainActivity extends AppCompatActivity {
RequestQueue rq;
Double conversionDouble;
String url = "http://free.currencyconverterapi.com/api/v3/convert?q=CAD_USD&compact=ultra";
private Spinner toSpinner, fromSpinner;
private Button convertBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addItemsOnToSpinner();
addListenerOnButton();
jsonSendRequest();
Button convertBtn = (Button) findViewById(R.id.convertBtn);
final EditText fromAmountEditText = findViewById(R.id.fromAmountEditText);
convertBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView toAmountTextView = findViewById(R.id.toAmountTextView);
String result = Double.toString(conversionDouble);
toAmountTextView.setText(result);
}
});
Spinner toSpinner = (Spinner) findViewById(R.id.toSpinner);
Spinner fromSpinner = (Spinner) findViewById(R.id.fromSpinner);
String toSpinnerText = toSpinner.getSelectedItem().toString();
String fromSpinnerText = fromSpinner.getSelectedItem().toString();
rq = Volley.newRequestQueue(this);
}
public void jsonSendRequest() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
conversionDouble = response.getDouble("CAD_USD");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
public void addItemsOnToSpinner(){
Spinner toSpinner = (Spinner) findViewById(R.id.toSpinner);
Spinner fromSpinner = (Spinner) findViewById(R.id.fromSpinner);
List<String> currency = new ArrayList<String>();
currency.add("USD");
currency.add("CAD");
currency.add("CNY");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, currency
);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
toSpinner.setAdapter(dataAdapter);
fromSpinner.setAdapter(dataAdapter);
}
public void addListenerOnButton() {
Spinner fromSpinner = (Spinner) findViewById(R.id.fromSpinner);
Spinner toSpinner = (Spinner) findViewById(R.id.toSpinner);
Button convertBtn = (Button) findViewById(R.id.convertBtn);
}
}
Any help is appreciated.
//Replace your method with below
public void jsonSendRequest() {
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://free.currencyconverterapi.com/api/v3/convert?q=CAD_USD&compact=ultra";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject jsonobject = new JSONObject(response);
if(jsonobject.has("CAD_USD")){
conversionDouble = jsonobject.getDouble("CAD_USD");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
I have an app contains a recyclerview the code works correctly but the data repeat itself in the list when I want to parse Json into Android Studio
how can I fix that while the data is coming from internet
but when I use a normal ListView it is working great
and I am using same adapter
and this is my code
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerView_dAdapter;
public List<List_Item> listItems = new ArrayList<>();
private GridLayoutManager gridLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.m_RecyclerView);
recyclerView.setHasFixedSize(true);
gridLayoutManager = new GridLayoutManager(this, 1);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView_dAdapter = new RecyclerViewAdapter(listItems, this);
recyclerView.setAdapter(recyclerView_dAdapter);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (gridLayoutManager.findLastCompletelyVisibleItemPosition() == listItems.size() - 1) {
Get_All_Users(listItems.get(listItems.size()-1).getId());
}
}
});
Get_All_Users(0);
}
public void Get_All_Users(int limit) {
CheckInternetConnection cic = new CheckInternetConnection(getApplicationContext());
Boolean Ch = cic.isConnectingToInternet();
if (!Ch) {
Toast.makeText(this, R.string.no_internet_connection, Toast.LENGTH_SHORT).show();
} else {
StringRequest stringRequest = new StringRequest(Request.Method.GET,
"https://raw.githubusercontent.com/abodali/ox/master/f.txt?limit" + limit
,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonResponse = jsonArray.getJSONObject(0);
JSONArray jsonArray_usersS = jsonResponse.getJSONArray("All_storys");
for (int i = 0; i < jsonArray_usersS.length(); i++) {
JSONObject responsS = jsonArray_usersS.getJSONObject(i);
int id = responsS.getInt("id");
String story = responsS.getString("story_name");
String img_link = responsS.getString("img_link");
listItems.add(new List_Item(id, story, img_link));
}
recyclerView_dAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(stringRequest);
stringRequest.setShouldCache(false);
}
}
}
Kind Regards
When you get a new response, you are not clearing your list before adding your new data. I'm assuming that this is what you want.
So before your for-loop, add a line in there that will clear your list:
listItems.clear();
Hey i'm creating Android application which connect with my database MySQL. I created an ArrayList with categories and added it to Adapter and then to Spinner. I see Spinner items but after onClick nothing happens and when I try to check what is in my ArrayList I see that it is empty.Data downloaded.
After click in Spinner nothing change
Here is my code:
public class InsertProductActivity extends AppCompatActivity {
Spinner categories;
String categoriesURL = "myURL";
ArrayList<String> downloadedCategories = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_product);
categories = findViewById(R.id.categories);
getCategories();
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item,downloadedCategories);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
categories.setAdapter(adapter);
}
protected void getCategories(){
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, categoriesURL
, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("categories");
for(int i=0;i<jsonArray.length();i++){
downloadedCategories.add(jsonArray.getJSONObject(i).getString("name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
}
try this one.
protected void getCategories(){
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, categoriesURL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("categories");
downloadedCategories = new ArrayList<>(); // try to add your instantiation of your arrayList here.
for(int i=0;i<jsonArray.length();i++) {
downloadedCategories.add(jsonArray.getJSONObject(i).getString("name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//this block of code will prompt after your downloadedCategories finish storing your objects to your arrayList because if you put this in onCreate this wil call before your getCategories process not finish yet. So much better its much safer here.
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item,downloadedCategories);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
categories.setAdapter(adapter);
requestQueue.add(jsonObjectRequest);
}
I have figured out that my main issue right now is my intent code. I have no idea how to build my intent to make the data come back from the website so if anyone could help me with that, it would be awesome! I am trying to get JSON data from the openweather api and my app will load up the web page instead of bringing it into the list view. Right now with the intent I have, a web page opens up with the data I need. Any help would be great!
public class MainActivity extends AppCompatActivity {
private String url = "http://api.openweathermap.org/data/2.5/weather?q=London,us&APPID=805bd9f830268d5274c60e41613c28a5";
private List<String> items = new ArrayList<String>();
private ArrayAdapter<String> mArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btnRequest = (Button) findViewById(R.id.button); //your button id must be button
final ListView lv = (ListView) findViewById(R.id.listView); //your listview ide must be listview
final RequestQueue requestQueue = Volley.newRequestQueue(this);
final JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jcity = response.getJSONObject("city");
String name = jcity.getString("name");
JSONArray wlist = response.getJSONArray("list");
for (int i = 0; i < 10; i++) {
JSONObject jsonObject = wlist.getJSONObject(i);
String dt = jsonObject.getString("dt");
JSONArray warray = jsonObject.getJSONArray("weather");
JSONObject wobj = warray.getJSONObject(0);
String desc = wobj.getString("description");
items.add(dt + " " + desc);
Log.d("date", dt); //Log.d prints to the terminal
Log.d("desc", desc);//good for debugging
}
mArrayAdapter = new ArrayAdapter<String>
(getApplicationContext(),
android.R.layout.simple_list_item_1, items);
//lv.setAdapter(mArrayAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
btnRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestQueue.add(jor);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
}
}
I think that's because you missed the setting adapter to the ListView. And also make sure your items have data inside it .
mArrayAdapter = new ArrayAdapter<String> (getApplicationContext(), android.R.layout.simple_list_item_1, items);
lv.setAdapter(mArrayAdapter);