Configure Notification in MultipartUploadRequest - java

I m implementing 'net.gotev:uploadservice:4.5.1' to upload image to my server. I wrote below code but getting exception message Notification is not configured so file is not uploading. When i tried to configure notification using setNotificationConfig(new UploadNotificationConfig()), It ask for 6 Arguments to be passed in New UploadNotificationConfig().
Here is my complete code.
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, upload_path)
.addFileToUpload(currentPhotoPath, "image") //Adding file
.addParameter("name", image_file_name) //Adding text parameter to the request
.setMaxRetries(2).setNotificationConfig(new UploadNotificationConfig())
.setUploadID(uploadId)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
I tried but could not succeed to pass required arguments and get the method working. Can someone help to fix this.
Also attached image explaining kind of argument required. I understand first 2 but for other 4, not geting any idea how to work.

Related

how to fix "String can not convert to json object" error while trying to sign users to server host?

i am trying to send some user data (its registration android page) to my server host but there is an error while trying to get json object from server side, so how can i fix this problem?
update :: i am using byethost services and i understand that there is something with cookies. so how can i solve this problem using volley library?
i have a method called onResponse() in my RegisterActivity class and its where the problem begins. in this method i wrote this line which always throws exception about not converting string to json object which i think there is nothing to do with my java codes, the reason it cant convert string to json i guess is that its not a valid json object. but i dont know why it is not valid.
here is my register.php file
https://www.androidtutorialpoint.com/wp-content/uploads/2016/09/register.txt
https://www.androidtutorialpoint.com/wp-content/uploads/2016/09/update_user_info.txt
https://www.androidtutorialpoint.com/wp-content/uploads/2016/09/android_login_connect.txt
https://www.androidtutorialpoint.com/wp-content/uploads/2016/09/android_login_config.txt
by the way i i just followed a tutorial i do not know so much about php.
here is the method in my RegisterActivity class where the exception triggers.
#Override
public void onResponse(String response) {
Toast.makeText(RegisterActivity.this, response,
Toast.LENGTH_LONG).show();
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
String user =
jObj.getJSONObject("user").getString("name");
Toast.makeText(getApplicationContext(), "Hi " + user +
", You are successfully Added!",
Toast.LENGTH_SHORT).show();
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
i expect to have a valid json object to pass the user data to my server but what i already have is some invalid json which throws exceptions.
well if anyone have followed the tutorials for register and login page and it does not work here are some reasons.
1) there is a problem with your php file which mostly its this one.
2) if there are problem with converting string to json object, print the string and see if its a valid json.
3)if everything is fine with these stuff, probably you should check the database and see if everything can fit with the php and user data and etc.
my problem was neither of those, as it turns out my server host have something to do with cookies (byethost) and you should add some headers for solving the problem here is a good link
How to set custom header in Volley Request
but i just solved my problem by using another server host (000host) and it works just fine. by the way if you are trying to use wamp and it doesn't work too, just use free 000host. it's been three days i was stuck on this thing. good luck

Android Facebook Error: Failed to generate preview for user

I am trying to post a Custom Open graph story in Facebook integration with SDK 4.5 , but i am not able to post it. i have created a object and action in my code
I am getting this error:
Failed to generate preview for user.com.facebook.http.
protocol.ApiException: [code] 100 [message]: (#100)
App xxxx is not allowed to create actions of type
restaurant:Wants To Visit for user xxxxx [extra]:
My code:
public void SongRequest(){
try {
// Create an object
ShareOpenGraphObject object = new ShareOpenGraphObject.Builder()
.putString("og:type", "restaurant.restaurant")
.putString("og:title", "Peddlers")
.putString("og:image", "https://scontent.fdel1-1.fna.fbcdn.net/hphotos-xpt1/v/t1.0-9/11996901_943588275699701_6661729706633501716_n.jpg?oh=5ebb6e29eff2009e0f4c68f86b06923d&oe=56A8B7CE")
.putString("og:description", "Peddlers Under The Big Ben")
.putString("restaurant:contact_info:street_address", "1601 Willow Rd.")
.putString("restaurant:contact_info:locality", "Menlo Park")
.putString("restaurant:contact_info:region", "California")
.putString("restaurant:contact_info:postal_code", "160022")
.putString("restaurant:contact_info:country_name", "India")
.putString("restaurant:contact_info:email", "brian#example.com")
.putString("restaurant:contact_info:phone_number", "212-555-1234")
.putString("restaurant:contact_info:website", "https://www.facebook.com/peddlersrock")
.putString("place:location:latitude", "30.70516586")
.putString("place:location:longitude", "76.8010025")
.putString("og:url", "https://www.facebook.com/CompetentGroove")
.build();
//Then create an action and link the object to the action.
// Create an action
ShareOpenGraphAction action = new ShareOpenGraphAction.Builder()
.setActionType("restaurant.wants_to_visit")
.putObject("restaurant", object)
.build();
//Finally, create the content model to represent the Open Graph story.
// Create the content
ShareOpenGraphContent content = new ShareOpenGraphContent.Builder()
.setPreviewPropertyName("restaurant")
.setAction(action)
.build();
//Present the Share dialog by using the show method on ShareDialog.
ShareDialog.show(HelloFacebookSampleActivity.this, content);
} catch (Exception e) {
Log.e("Graph Stories.Exception", e.toString());
}
}

How can I pass data returned from Facebook when Request.callback onCompleted() method is called, to my fragment in Android?

I'm currently trying to integrate Facebook into my Android application. I've had no problems getting the app to connect and authenticate. But I'm having a little trouble understanding how I can handle data once the onCompleted(Response response) callback method is executed.
The method below works:
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
new Request(session, "/me", null, HttpMethod.GET,
new Request.Callback() {
#Override
public void onCompleted(Response response) {
GraphObject graphObject = response.getGraphObject();
JSONObject data = graphObject.getInnerJSONObject();
Log.i(TAG, "My DETAILS: ");
try {
Log.i(TAG, "ID: " + data.getLong("id"));
Log.i(TAG, "Name: " + data.getString("name"));
Log.i(TAG, "Email: " + data.getString("email"));
Log.i(TAG,
"Gender: " + data.getString("gender"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}).executeAsync();
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
}
When I run my application, Facebook authenticates, the data is retrieved and successfully outputs to the Logcat window. However, I'm at a loss to understand how I can pass the JSONObject back to my fragment for further processing.
Most examples I've looked at online simply set the JSONObject content to views in the fragment, or even less helpful simply say /* Handle response here */ or something similar.
I have another similar method where I want to get a profile image url and download the image, but I can't get the url back to my fragment for further processing.
Should I do something like develop a runnable class that accepts a JSONObject as a parameter and start a separate thread from the onCompleted() method to process it the way I want?
My current goal is to get a list of the users friends who use my app and save their profile pictures for use within the app. Am I going about this the wrong way?
SO if I understand you properly, you are getting all data, you are able to parse the JSON but you are not able to pass the data to your other fragment? Why dont you write to a file, which can be accessible from anywhere?
Why do you want to "DOWNLOAD" the images, that will increase your processing time. Just use this URL: https://graph.facebook.com/"+uid.trim()+"/picture?type=normal Where uid is your users id. Use this in Conjunction with Universal Image Loader to asynchronously load your images in image view. You save your time - you save a headache of manually caching files or saving them on the SD.
But bro, the problem here is that Facebook will stop support to the API you are using by April of 2015. Start porting your app to use the latest facebook API; which however is not so useful in getting users information. Cheers and keep on coding :)

How can I delete a pre-existing image from storage before re-downloading using DownloadManager?

I am writing code for an Android app using Eclipse that is supposed to download an image from a URL (which is generated by the app, elsewhere in the code, using GPS information), then attach the newly downloaded image to an e-mail to be sent. I am able to, in general, accomplish this without much issue.
My problem is this: I only want one image downloaded by the app to be present in the device's external storage at any given time. Deleting the image after the email intent does not work, because because the app doesn't always call onStop or onDestroy when switching to another app to send the email. Time-sensitive deleting of the image will not work either, because I cannot assume that the user will send only one email from the app per hour. I want to give the user the freedom of sending as many of these emails (with one newly downloaded image, each) as they wish.
My current method (which works MOST of the time) is this: in the downloadFile method, simply check for the file's existence (I call it sensorMap.png), then delete it if it exists, before downloading a new one. This SHOULD ensure that there may be only one sensorMap.png image in external storage at any given time (EDIT: it does do this), and that when it comes time to attach the image to the email intent, there will be exactly one image ready to go. Instead, I see that sometimes a second sensorMap image is sometimes being downloaded into storage (i.e. "sensorMap-1.png"), OR the image cannot be attached to the email due to a "File size: 0 bytes" error, OR the image cannot be attached due to a "File does not exist" error. I am unsure what the difference between the latter two problems is. EDIT: Upon manually examining the contents of the directory I created, it seems that, as intended, I end up with only one image titled "sensorMap.png" at a time; it remains in the directory after the app closes, as expected. However, I still occasionally get the "File size: 0 bytes" message or the "File does not exist." message with no attached image, even though I see that the image DOES exist upon looking in directory afterwards. Other times, everything works just fine. It's rather bewildering.
In addition, there is an issue of the button which sends the email becoming unresponsive occasionally. Most of the time, it prompts the user to select an email client, as intended, but occasionally the button will LOOK as if clicked, but do nothing. When this happens, the logcat does not sense that the button was even clicked (I inserted a println statement to test it).
I am unsure of why my delete-before-download is not working flawlessly; the basic idea, at least, appears to be logically sound. Here is the code pertaining to my issue:
Code used to download file (in MainCountActivity.java):
//Function to download image given URL. Will use to attach image file to email.
public void downloadFile(String uRl) {
//delete existing file first so that only one sensorMap image exists in memory
//at any given time.
File file = new File(Environment.getExternalStorageDirectory()+"/SensorLocationImages");
File checkFile = new File(Environment.getExternalStorageDirectory()+"/SensorLocationImages/sensorMap.png");
if(checkFile.exists())
{
//debugging:
System.out.println("About to delete file!");
//deleteFiles(Environment.getExternalStorageDirectory()+"/SensorLocationImages");
checkFile.delete();
}
DownloadManager mgr = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(uRl);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false).setTitle("Sensor Location Map")
.setDescription("Pinpointed is the location from which the log file was sent.")
.setDestinationInExternalPublicDir("/SensorLocationImages", "sensorMap.png");
mgr.enqueue(request);
}
public Activity getActivity() //I wasn't sure if this would work, but it did. Or at least appears to.
{ return this; }
Method to send email (in MainCountActivity.java):
public void sendEmail(String toAddress, String ccAddress, String bccAddress, String subject, String body, String attachmentMimeType) throws Exception{
try {
Intent emailIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
emailIntent.setType(attachmentMimeType); //new
String sToAddress[] = { toAddress };
String sCCAddress[] = { ccAddress};
String sBCCAddress[] = { bccAddress };
emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
emailIntent.putExtra(Intent.EXTRA_EMAIL, sToAddress);
emailIntent.putExtra(android.content.Intent.EXTRA_CC, sCCAddress);
emailIntent.putExtra(android.content.Intent.EXTRA_BCC, sBCCAddress);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, body);
//get URI of logfile
File tempFile = new File(Environment.getExternalStorageDirectory () + MainCountActivity.dirPath);
Uri uri = Uri.fromFile(tempFile);
//create URI arraylist and add first URI
ArrayList<Uri> uris = new ArrayList<Uri>();
uris.add(uri);
//get URI of map image and add to arraylist
//make sure it is there to attach
File file = new File(Environment.getExternalStorageDirectory()+"/SensorLocationImages");
do {
downloadFile(getMapLink());
//createDirectoryAndSaveFile(getBitmapFromURL(getMapLink()), "sensorMap.png");
} while (!file.exists());
uris.add(Uri.fromFile(new File(Environment
.getExternalStorageDirectory()
+ "/SensorLocationImages/sensorMap.png")));
//+ "/sdcard/SensorLocationImages/sensorMap.png")));
emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
startActivity(emailIntent);
}
catch(Exception ex) {
ex.printStackTrace();
throw ex;
}
}
OnClick method, for my occasional button issue (In MaincountActivity.java):
public void onClick(View v){
switch(v.getId())
{
case R.id.textView1:
{
break;
}
case R.id.Reset:
{
//allowCounting will let the program know when to let it to count or not, depending if Start or Stop button are pressed.
logCount=0;
mCounter.setText("Total: 0");
mToggle.setChecked(false);
break;
}
/* case R.id.toggleButton:
{
break;
}*/
case R.id.SendEmail:
{
//for debugging purposes:
System.out.println("Email button being clicked!");
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
Toast.makeText(this, "GPS is enabled in your device", Toast.LENGTH_SHORT).show();
try {
sendEmail("","","","Sensor Log Info",getEmailBody(),"multipart/mixed");
} catch (Exception e) {
e.printStackTrace();
}
}
else
{
showGPSAlertForEmail();
}
break;
}
}
Basically, I really want to know why my delete-then-download method has not worked every time. Logcat errors have provided no insight. Thank you for your time.

Unable to create link with DBX chooser error android

I am attempting to integrate the Dropbox chooser drop-in api into my application. I am running into an abnormal issue. In my app when I launch the dbx chooser, anytime that I select a file the application fails with the following error code:
Sorry, an error has occurred. Please try again later.
Here is the portion of my code that implements the Dropbox API. This portion of the code is where the dropbox api is initially invoked.
public void StartDropboxApplication() {
// create the chooser
DbxChooser chooser = new DbxChooser(APP_KEY);
DbxChooser.ResultType result;
// determine which mode to be in // TODO REMOVE ALL BUT FILE CONTENT TODO SIMPLIFY by making this a setting
switch(( (RadioGroup) ParentActivity.findViewById(R.id.link_type)).getCheckedRadioButtonId() ) {
case R.id.link_type_content:
result = DbxChooser.ResultType.DIRECT_LINK;
break;
default:
throw new RuntimeException("Radio Group Related error.");
}
// launch the new activity
chooser.forResultType(result).launch(ParentActivity, 0);
}
Here is the position where the code should then pick it up although it never does.
protected void onActivityResult( int request, int result, Intent data ) {
Log.i(fileName, "result: " + result);
// check to see if the camera took a picture
if (request == 1) {
// check to see if the picture was successfully taken
if (result == Activity.RESULT_OK) {
onPicture();
} else {
Log.i(fileName, "Camera App cancelled.");
}
} else if (request == 0) {
if ( result == Activity.RESULT_OK ) {
onDropbox(data);
} else {
Log.i(fileName, "dropbox related issue.");
}
}
}
Thank you for any help or suggestions that you are able to provide.
I was able to solve my own issues and get this working. On the off chance that someone else has a similar problem I will detail the solution. The first issue was I was that my APP_KEY was incorrect.
The next issue was that I was attempting to read from a direct link instead of a content link. The direct link provides the application with a link to the file on the Dropbox server whereas the content link provides the application with a cached version of the file. If the file is not present on the device, the SDK downloads a copy for you.

Categories