Multiple upload photo using LoopJ AndroidAsyncHttp - java

I'm going to upload multiple photo/video using LoopJ AndroidAsyncHttp to server. My problem is i need to add cancel button for each of the photo and allow the user to cancel the uploading. May i know anyone got the solution for this? or any others better example for me to refer?
My Code as below :-
public static void putMultipleUploadPhoto(String server,
final ProgressBar progressbarb, final String FileType, final TextView textviewb, final String FolderPath, final int itemcount, final int position)
{
final String url = "http://" + server + ":" + server.Photo_Upload;
File myFile = new File(data);
final RequestParams params = new RequestParams();
try {
params.put("data", myFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
final AsyncHttpClient client = new AsyncHttpClient();
final int totalprogress1 = 0;
try {
client.post(url,params,new AsyncHttpResponseHandler() {
public void onStart() {
// Initiated the request
progressbarb.setProgress(0);
}
#Override
public void onProgress(int position, int length) {
// TODO Auto-generated method stub
int totalprogress;
totalprogress = (position*100)/length;
progressbarb.setProgress(totalprogress);
super.onProgress(position, length);
}
#Override
public void onSuccess(String response) {
String regex = "\n"; // Only this line is changed.
String split[] = response.split(regex, 2);
if (split[0] != null)
{
String status[]=split[0].split("\\t");
if (status[0].equals("true"))
{
textviewb.setVisibility(View.VISIBLE);
textviewb.setText("Success");
if (status[0].equals("false"))
{
textviewb.setText("Fail";
textviewb.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onFailure(Throwable e, String response) {
textviewb.setVisibility(View.VISIBLE);
textviewb.setText("Fail");
}
});
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}

Very simple dear-
1)just send one by one image on server and then create a popup window for send next image or cancel.
2)In your database or where you have images just set flag 0 and 1. So you can easily make query
for send image on server which one is pending.
3)And when you got successes response from server change your flag value in database.

Related

BufferingResponseListener and getContentAsString append the previously fetched content

I run a custom WebSocketServlet for Jetty, which sends short text push notifications (for an async mobile and desktop word game) to many platforms (Facebook, Vk.com, Mail.ru, Ok.ru also Firebase and Amazon messaging) using a Jetty HttpClient instance:
public class MyServlet extends WebSocketServlet {
private final SslContextFactory mSslFactory = new SslContextFactory();
private final HttpClient mHttpClient = new HttpClient(mSslFactory);
#Override
public void init() throws ServletException {
super.init();
try {
mHttpClient.start();
} catch (Exception ex) {
throw new ServletException(ex);
}
mFcm = new Fcm(mHttpClient); // Firebase
mAdm = new Adm(mHttpClient); // Amazon
mApns = new Apns(mHttpClient); // Apple
mFacebook = new Facebook(mHttpClient);
mMailru = new Mailru(mHttpClient);
mOk = new Ok(mHttpClient);
mVk = new Vk(mHttpClient);
}
This has worked very good for the past year, but since I have recently upgraded my WAR-file to use Jetty 9.4.14.v20181114 the trouble has begun -
public class Facebook {
private final static String APP_ID = "XXXXX";
private final static String APP_SECRET = "XXXXX";
private final static String MESSAGE_URL = "https://graph.facebook.com/%s/notifications?" +
// the app access token is: "app id | app secret"
"access_token=%s%%7C%s" +
"&template=%s";
private final HttpClient mHttpClient;
public Facebook(HttpClient httpClient) {
mHttpClient = httpClient;
}
private final BufferingResponseListener mMessageListener = new BufferingResponseListener() {
#Override
public void onComplete(Result result) {
if (!result.isSucceeded()) {
LOG.warn("facebook failure: {}", result.getFailure());
return;
}
try {
// THE jsonStr SUDDENLY CONTAINS PREVIOUS CONTENT!
String jsonStr = getContentAsString(StandardCharsets.UTF_8);
LOG.info("facebook success: {}", jsonStr);
} catch (Exception ex) {
LOG.warn("facebook exception: ", ex);
}
}
};
public void postMessage(int uid, String sid, String body) {
String url = String.format(MESSAGE_URL, sid, APP_ID, APP_SECRET, UrlEncoded.encodeString(body));
mHttpClient.POST(url).send(mMessageListener);
}
}
Suddenly the getContentAsString method called for successful HttpClient invocations started to deliver the strings, which were fetched previously - prepended to the the actual result string.
What could it be please, is it some changed BufferingResponseListener behaviour or maybe some non-obvious Java quirk?
BufferingResponseListener was never intended to be reusable across requests.
Just allocate a new BufferingResponseListener for every request/response.

Check network connection in libGDX

I would like to check network connection with use of libGDX and tried to use code below.
HttpRequestBuilder requestBuilder = new HttpRequestBuilder();
Net.HttpRequest httpRequest = requestBuilder.newRequest().method(Net.HttpMethods.GET).url("https://api.vk.com/").build();
Net.HttpResponseListener httpResponseListener = new httpResponseListener() {
public void handleHttpResponse (Net.HttpResponse httpResponse) {
HttpStatus status = httpResponse.getStatus();
if (status.getStatusCode() >= 200 && status.getStatusCode() < 300) {
// it was successful
} else {
// do something else
}
}
}
Gdx.net.sendHttpRequest(httpRequest, httpResponseListener);
It has several errors, like Gdx.net doesn't have sendHttpRequest() function now. How should I correct this code?
Gdx.net has got sendHttpRequest() method - it seems that you are using not proper HttpRequest instance (why this Net... is starting with uppercase?)
A proper minimal example of how to use Gdx.net is beneath - I have also added a comments where it was necessary
public class HttpManager implements HttpResponseListener
{
public HttpState state;
private String result;
private byte[] byteResult;
HttpRequest request;
public HttpManager()
{
request = new HttpRequest();
request.setMethod(Net.HttpMethods.GET); //or POST
request.setContent(""); //you can put here some PUT/GET content
request.setUrl(url);
Gdx.net.sendHttpRequest(request, this);
}
#Override
public void handleHttpResponse(HttpResponse httpResponse)
{
if( httpResponse.getStatus().getStatusCode() != 200 )
{
//ERROR
float errorCode = httpResponse.getStatus().getStatusCode();
}
else
{
byte[] byteResult = httpResponse.getResult(); //you can also get result as String by using httpResponse.getResultAsString();
}
}
#Override
public void failed(Throwable t)
{
// TODO Auto-generated method stub
}
#Override
public void cancelled()
{
// TODO Auto-generated method stub
}
}

Calling class on ButtonClick (Android)

I am new to Android developer. I have 2 different class (MainActivity.java & Upload.java)
I have problem to call Upload.java into Main.Activity.
When I click the button, the app is crashing.
Is there anything that I have done wrong?
MainActivity.java
Button upload = (Button)findViewById(R.id.upload_Btn);
upload.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Update_Table dbClient = new Update_Table();
try {
dbClient.DynamoDBClient();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.i("sys", "Success");
}
}
}
Upload.java
public class Update_Table
{
private String tableName = "Test";
private AmazonDynamoDBClient client =null;
public void DynamoDBClient() throws IOException
{
AWSCredentials cred = new PropertiesCredentials(Update_Table.class
.getResourceAsStream("AwsCredentials.properties"));
client = new AmazonDynamoDBClient(cred);
}
}
LOGCAT:
Change the line in the method like below:-
public class Update_Table
{
private String tableName = "Test";
private AmazonDynamoDBClient client =null;
public void DynamoDBClient() throws IOException
{
//changed the below line
AWSCredentials cred = new PropertiesCredentials(ClassLoader.getResourceAsStream("src/com.afdal.ftsmetheses/AwsCredentials.properties"));
//OR try this
AWSCredentials cred = new PropertiesCredentials(ClassLoader.getResourceAsStream("com.afdal.ftsmetheses/AwsCredentials.properties"));
client = new AmazonDynamoDBClient(cred);
}
}

AutoCompleteTextView & Async class

I am a rookie in the Android world and I built up a small training SW based on the 2.1 Google API.
At that time I did not know yet about main thread and worker threads, so I put all my code in the main thread.
Since, I fixed it with async classes for my netwkork access to fit the 4.0 Google API.
Ok, but one last thing bothers me and I just can not find any clues.
It is about an AutoCompleteTextView on a field ville ("town" in french).
BEFORE (2.1):
public void onTextChanged(CharSequence s, int start, int before, int count)
{
String result = null;
InputStream is = null;
List<String> r = new ArrayList<String>();
if (ville.enoughToFilter())
{
is = connexionHttp(BASE_URL + "ville.php?ville=" + ville.getText());
result = lectureData(is);
try
{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
r.add(json_data.getString("VILLE"));
a_idVil.add(json_data.getString("CLEF_VILLE"));
}
ville.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_selectable_list_item,r));
ville.setOnItemSelectedListener(new villeListener());
}
catch(JSONException e1)
{
Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
Log.d("***** TestActivity/onTextChanged: JSONException *****", "--"+e1.toString()+"--");
}
catch(ParseException e1)
{
Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
Log.d("***** TestActivity/onTextChanged: ParseException *****", "--"+e1.toString()+"--");
}
}
}
public class villeListener implements OnItemSelectedListener
{
public void onItemSelected(AdapterView<?> parent, View v, int pos, long row)
{
villePosition = pos;
}
public void onNothingSelected(AdapterView<?> arg0) { }
}
runs 100% perfect:
-> after the 4th caracters, the query runs on MySql to find all the towns beginning with the 4 given letters, and displays the selection list to select the right one: OK
-> the listener give the index of the choosen town: OK
AFTER (4.0)
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if (ville.enoughToFilter())
{
new RemplirVille().execute(BASE_URL + "ville.php?ville=" + ville.getText());
Log.d("***********","AVANT");
ville.setOnItemSelectedListener(new villeListener());
Log.d("***********","APRES");
}
}
public class villeListener implements OnItemSelectedListener
{
public void onItemSelected(AdapterView<?> parent, View v, int pos, long row)
{
villePosition = pos;
Log.d("*************9999999", "1111111111");
}
public void onNothingSelected(AdapterView<?> arg0) { }
}
class RemplirVille extends AsyncTask<String, String, List<String>>
{
Integer errorMsgId;
String errorMsgParam;
protected List<String> doInBackground(String... param)
{
List<String> listeAffichageVille = new ArrayList<String>();
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(param[0]);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() < 400)
{
HttpEntity entity = response.getEntity();
String entityStr = EntityUtils.toString(entity);
JSONArray json_array = new JSONArray(entityStr);
for(int i=0;i<json_array.length();i++)
{
JSONObject json_ligne = json_array.getJSONObject(i);
listeAffichageVille.add(json_ligne.getString("VILLE"));
a_idVil.add(json_ligne.getString("CLEF_VILLE"));
}
}
else
{
Log.d("***** TestActivity/ASYNC RemplirVille: EXCEPTION http error *****", "--"+response.getStatusLine().toString()+"--");
this.errorMsgId = R.string.http_site_error;
listeAffichageVille = null;
}
}
catch (Exception ex)
{
Log.d("***** TestActivity/ASYNC RemplirVille: EXCEPTION decode error *****", "--"+ex.toString()+"--");
this.errorMsgId = R.string.http_decode_error;
this.errorMsgParam = ex.getLocalizedMessage();
listeAffichageVille = null;
}
return listeAffichageVille;
}
protected void onProgressUpdate(String... item) { }
protected void onPreExecute(List<String> list) { }
protected void onPostExecute(List<String> list)
{
if (list == null)
{
if (this.errorMsgId != null)
{
String msg = TestActivity.this.getString(this.errorMsgId);
Toast.makeText(TestActivity.this,msg,Toast.LENGTH_LONG).show();
}
}
else
{
ville.setAdapter(new ArrayAdapter<String>(TestActivity.this,android.R.layout.simple_selectable_list_item,list));
}
}
}
runs with troubles:
-> you have to put in (enoughToFilter + 1) caractères to diplay the list of the towns: BAD
-> the listener is even not run anymore: BAD
In fact enoughToFilter works well, it launches the RemplirVille class which runs ok except that it does not displays the list!
But, if you put in 1 more caracter:
-> enoughToFilter still working well
-> RemplirVille brings the data one more time.... but this time the selection list displays well.
Any idea about that topic?
I guess it is a context problem, but even with a GetApplicationCOntext I just can not get it.
Thanks.
Calling AutoCompleteTextView.setAdapter() does not automatically show the dropdown, but you can force the dropdown to be shown with AutoCompleteTextView.showDropDown().
protected void onPostExecute(List<String> list){
//...
ville.setAdapter(new ArrayAdapter<String>(TestActivity.this,android.R.layout.simple_selectable_list_item,list));
if(ville.isInputMethodTarget()){
ville.showDropDown();
}
//...
}
Without this, the dropdown was not shown until the next character was typed, which gave the (enoughToFilter + 1) problem.

Permissions Error - Trying to get friends using android facebook sdk

I am trying to add a feature to my android app that allows users to "checkin" with other people tagged to the checkin.
I have the checkins method working no problem and can tag some one by adding the user ID as a parameter (see code below)
public void postLocationTagged(String msg, String tags, String placeID, Double lat, Double lon) {
Log.d("Tests", "Testing graph API location post");
String access_token = sharedPrefs.getString("access_token", "x");
try {
if (isSession()) {
String response = mFacebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("access_token", access_token);
parameters.putString("place", placeID);
parameters.putString("Message",msg);
JSONObject coordinates = new JSONObject();
coordinates.put("latitude", lat);
coordinates.put("longitude", lon);
parameters.putString("coordinates",coordinates.toString());
parameters.putString("tags", tags);
response = mFacebook.request("me/checkins", parameters, "POST");
Toast display = Toast.makeText(this, "Checkin has been posted to Facebook.", Toast.LENGTH_SHORT);
display.show();
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} else {
// no logged in, so relogin
Log.d(TAG, "sessionNOTValid, relogin");
mFacebook.authorize(this, PERMS, new LoginDialogListener());
}
} catch(Exception e) {
e.printStackTrace();
}
}
This works fine (I've posted it in case it is of help to anyone else!), the problem i am having is i am trying to create a list of the users friends so they can select the friends they want to tag. I have the method getFriends (see below) which i am then going to use to generate an AlertDialog that the user can select from which in turn will give me the id to use in the above "postLocationTagged" method.
public void getFriends(CharSequence[] charFriendsNames,CharSequence[] charFriendsID, ProgressBar progbar) {
pb = progbar;
try {
if (isSession()) {
String access_token = sharedPrefs.getString("access_token", "x");
friends = charFriendsNames;
friendsID = charFriendsID;
Log.d(TAG, "Getting Friends!");
String response = mFacebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("access_token", access_token);
response = mFacebook.request("me/friends", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} else {
// no logged in, so relogin
Log.d(TAG, "sessionNOTValid, relogin");
mFacebook.authorize(this, PERMS, new LoginDialogListener());
}
} catch(Exception e) {
e.printStackTrace();
}
}
When i look at the response in the log it reads:
"got responce: {"error":{"type":"OAuthException", "message":"(#200) Permissions error"}}"
I have looked through the graphAPI documentation and searched for similar questions but to no avail! I'm not sure if i need to request extra permissions for the app or if this is something your just not allowed to do! Any help/suggestions would be greatly appreciated.
You might need the following permissions:
user_checkins
friends_checkins
read_friendlists
manage_friendlists
publish_checkins
Check the related ones from the API docs. Before that, make sure that which line causes this permission error and try to fix it.
The solution is to implement a RequestListener when making the request to the Facebook graph API. I have the new getFriends() method (see below) which uses the AsyncGacebookRunner to request the data.
public void getFriends(CharSequence[] charFriendsNames,String[] sFriendsID, ProgressBar progbar) {
try{
//Pass arrays to store data
friends = charFriendsNames;
friendsID = sFriendsID;
pb = progbar;
Log.d(TAG, "Getting Friends!");
//Create Request with Friends Request Listener
mAsyncRunner.request("me/friends", new FriendsRequestListener());
} catch (Exception e) {
Log.d(TAG, "Exception: " + e.getMessage());
}
}
The AsyncFacebookRunner makes the the request using the custom FriendsRequestListener (see below) which implements the RequestListener class;
private class FriendsRequestListener implements RequestListener {
String friendData;
//Method runs when request is complete
public void onComplete(String response, Object state) {
Log.d(TAG, "FriendListRequestONComplete");
//Create a copy of the response so i can be read in the run() method.
friendData = response;
//Create method to run on UI thread
FBConnectActivity.this.runOnUiThread(new Runnable() {
public void run() {
try {
//Parse JSON Data
JSONObject json;
json = Util.parseJson(friendData);
//Get the JSONArry from our response JSONObject
JSONArray friendArray = json.getJSONArray("data");
//Loop through our JSONArray
int friendCount = 0;
String fId, fNm;
JSONObject friend;
for (int i = 0;i<friendArray.length();i++){
//Get a JSONObject from the JSONArray
friend = friendArray.getJSONObject(i);
//Extract the strings from the JSONObject
fId = friend.getString("id");
fNm = friend.getString("name");
//Set the values to our arrays
friendsID[friendCount] = fId;
friends[friendCount] = fNm;
friendCount ++;
Log.d("TEST", "Friend Added: " + fNm);
}
//Remove Progress Bar
pb.setVisibility(ProgressBar.GONE);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FacebookError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
Feel free to use any of this code in your own projects, or ask any questions about it.
You can private static final String[] PERMISSIONS = new String[] {"publish_stream","status_update",xxxx};xxx is premissions

Categories

Resources