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);
}
Related
Recently I am working on Android project with Volley for registration and for further operation, I can make function for insertion and other one is for retrieval data. When insert button click 'Insert' function called and data has been inserted to database through volley, and at the same time retrieval function also called. But when USER clicked the button and function called then data showed(database inserted data) with blinking effect, look like loading.
I want to get rid of that effect. I want to show data smoothly without any blinking effect. I do searching but can not find any solution. Please suggest me solution I'am newbie so kindly short and efficient required.
package com.darkcoderz.parsejson;
public class MainActivity extends AppCompatActivity {
private Context mContext;
private Activity mActivity;
//private CoordinatorLayout mCLayout;
private TextView mTextView;
private String mJSONURLString = "http://192.168.10.4/volley/api.php";
String url = "http://192.168.10.4/volley/register.php";
private EditText sms;
private Button sendsms;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the application context
//mContext = getApplicationContext();
//mActivity = MainActivity.this;
// Get the widget reference from XML layout
//mCLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
mTextView = (TextView) findViewById(R.id.tv);
sms = (EditText) findViewById(R.id.sms);
sendsms = (Button) findViewById(R.id.sendsms);
final Handler firesms = new Handler();
firesms.post(new Runnable() {
#Override
public void run() {
getdata();
firesms.postDelayed(this, 100);
}
});
sendsms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
reg();
}
});
getdata();
}
// insert
public void reg()
{
final String msg = sms.getText().toString();
StringRequest stringreq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("success"))
{
Toast.makeText(MainActivity.this, "Registration Successfull!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "Username Already Exist!", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Great Error "+error.toString(), Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("sms",msg);
return params;
}
};
RequestQueue reqest = Volley.newRequestQueue(MainActivity.this);
reqest.add(stringreq);
}
private void getdata() {
// Empty the TextView
mTextView.setText("");
// Initialize a new RequestQueue instance
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
// Initialize a new JsonArrayRequest instance
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, mJSONURLString, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Do something with response
//mTextView.setText(response.toString());
// Process the JSON
try{
// Loop through the array elements
for(int i=0;i<response.length();i++){
// Get current json object
JSONObject student = response.getJSONObject(i);
// Get the current student (json object) data
// String firstName = student.getString("fname");
// String lastName = student.getString("lname");
String age = student.getString("email");
// Display the formatted json data in text view
mTextView.append("SMS : " + age);
mTextView.append("\n\n");
}
}catch (JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
// Do something when error occurred
Toast.makeText(mContext, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
}
);
// Add JsonArrayRequest to the RequestQueue
requestQueue.add(jsonArrayRequest);
}
}
private void getdata() {
// Empty the TextView
mTextView.setText("");
// Initialize a new RequestQueue instance
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
// Initialize a new JsonArrayRequest instance
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, mJSONURLString, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//before parsing check your response is in JSONArray Format or JSONObject format
// Process the JSON
try{
}catch (JSONException e){
e.printStackTrace();
//print here to know JSONException if exists
Toast.makeText(mContext, "Exception"+e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
// Do something when error occurred
Toast.makeText(mContext, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
}
);
// Add JsonArrayRequest to the RequestQueue
requestQueue.add(jsonArrayRequest);
}
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.
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);
I want to move GET method inside (if) that located inside onResponse of POST request without calling URL again because once the user post edittext php file will echo json result that will show up inside listview in activity so if call URL again in other method nothing will show up, how can I do that please?
public class supportActivity extends AppCompatActivity implements View.OnClickListener{
private EditText ticketsupport;
private Button button;
private List<supportContent> con = new ArrayList<supportContent>();
private ListView supportlist;
private supportAdapter adapter;
private String ticketinput;
private String url = "http://10.0.3.2/aalm/getticket.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_support);
ticketsupport = (EditText)findViewById(R.id.insertticketnumber);
supportlist = (ListView)findViewById(R.id.supportlistview);
adapter = new supportAdapter(this, con);
supportlist.setAdapter(adapter);
button = (Button)findViewById(R.id.buttonsupprt);
button.setOnClickListener(this);
}
private void inquiry() {
ticketinput = ticketsupport.getText().toString().trim();
StringRequest stringRequest1 = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equals("responseticket")) {
showTicket();
} else {
Toast.makeText(supportActivity.this, "Check the number please", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(supportActivity.this, "something wrong" , Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String,String> getParams() throws AuthFailureError{
Map<String,String> map = new HashMap<String,String>();
map.put("ticknumber", ticketinput);
return map;
}
};
RequestQueue requestQueue1 = Volley.newRequestQueue(getApplicationContext());
requestQueue1.add(stringRequest1);
}
private void showTicket(){
RequestQueue requestQueue2 = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("responseticket");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject ticket = jsonArray.getJSONObject(i);
supportContent support = new supportContent();
support.setTicketnumber(ticket.getString("ticketnumber"));
support.setSubject(ticket.getString("subject"));
support.setResponse(ticket.getString("response"));
con.add(support);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error", "Volley");
}
}
);
requestQueue2.add(jsonObjectRequest);
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public void onClick(View view){
inquiry();
}
}