My question is when scanning a pdf417 barcode format sometimes it returns a UPC_E format base on the scan result?
here is a snippet of my code
private BarcodeView barcodeView;
private BarcodeCallback callback = new BarcodeCallback() {
#Override
public void barcodeResult(BarcodeResult result) {
if (result.getText() != null) {
Toast.makeText(getActivity(), result.getText(), Toast.LENGTH_LONG).show();
}
}
#Override
public void possibleResultPoints(List<ResultPoint> resultPoints) {
}
};
here is the library
compile 'com.journeyapps:zxing-android-embedded:3.3.0'
This solved the problem. long time ago :)
private BarcodeCallback callback = new BarcodeCallback() {
#Override
public void barcodeResult(BarcodeResult result) {
if (result.getText() != null) {
String barcodeResult = result.getText();
String barcodeFormat = result.getBarcodeFormat().toString();
if (barcodeFormat.equals("PDF_417")) {
try {
String barcodeEncodedResult = new ConvertUtil().encodeIntoBase64(barcodeResult);
processEncodedResult(barcodeEncodedResult);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getActivity(), "Unable to read as PDF_417 barcode format", Toast.LENGTH_LONG).show();
}
}
}
you can pass the format to scan with intent integrator. Something like :
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.setDesiredBarcodeFormats(IntentIntegrator.PDF_147);
intent = integrator.createScanIntent();
barcodeView.initializeFromIntent(intent);
Related
I have an app which automatically fetch data online whenever it is opened. I would like to make it a way that the app will only check for update online when a blacklisted app is not detected.
This is the update core.
public class UpdateCore extends AsyncTask<String, String, String> {
private static final String TAG = "NetGuard.Download";
private Context context;
private Listener listener;
private PowerManager.WakeLock wakeLock;
private HttpURLConnection uRLConnection;
private InputStream is;
private TorrentDetection torrent;
private BufferedReader buffer;
private String url;
public interface Listener {
void onLoading();
void onCompleted(String config) throws Exception;
void onCancelled();
void onException(String ex);
}
public UpdateCore(Context context, String url, Listener listener) {
this.context = context;
this.url = url;
this.listener = listener;
}
#Override
protected void onPreExecute() {
listener.onLoading();
}
#Override
protected String doInBackground(String... args) {
try {
String api = url;
if(!api.startsWith("http")){
api = new StringBuilder().append("http://").append(url).toString();
}
URL oracle = new URL(api);
HttpClient Client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(oracle.toURI());
HttpResponse response = Client.execute(httpget);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
in, "iso-8859-1"), 8);
//BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
return str.toString();
} catch (Exception e) {
return "error";
} finally {
if (buffer != null) {
try {
buffer.close();
} catch (IOException ignored) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException ignored) {
}
}
if (uRLConnection != null) {
uRLConnection.disconnect();
}
}
}
#Override
protected void onCancelled() {
super.onCancelled();
// Log.i(TAG, "Cancelled");
// pd.dismiss();
listener.onCancelled();
}
#Override
protected void onPostExecute(String result) {
// wakeLock.release();
//nm.cancel(1);
// pd.dismiss();
try
{
if (result.equals("error"))
{
listener.onException(result);
}
else {
listener.onCompleted(result);
}
}
catch (Exception e)
{
listener.onException(e.getMessage());
}
}
}
This is the detection code
public class TorrentDetection
{
private Context context;
private String[] items;
private TorrentDetection.TorrentListener listener;
private Timer timer;
private Handler handler;
public interface TorrentListener {
public void detected(ArrayList pkg);
}
public TorrentDetection(Context c, String[] i, TorrentListener listener) {
context = c;
items = i;
this.listener = listener;
}
private boolean check(String uri)
{
PackageManager pm = context.getPackageManager();
boolean app_installed = false;
try
{
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
app_installed = true;
}
catch (PackageManager.NameNotFoundException e)
{
app_installed = false;
}
return app_installed;
}
void check() {
ArrayList arrayList2 = new ArrayList();
for (String pack : items)
{
if(check(pack)){
arrayList2.add(pack);
}
}
if (arrayList2.size() > 0)
{
listener.detected(arrayList2);
stop();
}
}
public void start() {
handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run()
{
handler.post(new Runnable() {
public void run()
{
check();
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 3000);
}
public void stop() {
if(timer != null){
timer.cancel();
timer = null;
}
if(handler != null){
handler = null;
}
}
}
The torrent detection code checks if the following apps are installed and returns a message that an unsupported app is installed.
public class Constraints
{
public static String updater = "https://pastenord.org/raw/random";
public static String[] torrentList = new String[]{
"com.guoshi.httpcanary",
"com.adguard.android.contentblocker"};
}
In my MainActivity this initiates the detection before the online update is done with torrent.start();
void update() {
torrent.start();
new UpdateCore(this, Constraints.updater, new UpdateCore.Listener() {
#Override
public void onLoading() {
}
#Override
public void onCompleted(final String config) {
try {
final JSONObject obj = new JSONObject(MilitaryGradeEncrypt.decryptBase64StringToString(config, Constraints.confpass));
if (Double.valueOf(obj.getString("Version")) <= Double.valueOf(conts.getConfigVersion())) {
} else {
new SweetAlertDialog(MainActivity.this, SweetAlertDialog.CUSTOM_IMAGE_TYPE)
.setTitleText("Update")
.setContentText("\n" + obj.getString("Message"))
.setConfirmText("Yes,Update it!")
.setCustomImage(R.drawable.ic_update)
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sDialog) {
sDialog.dismissWithAnimation();
welcomeNotif();
restart_app();
try {
db.updateData("1", config);
sp.edit().putString("CurrentConfigVersion", obj.getString("Version")).commit();
} catch (JSONException e) {}
}
})
.show();
}
} catch (Exception e) {
// Toast.makeText(MainActivity.this, e.getMessage() , 0).show();
}
}
#Override
public void onCancelled() {
}
#Override
public void onException(String ex) {
}
}).execute();
}
}
It then makes a popup when an unsupported app is detected with this.
torrent = new TorrentDetection(this, Constraints.torrentList, new TorrentDetection.TorrentListener() {
#Override
public void detected(ArrayList pkg)
{
stopService();
new AlertDialog.Builder(MainActivity.this)
.setTitle("unsupported App!")
.setMessage(String.format("%s", new Object[]{TextUtils.join(", ", (String[]) pkg.toArray(new String[pkg.size()]))}))
.setPositiveButton("OK", null)
//.setAnimation(Animation.SLIDE)
.setCancelable(false)
.create()
//.setIcon(R.mipmap.ic_info, Icon.Visible)
.show();
}
});
I would like the make the app only check for online update only when done of the blacklisted apps are installed. Any form of help is welcomed and appreciated.
use this method to check if an application is installed or not
public boolean isPackageInstalled(String packageName, PackageManager packageManager) {
try {
packageManager.getPackageInfo(packageName, 0);
return true;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
then to check, simply call:
PackageManager pm = context.getPackageManager();
boolean isInstalled = isPackageInstalled("com.somepackage.name", pm);
// simply put an if statemement
if(!isInstalled){
//do your update here
}
else{
//display you have installed a blacklisted app
}
sidenote, if you are targeting android 11 and above, you need to provide the information about the packages you want to find out about in the manifest like this
<queries>
<!--Add queries here-->
<package android:name="com.somepackage.name" />
</queries>
First, Thank you very much for looking at this!
I've been handed an app someone wrote before Marshmallow. I've fixed the Theme and SSL issues that came with Nougat but I'm having a heck of a time with Write to External Storage Permission or something associated. Debug is lacking or I'm not using it properly. This app creates a file onto the device and adds the ssl cert and login info in a folder called My Documents.
When I open the app it say network timeout right away. That message is from LoginActivity.java . I click ok then I get the Android pop up asking to allow permissions. I allow it. After that I put in the username and password and click login. It instantly gives the network timeout message from LoginActivity.java. LoginActivity.java is the Main Activity. If I click ok it's back to the login screen. All permissions are in the Android Manifest as well.
Maybe it's not from permissions but it works fine in version 22. I've worked on this 12 hours today and thought if you guys could help that'd be great. I'm a network engineer dabbling in Java so please excuse my question if it's "ugly".
I tried to find a line by line debug like I've done with phonegap but wasn't successful.
My Apps Main Activity LoginActivity.java and associated activity is LoginScreen.java and shown below.
LoginActivity.java
public class LoginActivity extends Activity {
private String userName = "";
private static final int PERMS_REQUEST_CODE = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.blackactivity);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
new SSLHandler().execute();
if(Variables.testing)
{
}
if (hasPermissions()){
// our app has permissions.
try {
attemptLogin();
} catch (Exception e) {
GUI.oneOptionDialog(this, e.toString(), "OK", false);
e.printStackTrace();
}
}
else {
//our app doesn't have permissions, So i m requesting permissions.
requestPerms();
}
}
//Begin Permission Methods
#SuppressLint("WrongConstant")
private boolean hasPermissions(){
int res = 0;
//string array of permissions,
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
for (String perms : permissions){
res = checkCallingOrSelfPermission(perms);
if (!(res == PackageManager.PERMISSION_GRANTED)){
return false;
}
}
return true;
}
private void requestPerms(){
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
requestPermissions(permissions,PERMS_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
boolean allowed = true;
switch (requestCode){
case PERMS_REQUEST_CODE:
for (int res : grantResults){
// if user granted all permissions.
allowed = allowed && (res == PackageManager.PERMISSION_GRANTED);
}
break;
default:
// if user not granted permissions.
allowed = false;
break;
}
if (allowed){
//user granted all permissions we can perform our task.
try {
attemptLogin();
} catch (Exception e) {
GUI.oneOptionDialog(this, e.toString(), "OK", false);
e.printStackTrace();
}
}
else {
// we will give warning to user that they haven't granted permissions.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(this, "Storage Permissions denied.", Toast.LENGTH_SHORT).show();
}
}
}
}
//End Permission Methods
private void attemptLogin() throws IOException {
String filepath = Variables.fileFolder + "/login.txt";
File tempFile = new File(filepath);
if (!tempFile.exists()) {
startActivity(new Intent(LoginActivity.this, LoginScreen.class));
finish();
}
String username = "";
String passwordHash = "";
String salt = "";
boolean fileExists = false;
BufferedReader reader = null;
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(new File(filepath));
InputStreamReader inputStreamReader = new InputStreamReader(
fileInputStream);
reader = new BufferedReader(inputStreamReader);
username = reader.readLine();
passwordHash = reader.readLine();
salt = reader.readLine();
reader.close();
userName = username;
fileInputStream.close();
} catch (Exception e) {
startActivity(new Intent(LoginActivity.this, LoginScreen.class));
finish();
}
fileExists = true;
if (fileExists) {
try {
LoginTask login = new LoginTask();
login.execute(username, passwordHash, salt);
} catch (Exception e) {
}
}
}
private class LoginTask extends AsyncTask<String, Void, Boolean> {
Boolean success = false;
Boolean timedOut = false;
ProgressDialog mProgressDialog;
#Override
protected void onPostExecute(Boolean result) {
try {
mProgressDialog.dismiss();
} catch (Exception e) {
}
if (timedOut) {
AlertDialog.Builder builder = new AlertDialog.Builder(
LoginActivity.this);
builder.setMessage("Network Timed Out").setTitle("Notice");
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
startActivity(new Intent(LoginActivity.this,
LoginScreen.class));
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else {
if (result) {
Variables.storeTechName(userName, LoginActivity.this);
Variables.assignTechName();
startActivity(new Intent(LoginActivity.this,
MainActivity.class));
finish();
} else {
startActivity(new Intent(LoginActivity.this,
LoginScreen.class));
finish();
}
}
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(LoginActivity.this,
"Loading...", "Logging you in...");
mProgressDialog.getWindow().setGravity(Gravity.BOTTOM);
}
#Override
protected Boolean doInBackground(String... params) {
try {
URL json = new URL(Variables.urlPrefix + "/Login.svc/input?a="
+ params[0] + "&b=" + params[1] + "&c=" + params[2]);
HttpsURLConnection jc = (HttpsURLConnection) json
.openConnection();
jc.setConnectTimeout(Variables.timeoutTimeLimit);
jc.setSSLSocketFactory(Variables.context.getSocketFactory());
InputStreamReader input = new InputStreamReader(
jc.getInputStream());
BufferedReader reader = new BufferedReader(input);
String line = reader.readLine();
JSONObject jsonResponse = new JSONObject(line);
success = jsonResponse.getBoolean("LoginMethodResult");
jc.disconnect();
reader.close();
} catch (Exception e) {
System.out.println(e.toString());
timedOut = true;
}
return success;
}
}
#Override
protected void onPause() {
super.onPause();
}
}
LoginScreen.java
public class LoginScreen extends Activity {
private String userName;
private static final int PERMS_REQUEST_CODE = 123;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginscreen);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (!SSLHandler.loaded) {
new SSLHandler().execute();
}
// Creates login and name files and attempts to log in
Button createButton = (Button) findViewById(R.id.createbutton);
createButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((EditText) findViewById(R.id.usernamefield)).getText()
.toString().isEmpty()
|| ((EditText) findViewById(R.id.passwordfield))
.getText().toString().isEmpty()) {
GUI.oneOptionDialog(LoginScreen.this,
"Missing field entries", "OK", false);
} else {
createLoginFile();
((EditText) findViewById(R.id.usernamefield)).setText("");
((EditText) findViewById(R.id.passwordfield)).setText("");
attemptLogin();
}
}
});
}
#SuppressLint("WrongConstant")
private boolean hasPermissions(){
int res = 0;
//string array of permissions,
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
for (String perms : permissions){
res = checkCallingOrSelfPermission(perms);
if (!(res == PackageManager.PERMISSION_GRANTED)){
return false;
}
}
return true;
}
private void requestPerms(){
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
requestPermissions(permissions,PERMS_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
boolean allowed = true;
switch (requestCode){
case PERMS_REQUEST_CODE:
for (int res : grantResults){
// if user granted all permissions.
allowed = allowed && (res == PackageManager.PERMISSION_GRANTED);
}
break;
default:
// if user not granted permissions.
allowed = false;
break;
}
if (allowed){
//user granted all permissions we can perform our task.
createFiles();
}
else {
// we will give warning to user that they haven't granted permissions.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(this, "Storage Permissions denied.", Toast.LENGTH_SHORT).show();
}
}
}
}
private void createFiles() {
}
private void attemptLogin() {
String username = "";
String passwordHash = "";
String salt = "";
boolean fileExists = false;
try {
String filepath = Variables.fileFolder + "/login.txt";
FileInputStream fileInputStream = new FileInputStream(new File(
filepath));
InputStreamReader inputStreamReader = new InputStreamReader(
fileInputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
username = reader.readLine();
passwordHash = reader.readLine();
salt = reader.readLine();
reader.close();
userName = username;
fileInputStream.close();
fileExists = true;
}
catch (Exception e) {
GUI.oneOptionDialog(LoginScreen.this,
"Login file does not exist. Please enter login info.",
"OK", false);
}
if (fileExists) {
try {
LoginTask login = new LoginTask();
login.execute(username, passwordHash, salt);
} catch (Exception e) {
}
}
}
private class LoginTask extends AsyncTask<String, Void, Boolean> {
Boolean timedOut = false;
Boolean success = false;
ProgressDialog mProgressDialog;
#Override
protected void onPostExecute(Boolean result) {
try {
mProgressDialog.dismiss();
} catch (Exception e) {
}
if (timedOut) {
GUI.oneOptionDialog(LoginScreen.this, "Network Timed Out",
"OK", false);
} else {
if (result) {
Variables.storeTechName(userName, LoginScreen.this);
Variables.assignTechName();
startActivity(new Intent(LoginScreen.this,
MainActivity.class));
finish();
} else {
GUI.oneOptionDialog(LoginScreen.this,
"Login Failed. Please try again.", "OK", false);
}
}
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(LoginScreen.this,
"Loading...", "Logging you in...");
}
#Override
protected Boolean doInBackground(String... params) {
try {
URL json = new URL(Variables.urlPrefix + "/Login.svc/input?a="
+ params[0] + "&b=" + params[1] + "&c=" + params[2]);
HttpsURLConnection jc = (HttpsURLConnection) json
.openConnection();
jc.setConnectTimeout(Variables.timeoutTimeLimit);
jc.setSSLSocketFactory(Variables.context.getSocketFactory());
jc.setConnectTimeout(Variables.timeoutTimeLimit);
InputStreamReader input = new InputStreamReader(
jc.getInputStream());
BufferedReader reader = new BufferedReader(input);
String line = reader.readLine();
JSONObject jsonResponse = new JSONObject(line);
success = jsonResponse.getBoolean("LoginMethodResult");
jc.disconnect();
reader.close();
} catch (Exception e) {
timedOut = true;
}
return success;
}
}
private void createLoginFile() {
try {
File dir = new File(Variables.fileFolder);
if (!dir.isDirectory()) {
dir.mkdirs();
}
String filepath = Variables.fileFolder + "/Login.txt";
String username = ((EditText) findViewById(R.id.usernamefield))
.getText().toString();
String password = ((EditText) findViewById(R.id.passwordfield))
.getText().toString();
String salt = new RandomString(20).nextString();
String passwordHash = Variables.sha256(password + salt);
PrintWriter writer = new PrintWriter(filepath, "UTF-8");
writer.println(username);
writer.println(passwordHash);
writer.println(salt);
writer.close();
} catch (Exception e) {
GUI.oneOptionDialog(LoginScreen.this, e.toString(), "OK", false);
}
}
#Override
protected void onPause() {
super.onPause();
}
}
java.lang.IllegalStateException: Your Realm is opened from a thread
without a Looper and you provided a callback, we need a Handler to
invoke your callback
I'm Writing a code that will do in background- read from a text file(inside assets) and then placing them into a realm database.But i seem to get this error
"java.lang.IllegalStateException: Your Realm is opened from a thread without a Looper and you provided a callback, we need a Handler to invoke your
callback"
In my onCreate i have this
Realm.init(context);
realm = Realm.getDefaultInstance();
ParseInBackground task = new ParseInBackground();
task.execute();
and in the do-in-background task of AsyncTask i got this
try {
realm = Realm.getDefaultInstance();
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgRealm) {
final ModelClass modelClass = bgRealm.createObject(ModelClass.class);
try {
InputStream file = getAssets().open("goodie.txt");
reader = new BufferedReader(new InputStreamReader(file));
final String[] line = {reader.readLine()};
while (line[0] != null) {
handler.post(new Runnable() {
#Override
public void run() {
try {
line[0] = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
String[] namelist = line[0].split(":");
String iWord = namelist[0];
String iDesc = namelist[1];
modelClass.setName(iWord);
modelClass.setDesc(iDesc);
count++;
}
});
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (realm != null)
realm.close();
}
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Added " + count + "items", Toast.LENGTH_SHORT).show();
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
}
}
);
} catch (Exception e) {
e.printStackTrace();
}
and a Model class called ModelClass has this
private String name;
private String desc;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
Desperately in need of help.Thanks in advance
Check http://developer.android.com/reference/android/os/Handler.html and http://developer.android.com/reference/android/os/Looper.html
Basically Realm need a way to communicate with your thread when doing asyc query, on Android, naturally Looper and Handler is the way to go.
Check this for more sample code.
https://github.com/realm/realm-java/tree/master/examples/threadExample
You need to remove Handler.post(...) from within the execute callback.
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgRealm) {
final ModelClass modelClass = bgRealm.createObject(ModelClass.class);
try {
InputStream file = getAssets().open("goodie.txt");
reader = new BufferedReader(new InputStreamReader(file));
final String[] line = {reader.readLine()};
while (line[0] != null) {
try {
line[0] = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
String[] namelist = line[0].split(":");
String iWord = namelist[0];
String iDesc = namelist[1];
modelClass.setName(iWord);
modelClass.setDesc(iDesc);
count++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (realm != null)
realm.close();
}
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Added " + count + "items", Toast.LENGTH_SHORT).show();
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
}
}
);
} catch (Exception e) {
e.printStackTrace();
}
I hope this helps.
I'm using Apache's FTPClient to upload files to my server (images from the gallery if it matters)
I'm having a small and pretty insignificant problem, but I would still like to solve it.
The problem is that the bar is filled and reaches 100% before the upload actually completes, causing the dialog to show 100% for an extra 2-3 seconds on small files (and could be a lot more on files weighing several MBs).
I'm guessing it's because of the conversion from long to int, but that's just a guess.
Here's the code:
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(UploadActivity.this);
dialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
uploadImage.cancel(true);
}
});
dialog.setMessage("Uploading...\nPlease Wait.");
dialog.setIndeterminate(false);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
dialog.setCancelable(false);
dialog.setMax((int)(file.length()/1024));
dialog.setProgressNumberFormat ("%1dKB/%2dKB");
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
CopyStreamAdapter streamListener = new CopyStreamAdapter() {
#Override // THIS PART IS RESPONSIBLE FOR UPDATING THE PROGRESS
public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) {
int percent = (int) (totalBytesTransferred * 100 / file.length());
publishProgress(percent);
}
};
String name = null;
ftp.setCopyStreamListener(streamListener);
FileInputStream fis = null;
try {
String extension = "";
String fileName = file.getName();
int i = fileName.lastIndexOf('.');
int p = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));
if (i > p) {
extension = fileName.substring(i + 1);
}
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyy-hhmmss-SSS");
name = String.format("File-%s.%s", sdf.format(new Date()), extension);
ftp.connect(FTP_SERVER);
ftp.enterLocalPassiveMode();
ftp.login(ftpUser, ftpPassword);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
fis = new FileInputStream(file);
if (!ftp.storeFile(name, fis)) {
showToast("Failed uploading");
return null;
}
ftp.logout();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return name;
}
#Override
protected void onProgressUpdate(Integer... values) {
dialog.setProgress(values[0]);
}
Thanks!
I tried this: when isSessionValid getDetails directly else facebook.authorize and then getDetails in onActivityResult
public class MainActivity extends Activity {
Facebook facebook = new Facebook("xxxxxxxxxxxxxxxx");
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
private SharedPreferences mPrefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] {}, new DialogListener() {
#Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
});
}else{
try {
JSONObject json = Util.parseJson(facebook.request("me"));
String facebookID = json.getString("id");
String firstName = json.getString("first_name");
String lastName = json.getString("last_name");
String email = json.getString("email");
String gender = json.getString("gender");
} catch (Exception e) {
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
try {
JSONObject json = Util.parseJson(facebook.request("me"));
String facebookID = json.getString("id");
String firstName = json.getString("first_name");
String lastName = json.getString("last_name");
String email = json.getString("email");
String gender = json.getString("gender");
} catch (Exception e) {
}
}
public void onResume() {
super.onResume();
facebook.extendAccessTokenIfNeeded(this, null);
}
}
This works fine when I have facebook app installed on my system. But If not installed i get a Web View to enter facebook credentials and in logcat shows login-success, but none of the getDetails block is called.
Here in initFacebook() function through you can login and perform you functionality, here i am fetching user's friends information.
private void initFacebook()
{
try
{
if (APP_ID == null)
{
Util.showAlert(this,"Warning","Facebook Applicaton ID must be "+ "specified before running this example: see Example.java");
}
mFacebook = new Facebook();
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
mFacebook.authorize(FacebookList.this, APP_ID, new String[] {"email", "read_stream", "user_hometown", "user_location","friends_about_me", "friends_hometown", "friends_location","user_relationships", "friends_relationship_details","friends_birthday", "friends_education_history","friends_website" }, new DialogListener()
{
public void onComplete(Bundle values)
{
getHTTPConnection();
}
public void onFacebookError(FacebookError error)
{
Log.i("public void onFacebookError(FacebookError error)....","....");
}
public void onError(DialogError e)
{
Log.i("public void onError(DialogError e)....", "....");
CustomConfirmOkDialog dialog = new CustomConfirmOkDialog(FacebookList.this, R.style.CustomDialogTheme, Utils.FACEBOOK_CONNECTION_ERROR);
dialog.show();
}
public void onCancel()
{
Log.i("public void onCancel()....", "....");
}
});
SessionStore.restore(mFacebook, this);
SessionEvents.addAuthListener(new SampleAuthListener());
SessionEvents.addLogoutListener(new SampleLogoutListener());
}
catch (Exception e)
{
e.printStackTrace();
}
}
Here in getHTTPConnection(), proceeding for connection and sending fields, that we require about user's friends as here we can see that passing fields are fields=id,first_name,last_name,location,picture of friends. here you can change this fields according to application's requirements.
private void getHTTPConnection()
{
try
{
mAccessToken = mFacebook.getAccessToken();
HttpClient httpclient = new DefaultHttpClient();
String result = null;
HttpGet httpget = new HttpGet("https://graph.facebook.com/me/friends?access_token="+ mAccessToken + "&fields=id,first_name,last_name,location,picture");
HttpResponse response;
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null)
{
result = EntityUtils.toString(entity);
parseJSON(result);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
Now after successfully connecting with facebook , we are getting JSON data and further to parse it .
private void parseJSON(String data1) throws Exception,NullPointerException, JSONException
{
try
{
JSONObject jObj = new JSONObject(data1);
JSONArray jObjArr = jObj.optJSONArray("data");
int lon = jObjArr.length();
for (int i = 0; i < lon; i++)
{
JSONObject tmp = jObjArr.optJSONObject(i);
String temp_image = tmp.getString("picture"); String temp_fname = tmp.getString("first_name");
String temp_lname = tmp.getString("last_name");
String temp_loc = null;
JSONObject loc = tmp.getJSONObject("location");
temp_loc = loc.getString("name");
}
}
catch (Exception e)
{
Log.i("Exception1 is Here>> ", e.toString());
e.printStackTrace();
}
}
It is assumed that you have already added a facebook jar in to your application and for proceeding this code you can call initFacebook() in to onCreate() of your activity