How do I make java wait for boolean to run funciton - java

I'm sure this is pretty simple but I can't figure out and it sucks I'm up on suck on (what should be) an easy step.
ok. I have a method that runs one function that give a response. this method actually handles the uploading of the file so o it takes a second to give a response. I need this response in the following method. sendPicMsg needs to complete and then forward it's response to sendMessage. Please help.
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(!uploadMsgPic.equalsIgnoreCase("")){
Log.v("response","Pic in storage");
sendPicMsg();
sendMessage();
}else{
sendMessage();
}
1st Method
public void sendPicMsg(){
Log.v("response", "sendPicMsg Loaded");
if(!uploadMsgPic.equalsIgnoreCase("")){
final SharedPreferences preferences = this.getActivity().getSharedPreferences("MyPreferences", getActivity().MODE_PRIVATE);
AsyncHttpClient client3 = new AsyncHttpClient();
RequestParams params3 = new RequestParams();
File file = new File(uploadMsgPic);
try {
File f = new File(uploadMsgPic.replace(".", "1."));
f.createNewFile();
//Convert bitmap to byte array
Bitmap bitmap = decodeFile(file,400);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
params3.put("file", f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
params3.put("email", preferences.getString("loggedin_user", ""));
params3.put("webversion", "1");
client3.post("http://*******.com/apiweb/******upload.php",params3, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Log.v("response", "Upload Complete");
refreshChat();
//responseString = response;
Log.v("response","msgPic has been uploaded"+response);
//parseChatMessages(response);
response=picurl;
uploadMsgPic = "";
if(picurl!=null){
Log.v("response","picurl is set");
}
if(picurl==null){
Log.v("response", "picurl no ready");
};
}
});
sendMessage();
}
}
2nd Method
public void sendMessage(){
final SharedPreferences preferences = this.getActivity().getSharedPreferences("MyPreferences", getActivity().MODE_PRIVATE);
if(preferences.getString("Username", "").length()<=0){
editText1.setText("");
Toast.makeText(this.getActivity(), "Please Login to send messages.", 2);
return;
}
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
if(type.equalsIgnoreCase("3")){
params.put("toid",user);
params.put("action", "sendprivate");
}else{
params.put("room", preferences.getString("selected_room", "Adult Lobby"));
params.put("action", "insert");
}
Log.v("response", "Sending message "+editText1.getText().toString());
params.put("message",editText1.getText().toString() );
params.put("media", picurl);
params.put("email", preferences.getString("loggedin_user", ""));
params.put("webversion", "1");
client.post("http://peekatu.com/apiweb/*********.php",params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
refreshChat();
//responseString = response;
Log.v("response", response);
//parseChatMessages(response);
if(picurl!=null)
Log.v("response", picurl);
}
});
editText1.setText("");
lv.setSelection(adapter.getCount() - 1);
}

From what I understand, you need serial execution of background tasks.
What I do in the case is use a class that extends AsyncTask, takes some sort of listener in its constructor and calls the listener's callback in onPostExecute.
A quick example:
class ExampleTask<T,S,U> extends AsyncTask<T,S,U>
{
public interface ExampleListener
{
public void onTaskCompleted(boolean success);
}
private ExampleListener mListener;
public ExampleTask(ExampleListener listener)
{
mListener = listener;
}
...
#Override
protected void onPostExecute(U result)
{
...
if (mListener != null)
{
mListener.onTaskCompleted(yourBooleanResult);
}
}
}
Just pass a new ExampleListener implementation that calls the second method.
Here's an implementation of the listener:
ExampleListener sendMessageListener = new ExampleListener()
{
public void onTaskCompleted(boolean success)
{
if(success)
sendMessage();
}
}

Don't mix this IO and RPC intensive with your client thread. When your button is clicked, start another thread which handles the communication.
In that thread (potentially a separate class) you send the picture and wait for response; at the same time mark your button to be disabled to avoid clicking again. Then when you receive response, send the message again. Afterwards, raise an event back to the GUI thread, enable the button and display the message.

An easy way to solve this; call your method sendMessage() after the sendPicMsg() in the "onSuccess()" method

Related

Android: Start thread, join it and interrupt doesn't work well

I have a problem and I can't find the solution on the internet. I saw a lot of examples but no one really answered to my problem.
I have a login page and then, after checked if the both fields (login/pass) are filled, try to connect by another thread.
public class LoginActivity extends AppCompatActivity {
private EditText login = null;
private EditText password = null;
private RadioButton radioButton = null;
private Button button = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login = (EditText)findViewById(R.id.loginEditText);
password = (EditText)findViewById(R.id.passwordEditText);
radioButton = (RadioButton)findViewById(R.id.saveRadioButton);
button = (Button)findViewById(R.id.ConnectionButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (login.getText().toString().equals("")
|| password.getText().toString().equals("")) {
alert(getString(R.string.alertDialoguErrorTitle), getString(R.string.UnfilledFieldLogin));
} else {
boolean haveToSave = radioButton.isChecked();
User user = User.getUser(login.getText().toString(), password.getText().toString());
try {
Intranet.login.start();
Intranet.login.join();
Intranet.login.interrupt();
Intranet.login.join();
} catch (InterruptedException e) {
alert(getString(R.string.alertDialoguErrorTitle), e.toString());
login.setText("");
password.setText("");
} finally {
if (!user._token.equals("")) {
if (haveToSave) {
// SAVE DATA
}
finish();
} else {
login.setText("");
password.setText("");
alert(getString(R.string.alertDialoguErrorTitle), getString(R.string.badLoginPassword));
}
}
}
}
});
}
public void alert(String title, String message) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(LoginActivity.this);
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setPositiveButton("Close",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// nothing
}
});
alertDialog.show();
}
}
// The class using on the other thread
public class Intranet {
public static int responseCode = 0;
public static String responseString = "";
public static Thread login = new Thread(new Runnable() {
private OkHttpClient client = new OkHttpClient();
private String url = "https://epitech-api.herokuapp.com/login";
private User user = User.getUser();
public void run() {
try {
// Build the request
RequestBody formBody = new FormEncodingBuilder()
.add("login", user._login)
.add("password", user._password)
.build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Response responses = null;
// Reset the response code
responseCode = 0;
// Make the request
responses = client.newCall(request).execute();
if ((responseCode = responses.code()) == 200) {
// Get response
String jsonData = responses.body().string();
// Transform reponse to JSon Object
JSONObject json = new JSONObject(jsonData);
// Use the JSon Object
user._token = json.getString("token");
}
} catch (IOException e) {
responseString = e.toString();
} catch (JSONException e) {
responseString = e.toString();
}
;
}
});
}
I tried a lot of solutions with join() which wait the end of the thread. But finally, all time at the second time, when I try to connect myself, an exception comes up (The thread is already started). So how can this thread still running if it's interrupted before continuing?

Google Drive Android API how to upload a audio file to my drive ? How to sync drive files?

I have gone through Demo's but I tried with the QuickStart example in which a image is uploaded. but I am not getting how to upload a audio file in which i will give path to my files or Intent Picker to select the file.I am using createFile() method
how to upload a audio file to my drive?
I need to convert it to any streams ?
why google has made this so much complicated just to upload file?
How to Synch Drive files ?
How to stream (play audio file from drive)?
The Below code just upload file which contains nothing.
public class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
private static final String TAG = "android-drive-quickstart";
//private static final int REQUEST_CODE_CAPTURE_IMAGE = 1;
private static final int REQUEST_CODE_CREATOR = 2;
private static final int REQUEST_CODE_RESOLUTION = 3;
private static final int PICKFILE_RESULT_CODE = 1;
private static Uri fileUri;
private ContentsResult result;
private GoogleApiClient mGoogleApiClient;
private Bitmap mBitmapToSave;
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
// Create the API client and bind it to an instance variable.
// We use this instance as the callback for connection and connection
// failures.
// Since no account name is passed, the user is prompted to choose.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
// Connect the client. Once connected, the camera is launched.
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Called whenever the API client fails to connect.
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// show the localized error dialog.
showToast("Error in on connection failed");
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
return;
}
// The failure has a resolution. Resolve it.
// Called typically when the app is not yet authorized, and an
// authorization
// dialog is displayed to the user.
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
showToast("error"+e.toString());
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "API client connected.");
showToast("Inside Connected");
result = Drive.DriveApi.newContents(mGoogleApiClient).await();
showToast(""+result.getContents().toString());
OutputStream outputStream = result.getContents().getOutputStream();
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
//java.io.File fileContent = new java.io.File(fileUri.getPath());
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("New file")
.setMimeType("audio/MP3")
.setStarred(true).build();
showToast("meta data created");
DriveFileResult dfres= Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFile(getGoogleApiClient(), changeSet, result.getContents())
.await();
showToast("await() complete");
if (!result.getStatus().isSuccess()) {
showToast("Error while trying to create the file");
return;
}
showToast("Created a file: " + dfres.getDriveFile().getDriveId());
}
private void saveFileToDrive()
{
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
mGoogleApiClient.connect();
showToast("Connected");
}
}
#Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_SHORT).show();
}
});
}
public GoogleApiClient getGoogleApiClient() {
return mGoogleApiClient;
}
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "GoogleApiClient connection suspended");
}
}
Try this:
**
* An AsyncTask that maintains a connected client.
*/
public abstract class ApiClientAsyncTask<Params, Progress, Result>
extends AsyncTask<Params, Progress, Result> {
private GoogleApiClient mClient;
public ApiClientAsyncTask(Context context) {
GoogleApiClient.Builder builder = new GoogleApiClient.Builder(context)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE);
mClient = builder.build();
}
#Override
protected final Result doInBackground(Params... params) {
Log.d("TAG", "in background");
final CountDownLatch latch = new CountDownLatch(1);
mClient.registerConnectionCallbacks(new ConnectionCallbacks() {
#Override
public void onConnectionSuspended(int cause) {
}
#Override
public void onConnected(Bundle arg0) {
latch.countDown();
}
});
mClient.registerConnectionFailedListener(new OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult arg0) {
latch.countDown();
}
});
mClient.connect();
try {
latch.await();
} catch (InterruptedException e) {
return null;
}
if (!mClient.isConnected()) {
return null;
}
try {
return doInBackgroundConnected(params);
} finally {
mClient.disconnect();
}
}
/**
* Override this method to perform a computation on a background thread, while the client is
* connected.
*/
protected abstract Result doInBackgroundConnected(Params... params);
/**
* Gets the GoogleApliClient owned by this async task.
*/
protected GoogleApiClient getGoogleApiClient() {
return mClient;
}
}
Class to save file:
/**
* An async task that creates a new text file by creating new contents and
* metadata entities on user's root folder. A number of blocking tasks are
* performed serially in a thread. Each time, await() is called on the
* result which blocks until the request has been completed.
*/
public class CreateFileAsyncTask extends ApiClientAsyncTask<String, Void, Metadata>
{
public CreateFileAsyncTask(Context context)
{
super(context);
}
#Override
protected Metadata doInBackgroundConnected(String... arg0)
{
// First we start by creating a new contents, and blocking on the
// result by calling await().
DriveApi.ContentsResult contentsResult = Drive.DriveApi.newContents(getGoogleApiClient()).await();
if (!contentsResult.getStatus().isSuccess()) {
// We failed, stop the task and return.
return null;
}
//file to save in drive
String pathFile = arg0[0];
File file = new File(pathFile);
// Read the contents and open its output stream for writing, then
// write a short message.
Contents originalContents = contentsResult.getContents();
OutputStream os = originalContents.getOutputStream();
try
{
InputStream dbInputStream = new FileInputStream(file);
byte[] buffer = new byte[1024];
int length;
int counter = 0;
while((length = dbInputStream.read(buffer)) > 0)
{
++counter;
os.write(buffer, 0, length);
}
dbInputStream.close();
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
// Create the metadata for the new file including title and MIME
// type.
MetadataChangeSet originalMetadata = new MetadataChangeSet.Builder()
.setTitle(file.getName())
.setMimeType("application/x-sqlite3").build();
// Create the file in the root folder, again calling await() to
// block until the request finishes.
DriveFolder rootFolder = Drive.DriveApi.getRootFolder(getGoogleApiClient());
DriveFolder.DriveFileResult fileResult = rootFolder.createFile(
getGoogleApiClient(), originalMetadata, originalContents).await();
if (!fileResult.getStatus().isSuccess()) {
// We failed, stop the task and return.
return null;
}
// Finally, fetch the metadata for the newly created file, again
// calling await to block until the request finishes.
DriveResource.MetadataResult metadataResult = fileResult.getDriveFile()
.getMetadata(getGoogleApiClient())
.await();
if (!metadataResult.getStatus().isSuccess()) {
// We failed, stop the task and return.
return null;
}
// We succeeded, return the newly created metadata.
return metadataResult.getMetadata();
}
#Override
protected void onPostExecute(Metadata result)
{
super.onPostExecute(result);
if (result == null)
{
// The creation failed somehow, so show a message.
App.showAppMsg(getActivity(),"Error while creating the file.",Style.ALERT);
return;
}
// The creation succeeded, show a message.
App.showAppMsg(getActivity(),"File created: " + result.getDriveId(),Style.CONFIRM);
}
}
I haven't played with audio files, but in general, the Google Drive Android API (GDAA) does not deal with audio files per say. You just create a file, set metadata and stuff binary content in it. Look at the code here (plus some readme blah blah here). You'll find a code line
byte[] buff = ("written on: " + _dfn.getName()).getBytes();
if (null == _gc.creatFile(fldr, name, MIMETEXT, buff)) return;
there, that produces byte[] buffer and creates a file with text MIME type. So, try to use it, just replace the MIME type and stuff the 'buff' with your audio stream. I do it successfully with JPEG binaries.
There is also GooApiClnt wrapper class there that handles most of the basic GDAA functions. Don't try to code this way at work, though, it may get you fired :-).
Good luck.
In your onConnected method you create the new file, but you never put any new content in it. You create the new content in this line:
result = Drive.DriveApi.newContents(mGoogleApiClient).await();
Than you get a hold of it's output stream in this line:
OutputStream outputStream = result.getContents().getOutputStream();
And than you create an empty byte array output stream in this line:
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
But you never fill this 'bitmapStream' with any content, and worst: you never write it to your content's 'outputStream'.
What you should do next is write your audio file's contents to 'bitmapStream' something like this:
InputStream in = file.getInputStream(/*you need to get the file's path and put it here*/ "some_audio_file.mp3");
int singleByte;
while((singleByte = in.read()) != -1){
bitmapStream.write(b);
}
Now you'd have your file's content inside 'bitmapStrea' and you can write it to the new content's 'outputStream' like this:
outputStream.write(bitmapStream.toByteArray());
Than you do the 'MetadataChangeSet' stuff and you should be fine.
Some advices:
1. It is not a good practice to do I/O operations like file or network activities (or file AND network activities in your case) on the main thread. Better use an AsyncTask to do it in a background thread.
Don't call your ByteArrayOutputStream instance 'bitmapStream' if you use it to upload an audio file.
Here's an example of a class that uses an AsyncTask to upload an image (and guess what I called the ByteArrayOutputStream... right - 'bitmapStream'):
public class TakePhotoActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
/**
* Request code for auto Google Play Services error resolution.
*/
protected static final int REQUEST_CODE_RESOLUTION = 1;
private static final String TAG = "TakePhotoActivity";
private static final String KEY_IN_RESOLUTION = "is_in_resolution";
private static final int REQUEST_CODE_CREATOR = 2;
/**
* Google API client.
*/
private GoogleApiClient mGoogleApiClient;
/**
* Receives the new file's contents and executes the editor AsyncTask
*/
private ResultCallback<DriveApi.ContentsResult> mSaveFileCallback = new ResultCallback<DriveApi.ContentsResult>() {
#Override
public void onResult(DriveApi.ContentsResult contentsResult) {
EditFileAsyncTask editFileAsyncTask = new EditFileAsyncTask();
editFileAsyncTask.execute(contentsResult);
}
};
/**
* Determines if the client is in a resolution state, and
* waiting for resolution intent to return.
*/
private boolean mIsInResolution;
private Bitmap mBitmapToSave;
/**
* Called when the activity is starting. Restores the activity state.
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_take_menu_photo);
if (savedInstanceState != null) {
mIsInResolution = savedInstanceState.getBoolean(KEY_IN_RESOLUTION, false);
}
try {
InputStream inputStream = getAssets().open("some_image.jpg");
mBitmapToSave = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Called when the Activity is made visible.
* A connection to Play Services need to be initiated as
* soon as the activity is visible. Registers {#code ConnectionCallbacks}
* and {#code OnConnectionFailedListener} on the
* activities itself.
*/
#Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
// Optionally, add additional APIs and scopes if required.
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
Log.d("test", "connect()");
mGoogleApiClient.connect();
}
/**
* Called when activity gets invisible. Connection to Play Services needs to
* be disconnected as soon as an activity is invisible.
*/
#Override
protected void onStop() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onStop();
}
/**
* Saves the resolution state.
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(KEY_IN_RESOLUTION, mIsInResolution);
}
/**
* Handles Google Play Services resolution callbacks.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_RESOLUTION:
retryConnecting();
break;
}
}
private void retryConnecting() {
mIsInResolution = false;
if (!mGoogleApiClient.isConnecting()) {
Log.d("test", "connect()");
mGoogleApiClient.connect();
}
}
/**
* Called when {#code mGoogleApiClient} is connected.
*/
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "GoogleApiClient connected");
// TODO: Start making API requests.
if (mBitmapToSave != null) {
saveFileToDrive();
}
}
/**
* Called when {#code mGoogleApiClient} connection is suspended.
*/
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "GoogleApiClient connection suspended");
retryConnecting();
}
/**
* Called when {#code mGoogleApiClient} is trying to connect but failed.
* Handle {#code result.getResolution()} if there is a resolution
* available.
*/
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// Show a localized error dialog.
GooglePlayServicesUtil.getErrorDialog(
result.getErrorCode(), this, 0, new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
retryConnecting();
}
}
).show();
return;
}
// If there is an existing resolution error being displayed or a resolution
// activity has started before, do nothing and wait for resolution
// progress to be completed.
if (mIsInResolution) {
return;
}
mIsInResolution = true;
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
retryConnecting();
}
}
private void saveFileToDrive() {
Log.i(TAG, "Creating new contents.");
Drive.DriveApi.newContents(mGoogleApiClient).setResultCallback(mSaveFileCallback);
}
private void showMessage(String message) {
Log.i(TAG, message);
// Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
private class EditFileAsyncTask extends AsyncTask<DriveApi.ContentsResult, Void, Boolean> {
#Override
protected Boolean doInBackground(DriveApi.ContentsResult... params) {
DriveApi.ContentsResult contentsResult = params[0];
if (!contentsResult.getStatus().isSuccess()) {
showMessage("Failed to create new contents.");
return false;
}
showMessage("New contents created.");
OutputStream outputStream = contentsResult.getContents().getOutputStream();
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
mBitmapToSave.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
try {
outputStream.write(bitmapStream.toByteArray());
} catch (IOException e) {
showMessage("Unable to write file contents.");
e.printStackTrace();
}
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType("image/jpeg")
.setTitle("some_image.jpg")
.build();
IntentSender intentSender = Drive.DriveApi
.newCreateFileActivityBuilder()
.setInitialMetadata(metadataChangeSet)
.setInitialContents(contentsResult.getContents())
.build(mGoogleApiClient);
try {
startIntentSenderForResult(intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
} catch (SendIntentException e) {
showMessage("Failed to launch file chooser.");
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
if (!result) {
showMessage("Error while editing contents");
return;
}
showMessage("Successfully edited contents");
}
}
}
By the way, most of the code in this class was auto-generated by Android Studio, because when I created the project I marked the initial class to be a google services class.
It,s simple. After I trying hard, I found the solution.
private String mFileName = null;
File folder = new File(Environment.getExternalStorageDirectory() +
"/FolderFile");
if (!folder.exists()) {
folder.mkdir();
}
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/FolderFile/a.mp3";
After the audio is recorded. You must
buildGoogleSignInClient()
createFileWithIntent(mFileName);
private void createFileWithIntent(String I) {
final String audio = I;
final Task<DriveFolder> rootFolderTask = getDriveResourceClient().getRootFolder();
final Task<DriveContents> createContentsTask = getDriveResourceClient().createContents();
Tasks.whenAll(rootFolderTask, createContentsTask)
.continueWithTask(new Continuation<Void, Task<DriveFile>>() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public Task<DriveFile> then(#NonNull Task<Void> task) throws Exception {
DriveFolder PASTA = rootFolderTask.getResult();
DriveContents DADOS = createContentsTask.getResult();
File file = new File(audio);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
FileInputStream fis = new FileInputStream(file);
for (int readNum; (readNum = fis.read(buf)) != -1;) {
baos.write(buf, 0, readNum);
}
OutputStream outputStream = DADOS.getOutputStream();
outputStream.write(baos.toByteArray());
MetadataChangeSet TIPO = new MetadataChangeSet.Builder()
.setMimeType("audio/mp3")
.setTitle("audio.mp3")
.setStarred(true)
.build();
return getDriveResourceClient().createFile(PASTA, TIPO, DADOS);
}
});
}

Android login not working

Hi Please Can someone help me look at this code? Don't know what am doing wrong,But the try block doesn't run. instead it goes to the catch block.
public void onClick(View arg0) {
//Toast.makeText(getBaseContext(), "connecting",Toast.LENGTH_SHORT).show();
// TODO Auto-generated method stub
httpclient = new DefaultHttpClient();
htpost = new HttpPost("http://10.0.2.2/fanaticmobile/log_in.php");
uname= username.getText().toString();
pass= password.getText().toString();
try {
namearray = new ArrayList<NameValuePair>();
namearray.add(new BasicNameValuePair("username", uname));
namearray.add(new BasicNameValuePair("password", pass));
htpost.setEntity(new UrlEncodedFormEntity(namearray));
response= httpclient.execute(htpost);
if(response.getStatusLine().getStatusCode()==200){
entity= response.getEntity();
if(entity != null){
InputStream stream = entity.getContent();
JSONObject jresponse = new JSONObject(ConvertInput(stream));
String logged= jresponse.getString("logged");
login_err.setText(""+logged);
if(logged.equals("true")){
Toast.makeText(getBaseContext(), "Successfull",Toast.LENGTH_SHORT).show();
//String retname= jresponse.getString("name");
//String retmail= jresponse.getString("email");
}else if(logged.equals("false")){
String message=jresponse.getString("message");
Toast.makeText(getBaseContext(), message,Toast.LENGTH_SHORT).show();
}
}
}else{
}
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Poor Connection",Toast.LENGTH_SHORT).show();
}
}//
This is the function to read the json object
private static String ConvertInput(InputStream is){
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line ="";
try {
while((line = reader.readLine())!= null){
sb.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
is.close();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
return sb.toString();
}// end of convert function
Please am new to this and i followed a tutorial to this point,but mine is not working. Have set permission(internet) in the manifest file
I have a suggestion Try to Use AsyncHttpclient for getting responses from server no need of this long codes.
http://loopj.com/android-async-http/
AsyncHttpClient asyncHttpClient=new AsyncHttpClient();
RequestParams params=new RequestParams();
params.put("username", uname);
params.put("password", pass);
asyncHttpClient.post("http://10.0.2.2/fanaticmobile/log_in.php", params,new AsyncHttpResponseHandler(){
#Override
public void onFailure(Throwable arg0, String arg1) {
// TODO Auto-generated method stub
super.onFailure(arg0, arg1);
}
#Override
public void onSuccess(String arg0) {
// TODO Auto-generated method stub
super.onSuccess(arg0);
}
});
Just include the jar file in your project it will be simple to use.
Like already been stated in the comments, you're running a network operation in your main thread (the UI thread). This is not only discouraged (lengthy operations should never use the Main Thread), but also forbidden in the case of networking.
response= httpclient.execute(htpost)
^ this fails.
Read how to move that code to an AsyncTask and do it the right way in the official google reference. Googling AsyncTask will help too.
A Pseudo Code version would be:
public class YourTask extends AsyncTask<Void, Void, Void>{
YourListener mListener;
public YourTask(final YourListener listener) {
mListener = listener;
}
#Override
protected Void doInBackground(final Void... params) {
// do your lengthy operation here
return null;
}
#Override
protected void onPostExecute(Void result) {
mListener.onVeryLongTaskDone();
}
public interface YourListener {
public void onVeryLongTaskDone();
}
}
Then make your activity implement that "YourListener" interface and the method onVeryLongTaskDone() will be called.
How do you start the task?
in your onClick method:
(new YourTask(YourActivityName.this)).execute();

Can't cancel doInBackground process in AsyncTask even using cancel method

I have declared instance of FileUploadTask which extends AsyncTask in onCreate() method
FileUploadTask uploadTask= null;
and executes the background method by following code
public class UploadFiles implements OnClickListener{
....
if(SOTCNetStat.chkConnectionStatus(UploadResult.this)){
uploadTask=new FileUploadTask();
uploadTask.execute("");
}
else
{
Toast.makeText(UploadResult.this, getResources().getString(R.string.Text_CheckNetworkConnections) , Toast.LENGTH_LONG).show();
}
....
}
Having a cancel button to cancel the background process
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d(TAG,"cancel button clicked.....");
//FileUploadTask uploadTask= new FileUploadTask();
if(uploadTask!=null)
{
Log.d(TAG,"click event null checking....");
uploadTask.cancel(true);
}
}
}
In FileUploadTask class declared a boolean to check the running status
public class FileUploadTask extends AsyncTask<String, Integer, String> {
....
boolean isRunning=true;
The doInBackground method
#Override
protected String doInBackground(String... arg0) {
for(int i=0; i<fp.size(); i++){
index = i+1;
if(isCancelled() && !isRunning)
{
Log.d(TAG,"Cancel 1 Condition Checked ["+i+"]");
Log.d(TAG,"doInBackground canceled");
break;
}
else
{
Log.d(TAG,"Cancel 1 Canceled ["+i+"]");
}
file1 = new File(fp.get(i));
String urlString = Constants.UPLOAD_URL;
try {
Log.e("doInBackground", "urlString: " + urlString);
Log.e("doInBackground", "domainPref: " + domainName);
urlString = urlString.replace("domain", URLEncoder.encode(domainName, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
FileBody bin1 = new FileBody(file1);
ProgressMultipart reqEntity = new ProgressMultipart(new ProgressListener() {
#Override
public void transferred(long num) {
//publishProgress((int) ((num / (float) file1.length() ) * 100));
publishProgress((int) ((num / (float) totalSize ) * 100));
}
});
reqEntity.addPart("userfile", bin1);
if(getIntent().hasExtra("show_id"))
{
//String showId = getIntent().getStringExtra("show_id");
reqEntity.addPart("mobileshow", new StringBody("1"));
reqEntity.addPart("show_ids", new StringBody(getIntent().getStringExtra("show_id")));
}
reqEntity.addPart("Filename", new StringBody(file1.getName()));
reqEntity.addPart("user_id", new StringBody("2"));
reqEntity.addPart("privateasset", new StringBody("true"));
reqEntity.addPart("uploadtype", new StringBody("Normal"));
reqEntity.addPart("version_num", new StringBody("1"));
totalSize = reqEntity.getContentLength();
post.setEntity(reqEntity);
System.err.println("post :"+post.toString());
//to be check the cancel operation
if(isCancelled() && !isRunning)
{
Log.d(TAG,"Cancel 2 Condition Checked ["+i+"]");
Log.d(TAG,"File Uploading Cancelled in doInBackground method");
break;
}
else
{
Log.d(TAG,"Cancel 2 Canceled ["+i+"]");
}
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
response_str = EntityUtils.toString(resEntity);
}
....
return response_str;
}
and overloaded onCancelled methods
#Override
protected void onCancelled() {
// TODO Auto-generated method stub
Log.d(TAG,"onCancelled() method called");
super.onCancelled();
}
#Override
protected void onCancelled(String result) {
// TODO Auto-generated method stub
Log.d(TAG,"onCancelled(String) method called");
isRunning=false;
this.cancel(true);
}
I tried a lot and explored . Even using cancel method I can't able to stop the uploading process in background. Please any one give solutions to the problem
Some links i referred
http://www.technotalkative.com/cancel-asynctask-in-android/
http://developer.android.com/reference/android/os/AsyncTask.html
You seem to be missing how AsyncTask works. The onCancelled() method will only be called after doInBackground() is finished, similar to the onPostExecute() method. It is not called immediately after uploadTask.cancel(true) is called as you think it will be. The way you are using it, you have no need for onCancelled() methods or an isRunning variable (currently in your code isRunning is never changed to false and thus your isCancelled() check never works). Remove both the onCancelled() methods and the isRunning variable and your AsyncTask will work.
check this, after canceling the asynctask write this condition.
if(asynctask.iscancel()){
break;
}
it may help for u. :)
http://developer.android.com/reference/android/os/AsyncTask.html

Android post picture to Facebook wall

I am trying to post a picture to my wall on Facebook. I have managed logging in and posting text to the wall. However, when I try posting the picture, nothing happens.
I am using the Android Facebook SDK.
Here is what I have so far:
Bundle params = new Bundle();
params.putString("method", "photos.upload");
Toast.makeText(FacebookPoster.this, "" + getIntent().getExtras().getByteArray("data").length, Toast.LENGTH_SHORT).show();
params.putByteArray("picture", getIntent().getExtras().getByteArray("data"));
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
The Toast shows 8733, which means the byte array isn't empty
NB. Logcat output some warnings (not errors):
03-02 14:19:29.554: WARN/Bundle(1891): Attempt to cast generated internal exception:
03-02 14:19:29.554: WARN/Bundle(1891): java.lang.ClassCastException: java.lang.String
03-02 14:19:29.554: WARN/Bundle(1891): at android.os.Bundle.getByteArray(Bundle.java:1305)
03-02 14:19:29.554: WARN/Bundle(1891): at com.facebook.android.Util.openUrl(Util.java:155)
03-02 14:19:29.554: WARN/Bundle(1891): at com.facebook.android.Facebook.request(Facebook.java:559)
03-02 14:19:29.554: WARN/Bundle(1891): at com.facebook.android.AsyncFacebookRunner$2.run(AsyncFacebookRunner.java:253)
03-02 14:19:29.584: WARN/Bundle(1891): Key method expected byte[] but value was a java.lang.String. The default value <null> was returned.
(Shows several times underneath each other.)
What am I doing wrong?
SOLVED.
This is what I did to make it work:
facebook.authorize(this, new String[] { "publish_stream" },
new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError dialogError) {
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle values) {
postToWall(values.getString(Facebook.TOKEN));
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
And the helper method:
private void postToWall(String accessToken) {
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, accessToken);
// The byte array is the data of a picture.
params.putByteArray("picture", getIntent().getExtras().getByteArray("data"));
try {
facebook.request("me/photos", params, "POST");
} catch (FileNotFoundException fileNotFoundException) {
makeToast(fileNotFoundException.getMessage());
} catch (MalformedURLException malformedURLException) {
makeToast(malformedURLException.getMessage());
} catch (IOException ioException) {
makeToast(ioException.getMessage());
}
}
first thing is that you are not using graph api to upload the pictures... u r using the old rest api... try to use graph api, its simple...
Use following code:
Bundle param = new Bundle();
param.putString("message", "picture caption");
param.putByteArray("picture", ImageBytes);
mAsyncRunner.request("me/photos", param, "POST", new SampleUploadListener());
According to error message, it looks like its giving errors in getting bytes from intent's bundle...
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
facebook.authorize(FbdemoActivity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"},new DialogListener() {
#Override
public void onComplete(Bundle values) {
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
});
}
});
public void postImageonWall() {
byte[] data = null;
Bitmap bi = BitmapFactory.decodeFile("/sdcard/viewitems.png");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, facebook.getAccessToken());
params.putString("method", "photos.upload");
params.putByteArray("picture", data);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
}
public class SampleUploadListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
try {
// process the response here: (executed in background thread)
Log.d("Facebook-Example", "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
final String src = json.getString("src");
// then post the processed result back to the UI thread
// if we do not do this, an runtime exception will be generated
// e.g. "CalledFromWrongThreadException: Only the original
// thread that created a view hierarchy can touch its views."
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
}
try this code it will work i had used the same code and uploads the image on Facebook.
Here is the working code sample. Pass image path and message.
public static void postImageonWall(String FilePath,String msg ) {
try {
Bitmap bi = BitmapFactory.decodeFile(FilePath);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.PNG, 100, stream); // where bm is bitmap from Sdcard
byte[] byteArray = stream.toByteArray();
Bundle param = new Bundle();
param = new Bundle();
param.putString("message", msg);
param.putString("filename", "Dessert Dash");
param.putByteArray("image", byteArray);
param.putString("caption", "Dessert Dash in Android Market Now");
mAsyncRunner.request("me/photos", param, "POST", fbrq, null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String postwall(String uid)
{
String response = "";
try
{
String DIRECTORY_PATH = "/sdcard/159.jpg";
Bundle params = new Bundle();
Bitmap bitmap = BitmapFactory.decodeFile(DIRECTORY_PATH);
byte[] data = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
params.putString("app_id", uid);
params.putString("message", "picture caption");
params.putByteArray("picture", data);
mFacebook.authorize(this, PERMISSIONS, new LoginDialogListener());
mAsyncRunner.request("me/photos", params, "POST", new WallPostRequestListener());
mAsyncRunner.request(response, new WallPostRequestListener());
Log.e("post result", response);
}
catch (Exception e)
{
e.printStackTrace();
}
return response;
}
public class WallPostRequestListener extends BaseRequestListener
{
public void onComplete(final String response)
{
Log.d("Facebook-Example", "Got response: " + response);
String message = "<empty>";
try
{
JSONObject json = Util.parseJson(response);
message = json.getString("message");
}
catch (JSONException e)
{
Log.w("Facebook-Example", "JSON Error in response");
}
catch (FacebookError e)
{
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
final String text = "Your Wall Post: " + message;
}
}
I'm sure Facebook will fix this eventually, but for the time being these examples (posted by other users) are very misleading because they do NOT in fact post to the user's wall (in the regular sense). Instead they are added to the user's photo gallery, and then happen to end up on the wall, but not in the same way in which normal posts work... there is no title and no caption and if you add another photo it ends up side by side with the first (rather than as a separate entry). So, when you use the api command me/feed it just fails in a spectacular way where it actually adds a post to the wall but it's an empty post from the application (it even disregards the title and caption).
Hopefully Facebook will fix this sometime in the near term.
Posting the image and Text to Facebook wall from code, Once you logged in using facebook credentials.
note : This is applicable only after logging in to your app using facebook credentials
sharePhotoToFacebook(); //function called from any UI event
private void sharePhotoToFacebook(){
Bitmap bitmap=null;
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Download/";
try {
File file = new File(path, "image9.jpg");
bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
}
catch (Exception e){
Log.e("Error" , " Error in loading file");
}
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(bitmap)
.setCaption("A post from Android code")
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.build();
ShareApi.share(content, null);
Toast.makeText(LoginSuccessActivity.this, "Image posted successfully", Toast.LENGTH_LONG).show();
}

Categories