Question marks in my data base with volley - android

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

Related

Out of memory error using Volley using timers

I have this issue with Volley library requests. I make calls to API and since they have to be updated very often I implemented timers. After some time it throws me error:"Throwing OutOfMemoryError “pthread_create (1040KB stack) failed: Try again. I used the method which was suggested in this post: Throwing OutOfMemoryError "pthread_create (1040KB stack) failed: Try again" when doing asynchronous posts using Volley , but for me it did not work, the data coming from API stopped updating. I thought it might be something with timers or it is just something I am doing wrong using Volley.
If you have any idea, feel welcome to share.
My printer class
public void setMenuInformation(String url, Context context, final VolleyCallback callback) {
Log.d("API", "Currently calling URL " + url);
if (eRequestQueue == null) {
eRequestQueue = Volley.newRequestQueue(context);
eRequestQueue.add(new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String temp = response.substring(2, response.length() - 2);
Log.d("API", "Current menu" + response);
byte msgArray[];
try {
msgArray = temp.getBytes("ISO-8859-1");
currentMenu = msgArray[0];
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
menuInformation = response;
callback.onSuccess(menuInformation);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("API", "Current menu Nope ");
callback.onFailure(error);
}
}));
}
}
Main Activity:
myPrinterDetails.setMenuInformation("http://" + nsdServiceInfo.getHost() + "/GetCurrentMenu",
MainActivity.this, new PrinterNew.VolleyCallback() {
#Override
public void onSuccess(String result) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d("NSD", "Current menu response succeded and added to array " + nsdServiceInfo);
//services.add(myPrinterDetails);
mAdapter.notifyDataSetChanged();
}
});
Log.d("NSD", "CurrentMenu " + myPrinterDetails.getMenuInformation());
myTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
myPrinterDetails.setMenuInformation("http://" + nsdServiceInfo.getHost() + "/GetCurrentMenu", MainActivity.this, new PrinterNew.VolleyCallback() {
#Override
public void onSuccess(String result) {
Log.d("NSD", "Current menu response added to timer " + nsdServiceInfo);
mAdapter.notifyDataSetChanged();
}
#Override
public void onFailure(Object response) {
Log.d("NSD", "Current menu timer failed");
}
});
}
});
}
}, 0, 2000);
}
#Override
public void onFailure(Object response) {
Log.d("NSD", "Current menu response failed");
}
});
}
};
}

Firebase realtime number 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!

Get location from Facebook Account API

I've made lots of attempts to get the city for this account to view the account on the app but it dont work
//Login Facebook
public void Login()
{
Dialog dialog = new Dialog(Home.this);
dialog.setContentView(R.layout.customdialog_login);
login_button = (LoginButton)dialog.findViewById(R.id.login_button);
login_button.setReadPermissions("public_profile", "email", "user_birthday", "user_friends","user_location");
callbackManager = CallbackManager.Factory.create();
dialog.show();
login_button.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
GraphRequest graphRequest = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(final JSONObject object, GraphResponse response) {
try {
SaveSystem.SaveStringData("userid" , object.getString("id"));
SaveSystem.SaveStringData("first_name" , object.getString("first_name"));
SaveSystem.SaveStringData("last_name" , object.getString("last_name"));
SaveSystem.SaveStringData("gender" , object.getString("gender"));
SaveSystem.SaveStringData("admin" , "0");
SaveSystem.SaveStringData("ban" , "0");
SaveSystem.SaveStringData("type" , "facebook");
//CheckUser
final RequestQueue requestQueue = Volley.newRequestQueue(Home.this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, Information.URL_CheckUsers + SaveSystem.LoadStringData("userid"), new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Toast.makeText(Home.this, "Location " + object.getJSONObject("location").getJSONObject("location").getString("city"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
if(response.equals("0"))
{
//Add Account
String URL_AddUser = Information.URL_AddUsers + SaveSystem.LoadStringData("userid") + "&username=" + SaveSystem.LoadStringData("first_name") + " " + SaveSystem.LoadStringData("last_name") + "&gender=" + SaveSystem.LoadStringData("gender") + "&admin=" + SaveSystem.LoadStringData("admin") + "&ban=" + SaveSystem.LoadStringData("ban") + "&type=" + SaveSystem.LoadStringData("type");
StringRequest stringRequest1 = new StringRequest(Request.Method.GET, URL_AddUser , new Response.Listener<String>() {
#Override
public void onResponse(String response) {
setAccountData();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Home.this, "Failed", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(stringRequest1);
}
else
{
setAccountData();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, first_name, last_name, email,gender, birthday, location{location}");
graphRequest.setParameters(parameters);
graphRequest.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
}
here I try to present the area to experience
try {
Toast.makeText(Home.this, "Location " + object.getJSONObject("location").getJSONObject("location").getString("city"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
can I view Json facebook on Chrome ?? , I do not know how to arrange Json on facebook
I searched a lot but I dont get the city. Is it a problem in my blades or what please help me really thank you

In my code, only one link is parse, but I have four different links. How can I parse all of them

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btn;
TextView price;
String url = "https://koinim.com/ticker/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.btn_get_information);
price = (TextView)findViewById(R.id.price);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v){
if (v.getId() == R.id.btn_get_information){
JsonObjectRequest jsonObjectRequest = new
JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
price.setText("BTC: " +
response.getString("sell")+ " " + "₺" );
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText((getApplicationContext()),"Error",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
MySingleton.getmInstance(getApplicationContext()).
addToRequestQue(jsonObjectRequest);
}
}
}
I am a new developer in android.
I looked at the sources and made the parse from one link. But I have four links. How do I parse the four links?
Instead of having a String url, create an ArrayList of Strings that holds all your URLs.
In the method onClick() loop through the URLs.
Note that the ArrayList is filled in onCreate. I also added a try/catch clause in onClick, so if something goes wrong with one URL, the others will be parsed anyways.
Handling different URLs:
For parsing the Koinim ticker, you needed the key "sell", for Paribu you will need "last".
In the loop I am checking if the URL contains either Koinim or Paribu and adjust they key accordingly.
ArrayList<String> urls = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn_get_information);
price = (TextView) findViewById(R.id.price);
urls.add("https://koinim.com/ticker/");
urls.add("url2");
urls.add("url3");
urls.add("url4");
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btn_get_information) {
for (String url : urls) {
try {
JsonObjectRequest request = null;
if(url.contains("koinim"))
{
request = getSellPrice("sell");
}
else if(url.contains("paribu"))
{
request = getSellPrice("last");
}
if(request != null)
{
MySingleton.getmInstance(getApplicationContext()).
addToRequestQue(jsonObjectRequest);
}
} catch (Exception ex) {
// something went wrong, handle exception here
}
}
}
}
private JsonObjectRequest getSellPrice(String key)
{
JsonObjectRequest jsonObjectRequest = new
JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
price.setText("BTC: " +
response.getString(key) + " " + "₺");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText((getApplicationContext()), "Error", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
return jsonObjectRequest;
}

Firebase has no response regarding volley request

I am new to firebase. I tried to store user data in firebase database using volley. However, firebase has no response regarding my volley request and the database still is null. This is the tutorial I followed.
This is the volley request I used to connect firebase.
public void executeFirebase(){
StringRequest request = new StringRequest(Request.Method.GET, FIREBASE_REGISTER_URL, new Response.Listener<String>(){
#Override
public void onResponse(String s) {
Firebase reference = new Firebase("https://tradeal-930ad.firebaseio.com/users");
if(s.equals("null")) {
reference.child(name).child("password").setValue(password);
Toast.makeText(activity, "registration successful 1", Toast.LENGTH_LONG).show();
}
else {
try {
JSONObject obj = new JSONObject(s);
if (!obj.has(name)) {
reference.child(name).child("password").setValue(password);
Toast.makeText(activity, "registration successful 2", Toast.LENGTH_LONG).show();
Intent intent = new Intent(activity, MainPageActivity.class);
activity.startActivity(intent);
activity.finish();
loginUserActivity.finish();
} else {
Toast.makeText(activity, "username already exists", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
loading.dismiss();
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError volleyError) {
System.out.println("" + volleyError );
loading.dismiss();
}
});
RequestQueue rQueue = Volley.newRequestQueue(activity);
rQueue.add(request);
}
change the rules of your database to public
{
"rules" :
{
".read" : true,
".write" : true
}
}
otherwise
{
"error" : "Permission denied"
}
this will be your response
to know more about rules you can visit security rules

Categories

Resources