I am developing an app about nearest places in android . But i do not know how to calculate distance and how to sort as ascending in listview. What should i use ?
I did an example like this using Foursquare service with Volley
The most important part of the project is this:
private void getPlaces(){
String apiCall = "https://api.foursquare.com/v2/venues/search?client_id="+CLIENT_ID+"&client_secret="+CLIENT_SECRET+"&v=20130815%20&ll="+latitude+","+longtitude;
JsonObjectRequest Request = new JsonObjectRequest(com.android.volley.Request.Method.GET,
apiCall,
(String) null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Respuesta", response.toString());
//Parseamos la frase
venuesList = (ArrayList<FoursquareVenue>) parseFoursquare(response);
List<String> listTitle = new ArrayList<String>();
for (int i = 0; i < venuesList.size(); i++) {
listTitle.add(i, venuesList.get(i).getName() + ", " + venuesList.get(i).getCategory() + "" + venuesList.get(i).getCity());
}
// set the results to the list
// and show them in the xml
myAdapter = new ArrayAdapter<String>(MainActivity.this, R.layout.row_layout, R.id.listText, listTitle);
setListAdapter(myAdapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Respuesta", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
"Error: "+ error.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
//Añadimos la solicitud a la cola de solicitudes
AppController.getInstance().addToRequestQueue(Request);
}
Here is the entire project
Related
I'm developing a chat with firebase. Actually I'm sending audios between devices, saving it on the Storage ("new_audio"+number+".mp3") and saving that number on the Realtime Database (To know what was the last audio sended)
With the following code I can get the last number, and after that (when is uploading an audio) give him 1 more (number++).
When I start the chat with an user, the number is retrieved with out problems, but when the chat is open and User1 send an audio (new_audio3.mp3) and User2 send another audio after this dont retrieve the Number(Use the same audio number! new_audio3.mp3). In short, the updated number is not received at the same time by the other device, it works just when the chat was recently opened.
String audiosURL = "https://xxxxx.firebaseio.com/audios/" + UserDetails.username + "_" + UserDetails.chatWith +"/audiosEnviados.json";
StringRequest request = new StringRequest(Request.Method.GET, audiosURL, new Response.Listener<String>(){
#Override
public void onResponse(String s) {
try{
int numero = Integer.parseInt(s.trim());
System.out.println("------NUMERO DESDE BD------ "+numero);
if (numero > 0) {
numeroJson = numero;
} else {
numeroJson = -1;
//numeroJson = 0;
}
}catch(Exception E){
numeroJson = 0;
}
reference1.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map map = dataSnapshot.getValue(Map.class);
String message = map.get("message").toString();
String userName = map.get("users").toString();
final String url = "https://xxxxx.firebaseio.com/users/"+UserDetails.username+"/amigos.json";
//ASIGNA EL NOMBRE DE AMIGO EN LA BARRA HEADER CHAT SEGÚN SU ANDROID ID
StringRequest requestAmigo = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject obj = new JSONObject(s);
Iterator i = obj.keys();
String key = "";
String keyNick = "";
while(i.hasNext()) {
key = i.next().toString();
if(!key.equals(UserDetails.username)) {
try {
keyNick = obj.get(key).toString();
if(UserDetails.chatWith.equals(key)){
//UserDetails.chatWith = keyNick;
headerArea.setText(keyNick);
Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/Minecrafter.Reg.ttf");
headerArea.setTypeface(custom_font);
}
} catch (JSONException e) {
// Something went wrong!
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
System.out.println("" + volleyError);
//OJO COMENTE DISMISSSS
//pd.dismiss();
}
});
RequestQueue rQueueAmigos = Volley.newRequestQueue(Chat.this);
rQueueAmigos.add(requestAmigo);
if(userName.equals(UserDetails.username)){
//addMessageBox(" Tú:\n" + " "+message + " \n", 1); el correcto
//addMessageBox(" Tú:\n" + " "+message + " \n \n", 1);
addMessageBox(" "+message + " \n", 1);
}
else{
//addMessageBox(" "+UserDetails.chatWith + ":\n" + " "+message + " \n", 2); EL CORRECTO
//addMessageBox(" "+UserDetails.chatWith + ":\n" +" "+ message + " \n \n", 2);
addMessageBox(" "+message + " \n", 2);
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError volleyError) {
System.out.println("" + volleyError);
}
});
RequestQueue rQueue = Volley.newRequestQueue(Chat.this);
rQueue.add(request);
Upload audio and save number (realtime firebase):
private void uploadAudio(){
mProgress.setMessage("Enviando grabación ...");
mProgress.show();
System.out.println("NUMERO Antes de SUBIR JSON "+numeroJson);
numeroJson++;
StorageReference filepath = mStorage.child("Audio").child(UserDetails.username + "_" + UserDetails.chatWith).child("new_audio"+numeroJson+".mp3");
System.out.println("NUMERO AL SUBIR JSON "+numeroJson);
//SUBE NUMERO DE AUDIOS A SU LISTA
Firebase reference = new Firebase("https://xxxxx.firebaseio.com/audios/"+UserDetails.username + "_" + UserDetails.chatWith);
reference.child("audiosEnviados").setValue(numeroJson);
//SUBE NUMERO DE AUDIOS A LA LISTA DEL AMIGO
Firebase reference2 = new Firebase("https://xxxxx.firebaseio.com/audios/"+UserDetails.chatWith + "_" + UserDetails.username);
reference2.child("audiosEnviados").setValue(numeroJson);
System.out.println("fpath "+filepath);
System.out.println("filename "+mFileName);
Uri uri = Uri.fromFile(new File(dirTest+"/recorded_audio.mp3"));
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
}
});
}
I hope someone knows how to receive the number each time an audio is received / sent in the chat, THANKS <3!
I have a problem with old devices , when the data is sent to the server using an old device api 15 + 16 + 17 in Spanish or Portuguese, question marks will appear, and the new devices have no problems
txt_ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(edit_post.length() > 0)
{
txt_ok.setVisibility(View.GONE);
pd_newpostloading.setVisibility(View.VISIBLE);
String url = Information.URL_AddPendingPosts + Information.userid + "&authorname=" + Information.username + "&message=" + edit_post.getText().toString() + "&type=" + edit_category.getText().toString() + "&date=" + nowAsString;
try {
encodedValue = URLEncoder.encode(url,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
RequestQueue requestQueue = Volley.newRequestQueue(ShowMessages.this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, encodedValue, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
txt_ok.setVisibility(View.VISIBLE);
pd_newpostloading.setVisibility(View.GONE);
Toast.makeText(ShowMessages.this, "Done", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
txt_ok.setVisibility(View.VISIBLE);
pd_newpostloading.setVisibility(View.GONE);
Toast.makeText(ShowMessages.this, "Failed", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(stringRequest);
}
else
{
Toast.makeText(ShowMessages.this, "Empty", Toast.LENGTH_SHORT).show();
}
}
});
I hope to get some help thanks in advance :)
I am working on my app, till morning it was working fine. I used volley in my app. suddenly it stopped working . I am not able to send request to server and get response. It goes to onErrorResponse method. Following is my snippet code
private void makeJsonArrayRequestCountry() {
showpDialog();
JsonArrayRequest req = new JsonArrayRequest( myorderlist_url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("ress", response.toString());
placeorderlists=new ArrayList<MyOrderModel>();;
if(response.length() > 0)
{
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
MyOrderModel movie = new MyOrderModel();
movie.setOrder_Id(obj.getString("orderID"));
movie.setOrder_Name(obj.getString("packDesc"));
movie.setOrder_Imgpath(obj.getString("packImagePath"));
movie.setOrder_Img(obj.getString("packImageName"));
movie.setOrder_date(obj.getString("orderDate"));
movie.setOrder_Status(obj.getString("orderStatus"));
movie.setCancel_Status(obj.getString("isCancelled"));
placeorderlists.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
textcounter.setText("Total Order : "+placeorderlists.size());
}
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(MyOrderListActivity.this);
builder.setMessage("You Have No Order");
String positiveText = getString(android.R.string.ok);
builder.setPositiveButton(positiveText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// positive button logic
Intent intentc=new Intent(MyOrderListActivity.this,OrderActivity.class);
startActivity(intentc);
}
});
String negativeText = getString(android.R.string.cancel);
builder.setNegativeButton(negativeText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// negative button logic
}
});
AlertDialog dialog = builder.create();
// display dialog
dialog.show();
}
// Parsing json
rcAdapter = new RecyclerViewAdapterMyorderlist(MyOrderListActivity.this, placeorderlists);
rView.setAdapter(rcAdapter);
// notifying list adapter about data changes
// so that it renders the list view with updated data
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("ErrorVolley", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
MyApplication.getInstance().addToReqQueue(req, "jreq");
}
in my logcat it shows blank message and getting blank toast
VolleyLog.d("ErrorVolley", "Error: " + error.getMessage());
Once check with below code snippet for error.
#Override
public void onErrorResponse(VolleyError error) {
String body;
//get status code here
String statusCode = String.valueOf(error.networkResponse.statusCode));
//get response body and parse with appropriate encoding
if(error.networkResponse.data!=null) {
try {
body = new String(error.networkResponse.data,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
//do stuff with the body...
}
I am working on a project in which we enter an email and that is checked with the emails present in different tables of the database. Depending upon tables in which the entered email is present I want to display a list of check boxes in a dialog box on clicking a button. My problem is the names of check boxes get updated only on the second click and on further clicks the order of names change. I am not able to figure out this and spent many hours in same. Please help!
MainActivity.java
public class MainActivity extends AppCompatActivity {
public EditText et;
public Main2Activity act;
private String s;
private String[] st = {"","",""};
private int i,j;
private Boolean x;
private String url1 = "http://192.168.56.1:80/axis/results.json";
private String url2 = "http://192.168.56.1:80/hdfc/results.json";
private String url3 = "http://192.168.56.1:80/sbi/results.json";
private ProgressDialog pDialog;
private static String TAG = MainActivity.class.getSimpleName();
private String[] items= {"","",""};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//mail entered into the edittext
et = (EditText)findViewById(R.id.editText);
j=0;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
// on click
public void makeJsonArrayRequest(View view) {
j=0;
s=et.getText().toString();//email to string
JsonArrayRequest req1 = new JsonArrayRequest(url1,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String email = person.getString("email");
if(email.equals(s)){
System.out.println("Axis");
//if present in the table add to list
addItem("AXIS");
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
JsonArrayRequest req2 = new JsonArrayRequest(url2,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String email = person.getString("email");
if(email.equals(s)) {
System.out.println("HDFC");
addItem("HDFC");
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
JsonArrayRequest req3 = new JsonArrayRequest(url3,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String email = person.getString("email");
if(email.equals(s)){
System.out.println("SBI");
addItem("SBI");}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(req1);
AppController.getInstance().addToRequestQueue(req2);
AppController.getInstance().addToRequestQueue(req3);
dialogadd();
}
public void addItem(String s)
{
items[j]=s;
j++;
}
public void dialogadd()
{
Dialog dialog;
final ArrayList itemsSelected = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select banks you want to connect to: ");
builder.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int selectedItemId,
boolean isSelected) {
if (isSelected) {
itemsSelected.add(selectedItemId);
} else if (itemsSelected.contains(selectedItemId)) {
itemsSelected.remove(Integer.valueOf(selectedItemId));
}
}
})
.setPositiveButton("Done!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
//Your logic when OK button is clicked
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
});
dialog = builder.create();
dialog.show();}
}
here is the log cat
logcat
on first click
on second click
on third click
AppController.getInstance().addToRequestQueue(req1); // this will take some time get data
AppController.getInstance().addToRequestQueue(req2); // even this will take some time get data
AppController.getInstance().addToRequestQueue(req3); //last this also will take some time get data
dialogadd(); // but this is an instant call. which will show the dialog, since previous all three call are pending your data get shown unless they complete.
solution : use below call to show the dialog
JsonArrayRequest req3 = new JsonArrayRequest(url3,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String email = person.getString("email");
if(email.equals(s)){
System.out.println("SBI");
addItem("SBI");}
// use this last call show dialog
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Advice
use Future request in volley, i think wt you need is synchronous call one after another
I am fetching json data through Volley. The problem I am having
is that Volley's onResponse is never called, and hence the data are not parsed and displayed.
Sample JSON data
{
"title": "This is a sample text title title",
"cat": {
"origin" : "United states",
"target" : "Asia",
},
"content": "Lorem ipsum ipsum trxt hag jlak jshss jsyts pjqgq uuqtyq usiuqjo uwywh",
}
NewsActivity
public class NewsDetails extends AppCompatActivity {
private final String TAG = "NewsDetails";
private ProgressDialog mProgresscircle;
TextView newsTitle, newsOrigin, newsContent;
//private int news_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_details);
newsTitle = (TextView) findViewById(R.id.dnews_title);
newsOrigin = (TextView) findViewById(R.id.dnews_origin);
newsContent = (TextView) findViewById(R.id.dnews_content);
if (NetworkCheck.isAvailableAndConnected(this)) {
//Calling method to load newss
loadNews();
} else {
final Context context;
context = this;
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle(R.string.alert_titl);
alertDialog.setCancelable(false);
alertDialog.setIcon(R.mipmap.ic_launcher);
alertDialog.setMessage(R.string.failed_news);
alertDialog.setPositiveButton(R.string.alert_retry, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!NetworkCheck.isAvailableAndConnected(context)) {
alertDialog.show();
} else {
loadNews();
}
}
});
alertDialog.setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.show();
}
}
private void loadNews() {
Log.d(TAG, "loadNews called");
mProgresscircle = new ProgressDialog(NewsDetails.this);
mProgresscircle.setCancelable(false);
mProgresscircle.setMessage(null);
mProgresscircle.show();
int news_id = getIntent().getIntExtra("NewsId", -1);
Toast.makeText(NewsDetails.this, "News id is" + news_id, Toast.LENGTH_SHORT).show();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DetailConfig.GET_DURL + news_id,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called NewsDetails");
//Dismissing progressbar;
if (mProgresscircle != null) {
mProgresscircle.dismiss();
}
//Calling method to parse json array
parseNews(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to queue
requestQueue.add(djsonArrayRequest);
}
//This method will parse json data of news
private void parseNews(JSONArray jsonArray) {
Log.d(TAG, "Parsing news array");
for (int i = 0; i<jsonArray.length(); i++) {
JSONObject jsonObject = null;
try {
jsonObject = jsonArray.getJSONObject(i);
String title = jsonObject.getString(DetailConfig.TAG_DPOST_TITLE);
newsTitle.setText(title);
JSONObject pOrigin = jsonObject.getJSONObject("cat");
String origin = pOrigin.getString("origin");
newsOrigin.setText(origin);
String content = jsonObject.getString(DetailConfig.TAG_DPOST_CONTENT);
newsContent.setText(content);
} catch (JSONException w) {
w.printStackTrace();
}
}
}
}
The things I know
In logcat, loadNews method is called.
I'm logging Volley, and from logcat volley is not complaining in anyway
I can't see "onResponse called NewsDetails" in logcat, meaning that for some reason not known to me, it's not called
So, my question is why is onResponse not called and how should I fix it?
You should use JsonObjectRequest instead of JsonArrayRequest because you are getting jsonobject in the response.
For getting more knowledge you may go through Volley tutorial
/* you are getting json in response but your response listener method is get Json Array replace your code with below code and also add an debug point in your error listener method */
private void loadNews() {
Log.d(TAG, "loadNews called");
mProgresscircle = new ProgressDialog(NewsDetails.this);
mProgresscircle.setCancelable(false);
mProgresscircle.setMessage(null);
mProgresscircle.show();
int news_id = getIntent().getIntExtra("NewsId", -1);
Toast.makeText(NewsDetails.this, "News id is" + news_id, Toast.LENGTH_SHORT).show();
final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
DetailConfig.GET_DURL, requestParam,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Debug", response.toString());
//TODO parsing code
parseNews(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to queue
requestQueue.add(djsonArrayRequest);
}
// or replace this code into your into your loadNews method
final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
DetailConfig.GET_DURL, requestParam,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Debug", response.toString());
//TODO parsing code
parseNews(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
}
});
**
You can also refer below link for complete tutorial http://www.hackpundit.com/android-turorial-json-parse-volley/
**