How can i get data from a JSON request in android? - android

Im trying to create a currency converter app on android.
im getting this String request from an api
{"base":"USD","date":"2018-07-27","rates":{"RON":3.9819354839}}
i'd like to somehow parse this string (using json) and get the RON value
this is my code:
public class MainActivity extends AppCompatActivity {
Button convert;
TextView textView;
RequestQueue requestQueue;
Spinner spinner;
Spinner spinner2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner=(Spinner)findViewById(R.id.spinner);
spinner2=(Spinner)findViewById(R.id.spinner2);
final EditText textBox1 = (EditText)findViewById(R.id.editText);
final EditText textBox2 = (EditText)findViewById(R.id.editText2);
final TextView textView=(TextView)findViewById(R.id.textView);
Button convert = (Button)findViewById(R.id.button);
Cache cache = new DiskBasedCache(getCacheDir(),1024*1024);
Network network = new BasicNetwork(new HurlStack());
requestQueue=new RequestQueue(cache,network);
requestQueue.start();
convert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text1 = spinner.getSelectedItem().toString();
String text2= spinner2.getSelectedItem().toString();
String URL ="https://exchangeratesapi.io/api/latest?base="+text1+"&symbols="+text2;
StringRequest stringRequest= new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
textView.setText(response);
Log.e("Rest response", response.toString());
// requestQueue.stop();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
textView.setText("error......");
error.printStackTrace();
}
});
requestQueue.add(stringRequest);
}
});
}
}

I managed to resolve this issue! Maybe this will help other people too.
JSONObject obj = new JSONObject(response);
JSONObject ratesObj = obj.getJSONObject("rates");
String currency = ratesObj.getString(convertedValue);

Related

Volley give me only: onErrorResponse

I start to work with volley and when i try to make a post request it give me only errore.
Can you guys tell me when im wrong?
Im working on the Android side of the project with VolleyLibrary.
public class MainActivity extends AppCompatActivity {
private EditText etUsername;
private EditText etPassword;
private Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUsername = findViewById(R.id.etUsername);
etPassword = findViewById(R.id.etPassword);
btnLogin = findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Login();
}
});
}
private void Login(){
String url = "http://myapies.youcantwatch.it/loginuser_module";
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(!response.trim().equals("errors")){
Intent intent = new Intent(MainActivity.this, LoggedActivity.class);
startActivity(intent);
} else {
Toast.makeText(MainActivity.this, "Login Fallito", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "La chiamata non รจ andata a buon fine", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("firstName","adkdmadm");
params.put("password","asdasdjn");
params.put("secretKey","dlwdmkemd3d455");
params.put("username", etUsername.getText().toString().trim());
params.put("passwordasdad", etPassword.getText().toString().trim());
return super.getParams();
}
};
requestQueue.add(stringRequest);
}
}
Replace StringRequest->JSONObjectRequest and check.
Pass request parameters in JSONObject, not in the header,
only pass Content-Type->application/json in header.
change volley to another libs like retrofit volley long time not updated

Why volley is not sending the values?

I'm new to android development. I'm trying to send some data to server using volley. But it is not sending parameters. Please help. The server is saying that the parameter is not set. I checked with the isset in php. When I tried sending data from a html form, it's working. But the volley is not sending the parameters.
public class MainActivity extends AppCompatActivity {
EditText uname;
EditText uotp;
RequestQueue myqueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname = (EditText) findViewById(R.id.uname);
uotp = (EditText) findViewById(R.id.uotp);
myqueue = Volley.newRequestQueue(this);
}
public void sendotp(View v)
{
String unameval = uname.getText().toString();
if(unameval.matches(""))
{
Toast.makeText(getApplicationContext(), "Enter Phone Number", Toast.LENGTH_SHORT).show();
}
else
{
HashMap<String, String> params = new HashMap<>();
params.put("phone", unameval);
String myUrl = "http://privateurlhere";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, myUrl, new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String dispname = response.getString("stat");
Toast.makeText(getApplicationContext(), dispname, Toast.LENGTH_SHORT).show();
}
catch(JSONException e)
{
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Resp err" + error.toString(), Toast.LENGTH_SHORT).show();
}
});
myqueue.add(request);
}
}
}

refresh current page without blinking android

My app has a list and a button to add element to the list and reload it in the same activity, when pressing the button I need to reload the activity without blinking or time of reloading Like when you send message in messenger.I try the following code:
recreate()
tvSender.setText("");
And this code :
Intent intent = getIntent();
finish();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
This works but it's still not what i want exact any help pls
the full code :
public class ChatRoom extends AppCompatActivity {
String username;
String username1;
TextView userroom;
String image1;
Message_adapter adapter;
ListView L_MESSAGES;
ArrayList<Messages> messages= new ArrayList<Messages>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_room);
Intent intent = getIntent();
username = intent.getStringExtra("username");
username1 = intent.getStringExtra("username1");
userroom =(TextView) findViewById(R.id.userroom);
final EditText tvSender =(EditText) findViewById(R.id.Sender);
final ImageButton btSender=(ImageButton)findViewById(R.id.btSender);
final ImageButton btBack=(ImageButton)findViewById(R.id.back);
btBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ChatRoom.this, ChatActivity.class);
intent.putExtra("username", username);
intent.putExtra("username1", username1);
ChatRoom.this.startActivity(intent);
}
});
btSender.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String message=tvSender.getText().toString();
Response.Listener<String> responselistener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("success");
if (success) {
recreate();
tvSender.setText("");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
MessageSender loginrequest = new MessageSender(message, username,username1, responselistener);
RequestQueue queue = Volley.newRequestQueue(ChatRoom.this);
queue.add(loginrequest);
}
});
getsendMessages();
}
private void getsendMessages(){
String url =config_message.DATA_URL1+username+"&username1="+username1;
userroom.setText(username1);
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJsonFriend(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(ChatRoom.this,volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}
);
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJsonFriend(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(config_message.JSON_ARRAY);
JSONObject collegeData =null;
messages.clear();
for(int i=0;i<result.length();i++) {
collegeData = result.getJSONObject(i);
String friend = collegeData.getString(config_message.KEY_SENDER);
image1 = collegeData.getString(config_message.KEY_IMAGE);
String time = collegeData.getString(config_message.KEY_Time);
String sender = collegeData.getString(config_message.KEY_Sender);
messages.add(new Messages(friend,image1,time,sender));
}
} catch (JSONException e) {
e.printStackTrace();
}
L_MESSAGES=(ListView) findViewById(R.id.chatRoomsList);
adapter = new Message_adapter(this,messages);
L_MESSAGES.setAdapter(adapter);
L_MESSAGES.setSelection(L_MESSAGES.getAdapter().getCount()-1);
}
}
this the button to refresh list:
public void onClick(View v) {
final String message=tvSender.getText().toString();
Response.Listener<String> responselistener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("success");
if (success) {
recreate();
tvSender.setText("");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
MessageSender loginrequest = new MessageSender(message, username,username1, responselistener);
RequestQueue queue = Volley.newRequestQueue(ChatRoom.this);
queue.add(loginrequest);
}
});
There is no need to restart whole Activity. Instead you can insert an element in your list dataset(ArrayList<> or something) and call adapter.notifyDataSetChanged() to make the changes in listview.

HTTP Post Request using Volley

I code to send some message and email using HTTP post using Volley.
when i run the emulator using Genymotion.Everything luking fine but i click the click button it show HTTP has been stopped. I am giving logcat picture Please click this Logcat picture to see Please help me what is wrong and how to resolve this problem
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final String URL_CLICK = "http://www.careoservice.goyalsoftwares.com/feedback/add.php";
public static final String KEY_MESSAGE = "message";
public static final String KEY_EMAIL = "email";
private EditText editTextMessages;
private EditText editTextEmail;
private Button buttonSend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextEmail = (EditText) findViewById(R.id.editmsg);
editTextEmail = (EditText) findViewById(R.id.editmail);
buttonSend = (Button) findViewById(R.id.btnclk);
buttonSend.setOnClickListener(this);
}
public void sendView() throws JSONException {
final String message = editTextMessages.getText().toString().trim();
final String email = editTextEmail.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_CLICK, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
Toast.makeText(MainActivity.this,s, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(KEY_MESSAGE, message);
params.put(KEY_EMAIL, email);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
public void onClick(View v) {
if (v == buttonSend) {
try {
sendView();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
You are not initialazing the "editTextMessages", this is your null pointer exception.

android Volley does not response when request again

all.
I am using volley to make a http request to my website server. And it works fine and response when click the commit button to add a request to request queue. But click the button again does not response. It still shows the progressdialog and response nothing. Is there something wrong ?
Here's code example below:
public class MainActivity extends ActionBarActivity {
private static final String URL = "http://www.google.com";
public RequestQueue mQueue = null;
public StringRequest request = null;
private Button mScanButton = null;
private TextView mDisplay = null;
private ProgressDialog dialog = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mScanButton = (Button) findViewById(R.id.button_scan);
mDisplay = (TextView) findViewById(R.id.display);
request = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("Response retrieved");
mDisplay.setText(response);
dialog.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mDisplay.setText("That didn't work.");
dialog.dismiss();
}
});
request.setShouldCache(false);
mScanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(MainActivity.this, "Mapping data", "please wait..");
mQueue = Volley.newRequestQueue(MainActivity.this);
mQueue.add(request);
System.out.println("Add to queue..");
}
});
}
try this May this guide you here is the complete source which helps you understand easily.
looking at this line
if (ServerConfig.isNetworkOnline(SplashScreen.this)) {
StringRequest strReq = new StringRequest(Request.Method.POST, "your server link", serverResponse, errorListener) {
};
AppController.getInstance().getRequestQueue().add(strReq);
} else {
Toast.makeText(getApplicationContext(), "Please check your network connection", Toast.LENGTH_SHORT).show();
finish();
}
you can remove those above code leaving with below code.
StringRequest strReq = new StringRequest(Request.Method.POST, "your server link", serverResponse, errorListener) {
};
AppController.getInstance().getRequestQueue().add(strReq);
I try to move the area of request declaration to on-click method and it works fine. But I still don't understand how it works.
public class MainActivity extends ActionBarActivity {
private static final String URL = "http://www.google.com";
public RequestQueue mQueue = null;
public StringRequest request = null;
private Button mScanButton = null;
private TextView mDisplay = null;
private ProgressDialog dialog = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mScanButton = (Button) findViewById(R.id.button_scan);
mDisplay = (TextView) findViewById(R.id.display);
mScanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(MainActivity.this, "Mapping data", "please wait..");
request = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("Response retrieved");
mDisplay.setText(response);
dialog.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mDisplay.setText("That didn't work.");
dialog.dismiss();
}
});
mQueue = Volley.newRequestQueue(MainActivity.this);
mQueue.add(request);
System.out.println("Add to queue..");
}
});
}

Categories

Resources