Firebase realtime number Android - android

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!

Related

Android Studio: Store push notifications

Hello I created an android application which receives automatic push notifications and store them in the main activity... Basically I am storing the notifications in an edit text just for testing and it is working... How can I get the messages in a listview instead of an edit text? and can I make a table and display the date and time in a column and the message in another column next to it?
My code for storing in edittext is the following:
final FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myRef = database.getReference("Fall_Detection_Status");
final DatabaseReference myRef1 = database.getReference("Fall_Detection_Status1");
final DatabaseReference myRef2 = database.getReference("Seizure");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
val = dataSnapshot.getValue(Long.class);
if(val.longValue() == 1 && val1.longValue() == 1) {
Date currentTime = Calendar.getInstance().getTime();
writeToFile(currentTime.toString() + "\n" + " Fall Detected" + "\n", getApplicationContext());
result.setText("");
result.setText(readFromFile(getApplicationContext()));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
myRef1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
val1 = dataSnapshot.getValue(Long.class);
if(val.longValue() == 1 && val1.longValue() == 1) {
Date currentTime = Calendar.getInstance().getTime();
writeToFile(currentTime.toString() + "\n" + " Fall Detected" + "\n", getApplicationContext());
result.setText("");
result.setText(readFromFile(getApplicationContext()));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
myRef2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Toast.makeText(getApplicationContext(),"This is a test!",Toast.LENGTH_LONG).show();
val2 = dataSnapshot.getValue(Long.class);
if(val2.longValue() == 1){
Date currentTime = Calendar.getInstance().getTime();
writeToFile(currentTime.toString() + "\n" + " Seizure Detected" + "\n", getApplicationContext());
result.setText("");
result.setText(readFromFile(getApplicationContext()));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
result.setText("");
result.setText(readFromFile(getApplicationContext()));
myRef.setValue(0);
myRef1.setValue(0);
myRef2.setValue(0);
private String readFromFile(Context context)
{
StringBuilder total = new StringBuilder();
BufferedReader r = null;
try {
r = new BufferedReader(new InputStreamReader(context.openFileInput("events.txt")));
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return total.toString();
}
private void writeToFile(String data,Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("events.txt", Context.MODE_APPEND));
outputStreamWriter.append(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
Take your push notification value in ArrayList and implement in recycler feature.
Notify the recycler adapter when you have new push message.
Recycler implementation example
Just read sqlLite database tutorial of android.
Android Database Tutorial

Question marks in my data base with volley

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 :)

Android Volley URL with parameters

I have written a code using a volley library (GET) and I have to fetch the data from the rest API in Django.
Actually the problem is i am getting a user id while i login , i just saved that id through shared preferences and i have to pass the id in the URL to get wallet details but i am getting error
BasicNetwork.performRequest: Unexpected response code 403
public class Wallet extends AppCompatActivity {
TextView all_tv1;
Button credit_bt, debit_bt;
SharedPreferences pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
setContentView(R.layout.activity_wallet);
pref=getApplication().getSharedPreferences("Options", MODE_PRIVATE);
Integer Key_UserID=pref.getInt("UserId_Value", 0);
// String a = Key_UserID.toString();
/Json Request/
String uri = "http://staging.exol.in/wallet/wallet/api/wallet-detail/+Key_UserID";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, uri, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Toast.makeText(getApplicationContext(),"stop",LENGTH_SHORT).show();
// String data = "";
try {
for(int i=0; i< response.length(); i++) {
JSONObject obj = response.getJSONObject(i);
String tnx_id = obj.getString("tnx_id");
String transition_type = obj.getString("transition_type");
// String email = obj.getString("email");
// System.out.print("\nggtrgtg"+user+"\ngfg"+amount);
Toast.makeText(getApplicationContext(),tnx_id + transition_type ,LENGTH_SHORT).show();
// data = "" + id + "" + name + "" + email + "";
//txtDisplay.setText(txtDisplay.getText()+"\n" + id + "" + name + "\n" + email + "");
// Adds the data string to the TextView "results"
}
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),"Faled Misreably" ,LENGTH_SHORT).show();
}
});
//add request to queue
requestQueue.add(jsonArrayRequest);
setTitle("Wallet Window");
Toolbar toolbar1 = (Toolbar)findViewById(R.id.tool_bar);
setSupportActionBar(toolbar1);
all_tv1 = (TextView)findViewById(R.id.all_tv);
all_tv1.setMovementMethod(new ScrollingMovementMethod());
credit_bt = (Button)findViewById(R.id.credit_details1__bt);
debit_bt = (Button) findViewById(R.id.debit_details1__bt);
credit_bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Credit Tab", LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), Wallet_Credit.class);
startActivity(i);
finish();
}
});
debit_bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Debit Tab", LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), Wallet_Debit.class);
startActivity(i);
finish();
}
});
}
}
Your uri string is not set properly (notice the closing "). Instead of
String uri = "http://staging.exol.in/wallet/wallet/api/wallet-detail/+Key_UserID";
It should be
String uri = "http://staging.exol.in/wallet/wallet/api/wallet-detail/"+Key_UserID;

Items Update on second click

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

How to find nearest places for example(like hospital)

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

Categories

Resources