Turn a fatal crash into a non-fatal crashlytics report - java

The code in question:
final GenericAsyncTask task = new GenericAsyncTask();
task.background = new Runnable() {
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(GCMIntentService.this.host);
String addremove = "add";
if(register == false) addremove = "remove";
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("cmd", addremove));
nameValuePairs.add(new BasicNameValuePair("subscription_key", SUBSCRIPTION_KEY)); // unique per app
nameValuePairs.add(new BasicNameValuePair("token", str));
nameValuePairs.add(new BasicNameValuePair("os_family", "android"));
if(addremove.equals("remove")) nameValuePairs.add(new BasicNameValuePair("hard", "" + hard));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs);
httppost.setEntity(entity);
Log.i(LCHApplication.TAG, "Name Value Pairs: " + nameValuePairs.toString());
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
task.result = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
};
task.callback = new Runnable() {
public void run() {
Log.i(LCHApplication.TAG, "registration response: " + task.result.toString());
}
};
task.execute();
Which works great MOST of the time. Sometimes, however, task.result.toString(); is sometimes NULL which throws a java.lang.NullPointerException. I want to keep this crash because I want it to report in crashlytics so I can see how many people it's effecting. If I use a try/catch what can I throw to make sure it's a non-fatal crash instead? That way it will still report to crashlytics but it won't kill the app.

You don't have to throw any caught exception, you can log them very easily like this:
try {
myMethodThatThrows();
} catch (Exception e) {
Crashlytics.logException(e);
// handle your exception here!
}
Source: http://support.crashlytics.com/knowledgebase/articles/202805-logging-caught-exceptions

Related

SSL handshake aborted: ssl=0xae8414e8: I/O error during system call, Connection reset by peer

Everything was working fine until I installed SSL certificate on my websites now i get this error when connecting to c# web api using IIS 10 from android . My code works on android 6 and above but not on android 4.
Here is my code
protected String doInBackground(String... strings) {
List<File> mFiles=new ArrayList<>();
String urlString = Common.URL+"SaveImage";
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
final List<FileBody> mFileBody=new ArrayList<>();
for(int i=0;i<Common.ImagePathList.size();i++){
FileBody bin1 = new FileBody(new File(Common.ImagePathList.get(i)));
mFileBody.add(bin1);
}
Looper.prepare();
MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
reqEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int i=0;i< mFileBody.size();i++){
reqEntity.addPart("Photo"+i,mFileBody.get(i));
}
// reqEntity.addTextBody("size",""+Common.ImagePathList.size(), cz.msebera.android.httpclient.entity.ContentType.parse(ContentType.TEXT_PLAIN));
reqEntity.addTextBody("adId",Common.AdId);
post.setEntity((HttpEntity) reqEntity.build());
//socketFactory.createSocket().connect(client.);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE", response_str);
runOnUiThread(new Runnable() {
public void run() {
try {
mFileBody.clear();
} catch (Exception e) {
e.printStackTrace();
}
}});
return response_str;
}
} catch (Exception ex){
Log.e("Debug", "error: " + ex.getMessage(), ex);
Toast.makeText(getApplicationContext(), ""+ ex.getMessage(), Toast.LENGTH_LONG).show();
}
return null;
}
I tried postman and to see if it was server issue but it works fine in postman but copying the java auto code from postman doesn't work in android and produced Response code 400
Thanks in advance

Android JSON Data Posting results in IO Exception Always

I have a server and I use following Link to post data in my DB
http://URL.php?action=insert&vhc=vehiclenumber&mobile=mobilenumberoftheperson&time=currenttime
To keep record of vehicle entering time, Now I want to post same Data from Android for which I am using Following Code:
Inside Button Goes this:
button.setOnClickListener(new View.OnClickListener() {
//Toast.makeText(getApplicationContext(),"Data is tried!", Toast.LENGTH_LONG).show();
public void onClick(View v)
{
new Thread(new Runnable() {
public void run() {
postData();
}
}).start();
}
});
And my PostData Function is defined below:
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("url.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("vhc", "ABC124"));
nameValuePairs.add(new BasicNameValuePair("mobile", "089944440000"));
nameValuePairs.add(new BasicNameValuePair("time", "2014-12-28 22:22:52"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
message = e.getMessage();
// TODO Auto-generated catch block
} catch (IOException e) {
message= e.getMessage();
// TODO Auto-generated catch block
}
}
Now I tried to debug and found it failing at HttpResponse response = httpclient.execute(httppost); step and leads it to IOException, Please indicate my error to resolve the issue. Thanks!
In you current solution you create a thread, but the thread execute you code sequentially and it does not wait for the response from your server. As a result your client get a null response.
Solution : you have to use AsyncTask for retrieve/send data from/to server. Execute data retrieve part in the doBackground method of AsyncTask. And get your response from the postExecute method. See details here

org.apache.http.client.ClientProtocolException appears when HttpClient executes

I want to send to server some data via POST-request. My code:
protected Void doInBackground(Void... arg)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("https://money.yandex.ru/oauth/authorize");
post.addHeader("Host", "m.sp-money.yandex.ru");
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
post.addHeader("Content-Length", "154");
//data back from server
String responseBackFromServer = "";
try
{
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("client_id", "51"));
pairs.add(new BasicNameValuePair("response_type", "code"));
pairs.add(new BasicNameValuePair("redirect_uri", "https://vk.com/"));
pairs.add(new BasicNameValuePair("scope", "account-info"));
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse server_response = httpclient.execute(post);//!!!exception is appearing here!!!
responseBackFromServer = EntityUtils.toString(server_response.getEntity());
}
catch (ClientProtocolException e)
{
e.printStackTrace();
Log.d(LOG_TAG, "" + e);
}
}
But on "HttpResponse server_response = httpclient.execute(post);" string ClientProtocolException appears. How can I fix it?
Try removing all the addHeader statements. The framework should add them for you.
See here for an example: https://hc.apache.org/httpcomponents-client-4.3.x/quickstart.html

Java application terminates at getOutputStream()

I'm creating an application for our Android devices. The aim of this section is to post a username and password (currently just assigned as a string) to a web service and to receive a login token. When running the code, at the getOutputStream() line, my code terminates and will no progress any further.
I have assigned the android emulator GSM access and also set the proxy and DNS server within Eclipse. I'm not sure where to go with it now!
This is within my onHandleIntent():
protected void onHandleIntent(Intent i) {
try{
HttpURLConnection http_conn = (HttpURLConnection) new URL("http://www.XXXXX.com").openConnection();
http_conn.setRequestMethod("POST");
http_conn.setDoInput(true);
http_conn.setDoOutput(true);
http_conn.setRequestProperty("Content-type", "application/json; charset=utf-8");
String login = URLEncoder.encode("XXXXX", "UTF-8") + "=" + URLEncoder.encode("XX", "UTF-8");
login += "&" + URLEncoder.encode("XXXXX", "UTF-8") + "=" + URLEncoder.encode("XX", "UTF-8");
OutputStreamWriter wr = new OutputStreamWriter(http_conn.getOutputStream());
//TERMINATES HERE
wr.write(login);
wr.flush();
BufferedReader rd = new BufferedReader(new InputStreamReader(http_conn.getInputStream()));
String line = rd.toString();
wr.close();
rd.close();
http_conn.disconnect();
}
catch (IOException e){
}
}
This is my first go at java and have only been writing it for a few days so bear with me if I've missed something obvious.
Thanks
If you want to POST something using HTTP, why not use HTTP POST? ;-)
Here is an example snippet:
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
Source: http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient
This may not be the appropriate answer, but will certainly be helpful to you. I have used this code for sending and receiving the request and reply resp, to a webservice.
This code is working, but will need some Refactoring, as i have used some extra variable, which are not needed.
I have used the NameValuePair here for Post
public String postData(String url, String xmlQuery) {
final String urlStr = url;
final String xmlStr = xmlQuery;
final StringBuilder sb = new StringBuilder();
Thread t1 = new Thread(new Runnable() {
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlStr);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.d("Vivek", response.toString());
HttpEntity entity = response.getEntity();
InputStream i = entity.getContent();
Log.d("Vivek", i.toString());
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
Log.d("YumZing", s);
sb.append(s);
}
Log.d("Check Now",sb+"");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} /*
* catch (ParserConfigurationException e) { // TODO
* Auto-generated catch block e.printStackTrace(); } catch
* (SAXException e) { // TODO Auto-generated catch block
* e.printStackTrace(); }
*/
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Getting from Post Data Method "+sb.toString());
return sb.toString();
}
String line = rd.toString();
should be
String line = rd.readLine();
that might do the trick. rd.toString() gives you a String representation of your BufferedReader. It does not trigger the HTTP operation. I did not test your code, so there might be other errors as well, this was just the obvious one.

Android, HttpPost for WCF

I'm trying to use httpost to get data from our WCF webservice
If the webservice function is without params , something like List getAllMessages()
I'm getting the List in json, no problem here
The tricky part is when the function needs to get argument
let's say Message getMessage(string id)
when trying to call this kind of functions I get error code 500
The working code is:
public String GetAllTitles()
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.xxx.com/Service/VsService.svc/GetAllTitles");
httppost.setHeader("Content-Type", "application/json; charset=utf-8");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
return readHttpResponse(response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
this code works great for functios without arguments..
I took this code and changed it to:
public String SearchTitle(final String id)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.xxx.com/Service/VsService.svc/SearchTitle");
httppost.setHeader("Content-Type", "application/json; charset=utf-8");
httppost.setHeader("Accept", "application/json; charset=utf-8");
NameValuePair data = new BasicNameValuePair("id",id);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(data);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
return readHttpResponse(response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
The function header in thr webservice is:
[OperationContract]
public TitleResult SearchTitle(string id)
{
Stopwatch sw = LogHelper.StopwatchInit();
try
{
TitleManager tm = new TitleManager();
Title title = tm.TitleById(id);
sw.StopAndLog("SearchTitle", "id: " + id);
return new TitleResult() { Title = title };
}
catch (Exception ex)
{
sw.StopAndLogException("SearchTitle", ex, "id: " + id);
return new TitleResult() { Message = ex.Message };
}
}
Anyone can see what am I missing?
Thanks, I'm breaking my head over this one.
List isn't json,
try
String data = "{ id : \"" + id + "\" }";
Don't forget to set Content-Length to data.length.

Categories