Data is not being saved to Database - android

In my android application I am trying to save some data in MongoDB database. I using this code (given below) for that. This code is displaying Toast that data is saved, but the data is not present in my database. I am not getting any exception. so kindly tell what can be the problem?
Code:
#Override
protected Boolean doInBackground(String... reminder) {
try {
URL requestUrl = new URL("MongoDB address");
HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.connect();
OutputStream save = connection.getOutputStream();
save.write(reminder[0].getBytes());
save.close();
connection.disconnect();
new Handler(context.getMainLooper()).post(new Runnable() {
public void run() {
Toast.makeText(context, "data is saved", Toast.LENGTH_LONG).show();
}
});
}
catch(Exception exception) {
Log.e("ERROR", "DB Saving", exception);
}
return true;
}

Related

Why my android app isn't responding after POST method?

I have a problem. I'm trying to execute POST method to my Node.js server. After POST method I'm getting all the data in server but then my app isn't responding a few seconds. Is there some bugs in my code?
My POST method:
public static void setTemp(String address, String hot, String cold) throws IOException
{
URL url = new URL(address); //in the real code, there is an ip and a port
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
try {
conn.connect();
JSONObject jsonParam = new JSONObject();
jsonParam.put("hot", hot);
jsonParam.put("cold", cold);
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
os.writeBytes(jsonParam.toString());
os.flush();
os.close();
Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("MSG" , conn.getResponseMessage());
} catch (Exception e) {
}
finally {
conn.disconnect();
}
}
This is how I call the POST method:
private void setTemp(String hot, String cold)
{
try {
WebAPI.setTemp(Tools.RestURLPost, hot, cold);
}
catch(IOException e) {
e.printStackTrace();
}
}
And here you can find my Node.js method which I use to test successful parsing of JSON:
router.post('/post', function(req, res, next) {
console.log(req.body);
});
Without seeing the whole code it's hard to know but you're never ending the request in Node, so use: req.send/json, otherwise the Android application will wait until the request is done, which won't happen and it will timeout.
router.post('/post', function(req, res, next) {
console.log(req.body);
res.json({ success: true });
});

How to Handle connection timeout in async task

I have a problem that I haven't solved yet and I need help.
When internet is slow application crashes. how can can I check connection timeout in asyntask.
I made an app that sometimes connect to web service to get data and i do that using async task
I want to make alert dialog on connection timeout when user can choose whether they want to retry or cancel, if they choose retry it will try to connect again
public class login extends AsyncTask<Void,Void,Void> {
InputStream ins;
String status, result, s = null, data = "",js;
int ss;
int responseCode;
#Override
protected void onPreExecute() {
super.onPreExecute();
pdlg.setTitle("Checking");
pdlg.setMessage("Please wait");
pdlg.setCancelable(false);
pdlg.show();
}
#Override
protected Void doInBackground(Void... params) {
StringBuilder sb = new StringBuilder();
ArrayList al;
try {
URL url = new URL("http://....login.php");
String param = "username=" + uname + "&password=" + pass;
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(15000);
connection.setReadTimeout(15000);
connection.setDoInput(true);
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
bw.write(param);
bw.flush();
bw.close();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
}
data = sb.toString();
JSONObject json = new JSONObject(data);
status=json.getString("Status");//{"Login Status":"Success","Receipt Details":"No data available"}
// js=json.getString("Login");//{"Login":"Failed"}
} catch (MalformedURLException e) {
Log.i("MalformedURLException", e.getMessage());
} catch (IOException e) {
Log.i("IOException", e.getMessage());
} catch (JSONException e) {
Log.i("JSONException", e.getMessage());
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
String status1=status.trim();
if (status1.equals("Success")) {
Toast.makeText(getApplicationContext(), "Login Succes !!", Toast.LENGTH_SHORT).show();
Intent i = new Intent(Login.this, Home.class);
startActivity(i);
finish();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("first_time", false);
editor.putString("userrname", uname);
editor.putString("password",pass);
editor.apply();
Toast.makeText(getApplicationContext(),"welcome : "+uname,Toast.LENGTH_LONG).show();
}
else {
Toast t=Toast.makeText(Login.this, "Username or Password is Incorrect", Toast.LENGTH_LONG);
t.setGravity(Gravity.BOTTOM,0,0);
t.show();
}
pdlg.dismiss();
}
}
You can use getErrorStream() ,
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream inp;
// if some error in connection
inp = connection.getErrorStream();
check this answer for more details..
according to the doc it returns
an error stream if any, null if there have been no errors, the
connection is not connected or the
server sent no useful data
.
use this two catch blocks to handle ConnectionTimeOut and socketTimeOut Exceptions
catch (SocketTimeoutException bug) {
Toast.makeText(getApplicationContext(), "Socket Timeout", Toast.LENGTH_LONG).show();
}
catch (ConnectTimeoutException bug) {
Toast.makeText(getApplicationContext(), "Connection Timeout", Toast.LENGTH_LONG).show();
}
For Connection time out add SocketTimeoutException in your catch block and its crashing because without null checking, you are trying to trim the string in onPostExecute
You should do like this, and check before using status
if(TextUtil.isEmpty(status)) {
pdlg.dismiss();
// We are getting empty response
return;
}
String status1=status.trim();
You can catch the Connection timeout exception in your code and then set the status according to your requirement and check for that status in onPostExecute to show the alert Dialog
try {
URL url = new URL("http://....login.php");
String param = "username=" + uname + "&password=" + pass;
// Your URL connection code here
catch (ConnectTimeoutException e) {
Log.e(TAG, "Timeout", e);
status="timeout"
} catch (SocketTimeoutException e) {
Log.e(TAG, " Socket timeout", e);
status="timeout"
}
in onPostExecute
if (status.equals("timeout")) {
// Show Alert Dialog.
}
What you are trying to do is previously done in some great networking lib. So I urge you to use one of the widley used network lib.
Volley.
Or if you want to understand you can just check the response status(or status code should be 408. I guess for connection time out) if it will return "connection time out" then you can call your code to the http client again to perform your task, you can also add a retry count to try for 2-3 times and then give up and send response to onpostexecute method.
Hope this helps.

Why my setDefaultHostnameVerifier() didn't work for the first time?

Here is my code:
private void upload() {
Task task = new Task();
task.execute();
}
class Task extends AsyncTask<String, String, String> {
#SuppressLint("NewApi")
#Override
protected String doInBackground(String... params) {
try {
URL mUrl = new URL(HttpUrls.getUrl() + HttpUrls.UPLOAD_IMAGE);
SSLContext sslContext = Global.getSSLContext(AppConfig.getApplicationContext());
HttpsURLConnection conn = (HttpsURLConnection) mUrl
.openConnection(); conn.setDefaultHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
conn.setSSLSocketFactory(sslContext.getSocketFactory());
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty(Constants.Field.USER_UUID, mProductUuid);
conn.setRequestProperty(Constants.Field.IMG_TYPE, IMGType.PDT_IMG.name());
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
OutputStream output = conn.getOutputStream();
if (StringUtils.isEmpty2(mImgPath)) {
output.write(begin(System.currentTimeMillis() + ".jpg"));
} else {
output.write(begin(mImgPath));
}
if (mUri != null) {
Bitmap bitmap = ImageFactory.getBitmapFormUri(GalleryActivity.this, mUri, true);
output.write(ImageFactory.bitmapToByteAAA(bitmap));
try {
bitmap.recycle();
} catch (Exception e) {
}finally{
if(bitmap!=null && !bitmap.isRecycled()){
bitmap.recycle();
bitmap = null;
}
}
} else {
output.write(ImageFactory.bitmapToByteBBB(mBitmap));
}
output.write(end());
output.flush();
output.close();
return IOUtils.toString(conn.getInputStream());
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
I use the self defined certificate in my server, and I have load the trust.bks in Gloabal.getSSLContext(Application.getApplicationContext()) ,and I call the upload() method every time I click the upload button.
But it is weird that when I click the upload button for the first time, I get the error "hostname is not verified", which means conn.setDefaultHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); in my code didn't work, and when I click the upload button for the second time, it works well, and I upload the file successfully, why? Is it have any delay when I call setDefaultHostnameVerifier()? If it is, how can I make it works for the first time I call upload() method? And can anybody tell me the principle of the method setDefaultHostnameVerifier()?

Android App and Http Requests

I'm currently trying to send an http request from an android app to google-app-engine, this request should be received by the server who will use the parameters passed in the URL to add a new item to the datastore.
I wrote this code:
private class AsyncConnection extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
try {
// creating the url
URL url = new URL(params[0]);
// opening the connection
URLConnection connection;
connection = url.openConnection();
// get data about the connection
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
// connection was properly established
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream input = httpConnection.getInputStream();
return input.toString();
} else {
Log.d("CONNECTION", "connection not HTTP_OK");
}
} catch (MalformedURLException e) {
Log.d("SMARTGAN", "MalformedURLException" ,e);
} catch (IOException e) {
Log.d("SMARTGAN", "IOException" ,e);
} catch (Exception e) {
Log.d("SMARTGAN", "Exception" ,e);
} finally { }
return null;
}
}
but when I try to execute it I don't see any new item in the datastore.
The URL itself and the code on the server are fine, when I tried and sent the URL using it worked. I don't see any error message of "connection not ok" message in the log.
Mostly probably could be with hostname, have tried this solution How to make http post from android to google app engine server?
Also refer to https://developers.google.com/appengine/docs/java/tools/devserver#Command_Line_Arguments

Android remote image ERROR

I want to Download An image from a remote server. But each time I get A nullpointer exception.
Method For Conencting to Server
private InputStream OpenHttpConnection(String urlString)
throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
Log.i("Download ", "Response: OK");
}
else
Log.i("Download ", "Response: NOK");
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
Method For Creating Bitmap
private Bitmap DownloadImage(String URL)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
Log.i("Download ", "InputStream Available: " +in.available());
bitmap = BitmapFactory.decodeStream(in);
Log.i("Download ", "Bitmap: " +bitmap.describeContents());
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
The null pointerException is thrown when I decodeStream, but when I use a different URL it works.
I run Apache on port 90. could this also have an effect if any.
try this I hope is working.
to connect with ftp use this code
public FTPClient mFTPClient = null;
public boolean ftpConnect(String host, String username,
String password, int port)
{
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
return status;
}
} catch(Exception e) {
Log.d(TAG, "Error: could not connect to host " + host );
}
return false;
}
to download file use this code
public boolean ftpDownload(String srcFilePath, String desFilePath)
{
boolean status = false;
try {
FileOutputStream desFileStream = new FileOutputStream(desFilePath);;
status = mFTPClient.retrieveFile(srcFilePath, desFileStream);
desFileStream.close();
return status;
} catch (Exception e) {
Log.d(TAG, "download failed");
}
return status;
}

Categories

Resources