Tried to use ACRA in my app, but I can't get the google drive or the email working (in google drive I don't know how to create the form from the template, email tells me there is no such email address even though I am sending from the same email address). I would rather get the google drive spreadsheet thing working or better yet - if there is a ready-to-use script for free web host that I can use to get the reports. Anyone knows of such a script?
EDIT: I need a php one...
Looks like ACRA uses a simple post. What language do you need it in? For asp.net:
protected void Page_Load(object sender, EventArgs e)
{
StringBuilder err = new StringBuilder();
foreach (string name in Request.Form)
{
err.AppendLine(name + ": " + Request.Form[name]);
}
TextWriter tw = null;
try
{
tw = new StreamWriter("f:\\errorLogs\\error_" + DateTime.Now.Ticks + ".txt");
tw.WriteLine(err.ToString());
}
catch (Exception) { }
finally
{
if(tw != null)
tw.Close();
}
}
Since you are using a "free web host", the location probably isn't valid for you, but this should at least get you pointed in the right direction. There is another post which is similar to yours. Most free web hosts use php.
EDIT:
Here is a basic PHP script (Not tested, but seems OK to me. My PHP is a bit rusty):
<?php
$file = 'postData.txt';
$arr= $_POST;
$fp = fopen($file, 'w') or die('Could not open file!');
foreach ($arr as $key => $value) {
$toFile = "Key: $key; Value: $value \n";
// write to file
fwrite($fp, "$toFile") or die('Could not write to file');
}
// close file
fclose($fp);
?>
Related
I'm trying to get this code below to work which was working perfectly a year ago the last time I tried it. After running it I receive no notification in my app. Using in Arduino IDE on ESP32 module. No changes were made at all to the sketch that was once working other than updating the token. I do not get the "firebase error" message in the serial output so assuming no error.
WiFiClient client;
String serve = "MY SERVER KEY";
String appToken = "MY APP TOKEN";
String data = "{";
data = data + "\"to\": \"" + appToken + "\",";
data = data + "\"notification\": {";
data = data + "\"body\": \"example body\",";
data = data + "\"title\" : \"my title\" ";
data = data + "} }";
Serial.println("Send data...");
if (client.connect("fcm.googleapis.com", 80)) {
Serial.println("Connected to the server..");
client.println("POST /fcm/send HTTP/1.1");
client.println("Authorization: key=" + serve + "");
client.println("Content-Type: application/json");
client.println("Host: fcm.googleapis.com");
client.print("Content-Length: ");
client.println(data.length());
client.print("\n");
client.print(data);
Serial.println("data");
Serial.println(data);
}
else {
Serial.println("firebase error");
}
Serial.println("Data sent...Reading response..");
while (client.available()) {
char c = client.read();
Serial.print(c);
}
Serial.println("Finished!");
client.flush();
client.stop();
}
I just updated Firebase in my app and migrated to AndroidX and can receive messages sent from the Firebase console and I'm currently using this library successfully to send and receive the notifications in my app. Below is the example I'm using and it's working perfectly.
#include <WiFi.h>
#include <FirebaseESP32.h>
#define WIFI_SSID "YOUR_WIFI_AP"
#define WIFI_PASSWORD "YOUR_WIFI_PASSWORD"
#define FIREBASE_HOST "YOUR_FIREBASE_PROJECT.firebaseio.com" //Do not include https:// in FIREBASE_HOST
#define FIREBASE_AUTH "YOUR_FIREBASE_DATABASE_SECRET"
#define FIREBASE_FCM_SERVER_KEY "YOUR_FIREBASE_PROJECT_CLOUD_MESSAGING_SERVER_KEY"
#define FIREBASE_FCM_DEVICE_TOKEN_1 "RECIPIENT_DEVICE_TOKEN"
#define FIREBASE_FCM_DEVICE_TOKEN_2 "ANOTHER_RECIPIENT_DEVICE_TOKEN"
FirebaseData firebaseData1;
unsigned long lastTime = 0;
int count = 0;
void sendMessage();
void setup()
{
Serial.begin(115200);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(300);
}
Serial.println();
Serial.print("Connected with IP: ");
Serial.println(WiFi.localIP());
Serial.println();
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
Firebase.reconnectWiFi(true);
firebaseData1.fcm.begin(FIREBASE_FCM_SERVER_KEY);
firebaseData1.fcm.addDeviceToken(FIREBASE_FCM_DEVICE_TOKEN_1);
firebaseData1.fcm.addDeviceToken(FIREBASE_FCM_DEVICE_TOKEN_2);
firebaseData1.fcm.setPriority("high");
firebaseData1.fcm.setTimeToLive(1000);
sendMessage();
}
void loop()
{
if (millis() - lastTime > 60 * 1000)
{
lastTime = millis();
sendMessage();
}
}
void sendMessage()
{
Serial.println("------------------------------------");
Serial.println("Send Firebase Cloud Messaging...");
firebaseData1.fcm.setNotifyMessage("Notification", "Hello World! " + String(count));
firebaseData1.fcm.setDataMessage("{\"myData\":" + String(count) + "}");
//if (Firebase.broadcastMessage(firebaseData1))
//if (Firebase.sendTopic(firebaseData1))
if (Firebase.sendMessage(firebaseData1, 0))//send message to recipient index 0
{
Serial.println("PASSED");
Serial.println(firebaseData1.fcm.getSendResult());
Serial.println("------------------------------------");
Serial.println();
}
else
{
Serial.println("FAILED");
Serial.println("REASON: " + firebaseData1.errorReason());
Serial.println("------------------------------------");
Serial.println();
}
count++;
}
I've tried sending the code at the top in data and notification message format with app in foreground and background and cannot receive a message. I'm wondering if something in the Firebase format or rules or such has changed within the last year. I need to use the code at the top instead of the library because I can just add a few more key value pairs in the message body and also send to iOS which I have done successfully in the past using the same code. I'm sure the key pairs could be added with the library actually which I'm working on now but would really prefer the simplicity of the top code. Would appreciate any advice.
I'm not certain but I believe the problem may be that the Arduino code is sending via HTTP and not HTTPS, which I read in the FB docs HTTPS is required. Maybe they changed that because this same code was working perfectly for me a year ago. But I was in the process of migrating my code over to ESP-IDF and this function below is working on that with no problem which has slight mods to comply with C++ I'm using in PlatformIO / VS Code IDE. This was the only thing changed:
esp_http_client_config_t config = {};
config.url = "https://fcm.googleapis.com/fcm/send";
config.event_handler = _http_event_handler;
I didn't need any type of SSL certificate, I just sent the code as shown. I didn't try messing around too much with the Arduino code for HTTPS.
static void firebasePost() {
esp_http_client_config_t config = {}; // important to initialize with "{}" when using C++ on ESP-IDF http client or it will crash easily
config.url = "https://fcm.googleapis.com/fcm/send";
config.event_handler = _http_event_handler;
esp_http_client_handle_t client = esp_http_client_init(&config);
esp_err_t err = esp_http_client_perform(client);
const char *post_data = "{\"to\": \"eCiC-20m8Zw:APA91bE4i1rkC(SHORTENED)9JZpbW3gFe5Qfz9BhOFmqua3aeZoDZEQ\",\"notification\": {\"body\": \"Sample Body\",\"title\" : \"Sample Title\"} }";
esp_http_client_set_header(client, "Authorization", "key=AAAAZrM4XXXX:APA91bFnSr_U15y6mX(SHORTENED)WqaWECxYWaCf_rVPE");
esp_http_client_set_header(client, "Content-Type", "application/json");
esp_http_client_set_method(client, HTTP_METHOD_POST);
esp_http_client_set_post_field(client, post_data, strlen(post_data));
err = esp_http_client_perform(client);
if (err == ESP_OK) {
ESP_LOGI(TAG, "HTTP POST Status = %d, content_length = %d",
esp_http_client_get_status_code(client),
esp_http_client_get_content_length(client));
} else {
ESP_LOGE(TAG, "HTTP POST request failed: %s", esp_err_to_name(err));
}
esp_http_client_cleanup(client);
}
The Arduino Firebase library connects to Firebase via SSL port 443 (HTTPS method) for both FCM and RTDB.
Your above assumption is not correct.
Your device token is invalid or not existed.
You don't have to know the code inside the Arduino library. Google only accept secure connection for their services. The problems can be the device uid or redundant of FCM payload data. You accept your answer with your own assumption. No solution for this issue. You need to open the issue at GitHub repo.
I am sagar, i am trying to implement the Parse Push-Notification in android using REST API (Service), and i am almost got success in implement the Push-Notification in Xamarin-Android using REST API. But i got stuck with one part in sending the Data into REST service. I trying to pass the ParseObject in service, but the in parse table there is a need of Object,(). I have tried to pass the ParseObject as below:
JsonConvert.SerializeObject(ParseUser.CurrentUser)
It convert ParseObject into array and array is not accepted in table and ,i got failed to save it in table. because there i a need of object.
I need solution or suggestion from developer guys. Yours help will be appreciated. I am trying the below code to achieve the result.
public static void RegisterPush(string regristrationId)
{
if (regristrationId != null) {
string appID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string restID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string masterID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
try {
var client = new RestClient ("https://api.parse.com");
var request = new RestRequest ("1/installations", RestSharp.Method.POST);
request.AddHeader ("Accept", "application/json");
request.AddHeader ("X-Parse-Application-Id", appID);
request.AddHeader ("X-Parse-REST-API-Key", restID);
request.Credentials = new NetworkCredential (appID, masterID);
request.Parameters.Clear ();
Console.Error.WriteLine ("ParseUser.CurrentUser-->"+ (ParseObject) ParseUser.CurrentUser);
//JsonConvert.SerializeObject(ParseUser.CurrentUser)
string strJSONContent = "{\"user\" :"+ JsonConvert.SerializeObject(ParseUser.CurrentUser)+",\"owner\":\"" + ParseUser.CurrentUser.ObjectId + "\",\"deviceType\":\"android\",\"GCMSenderId\":\"1234567890\",\"appName\":\"abcdefgh\",\"pushType\":\"gcm\",\"deviceToken\":\"" + regristrationId + "\"}";
Console.Error.WriteLine("json string-->"+ strJSONContent);
request.AddParameter ("application/json", strJSONContent, ParameterType.RequestBody);
client.ExecuteAsync (request, response => {
Console.Error.WriteLine ("response for android parse installation-->" + response.Content);
});
} catch (Exception ex) {
Console.WriteLine (ex.Message);
}
}
}`
Output:{"user" :[{"Key":"dealOffered","Value":4},{"Key":"dealRequested","Value":5},{"Key":"displayName","Value":"Cook"},{"Key":"email","Value":"lorenzo#gmail.com"},{"Key":"firstName","Value":"Lorenzo"},{"Key":"lastName","Value":"Cook"},{"Key":"mobileNumber","Value":9999999999.0},{"Key":"picture","Value":{"IsDirty":false,"Name":"tfss-afd25c29-6679-4843-842c-fe01f7fcf976-profile.jpg","MimeType":"image/jpeg","Url":"http://files.parsetfss.com/profile.jpg"}},{"Key":"provider","Value":"password"},{"Key":"userType","Value":"Merchant"},{"Key":"username","Value":"merchant#sailfish.com"},{"Key":"zipCode","Value":2342343}],"owner":"3cF1vHUXkW","deviceType":"android","GCMSenderId":"1234567890123","appName":"Sailfish","pushType":"gcm","deviceToken":"APA91bE3bsTIInQcoloOBE4kdLVVHVTRVtNyA1A788hYSC15wAVu8mUg-lwk7ZPk370rngrK7J6OoLmiM9HRr1CGPaBo6LCNrSUL7erBku4vepaFFkQzgqS6BcAemp"}
Error:{"code":111,"error":"invalid type for key user, expected *_User, but got array"}
maven
I found the solution in , parse xamarin docs, in one query , the way is simple, but i little bit hard to found out.
The issue is with the data passing in json format in REST, to pass any pointer using REST API, use as below.
The solution is as below:
`{
"user":{
"__type":"Pointer",
"className":"_User",
"objectId":"qYvzFzGAzc"
},
"owner":"qYvzFzGAzc",
"deviceType":"android",
"GCMSenderId":"123456789",
"appName":"NiceApp",
"pushType":"gcm",
"deviceToken":"APA91bFeM10jdrCS6fHqGGSkON17UjEJEfvJEmGpRM-d6hq3hQgDxKHbyrqAIxMnEGgbLEZf0E9AllHxiQQQCdEFiNMF1_A8q0n9tGpBE5NKhvS2ZGJ9PZ7585puWqz_1Z1EjSjOvgZ1LQo708DeL2KzA7EFJmdPAA"
}`
It looks like your column user is set up wrong. It should show as a Pointer<_User> not Pointer
If you load this class in your Data Browser, is the "user" key defined as a string, or a Pointer <_User>
This error seems to indicate that this is a string column, which is why the Parse.User object is not being accepted as a valid value. You might have tried setting a string on this key before, which in turn type-locked the "user" key as a string column.
Found it on the examples given on this page - https://www.parse.com/docs/rest
Have you check your REST API connection while passing ParseObject?
Because your error says:
Error:{"code":111,"error":"invalid type for key user, expected *_User, but got array"}
Here "code":111This error code comes when server refuse for connection
I want to upload image on Google Cloud Storage from my android app. For that I searched and found that GCS JSON Api provides this feature. I did a lot of research for Android sample which demonstrates its use. On the developer site they have provided code example that only support java. I don't know how to use that API in Android. I referred this and this links but couldn't get much idea. Please guide me on how i can use this api with android app.
Ok guys so I solved it and got my images being uploaded in Cloud Storage all good.
This is how:
Note: I used the XML API it is pretty much the same.
First, you will need to download a lot of libraries.
The easiest way to do this is create a maven project and let it download all the dependencies required. From this sample project :
Sample Project
The libraries should be:
Second, you must be familiar with Cloud Storage using the api console
You must create a project, create a bucket, give the bucket permissions, etc.
You can find more details about that here
Third, once you have all those things ready it is time to start coding.
Lets say we want to upload an image:
Cloud storage works with OAuth, that means you must be an authenticated user to use the API. For that the best way is to authorize using Service Accounts. Dont worry about it, the only thing you need to do is in the API console get a service account like this:
We will use this service account on our code.
Fourth, lets write some code, lets say upload an image to cloud storage.
For this code to work you must put your key generated in step 3 in assets folder, i named it "key.p12".
I don't recommend you to do this on your production version, since you will be giving out your key.
try{
httpTransport= new com.google.api.client.http.javanet.NetHttpTransport();
//agarro la key y la convierto en un file
AssetManager am = context.getAssets();
InputStream inputStream = am.open("key.p12"); //you should not put the key in assets in prod version.
//convert key into class File. from inputstream to file. in an aux class.
File file = UserProfileImageUploadHelper.createFileFromInputStream(inputStream,context);
//Google Credentianls
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(Collections.singleton(STORAGE_SCOPE))
.setServiceAccountPrivateKeyFromP12File(file)
.build();
String URI = "https://storage.googleapis.com/" + BUCKET_NAME+"/"+imagename+".jpg";
HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
GenericUrl url = new GenericUrl(URI);
//byte array holds the data, in this case the image i want to upload in bytes.
HttpContent contentsend = new ByteArrayContent("image/jpeg", byteArray );
HttpRequest putRequest = requestFactory.buildPutRequest(url, contentsend);
com.google.api.client.http.HttpResponse response = putRequest.execute();
String content = response.parseAsString();
Log.d("debug", "response is:"+response.getStatusCode());
Log.d("debug", "response content is:"+content);} catch (Exception e) Log.d("debug", "Error in user profile image uploading", e);}
This will upload the image to your cloud bucket.
For more info on the api check this link Cloud XML API
Firstly, You should get the below information by registering your application in the GCP console.
private final String pkcsFile = "xxx.json";//private key file
private final String bucketName = "your_gcp_bucket_name";
private final String projectId = "your_gcp_project_id";
Once you get the credentials, you should put the private key (.p12 or .json) in your assets folder. I'm using JSON format private key file. Also, you should update the image location to upload.
#RequiresApi(api = Build.VERSION_CODES.O)
public void uploadImageFile(String srcFileName, String newName) {
Storage storage = getStorage();
File file = new File(srcFileName);//Your image loaction
byte[] fileContent;
try {
fileContent = Files.readAllBytes(file.toPath());
} catch (IOException e) {
e.printStackTrace();
return;
}
if (fileContent == null || fileContent.length == 0)
return;
BlobInfo.Builder newBuilder = Blob.newBuilder(BucketInfo.of(bucketName), newName);
BlobInfo blobInfo = newBuilder.setContentType("image/png").build();
Blob blob = storage.create(blobInfo, fileContent);
String bucket = blob.getBucket();
String contentType = blob.getContentType();
Log.e("TAG", "Upload File: " + contentType);
Log.e("File ", srcFileName + " uploaded to bucket " + bucket + " as " + newName);
}
private Storage getStorage() {
InputStream credentialsStream;
Credentials credentials;
try {
credentialsStream = mContext.getAssets().open(pkcsFile);
credentials = GoogleCredentials.fromStream(credentialsStream);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return StorageOptions.newBuilder()
.setProjectId(projectId).setCredentials(credentials)
.build().getService();
}
This problem freak me out
I have an application and now i want to transer data between client android application and localhost tomcat 7 server, i did that many times ago, now when i want to send data from client to server it works well and i can see the data on the server, but something happend and the android application is trying to trigger an activity from another project i deleted that project then still try to trigger activty form another project
my actiivty name is "Signup", and the android client trying to trigger activiteis with the same name from another projects.
as in log :
NumberFormatException: unable to parse
'[Lorg.apache.http.Header;#44ee4c10' as integer
means you are trying to parse wrong string to Integer . wrap casting code inside try/catch block to avoid NumberFormatException as :
String str_NumberOfCities="";
Header[] headers = response.getAllHeaders();
for (int i=0; i < headers.length; i++) {
Header h = headers[i];
Log.i(TAG, "Header names: "+h.getName());
if(h.getName().toLowerCase().contains("NumberOfCities".toLowerCase()){
str_NumberOfCities=h.getValue();
}
Log.i(TAG, "Header Value: "+h.getValue());
}
int numberOfCities=0;
try {
numberOfCities = Integer.parseInt(str_NumberOfCities);
} catch (NumberFormatException e) {
numberOfCities=0;
}
Data.cities = new String[numberOfCities];
///....your code
I have read on net tutorials that cloud can be used for storing data.So i wanted to ask that whether sql server 2005 table data be stored in amazon cloud.Can anyone give me the sample code to store data from sql server in amazon and retrieve it in android application?
Amazon gives you a server instance with the operating system specified by you. you can technically, install anything on it and host that.
What you should technically do is to take an instance of your desired specification from Amazon.
Write a simple web application (I would do a java webapp. For sure you can go for the same as you already are doing Android programming.) with connectivity to your DB and that has controllers to run your SQL queries and returns the values.
Here is some example code. This uses Spring just so you know. You can use plain MVC as well if you want do it simple to start with.
#RequestMapping ( value = "runquery" , method = RequestMethod.GET )
#ResponseBody
public void runQuery()
{
Statement lStatement = null;
Connection lConnection = null;
ResultSet lResultSet = null;
try
{
lConnection = DBAccess.getConnection();
lStatement = lConnection.createStatement();
lResultSet = lStatement.executeQuery( "select * from table" );
while ( lResultSet.next() )
{
mLogger.info("The result set is : "+lResultSet.toString());
}
}
catch( Exception e )
{
e.printStackTrace();
mLogger.error("Exception occurred while trying to runQuery : "+e.getMessage());
}
finally
{
DBAccess.closeResultSet( lResultSet );
DBAccess.closeStatement( lStatement );
DBAccess.closeDBConnection( lConnection );
}
}