Timing problems when accessing a GCM message - java

I'm developing a multi-player quiz application. I'm using GCM to send messages from my server to the devices. The registration is done by this code
//skeletonactivity.java
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart(): Connecting to Google APIs");
mGoogleApiClient.connect();
regId = registerGCM();
appUtil=new ShareExternalServer();
shareRegidTask = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String result = appUtil.shareRegIdWithAppServer(context, regId);
return result;
}
#Override
protected void onPostExecute(String result) {
shareRegidTask = null;
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
};
shareRegidTask.execute(null, null, null);
Log.d("RegisterActivity", "GCM RegId: " + regId);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Intent intent=new Intent(SkeletonActivity.this,Quizform.class);
startActivity(intent);
finish();
}
}, 1000);
// i have tried making the activity launch after sometime, so that the GCM message will be recieved. but there's no change.
}
public String registerGCM() {
gcm = GoogleCloudMessaging.getInstance(this);
regId = getRegistrationId(context);
if (TextUtils.isEmpty(regId)) {
registerInBackground();
Log.d("RegisterActivity",
"registerGCM - successfully registered with GCM server - regId: "
+ regId);
}
return regId;
}
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getSharedPreferences(
SkeletonActivity.class.getSimpleName(), Context.MODE_PRIVATE);
String registrationId = prefs.getString(REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
return registrationId;
}
private void registerInBackground() {
new AsyncTask<Void,Void,String>() {
#Override
protected String doInBackground(Void...Params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regId = gcm.register(GOOGLE_PROJECT_ID);
Log.d("RegisterActivity", "registerInBackground - regId: "
+ regId);
msg = "Device registered, registration ID=" + regId;
storeRegistrationId(context, regId);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
Log.d("RegisterActivity", "Error: " + msg);
}
Log.d("RegisterActivity", "AsyncTask completed: " + msg);
return msg;
}
#Override
protected void onPostExecute(String msg) {
Toast.makeText(getApplicationContext(),
"Registered with GCM Server." + msg, Toast.LENGTH_LONG)
.show();
}
}.execute(null, null, null);
}
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getSharedPreferences(
SkeletonActivity.class.getSimpleName(), Context.MODE_PRIVATE);
Log.i(TAG, "Saving regId on app version" );
SharedPreferences.Editor editor = prefs.edit();
editor.putString(REG_ID, regId);
editor.commit();
}
The code for sharing with external activity is
shareExternalServer
public class ShareExternalServer {
public String shareRegIdWithAppServer(final Context context,
final String regId) {
String result = "";
Map paramsMap = new HashMap();
paramsMap.put("regId", regId);
try {
URL serverUrl = null;
try {
serverUrl = new URL(Config.APP_SERVER_URL);
} catch (MalformedURLException e) {
Log.e("AppUtil", "URL Connection Error: "
+ Config.APP_SERVER_URL, e);
result = "Invalid URL: " + Config.APP_SERVER_URL;
}
StringBuilder postBody = new StringBuilder();
Iterator<Entry> iterator = paramsMap.entrySet()
.iterator();
while (iterator.hasNext()) {
Entry param = iterator.next();
postBody.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
postBody.append('&');
}
}
String body = postBody.toString();
byte[] bytes = body.getBytes();
HttpURLConnection httpCon = null;
try {
httpCon = (HttpURLConnection) serverUrl.openConnection();
httpCon.setDoOutput(true);
httpCon.setUseCaches(false);
httpCon.setFixedLengthStreamingMode(bytes.length);
httpCon.setRequestMethod("POST");
httpCon.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
OutputStream out = httpCon.getOutputStream();
out.write(bytes);
out.close();
int status = httpCon.getResponseCode();
if (status == 200) {
result = "RegId shared with Application Server. RegId: "
+ regId;
} else {
result = "Post Failure." + " Status: " + status;
}
} finally {
if (httpCon != null) {
httpCon.disconnect();
}
}
} catch (IOException e) {
result = "Post Failure. Error in sharing with App Server.";
Log.e("AppUtil", "Error in sharing with App Server: " + e);
}
return result;
}
}
the code for GCMIntentService.java
public class GcmIntentService extends IntentService {
public GcmIntentService() {
super("GcmIntentService");
}
public SharedPreferences sharedPreferences;
public static SharedPreferences getSharedPreferences (Context ctxt) {
return ctxt.getSharedPreferences("message",0);
}
public static boolean flag;
public static final String TAG = "GCM Demo";
public String mess=" ";
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
sharedPreferences= getSharedPreferences(this);
SharedPreferences.Editor editor=sharedPreferences.edit();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType=gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
Log.i(TAG, "Completed work # " + SystemClock.elapsedRealtime());
mess= extras.getString("message");
editor.putString("mess",mess);
editor.commit();
Log.i(TAG, "Received: " + mess);
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
}
The above code gets the value from the broadcast receiver and stores it the string msg.
i try to access it as below in quizform.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); sharedPreferences=getApplicationContext().getSharedPreferences("messages",0);
setContentView(R.layout.activity_quizform);
txt = sharedPreferences.getString("mess","empty");
Toast.makeText(this, txt, Toast.LENGTH_LONG).show();
}
The value of txt is empty, and so i get only a blank toast.
The server sends the message as soon as it gets the regID. the code is:
<?php
//generic php function to send GCM push notification
function sendPushNotificationToGCM($registatoin_ids, $message) {
//Google cloud messaging GCM-API url
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
// Google Cloud Messaging GCM API Key
define("GOOGLE_API_KEY", "apikey");
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
function sendquestions()
{
$servername = " ";
$username = " ";
$password = " ";
$dbname=" ";
$conn = mysqli_connect($servername, $username, $password,$dbname);
$pushStatus = "";
$result= mysqli_query($conn,"SELECT id FROM regid");
while($row = $result->fetch_assoc()){
$gcmRegID=$row['id'];}
$pushMessage = "hello";
if (isset($gcmRegID) && isset($pushMessage)) {
$gcmRegIds = array($gcmRegID);
$message = array("message" => $pushMessage);
$pushStatus = sendPushNotificationToGCM($gcmRegIds, $message);
}
}
//this block is to receive the GCM regId from external (mobile apps)
if(!empty($_GET["shareRegId"]))
{
$gcmRegID = $_POST["regId"];
mysqli_query($conn,"INSERT INTO regid (id) VALUES('$gcmRegID')");
$retval = mysql_query( $mysqli, $conn );
mysqli_close($conn);
sendquestions();
exit;
}
?>
Please do suggest ways to get over the delay . thanks

Related

secure my Nfc tag by sending password on it

I am doing an application that can read nfc and then treat the content message but I only want certain people to be able to read the tag. So in a way I would like the user to scan the tag and be prompted for a password before being able to read the tag. Is this possible ?
Open to any ideas. It is also possible to keep only the read mode and change the write mode to kind of writing password on the tag to secure it.
btnWrite.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
try {
if(myTag ==null) {
Toast.makeText(context, ERROR_DETECTED, Toast.LENGTH_LONG).show();
} else {
write(message.getText().toString(), myTag);
Toast.makeText(context, WRITE_SUCCESS, Toast.LENGTH_LONG ).show();
}
} catch (IOException e) {
Toast.makeText(context, WRITE_ERROR, Toast.LENGTH_LONG ).show();
e.printStackTrace();
} catch (FormatException e) {
Toast.makeText(context, WRITE_ERROR, Toast.LENGTH_LONG ).show();
e.printStackTrace();
}
}
});
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
// Stop here, we definitely need NFC
Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
finish();
}
readFromIntent(getIntent());
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
writeTagFilters = new IntentFilter[] { tagDetected };
}
private void readFromIntent(Intent intent) {
String action = intent.getAction();
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage[] msgs = null;
if (rawMsgs != null) {
msgs = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
msgs[i] = (NdefMessage) rawMsgs[i];
}
}
buildTagViews(msgs);
}
}
private void buildTagViews(NdefMessage[] msgs) {
if (msgs == null || msgs.length == 0) return;
String text = "";
// String tagId = new String(msgs[0].getRecords()[0].getType());
byte[] payload = msgs[0].getRecords()[0].getPayload();
String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16"; // Get the Text Encoding
int languageCodeLength = payload[0] & 0063; // Get the Language Code, e.g. "en"
// String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
try {
// Get the Text
text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
} catch (UnsupportedEncodingException e) {
Log.e("UnsupportedEncoding", e.toString());
}
tvNFCContent.setText(text+"\n( taille de la trame: " + text.length () +")");
}
private void write(String text, Tag tag) throws IOException, FormatException {
NdefRecord[] records = { createRecord(text) };
NdefMessage message = new NdefMessage(records);
// Get an instance of Ndef for the tag.
Ndef ndef = Ndef.get(tag);
// Enable I/O
ndef.connect();
// Write the message
ndef.writeNdefMessage(message);
// Close the connection
ndef.close();
}
private NdefRecord createRecord(String text) throws UnsupportedEncodingException {
String lang = "en";
byte[] textBytes = text.getBytes();
byte[] langBytes = lang.getBytes("US-ASCII");
int langLength = langBytes.length;
int textLength = textBytes.length;
byte[] payload = new byte[1 + langLength + textLength];
// set status byte (see NDEF spec for actual bits)
payload[0] = (byte) langLength;
// copy langbytes and textbytes into payload
System.arraycopy(langBytes, 0, payload, 1, langLength);
System.arraycopy(textBytes, 0, payload, 1 + langLength, textLength);
NdefRecord recordNFC = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload);
return recordNFC;
}
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
readFromIntent(intent);
if(NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())){
myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
}
}
#Override
public void onPause(){
super.onPause();
WriteModeOff();
}
#Override
public void onResume(){
super.onResume();
WriteModeOn();
}
private void WriteModeOn(){
writeMode = true;
nfcAdapter.enableForegroundDispatch(this, pendingIntent, writeTagFilters, null);
}
private void WriteModeOff(){
writeMode = false;
nfcAdapter.disableForegroundDispatch(this);
}
}
You can have the password implementation either in the readFromIntent replacing the buildTagViews(msgs); with checkPasswordDialog(msgs)
private void readFromIntent(Intent intent) {
.....
.... checkPasswordDialog(msgs)
...
In the checkPasswordDialog(NdefMessage[] msgs), you check the password, if it is correct,then continue with buildTagViews(msgs); else, show error.
Or in the buildTagViews(msgs); itself, right before you display the message, the password then determines what you will display, the NFC message or an error( non-authorized user).
Assume I write a function called checkForPasswordDailog() thats asks a user for a password. If the password entered by user is correct then continue to display the messege otherwise display and unauthorised user messege. i.e
protected void checkForPasswordDialog(NdefMessage[] msgs){
/*create a dialog view with either both usename
and password or just a password if every user uses the same
password*/
MaterialDialog(this).show{
// add a title
View passwordDialogView = customView(R.layout.password_dialog_view)
//when the user submits their inputs
Textview userNameView = passwordDialogView.findViewById(R.id.username)
Textview passwordView = passwordDialogView.findViewById(R.id.password)
Button submitButton = passwordDialogView.findViewById(R.id.submit_button)
submitButton.setOnClickListener{
if(verifyUser(username.text, password.text)){
buildTagViews(msgs)
cancel()
}else{
showUnauthorizedUserError()
cancel()
}
}
}
protected boolean verifyUser(String username, String password){
//Verify user input
}
protected void showUnauthorizedUseError(){
//Display your message here Snackbar/Dialog e.t.c
}
And your xml file should include
<TextView id = "#+id/username"/>
<TextView id = "#+id/password"/>
<Button id = "#+id/submit_button"/>
Hopefully this helps

Uploading a Image Works on some devices but returns Stream FixedLengthSource .inputStream()

I am developing an android application that uploads an image to a specified directory using PHP and okhttp . Well , the frontend and backend work fine on my personal device , but it crashes on non-Samsung devices.
When I dug into the problem I found out that the server returns :
com.android.okhttp.internal.http.Http1xStream$FixedLengthSource#17768aa).inputStream()
on the non-Samsung devices.
The Java Code of the file Upload is as Follows :
public class UploadGalleryStoryPost {
private Context context;
private String fileName = "", User_Id = "",Type="";
private ProgressDialog progressDialog;
private int serverResponseCode = 0;
private String count = "";
private String fileCount = "";
public UploadGalleryStoryPost(String fileName, Context context, String User_Id, String Type, String count, String fileCount) {
this.fileName = fileName;
this.context = context;
this.User_Id = User_Id;
this.Type = Type;
this.count = count;
this.fileCount = fileCount;
new UploadingGalleryPost().execute();
}
private class UploadingGalleryPost extends AsyncTask<Void, Void, Void> {
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize =1024 * 1024;
File sourceFile_profile = new File(fileName);
private String upLoadServerUri = APP_SERVER_URL+"AddAStory.php";
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog=new ProgressDialog(context);
progressDialog.setMessage("Uploading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPostExecute(Void result) {
try{
if(serverResponseCode == 200){
int count1 = Integer.parseInt(count);
int fileCount1 = Integer.parseInt(fileCount);
Log.e("value", " "+ String.valueOf(count1-1)+" "+fileCount1);
if((fileCount1-1) == count1) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context, R.style.myDialog);
builder1.setCancelable(false);
builder1.setTitle("Alert!");
builder1.setMessage("Uploaded successfully.");
builder1.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Intent i = new Intent(context, DashBoard.class);
context.startActivity(i);
}
});
AlertDialog dialog1 = builder1.create();
dialog1.show();
}
else {
progressDialog.dismiss();
Toast.makeText(context, fileName+" has been uploaded successfully", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
Log.e("UploadtoserverException", "Exception : "
+ e.getMessage(), e);
}
super.onPostExecute(result);
}
#Override
protected Void doInBackground(Void... voids) {
try{
// open a URL connection to the Servlet
FileInputStream fileInputStream_profile = new FileInputStream(sourceFile_profile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
// conn.setChunkedStreamingMode(1024);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("Attachment", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"Attachment\";filename=\""+fileName+"\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream_profile.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream_profile.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream_profile.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream_profile.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"User_Id\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(User_Id);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"Type\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Type);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
conn.getErrorStream();
Log.e("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode+" "+ conn.getErrorStream());
//close the streams //
fileInputStream_profile.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
Log.e("UploadtoserverException", "Exception : "
+ e.getMessage(), e);
}
return null;
}
}
}
The php code is :
<?php
date_default_timezone_set('Asia/Kolkata');
$date = date('Y-m-d H:i:s');
$new_time = date("Y-m-d H:i:s", strtotime('+24 hours'));
$day = date("l");
$response = array();
include 'db_connect.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$User_Id = $_POST['User_Id'];
$Story_Content = $_POST['Story_Content'];
$B_Id = $_POST['B_Id'];
$Type = $_POST['Type'];
if($Type == 'BGTXT'){
$sql = "INSERT INTO Story_Common(User_Id,Timestamp_Start,Status, Timestamp_End)
VALUES('$User_Id','$date','Open','$new_time')";
$result = sqlsrv_query($conn, $sql);
if($result){
$sql1 = "SELECT TOP 1 * FROM Story_Common ORDER BY Story_Id DESC";
$res1 = sqlsrv_query($conn, $sql1);
if (sqlsrv_has_rows($res1) == true)
{
while ($row_sql1 = sqlsrv_fetch_array($res1, SQLSRV_FETCH_BOTH))
{
$Story_Id = $row_sql1["Story_Id"];
}
}
$sql2 = "INSERT INTO Story(Story_Id,Story_Content,B_Id)
VALUES('$Story_Id',N'$Story_Content','$B_Id')";
$result2 = sqlsrv_query($conn, $sql2);
if($result2){
$response['success'] = 200;
$response['message'] = "Insert in db success.";
}
else{
$response['success'] = 0;
$response['message'] = "Failed to insert db.";
}
}
else{
$response['success'] = 0;
$response['message'] = "Failed to insert db.";
}
}
else if($Type == 'Photo/Video'){
$sql = "INSERT INTO Story_Common(User_Id,Timestamp_Start,Status,Timestamp_End)
VALUES('$User_Id','$date','Open','$new_time')";
$result = sqlsrv_query($conn, $sql);
if($result){
if (empty($_FILES["Attachment"]["name"])) {
$path = "NA";
}
else {
$Attachment=$_FILES["Attachment"]["name"];
$temp=$_FILES["Attachment"]["tmp_name"];
$tst= time();
$url = "Post_Media/" . $tst . $Attachment;
$path="http://kidsfb.kidsfb.com/ver1PHP/".$url;
move_uploaded_file($temp,$url);
}
$sql1 = "SELECT TOP 1 * FROM Story_Common ORDER BY Story_Id DESC";
$res1 = sqlsrv_query($conn, $sql1);
if (sqlsrv_has_rows($res1) == true)
{
while ($row_sql1 = sqlsrv_fetch_array($res1, SQLSRV_FETCH_BOTH))
{
$Story_Id = $row_sql1["Story_Id"];
}
}
$sql2 = "INSERT INTO Story_Media(Story_Id,Media_Att)
VALUES('$Story_Id','$path')";
$result2 = sqlsrv_query($conn, $sql2);
if($result2){
$response['success'] = 200;
$response['message'] = "Insert in db success.";
}
else{
$response['success'] = 0;
$response['message'] = "Failed to insert db.";
}
}
else{
$response['success'] = 0;
$response['message'] = "Failed to insert db.";
}
}
echo json_encode($response);
}
?>
Tried increasing the buffer size to 2048 from 1024 still doesn't work on other devices.
It is work to me very well so please try this one
//php file imageUpload.php
$encodedImage = $_POST['image'];
$encodedImage_Name = $_POST['img_name'];
$imageLocation = "Images/IMG_$encodedImage_Name.jpg";
$imagpath="Images/IMG_$encodedImage_Name.jpg";
$uploade_url= 'http://192.168.1.18/'.$imagpath;
echo "[\n";
if(file_put_contents($imageLocation, base64_decode($encodedImage))){
$myObj=new \stdClass();
$myObj->success = 'true';
$myJSON = json_encode($myObj);
echo $myJSON;
}
else{
$myObj=new \stdClass();
$myObj->success = 'false';
$myJSON = json_encode($myObj);
echo $myJSON;
}
echo "]\n";
//java file
static final int PICK_FROM_GALLERY=123;
Bitmap imageBitmap;
boolean isSelected;
//to open the image from gallery
profile.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PICK_FROM_GALLERY);
} else {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, PICK_FROM_GALLERY);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} );
//open image set to Bitmap
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==PICK_FROM_GALLERY){
if (resultCode == RESULT_OK){
Uri path = data.getData();
try {
imageBitmap= MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(),path);
profile.setImageBitmap(imageBitmap);
Log.e("Image path",imageBitmap+"");
isSelected=true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void UploadImage(){
if (isSelected == true) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG,75, byteArrayOutputStream);
byte[] imageInByte = byteArrayOutputStream.toByteArray();
//picked image covert to base64
String encodedImage = Base64.encodeToString(imageInByte,Base64.DEFAULT);
OkHttpClient client = new OkHttpClient();
RequestBody reqestBody = new MultipartBody.Builder()
.setType( MultipartBody.FORM )
.addFormDataPart( "image",encodedImage )
.addFormDataPart( "img_name","abc" )
.build();
Request request = new Request.Builder()
.url("Upload Url in Server (exsample : http://192.168.1.18/imageUpload.php) " )
.post( reqestBody )
.build();
client.newCall( request ).enqueue( new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
final String myResponse = response.body().string();
getActivity().runOnUiThread( new Runnable() {
#Override
public void run() {
try {
String JSON_STRING = myResponse;
JSONArray mJsonArray = new JSONArray( JSON_STRING );
JSONObject mJsonObject = mJsonArray.getJSONObject( 0 );
String success = mJsonObject.getString( "success" );
Log.d( "Image Uploade", success );
if (success.equals( "true" )) {
Toast.makeText( getActivity(), " Success! ", Toast.LENGTH_LONG ).show();
} else {
pd.dismiss();
Toast.makeText( getActivity(), " failed! Please try again later", Toast.LENGTH_LONG ).show();
}
} catch (JSONException e) {
Log.e( "Image Uploade", e.toString() );
Toast.makeText( getActivity(), e.toString(), Toast.LENGTH_LONG ).show();
}
}
} );
} else {
Log.d( "Image Uploade", "Error" );
}
}
} );
}else{
Toast.makeText( getActivity(), " Please select a PostImage before submitting", Toast.LENGTH_LONG ).show();
}
}

How to Decode JSON Object File in PHP

I used JSON Request to send some parameters now I want to convert my json data by using json_decode but it does not allowing me to do so.
private void makeJsonObjReq() {
Map<Object, Object> postParam = new HashMap<>();
RequestQueue queue = Volley.newRequestQueue(this);
final String URL = "https://www.facilesol.com/api/test.php";
ArrayList<Map> myArray = new ArrayList<>();
Cursor data2 = dbHelper.getAllData();
if (data2.getCount() == 0)
{
Toast.makeText(getContext(), "Your cart is empty",
Toast.LENGTH_SHORT).show();
}
else if (data2.moveToFirst()) {
while (!data2.isAfterLast()) {
Map<String, String> map1 = new HashMap<>();
int pId = data2.getInt(1);
String quantity = data2.getString(3);
String price = data2.getString(4);
String priceID = data2.getString(6);
String toppingID = data2.getString(7);
map1.put("product_id", String.valueOf(pId));
map1.put("price_id", String.valueOf(priceID));
map1.put("topping_id", String.valueOf(toppingID));
map1.put("quantity", quantity);
map1.put("sale_price", String.valueOf(price));
myArray.add(map1);
data2.moveToNext();
}
}
postParam.put("branch_db",branchDb);
postParam.put("line_items", myArray);
Log.d(TAG, myArray.toString());
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
URL, new JSONObject(postParam),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Toast.makeText(CheckOut.this, String.valueOf(response), Toast.LENGTH_SHORT).show();
try {
Log.d(TAG, response.toString());
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
//Toast.makeText(CheckOut.this, "Please fill correct information and check your internet connection", Toast.LENGTH_SHORT).show();
}
});
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
100000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
jsonObjReq.setTag(TAG);
// Adding request to request queue
queue.add(jsonObjReq);
}
////////////////////////////////////////////////////////////////////////////
API File
//////////////////////////////////////////////////////////////////////////
<?php
include(DBConn.php);
$DBName = $_GET["branch_db"];
$JsonFile = $_GET["line_items"];
$arr = json_decode($JsonFile, true);
$Query = "SELECT MAX(cartid) As MaxOrderID FROM poscustomershoppingdata".
" WHERE cartid LIKE '".date("Ymd")."%'";
$rstOdr = mysql_db_query($DBName,$Query);
if (mysql_num_rows($rstOdr) > 0)
{
$objOdr = mysql_fetch_object($rstOdr);
if($objOdr->MaxOrderID == NULL)
{
$OrderID = 0;
}
else
{
$OrderID = substr($objOdr->MaxOrderID,9,11);
}
}
$OrderID = $OrderID + 1;
$CartID = date("Ymd")."-".str_pad($OrderID, 4, "0", STR_PAD_LEFT);
//echo $CartID ." ";
$CartDate = date("Y-m-d h:i:s");
$SqlCommand = "SELECT MAX(transid) FROM poscustomershopping";
$Result = mysql_db_query($DBName,$SqlCommand);
$MaxID = mysql_fetch_array($Result);
$TransactionID = $MaxID['0'];
$TransactionID = $TransactionID + 1;
foreach ($arr as $key => $value)
{
$Query = "INSERT INTO poscustomershopping".
" (cartid, transid, productid, priceid, toppingid, cartdate, quantity, saleprice) ".
" VALUES ($CartID, $TransactionID, '".($value["product_id"])."', '".($value["price_id"])."', '".($value["topping_id"])."', NOW(), '".($value["quantity"])."', '".($value["sale_price"])."')";
//echo $Query; die;
mysql_db_query($DBName,$Query);
}
//echo $Data; die;
?>
In Android Debugger everything is fine as shown in imageDebugger Screenshot but when I tried to decode_json file received via parameter I can't be able to insert data in mySQL although there is no error at all. Please brief me where is the issue and how can identify it for solution purposes.

i am facing this Problem E/catch ===: org.json.JSONException: No value for SorrySignUpFirst

I am Building a Project with PHP, MYSQL, java Volley Library
Problem is that it doesn't work all 3 at the same time getting this error
E/catch ===: org.json.JSONException: No value for SorrySignUpFirst
SorrySignUpFirst,
SorrySignUpFirst,
LoginPasswordWrong
If I comment 2 then run my Emulator its works so how to solve this Problem
PHP CODES
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
require_once("connection.php");
$data_array = array();
$login_email = $_POST['email'];
$login_email = strip_tags($login_email);
$login_email = str_replace(' ', '', $login_email); // remove spaces
$login_password = $_POST['password'];
$login_password = strip_tags($login_password);
$email = str_replace(' ', '', $login_password); // remove spaces
$db_email = mysqli_query($connection, "SELECT * FROM users WHERE email ='$login_email'");
if (mysqli_num_rows($db_email) == 0)
{
$data_array['SorrySignUpFirst'] = "1";
echo json_encode($data_array);
mysqli_close($connection);
}
else
{
$data = mysqli_fetch_array($db_email);
if (password_verify($login_password, $data['password']))
{
$data_array['LoginSuccessfull'] = "1";
$data_array['id'] = $data['id'];
$data_array['email'] = $data['email'];
echo json_encode($data_array);
mysqli_close($connection);
}
else
{
$data_array['LoginPasswordWrong'] = "1";
echo json_encode($data_array);
mysqli_close($connection);
}
}
}
?>
LoginActivity.java codes
final StringRequest LoginstringRequest = new StringRequest(Request.Method.POST, URLS.LOGIN_API, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String SorrySignUpFirst = jsonObject.getString("SorrySignUpFirst");
String LoginSuccessfull = jsonObject.getString("LoginSuccessfull");
String LoginPasswordWrong = jsonObject.getString("LoginPasswordWrong");
if (SorrySignUpFirst.contains("1")) {
Intent goToHomeScreenIntent = new Intent(LoginActivity.this, SignupActivity.class);
startActivity(goToHomeScreenIntent);
Toast.makeText(LoginActivity.this, "User Doen't Exist Sign Up", Toast.LENGTH_LONG).show();
}
if (LoginSuccessfull.contains("1")) {
String id = jsonObject.getString("id");
String fname = jsonObject.getString("email");
Intent goToHomeScreenIntent = new Intent(LoginActivity.this, HomeScreenActivity.class);
startActivity(goToHomeScreenIntent);
Toast.makeText(LoginActivity.this, "id = " + id + "email == " + fname, Toast.LENGTH_LONG).show();
}
if (LoginPasswordWrong.contains("1")) {
Toast.makeText(LoginActivity.this, "Password Wrong", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(LoginActivity.this, "if else if Error", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(LoginActivity.this, "catch -- " + e.toString(), Toast.LENGTH_LONG).show();
Log.e("catch === ", e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, "Error= 116" + error.toString(), Toast.LENGTH_LONG ).show();
Log.i("Catch error 116 ====", error.toString());
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> loginParams = new HashMap<>();
loginParams.put("email", Email);
loginParams.put("password", Password);
return loginParams;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(LoginstringRequest);
It seems to me that there is no attribute called SorrySignUpFirst on your jsonObject.
Try placing a breakpoint on this line:
String SorrySignUpFirst = jsonObject.getString("SorrySignUpFirst");
Inspect the jsonObject and check to see whether or not SorrySignUpFirst exists on it.

if/else trouble onPostExecute on a RegisterActivity

I am just new in programming world with no experience. I am about to finish my Android project but my problem is: My toast message always says Success even if I entered the exists phone no from my application. Please help me with the correct code!! (i am doing this for a long time) and the query is executed right function but the message is not shown properly.
//java
public class SignupActivity extends AsyncTask<String, Void, String> {
private Context context;
public SignupActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String fullName = arg0[0];
// String userName = arg0[1];
String passWord = arg0[1];
String phoneNumber = arg0[2];
String emailAddress = arg0[3];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?fullname=" + URLEncoder.encode(fullName, "UTF-8");
// data += "&username=" + URLEncoder.encode(userName, "UTF-8");
data += "&password=" + URLEncoder.encode(passWord, "UTF-8");
data += "&phonenumber=" + URLEncoder.encode(phoneNumber, "UTF-8");
data += "&emailaddress=" + URLEncoder.encode(emailAddress, "UTF-8");
link = "http://mangoair.in/MangoAir_User/mangoair_reg/tryrr.php" + data;
// link = "http://hostogen.com/mangoair10/tryrr.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
// return new String("Exception: " + e.getMessage());
return null;
}
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Data inserted successfully. Signup successfully.", Toast.LENGTH_LONG).show();
}
else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Data could not be inserted. Signup failed.", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
// Toast.makeText(context, "Error parsing JSON Please data Fill all the records.", Toast.LENGTH_SHORT).show();
// Toast.makeText(context, "Please LogIn", Toast.LENGTH_SHORT).show();
Toast.makeText(context, "Please Login", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}

Categories