I uploaded the videos in facebook using facebook sdk 3.6. I was successfully uploaded the videos but I want to share the location as well while uploading the file. How to do that?
I am using the following code for uploading the video file. I tried but I am not getting. Please can anyone help me on this.
try {
Request videoRequest = Request
.newUploadVideoRequest(session,
file,
new Request.Callback() {
#Override
public void onCompleted(
Response response) {
if (response
.getError() == null) {
Toast.makeText(
AndroidCamera.this,
"video shared successfully",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(
AndroidCamera.this,
response.getError().getErrorMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
Bundle parameters = videoRequest.getParameters();
parameters.putString("caption",
"Video");
if (Nim_Constants.bUseLocation) {
parameters.putString("name",
Nim_Constants.Location);
}
parameters
.putString("link",
"https://developers.facebook.com/android");
videoRequest.setParameters(parameters);
// Execute the request in a separate thread
videoRequest.executeAsync();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Finally I found solution. It's pretty simple. Use the Request class instead of using newUploadVideoRequest() method because it doesn't allow to pass parameters like title, description. So use the Request class if you want to set the title, desrcription. For this, Just Pass the file as ParcelFileDescriptor and pass location(What ever you have to pass) as description.
Upload Video on Facebook
File file = new File(filepath);
try {
ParcelFileDescriptor descriptor = ParcelFileDescriptor.open(file,ParcelFileDescriptor.MODE_READ_ONLY);
Bundle parameters = new Bundle();
parameters.putParcelable(file.getName(),descriptor);
parameters.putString("description","Location");
Request videoRequest = new Request(session,"me/videos", parameters,HttpMethod.POST,
new Request.Callback() {
#Override
public void onCompleted(
Response response) {
if (response.getError() == null) {
Toast.makeText(
AndroidCamera.this,
"video shared successfully",
Toast.LENGTH_SHORT)
.show();
} else {
System.out
.println(response
.getError()
.getErrorMessage());
Toast.makeText(
AndroidCamera.this,
response.getError()
.getErrorMessage(),
Toast.LENGTH_SHORT)
.show();
}
}
});
// Execute the request in a separate thread
videoRequest.executeAsync();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Related
I what to use my online Excel database to populate my recycler view, but when I run my app the file it cannot be downloaded, it always returns the onFailure() method as in code. I test the app on an Android 4.4 kitkat phone with internet connection.
client = new AsyncHttpClient();
//Download link for my database
String db = "https://github.com/SentsAbix/Android/blob/main/computerscience.xls?raw=true";
//Download database and save it in file
client.get(db, new FileAsyncHttpResponseHandler(this) {
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) {
fail();
}
//After Download completition
#Override
public void onSuccess(int statusCode, Header[] headers, File file) {
passed();
WorkbookSettings wbs = new WorkbookSettings();
wbs.setGCDisabled(true);
if(file != null){
try {
datab = Workbook.getWorkbook(file);
Sheet sheet = datab.getSheet(0);
//get rows available in our sheet
for(int i = 0; i < sheet.getRows() ; i++){
//store the rows in an array
Cell[] rows = sheet.getRow(i);
//then each row is stored accordingly
Regnoss.add(rows[0].getContents());
Names.add(rows[1].getContents());
}
getthedb();
} catch (IOException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
}
}
}
});
public void fail(){
Toast.makeText(this, "Failed to connect to the server", Toast.LENGTH_LONG).show();
}
public void passed(){
Toast.makeText(this, "Please wait while processing results", Toast.LENGTH_LONG).show();
}
The link you are using does not exist (publicly?). You always end up in onFailure() because there is no file associated with the link. The repository needs to be public.
I am trying to get youtube title from url using json file but i do not get any result and i also do not get any exception. I try to toast exception in toast message is null / blank. Can any one help me please. my code is here...
String link = youtube url;
URL embededURL = null;
try {
embededURL = new URL("http://www.youtube.com/oembed?url=" + link + "&format=json");
} catch (MalformedURLException e) {
e.printStackTrace();
makeToast(e.getMessage());
}
try {
title = new JSONObject(IOUtils.toString(embededURL)).getString("title");
} catch (JSONException e) {
e.printStackTrace();
makeToast(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
makeToast(e.getMessage());
}
makeToast(title);
First of all, since your question tag is android-volley, I'm going to give you an android-volley answer. However, there are a lot of libraries to look into that manage HTTP calls in a subjectively nicer way like OkHttp.
Now, the short answer to your question is your code is not even making a call to the internet.
Longer answer:
Add the volley dependency to your build.gradle
dependencies {
//... other dependencies
implementation 'com.android.volley:volley:1.1.1'
}
Put <uses-permission android:name="android.permission.INTERNET" /> in your AndroidManifest.xml
Make the app call to the internet like below. I tweaked the Android Volley simple example.
RequestQueue queue = Volley.newRequestQueue(context);
// sample of a URL-encoded url param, so you'll need to convert your link variable if you haven't already
String url = "https://www.youtube.com/oembed?url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DiwGFalTRHDA&format=json";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
String title = new JSONObject(response).getString("title");
Toast.makeText(context, title, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Error!", Toast.LENGTH_LONG).show();
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
I have limited Android Experience and had a very basic doubt. My scenario is as follows:
I currently have 2 applications, one being a QR Code Scanner and another which displays a QR Code. These will be running on multiple devices. The communication steps which take place are as follows:
Prior Setup:
There is a firebase database containing strings for QR Codes to be generated.
Device 2 reads the Code off the Firebase Database and displays it on the Screen (2nd App).
Device Communication:
Device 1 has the Scanner App and Device 2 has the QR Code displayed on Screen.
Device 1 now scans the QR Code from the Device 2 and verifies through some logic whether QR Code is valid or not.
If QR Code is valid, then the following takes place:
Device 1 calculates a new QR Code and places it on the Firebase Database.
The Device 2 should now move from displaying the QR Code to another activity which has the logic to Scan QR Codes of other Devices and verifies if they are correct.
Device 3 onwards must display a new QR Code which is on the Firebase Database which can now be scanned by Devices 1 and 2.
Note: The QR Code Updates on UI must keep happening until there is some sort of indication which makes the Device move to the QR Code Scanning stage.
Things which are working:
The 2 activities of the application (QR Code Display and QR Code Scanning) working independently.
QR Code Updates on UI whenever Firebase Database updated.
Things which are not working:
Moving from QR Code Display to Scanning once the QR Code is deemed valid.
Things I have tried:
Creating a Server Socket Implementation on the QR Code Display Application which is running as a Service called by my Main Activity. Client Socket Implementation (placed as a Service) is on the QR Code Scanner, which will send data to the Listening Server Socket once the QR Code is deemed valid. (Issue is that neither data is sent nor received).
Creating a Server Socket Implementation on the QR Code Display Application which is running as a Service called by my Main Activity. Client Socket Implementation (placed on UI Thread) is on the QR Code Scanner, which will send data to the Listening Server Socket once the QR Code is deemed valid.(Issue is that neither data is sent nor received)
I am very confused as to whether my approach is correct. Is there a better way to do it? Code for my service is as follows:
Device 2 - QR Code Display App:
Service
public class MyService extends Service {
private static final String TAG = "MyService";
private T_Client client;
#Override
public void onDestroy() {
Log.v(TAG, "onDestroy");
if (client != null) {
try {
client.stopClient();
} catch (Exception e) {
Log.e(TAG, "Error on close: " + e);
}
}
super.onDestroy();
Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v(TAG, "onStartCommand");
client = new T_Client();
client.start();
Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Display Server Implementation (Called T_Client)
public class T_Client extends Thread {
private static final String TAG = "T_Client";
private Socket sock = null;
private boolean running = false;
private ObjectInputStream in;
private ObjectOutputStream out;
private Object objIn;
public void send(String _msg) {
if (out != null) {
try {
out.writeObject(_msg);
out.flush();
Log.i("Send Method", "Outgoing : " + _msg.toString());
} catch (IOException ex) {
Log.e("Send Method", ex.toString());
}
}
}
public void stopClient() {
Log.v(TAG,"stopClient method run");
running = false;
}
#Override
public void run() {
running = true;
try {
ServerSocket sock1 = new ServerSocket(9999);
try {
Log.i(TAG, "C: Connected.");
while (running) {
sock = sock1.accept();
out = new ObjectOutputStream(sock.getOutputStream());
in = new ObjectInputStream(sock.getInputStream());
objIn = in.readObject();
Log.i("Object Read Class", objIn.getClass().toString());
Log.i("Object Read", objIn.toString());
/* Currently commented because startActivity not recognised
if (objIn != null) {
Intent dialogIntent = new Intent();
dialogIntent.setClass(this, MainActivity.class);
dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialogIntent);
}
Atleast the data should get read here
*/
System.out.println("Object Read Class" + objIn.getClass().toString());
System.out.println("Object Read" + objIn.toString());
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + objIn + "'");
} catch (Exception e) {
Log.e(TAG, "S: Error", e);
} finally {
out.close();
in.close();
sock.close();
Log.i(TAG, "Closing socket: " + sock);
}
} catch (Exception e) {
Log.e(TAG, "C: Error", e);
}
}
}
Intent intent=new Intent(getContext().getApplicationContext(),MyService.class);
getContext().startService(intent);
Scanner Application: (Written in Kotlin)
Scanner Client Implementation (Called T_Server)
internal class T_Server : Thread() {
private var sock: Socket? = null
private var running = false
private var out: ObjectOutputStream? = null
private val objIn: Any? = null
var blockchain_kotlin_copy = SecondActivity().blockchain_kotlin_copy
fun send(_msg: String) {
if (out != null) {
try {
out!!.writeObject(_msg)
out!!.flush()
Log.i("Send Method", "Outgoing : $_msg")
} catch (ex: IOException) {
Log.e("Send Method", ex.toString())
}
}
}
fun stopClient() {
Log.v(TAG, "stopClient method run")
running = false
}
override fun run() {
running = true
try {
val sock1 = ServerSocket(9999)
try {
Log.i(TAG, "C: Connected.")
while (running) {
sock = sock1.accept()
try {
out = ObjectOutputStream(sock!!.getOutputStream())
out!!.writeObject(blockchain_kotlin_copy)
out!!.flush()
out!!.reset()
Log.i("Send Method", "Outgoing : $blockchain_kotlin_copy")
println("Out is being sent")
println("$blockchain_kotlin_copy")
} catch (ex: IOException) {
Log.e("Send Method", ex.toString())
}
}
} catch (e: Exception) {
Log.e(TAG, "S: Error", e)
} finally {
out!!.close()
sock!!.close()
Log.i(TAG, "Closing socket: " + sock!!)
}
} catch (e: Exception) {
Log.e(TAG, "C: Error", e)
}
}
companion object {
private val TAG = "T_Server"
}
}
Service
public class MyService extends Service {
private static final String TAG = "MyService";
private T_Server client;
#Override
public void onDestroy() {
Log.v(TAG, "onDestroy");
if (client != null) {
try {
client.stopClient();
} catch (Exception e) {
Log.e(TAG, "Error on close: " + e);
}
}
super.onDestroy();
Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v(TAG, "onStartCommand");
client = new T_Server();
client.start();
Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Main Activity
val intent = Intent(this, MyService::class.java)
this.startService(intent)
It sounds like you might be interested in Firebase Device-to-Device notification. You might do as follows
Device X displays QR code
Some Device Y reads the QR code from Device X and if(verified) sendNotificationToDevice(X)
Device X moves to Scanner activity to read from some other Device Z.
Besides the link above, there are a number of YouTube tutorials and Medium blog posts on how to implement Device-to-Device notification.
In the LoginActivity.java class, when a user clicks a register button, then the code sets the login session true and then switches the activity from LoginActivity to MainActivity. Here's the login code snippet.
case(R.id.login):
String email = etEmail.getText().toString();
String password = etPassword.getText().toString();
if(email.trim().length() > 0 && password.trim().length() > 0) {
loginManager.checkLogin(email, password);
pDialog.setMessage("Logging in..");
showDialog();
session.setLogin(true);
if(loginManager.isLoginSuccessful()) {
hideDialog();
Toast.makeText(this, getResources().getString(R.string.welcome_msg), Toast.LENGTH_LONG).show();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
finish();
} else {
Toast.makeText(this, loginManager.getErrorMessage(), Toast.LENGTH_LONG).show();
}
} else if(email.trim().length() < 1) {
Toast.makeText(this, "Please enter the email", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Please enter the password", Toast.LENGTH_SHORT).show();
}
break;
And here's the LoginManager.java file that deals with the login process. I used OkHttp for the HTTP library.
public class LoginManager {
private final String TAG_LOGIN = LoginManager.class.getSimpleName();
private OkHttpClient client = new OkHttpClient();
private final String loginURL = URL.getInstance().getUrlLogin();
private Request request = new Request.Builder().url(loginURL).build();
private static JSONObject jsonObject;
private boolean error;
public void checkLogin(final String email, final String password) {
client.newCall(request).enqueue(new Callback() {
// onFailure is called when the request could not be executed due to cancellation, a connectivity problem or timeout.
#Override
public void onFailure(Request request, IOException e) {
}
// onResponse is called when the HTTP response was successfully returned by the remote server.
// using POST request for login
#Override
public void onResponse(Response response) throws IOException {
Log.d(TAG_LOGIN, "Login response: " + response.body().string());
RequestBody body = new FormEncodingBuilder()
.add("tag", "login")
.add("email", email)
.add("password", password)
.build();
Request request = new Request.Builder().url(loginURL).post(body).build();
client.newCall(request).execute();
try {
jsonObject = new JSONObject(response.body().string());
error = jsonObject.getBoolean("error");
} catch(JSONException e) {
e.printStackTrace();
}
}
});
}
public boolean isLoginSuccessful() {
if(error) {
return false;
}
return true;
}
public String getErrorMessage() {
String errorMessage = null;
try {
jsonObject.getString("error_msg");
} catch(JSONException e) {
e.printStackTrace();
}
return errorMessage;
}
}
When I run the application, it shows the welcome toast message and suddenly quits with the following error log.
java.lang.IllegalStateException: closed
at com.squareup.okhttp.internal.http.HttpConnection$FixedLengthSource.read(HttpConnection.java:454)
at okio.Buffer.writeAll(Buffer.java:574)
at okio.RealBufferedSource.readByteArray(RealBufferedSource.java:87)
at com.squareup.okhttp.ResponseBody.bytes(ResponseBody.java:56)
at com.squareup.okhttp.ResponseBody.string(ResponseBody.java:82)
at com.marshall.thequizshow.application.http.LoginManager$1.onResponse(LoginManager.java:51)
at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:150)
at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
So, I must be having a bug with the try-catch phrase under the onResponse method in the LoginManager.java file.
try {
jsonObject = new JSONObject(response.body().string());
error = jsonObject.getBoolean("error");
} catch(JSONException e) {
e.printStackTrace();
}
I would like to ask you how I should fix the code so that it no longer catches the IllegalStateException.
Thank you in advance.
As a general answer, YES: The proper way to avoid a RuntimeException is to fix the code: They should not be catched by program, under normal circunstances.
Now, let's see your case... The IllegalStateException arises because the HttpConnection seems to be closed when trying to use it. Could it be because you are calling twice the method response.body()?
IllegalState exception is thrown when you call a method at a wrong time. Check the nature of your process then restructure you code to make the call at an appropriate time
I have a weird bug I'm hoping someone can help me with.
I am using the Google Drive app folder to backup some data from my app. It creates the file and writes my data without and issue, I can sign grab the file from drive at any time and it works fine.
However if I uninstall the app when I reinstall it the Google Drive App folder is empty. I'm assuming I'm missing some point of the sync process so it's only caching locally but I can't see what I've done wrong. My code to create and commit the file is below.
DriveFile file = ..//Get drive file;
file.open(mGoogleApiClient, DriveFile.MODE_WRITE_ONLY, null)
.setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Problem opening file, status is " + result.getStatus().toString());
return;
}
Log.i(TAG, "File opened");
writeFileContents(result.getDriveContents());
}
});
private void writeFileContents(final DriveContents contents) {
new AsyncTask<Object, Object, Integer>() {
#Override
protected Integer doInBackground(Object[] params) {
try {
ParcelFileDescriptor parcelFileDescriptor = contents.getParcelFileDescriptor();
// Overwrite the file.
FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor
.getFileDescriptor());
Writer writer = new OutputStreamWriter(fileOutputStream);
SyncUtils.writeXml("some xml", writer);
writer.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return;
}
#Override
protected void onPostExecute(final Integer x) {
contents.commit(mGoogleApiClient, null).setResultCallback(new ResultCallback<com.google.android.gms.common.api.Status>() {
#Override
public void onResult(com.google.android.gms.common.api.Status result) {
if(result.getStatus().isSuccess())
Log.i(TAG, "Write succeeded");
else
Log.i(TAG, "Write failed");
onConnectionCallbacks.onSynced(x);
}
});
}
}.execute();
According to the documentation, contents.getParcelFileDescriptor() only works with DriveFile.MODE_READ_WRITE. You are using DriveFile.MODE_WRITE_ONLY, so you should be calling contents.getOutputStream().