mirror of
https://github.com/sudoxnym/habitica-android.git
synced 2026-05-21 13:19:02 +00:00
Remove unused imports, format code
This commit is contained in:
parent
0cff8749d9
commit
60d90993e3
44 changed files with 1156 additions and 1593 deletions
|
|
@ -31,7 +31,6 @@ import com.raizlabs.android.dbflow.structure.ModelAdapter;
|
|||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Type;
|
||||
import java.text.DateFormat;
|
||||
import java.util.List;
|
||||
|
||||
import retrofit.Callback;
|
||||
|
|
@ -46,159 +45,166 @@ import retrofit.converter.GsonConverter;
|
|||
public class APIHelper implements ErrorHandler, Profiler {
|
||||
|
||||
private static final String TAG = "ApiHelper";
|
||||
// I think we don't need the APIHelper anymore we could just use ApiService
|
||||
public final ApiService apiService;
|
||||
private Context mContext;
|
||||
//private OnHabitsAPIResult mResultListener;
|
||||
//private HostConfig mConfig;
|
||||
public APIHelper(Context c, final HostConfig cfg) {
|
||||
this.mContext = c;
|
||||
// I think we don't need the APIHelper anymore we could just use ApiService
|
||||
public final ApiService apiService;
|
||||
private Context mContext;
|
||||
|
||||
RequestInterceptor requestInterceptor = new RequestInterceptor() {
|
||||
@Override
|
||||
public void intercept(RequestInterceptor.RequestFacade request) {
|
||||
request.addHeader("x-api-key", cfg.getApi());
|
||||
request.addHeader("x-api-user", cfg.getUser());
|
||||
//private OnHabitsAPIResult mResultListener;
|
||||
//private HostConfig mConfig;
|
||||
public APIHelper(Context c, final HostConfig cfg) {
|
||||
this.mContext = c;
|
||||
|
||||
RequestInterceptor requestInterceptor = new RequestInterceptor() {
|
||||
@Override
|
||||
public void intercept(RequestInterceptor.RequestFacade request) {
|
||||
request.addHeader("x-api-key", cfg.getApi());
|
||||
request.addHeader("x-api-user", cfg.getUser());
|
||||
|
||||
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
Type taskTagClassListType = new TypeToken<List<TaskTag>>() {}.getType();
|
||||
Type taskTagClassListType = new TypeToken<List<TaskTag>>() {
|
||||
}.getType();
|
||||
|
||||
|
||||
//Exclusion stratety needed for DBFlow https://github.com/Raizlabs/DBFlow/issues/121
|
||||
Gson gson = new GsonBuilder()
|
||||
.setExclusionStrategies(new ExclusionStrategy() {
|
||||
@Override
|
||||
public boolean shouldSkipField(FieldAttributes f) {
|
||||
return f.getDeclaredClass().equals(ModelAdapter.class);
|
||||
}
|
||||
Gson gson = new GsonBuilder()
|
||||
.setExclusionStrategies(new ExclusionStrategy() {
|
||||
@Override
|
||||
public boolean shouldSkipField(FieldAttributes f) {
|
||||
return f.getDeclaredClass().equals(ModelAdapter.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldSkipClass(Class<?> clazz) {
|
||||
return false;
|
||||
}
|
||||
})
|
||||
.registerTypeAdapter(taskTagClassListType, new TagsAdapter())
|
||||
.registerTypeAdapter(Boolean.class, booleanAsIntAdapter)
|
||||
.registerTypeAdapter(boolean.class, booleanAsIntAdapter)
|
||||
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
|
||||
.create();
|
||||
@Override
|
||||
public boolean shouldSkipClass(Class<?> clazz) {
|
||||
return false;
|
||||
}
|
||||
})
|
||||
.registerTypeAdapter(taskTagClassListType, new TagsAdapter())
|
||||
.registerTypeAdapter(Boolean.class, booleanAsIntAdapter)
|
||||
.registerTypeAdapter(boolean.class, booleanAsIntAdapter)
|
||||
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
|
||||
.create();
|
||||
|
||||
Server server = new Server(cfg.getAddress());
|
||||
Server server = new Server(cfg.getAddress());
|
||||
|
||||
RestAdapter adapter = new RestAdapter.Builder()
|
||||
.setEndpoint(server.toString())
|
||||
.setErrorHandler(this)
|
||||
.setProfiler(this)
|
||||
.setLogLevel(BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE)
|
||||
.setRequestInterceptor(requestInterceptor)
|
||||
.setConverter(new GsonConverter(gson))
|
||||
RestAdapter adapter = new RestAdapter.Builder()
|
||||
.setEndpoint(server.toString())
|
||||
.setErrorHandler(this)
|
||||
.setProfiler(this)
|
||||
.setLogLevel(BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE)
|
||||
.setRequestInterceptor(requestInterceptor)
|
||||
.setConverter(new GsonConverter(gson))
|
||||
|
||||
.build();
|
||||
this.apiService = adapter.create(ApiService.class);
|
||||
.build();
|
||||
this.apiService = adapter.create(ApiService.class);
|
||||
|
||||
}
|
||||
|
||||
private static final TypeAdapter<Boolean> booleanAsIntAdapter = new TypeAdapter<Boolean>() {
|
||||
@Override public void write(JsonWriter out, Boolean value) throws IOException {
|
||||
if (value == null) {
|
||||
out.nullValue();
|
||||
} else {
|
||||
out.value(value);
|
||||
}
|
||||
}
|
||||
@Override public Boolean read(JsonReader in) throws IOException {
|
||||
JsonToken peek = in.peek();
|
||||
switch (peek) {
|
||||
case BOOLEAN:
|
||||
return in.nextBoolean();
|
||||
case NULL:
|
||||
in.nextNull();
|
||||
return null;
|
||||
case NUMBER:
|
||||
return in.nextInt() != 0;
|
||||
case STRING:
|
||||
return Boolean.parseBoolean(in.nextString());
|
||||
default:
|
||||
throw new IllegalStateException("Expected BOOLEAN or NUMBER but was " + peek);
|
||||
}
|
||||
}
|
||||
};
|
||||
private static final TypeAdapter<Boolean> booleanAsIntAdapter = new TypeAdapter<Boolean>() {
|
||||
@Override
|
||||
public void write(JsonWriter out, Boolean value) throws IOException {
|
||||
if (value == null) {
|
||||
out.nullValue();
|
||||
} else {
|
||||
out.value(value);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean read(JsonReader in) throws IOException {
|
||||
JsonToken peek = in.peek();
|
||||
switch (peek) {
|
||||
case BOOLEAN:
|
||||
return in.nextBoolean();
|
||||
case NULL:
|
||||
in.nextNull();
|
||||
return null;
|
||||
case NUMBER:
|
||||
return in.nextInt() != 0;
|
||||
case STRING:
|
||||
return Boolean.parseBoolean(in.nextString());
|
||||
default:
|
||||
throw new IllegalStateException("Expected BOOLEAN or NUMBER but was " + peek);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
public void createNewTask(Task item, Callback cb) {
|
||||
this.apiService.createItem(item, cb);
|
||||
this.apiService.createItem(item, cb);
|
||||
}
|
||||
|
||||
public void retrieveUser(HabitRPGUserCallback callback) {
|
||||
this.apiService.getUser(callback);
|
||||
}
|
||||
public void retrieveUser(HabitRPGUserCallback callback) {
|
||||
this.apiService.getUser(callback);
|
||||
}
|
||||
|
||||
public void updateTaskDirection(String id, TaskDirection direction, TaskScoringCallback callback) {
|
||||
public void updateTaskDirection(String id, TaskDirection direction, TaskScoringCallback callback) {
|
||||
this.apiService.postTaskDirection(id, direction.toString(), callback);
|
||||
}
|
||||
public void registerUser(View btnClicked, String username, String email, String password, String confirmPassword) {
|
||||
}
|
||||
|
||||
// ATAskRegisterUser reg = new ATAskRegisterUser(mResultListener,mConfig,btnClicked);
|
||||
// String[] params = {username,email,password,confirmPassword};
|
||||
// reg.execute(params);
|
||||
public void registerUser(View btnClicked, String username, String email, String password, String confirmPassword) {
|
||||
|
||||
}
|
||||
public void connectUser(String username, String password, Callback<UserAuthResponse> callback) {
|
||||
// ATaskConnectUser con = new ATaskConnectUser(mResultListener,mConfig,btnClicked);
|
||||
// String[] params = {username,password};
|
||||
// con.execute(params);
|
||||
// ATAskRegisterUser reg = new ATAskRegisterUser(mResultListener,mConfig,btnClicked);
|
||||
// String[] params = {username,email,password,confirmPassword};
|
||||
// reg.execute(params);
|
||||
|
||||
}
|
||||
|
||||
public void connectUser(String username, String password, Callback<UserAuthResponse> callback) {
|
||||
// ATaskConnectUser con = new ATaskConnectUser(mResultListener,mConfig,btnClicked);
|
||||
// String[] params = {username,password};
|
||||
// con.execute(params);
|
||||
UserAuth auth = new UserAuth();
|
||||
auth.setUsername(username);
|
||||
auth.setPassword(password);
|
||||
this.apiService.connectLocal(auth, callback);
|
||||
}
|
||||
|
||||
public void deleteTask(Task item, TaskDeletionCallback cb) {
|
||||
this.apiService.deleteTask(item.getId(), cb);
|
||||
}
|
||||
|
||||
public void updateTask(Task item, Callback cb) {
|
||||
this.apiService.updateTask(item.getId(), item, cb);
|
||||
}
|
||||
public void deleteTask(Task item, TaskDeletionCallback cb) {
|
||||
this.apiService.deleteTask(item.getId(), cb);
|
||||
}
|
||||
|
||||
//public void buyItem(Reward.SpecialReward itemBought, View btn) {
|
||||
// ATaskBuyItem buyItem = new ATaskBuyItem(mResultListener,btn, mConfig);
|
||||
// buyItem.execute(itemBought);
|
||||
//}
|
||||
public void changeTimeZone(int timeZoneOffset) {
|
||||
public void updateTask(Task item, Callback cb) {
|
||||
this.apiService.updateTask(item.getId(), item, cb);
|
||||
}
|
||||
|
||||
//public void buyItem(Reward.SpecialReward itemBought, View btn) {
|
||||
// ATaskBuyItem buyItem = new ATaskBuyItem(mResultListener,btn, mConfig);
|
||||
// buyItem.execute(itemBought);
|
||||
//}
|
||||
public void changeTimeZone(int timeZoneOffset) {
|
||||
// ATaskChangeTimeZone changeTimeZone= new ATaskChangeTimeZone(mResultListener,mConfig);
|
||||
// changeTimeZone.execute(timeZoneOffset);
|
||||
}
|
||||
// changeTimeZone.execute(timeZoneOffset);
|
||||
}
|
||||
|
||||
public void revive() {
|
||||
public void revive() {
|
||||
Log.w(TAG, "Not done yet - revive");
|
||||
// ATaskRevive rev = new ATaskRevive(mResultListener,mConfig);
|
||||
// rev.execute();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Throwable handleError(RetrofitError cause) {
|
||||
@Override
|
||||
public Throwable handleError(RetrofitError cause) {
|
||||
final Activity activity = (Activity) this.mContext;
|
||||
|
||||
if (cause.getKind().equals(RetrofitError.Kind.NETWORK)) {
|
||||
if (cause.getKind().equals(RetrofitError.Kind.NETWORK)) {
|
||||
//It also handles timeouts
|
||||
showConnectionProblemDialog(activity, R.string.network_error_no_network_body);
|
||||
}else{
|
||||
} else {
|
||||
/*
|
||||
* CONVERSION An exception was thrown while (de)serializing a body.
|
||||
* HTTP A non-200 HTTP status code was received from the server e.g. 502, 503, etc...
|
||||
* UNEXPECTED An internal error occurred while attempting to execute a request.
|
||||
*/
|
||||
showConnectionProblemDialog(activity,R.string.internal_error_api);
|
||||
showConnectionProblemDialog(activity, R.string.internal_error_api);
|
||||
}
|
||||
|
||||
return cause;
|
||||
}
|
||||
return cause;
|
||||
}
|
||||
|
||||
private void showConnectionProblemDialog(final Activity activity, final int resourceMessageString){
|
||||
private void showConnectionProblemDialog(final Activity activity, final int resourceMessageString) {
|
||||
activity.runOnUiThread(new Runnable() {
|
||||
public void run() {
|
||||
new AlertDialog.Builder(activity)
|
||||
|
|
@ -214,298 +220,17 @@ public class APIHelper implements ErrorHandler, Profiler {
|
|||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object beforeCall() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterCall(RequestInformation requestInfo, long elapsedTime, int statusCode, Object beforeCallData) {
|
||||
|
||||
}
|
||||
|
||||
public void toggleSleep(Callback<Void> cb){
|
||||
apiService.sleep(cb);
|
||||
}
|
||||
|
||||
/*
|
||||
private class ATaskGetUser extends AsyncTask<Void, Void, Void> {
|
||||
private OnHabitsAPIResult callback;
|
||||
private HostConfig config;
|
||||
|
||||
public ATaskGetUser(OnHabitsAPIResult callback, HostConfig config) {
|
||||
this.callback = callback;
|
||||
this.config=config;
|
||||
}
|
||||
@Override
|
||||
protected void onPreExecute() {
|
||||
this.callback.onPreResult();
|
||||
}
|
||||
@Override
|
||||
protected Void doInBackground(Void... params) {
|
||||
GetUser getUser = new GetUser(this.callback,this.config);
|
||||
Answer as = getUser.getData();
|
||||
if(as!=null)
|
||||
as.parse();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private class ATaskPostUserDirection extends AsyncTask<String, Void, Void> {
|
||||
private OnHabitsAPIResult callback;
|
||||
private View btnClicked;
|
||||
HostConfig config;
|
||||
public ATaskPostUserDirection(OnHabitsAPIResult callback, View btnClicked, HostConfig config) {
|
||||
this.callback = callback;
|
||||
this.btnClicked=btnClicked;
|
||||
this.config = config;
|
||||
}
|
||||
@Override
|
||||
protected void onPreExecute() {
|
||||
if(this.btnClicked!=null)
|
||||
this.btnClicked.setEnabled(false);
|
||||
this.callback.onPreResult();
|
||||
}
|
||||
@Override
|
||||
protected Void doInBackground(String... params) {
|
||||
PostTaskDirection post = new PostTaskDirection(callback, params[0], params[1], this.config);
|
||||
|
||||
Answer as = post.getData();
|
||||
if(as!=null)
|
||||
as.parse();
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPostExecute(Void arg) {
|
||||
if(this.btnClicked!=null)
|
||||
this.btnClicked.setEnabled(true);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private class ATaskPostTask extends AsyncTask<Task, Void, Void> {
|
||||
private OnHabitsAPIResult callback;
|
||||
private HostConfig config;
|
||||
public ATaskPostTask(OnHabitsAPIResult callback, HostConfig config) {
|
||||
this.callback = callback;
|
||||
this.config=config;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPreExecute() {
|
||||
this.callback.onPreResult();
|
||||
}
|
||||
@Override
|
||||
protected Void doInBackground(Task... habit) {
|
||||
PostTask post = new PostTask(callback, config, habit[0]);
|
||||
Answer as = post.getData();
|
||||
if(as!=null)
|
||||
as.parse();
|
||||
return null;
|
||||
}
|
||||
@Override
|
||||
public Object beforeCall() {
|
||||
return null;
|
||||
}
|
||||
|
||||
private class ATaskDeleteTask extends AsyncTask<Task, Void, Void> {
|
||||
private OnHabitsAPIResult callback;
|
||||
private HostConfig config;
|
||||
public ATaskDeleteTask(OnHabitsAPIResult callback, HostConfig config) {
|
||||
this.callback = callback;
|
||||
this.config=config;
|
||||
}
|
||||
@Override
|
||||
public void afterCall(RequestInformation requestInfo, long elapsedTime, int statusCode, Object beforeCallData) {
|
||||
|
||||
@Override
|
||||
protected void onPreExecute() {
|
||||
this.callback.onPreResult();
|
||||
}
|
||||
@Override
|
||||
protected Void doInBackground(Task... habit) {
|
||||
DeleteTask del = new DeleteTask(callback, config, habit[0]);
|
||||
Answer as = del.getData();
|
||||
if(as!=null)
|
||||
as.parse();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
private class ATaskUpdateTask extends AsyncTask<Task, Void, Void> {
|
||||
private OnHabitsAPIResult callback;
|
||||
private HostConfig config;
|
||||
public ATaskUpdateTask(OnHabitsAPIResult callback, HostConfig config) {
|
||||
this.callback = callback;
|
||||
this.config=config;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPreExecute() {
|
||||
this.callback.onPreResult();
|
||||
}
|
||||
@Override
|
||||
protected Void doInBackground(Task... habit) {
|
||||
PutTask put = new PutTask(callback, config, habit[0]);
|
||||
Answer as = put.getData();
|
||||
if(as!=null)
|
||||
as.parse();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
private class ATaskBuyItem extends AsyncTask<Reward.SpecialReward,Void,Void> {
|
||||
private final OnHabitsAPIResult callback;
|
||||
private final HostConfig config;
|
||||
private final View btnClicked;
|
||||
|
||||
public ATaskBuyItem(OnHabitsAPIResult callback, View btnClicked, HostConfig config) {
|
||||
this.callback = callback;
|
||||
this.config=config;
|
||||
this.btnClicked = btnClicked;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPreExecute() {
|
||||
if(this.btnClicked!=null)
|
||||
this.btnClicked.setEnabled(false);
|
||||
|
||||
this.callback.onPreResult();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Void doInBackground(Reward.SpecialReward... itemBought) {
|
||||
BuyItem buy = new BuyItem(callback,config,itemBought[0]);
|
||||
Answer as = buy.getData();
|
||||
if(as!=null)
|
||||
as.parse();
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPostExecute(Void arg) {
|
||||
if(this.btnClicked!=null)
|
||||
this.btnClicked.setEnabled(true);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private class ATAskRegisterUser extends AsyncTask<String,Void,Void>{
|
||||
private final HostConfig config;
|
||||
private final OnHabitsAPIResult callback;
|
||||
private final View btnClicked;
|
||||
|
||||
public ATAskRegisterUser(OnHabitsAPIResult callback, HostConfig mConfig, View btnClicked) {
|
||||
this.callback = callback;
|
||||
this.config = mConfig;
|
||||
this.btnClicked = btnClicked;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPreExecute() {
|
||||
if(this.btnClicked!=null)
|
||||
this.btnClicked.setEnabled(false);
|
||||
|
||||
this.callback.onPreResult();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Void doInBackground(String... us) {
|
||||
RegisterUser reg = new RegisterUser(callback,config,us[0],us[1],us[2],us[3]);
|
||||
Answer as = reg.getData();
|
||||
if(as!=null)
|
||||
as.parse();
|
||||
return null;
|
||||
}
|
||||
@Override
|
||||
protected void onPostExecute(Void arg) {
|
||||
if(this.btnClicked!=null)
|
||||
this.btnClicked.setEnabled(true);
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
private class ATaskConnectUser extends AsyncTask<String,Void,Void>{
|
||||
private final View btnClicked;
|
||||
private final HostConfig config;
|
||||
private final OnHabitsAPIResult callback;
|
||||
|
||||
public ATaskConnectUser(OnHabitsAPIResult callback, HostConfig config, View btnClicked) {
|
||||
this.callback =callback;
|
||||
this.config=config;
|
||||
this.btnClicked=btnClicked;
|
||||
}
|
||||
@Override
|
||||
protected void onPreExecute() {
|
||||
if(this.btnClicked!=null)
|
||||
this.btnClicked.setEnabled(false);
|
||||
|
||||
this.callback.onPreResult();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Void doInBackground(String... us) {
|
||||
AuthUser con = new AuthUser(callback,config,us[0],us[1]);
|
||||
Answer as = con.getData();
|
||||
if(as!=null)
|
||||
as.parse();
|
||||
return null;
|
||||
}
|
||||
@Override
|
||||
protected void onPostExecute(Void arg) {
|
||||
if(this.btnClicked!=null)
|
||||
this.btnClicked.setEnabled(true);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
private class ATaskRevive extends AsyncTask<Void,Void,Void> {
|
||||
private final HostConfig config;
|
||||
private final OnHabitsAPIResult callback;
|
||||
|
||||
public ATaskRevive(OnHabitsAPIResult callback, HostConfig config) {
|
||||
this.callback=callback;
|
||||
this.config=config;
|
||||
}
|
||||
@Override
|
||||
protected void onPreExecute() {
|
||||
this.callback.onPreResult();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Void doInBackground(Void... voids) {
|
||||
ReviveUser revive = new ReviveUser(callback,config);
|
||||
Answer as = revive.getData();
|
||||
if(as!=null)
|
||||
as.parse();
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
private class ATaskChangeTimeZone extends AsyncTask<Integer,Void,Void>{
|
||||
private final OnHabitsAPIResult callback;
|
||||
private final HostConfig config;
|
||||
|
||||
public ATaskChangeTimeZone(OnHabitsAPIResult callback, HostConfig config) {
|
||||
this.config = config;
|
||||
this.callback = callback;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Void doInBackground(Integer... offsets) {
|
||||
WebServiceInteraction changeTimeZone = new PutTimeZone(callback, config,offsets[0]);
|
||||
try {
|
||||
WebServiceInteraction.Answer ans = changeTimeZone.getData();
|
||||
ans.parse();//parse the object using the callback
|
||||
System.out.println("finished!");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}*/
|
||||
public void toggleSleep(Callback<Void> cb) {
|
||||
apiService.sleep(cb);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -140,9 +140,9 @@ public class AboutActivity extends AppCompatActivity {
|
|||
|
||||
@Override
|
||||
public CharSequence getPageTitle(int position) {
|
||||
if (position == 0){
|
||||
if (position == 0) {
|
||||
return getString(R.string.about_title);
|
||||
}else if(position == 1){
|
||||
} else if (position == 1) {
|
||||
return getString(R.string.about_libraries);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -92,14 +92,9 @@ public abstract class AvatarActivityBase extends InstabugAppCompatActivity {
|
|||
|
||||
avatarInHeader = new AvatarWithBarsViewModel(this, avatar_with_bars);
|
||||
|
||||
|
||||
// titleTextView = new TextView(this);
|
||||
// titleTextView.setTextAppearance(this, android.R.style.TextAppearance_Material_Widget_ActionBar_Title_Inverse);
|
||||
// titleTextView.setPadding(0,16,0,0);
|
||||
// toolbar.addView(titleTextView);
|
||||
}
|
||||
|
||||
protected void setTitle(String text){
|
||||
protected void setTitle(String text) {
|
||||
toolbar.setTitle(text);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,7 +13,6 @@ import com.mikepenz.materialdrawer.Drawer;
|
|||
import org.solovyev.android.checkout.ActivityCheckout;
|
||||
import org.solovyev.android.checkout.BillingRequests;
|
||||
import org.solovyev.android.checkout.Checkout;
|
||||
import org.solovyev.android.checkout.Inventory;
|
||||
import org.solovyev.android.checkout.ProductTypes;
|
||||
import org.solovyev.android.checkout.Purchase;
|
||||
import org.solovyev.android.checkout.RequestListener;
|
||||
|
|
|
|||
|
|
@ -20,7 +20,6 @@ import org.solovyev.android.checkout.PurchaseVerifier;
|
|||
import org.solovyev.android.checkout.RequestListener;
|
||||
|
||||
import java.io.File;
|
||||
import java.security.Security;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
|
@ -66,13 +65,12 @@ public class HabiticaApplication extends Application {
|
|||
|
||||
@Override
|
||||
public File getDatabasePath(String name) {
|
||||
return new File(getExternalFilesDir(null), "HabiticaDatabase/"+name);
|
||||
return new File(getExternalFilesDir(null), "HabiticaDatabase/" + name);
|
||||
}
|
||||
|
||||
// endregion
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* For better performance billing class should be used as singleton
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -9,7 +9,6 @@ import android.os.Bundle;
|
|||
import android.os.Handler;
|
||||
import android.preference.PreferenceManager;
|
||||
import android.support.design.widget.Snackbar;
|
||||
import android.support.v7.app.ActionBarActivity;
|
||||
import android.support.v7.app.AppCompatActivity;
|
||||
import android.text.SpannableString;
|
||||
import android.text.method.LinkMovementMethod;
|
||||
|
|
@ -20,8 +19,6 @@ import android.view.Menu;
|
|||
import android.view.MenuItem;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.view.Window;
|
||||
import android.view.WindowManager;
|
||||
import android.view.animation.Animation;
|
||||
import android.view.animation.Transformation;
|
||||
import android.widget.Button;
|
||||
|
|
@ -49,413 +46,328 @@ import retrofit.client.Response;
|
|||
* @author Mickael Goubin
|
||||
*/
|
||||
public class LoginActivity extends AppCompatActivity
|
||||
implements Callback<UserAuthResponse>,HabitRPGUserCallback.OnUserReceived {
|
||||
private final static String TAG_ADDRESS="address";
|
||||
private final static String TAG_USERID="user";
|
||||
private final static String TAG_APIKEY="key";
|
||||
implements Callback<UserAuthResponse>, HabitRPGUserCallback.OnUserReceived {
|
||||
private final static String TAG_ADDRESS = "address";
|
||||
private final static String TAG_USERID = "user";
|
||||
private final static String TAG_APIKEY = "key";
|
||||
|
||||
private Button mRegisterBtn, mLoginNormalBtn, mLoginTokensBtn;
|
||||
private ImageView mLoginBarcode;
|
||||
private LinearLayout mLoginNormalLayout, mLoginTokensLayout, mRegisterLayout, mLoginBtnContainer;
|
||||
private EditText mUserTokenET,mApiTokenET, mUsernameET, mPasswordET,mRegUsername,mRegEmail,mRegPassword,mRegConfirmPassword;
|
||||
private APIHelper mApiHelper;
|
||||
private Handler mMainHandler;
|
||||
private ProgressBar mProgressBar;
|
||||
public String mTmpUserToken;
|
||||
public String mTmpApiToken;
|
||||
private Button mRegisterBtn, mLoginNormalBtn, mLoginTokensBtn;
|
||||
private ImageView mLoginBarcode;
|
||||
private LinearLayout mLoginNormalLayout, mLoginTokensLayout, mRegisterLayout, mLoginBtnContainer;
|
||||
private EditText mUserTokenET, mApiTokenET, mUsernameET, mPasswordET, mRegUsername, mRegEmail, mRegPassword, mRegConfirmPassword;
|
||||
private APIHelper mApiHelper;
|
||||
private Handler mMainHandler;
|
||||
private ProgressBar mProgressBar;
|
||||
public String mTmpUserToken;
|
||||
public String mTmpApiToken;
|
||||
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
setContentView(R.layout.login_screen);
|
||||
setContentView(R.layout.login_screen);
|
||||
|
||||
mRegisterBtn = (Button) this.findViewById(R.id.register_btn);
|
||||
mLoginNormalBtn = (Button) this.findViewById(R.id.login_normal_btn);
|
||||
mLoginTokensBtn = (Button) this.findViewById(R.id.login_tokens_btn);
|
||||
mLoginBarcode = (ImageView) this.findViewById(R.id.login_barcode);
|
||||
mProgressBar = (ProgressBar) this.findViewById(R.id.PB_AsyncTask);
|
||||
mRegisterBtn = (Button) this.findViewById(R.id.register_btn);
|
||||
mLoginNormalBtn = (Button) this.findViewById(R.id.login_normal_btn);
|
||||
mLoginTokensBtn = (Button) this.findViewById(R.id.login_tokens_btn);
|
||||
mLoginBarcode = (ImageView) this.findViewById(R.id.login_barcode);
|
||||
mProgressBar = (ProgressBar) this.findViewById(R.id.PB_AsyncTask);
|
||||
|
||||
mLoginNormalLayout = (LinearLayout) this.findViewById(R.id.login_normal_layout);
|
||||
mLoginTokensLayout = (LinearLayout) this.findViewById(R.id.login_tokens_layout);
|
||||
mRegisterLayout = (LinearLayout) this.findViewById(R.id.register_layout);
|
||||
mLoginBtnContainer = (LinearLayout) this.findViewById(R.id.login_btn_container);
|
||||
mLoginNormalLayout = (LinearLayout) this.findViewById(R.id.login_normal_layout);
|
||||
mLoginTokensLayout = (LinearLayout) this.findViewById(R.id.login_tokens_layout);
|
||||
mRegisterLayout = (LinearLayout) this.findViewById(R.id.register_layout);
|
||||
mLoginBtnContainer = (LinearLayout) this.findViewById(R.id.login_btn_container);
|
||||
|
||||
mUserTokenET = (EditText) this.findViewById(R.id.userId);
|
||||
mApiTokenET = (EditText) this.findViewById(R.id.apiToken);
|
||||
mUserTokenET = (EditText) this.findViewById(R.id.userId);
|
||||
mApiTokenET = (EditText) this.findViewById(R.id.apiToken);
|
||||
|
||||
mUsernameET = (EditText) this.findViewById(R.id.username);
|
||||
mPasswordET = (EditText) this.findViewById(R.id.password);
|
||||
mUsernameET = (EditText) this.findViewById(R.id.username);
|
||||
mPasswordET = (EditText) this.findViewById(R.id.password);
|
||||
|
||||
mRegUsername = (EditText) this.findViewById(R.id.reg_username);
|
||||
mRegEmail = (EditText) this.findViewById(R.id.reg_email);
|
||||
mRegPassword = (EditText) this.findViewById(R.id.reg_password);
|
||||
mRegConfirmPassword = (EditText) this.findViewById(R.id.reg_confirm_password);
|
||||
mRegUsername = (EditText) this.findViewById(R.id.reg_username);
|
||||
mRegEmail = (EditText) this.findViewById(R.id.reg_email);
|
||||
mRegPassword = (EditText) this.findViewById(R.id.reg_password);
|
||||
mRegConfirmPassword = (EditText) this.findViewById(R.id.reg_confirm_password);
|
||||
|
||||
mRegisterBtn.setOnClickListener(mRegisterClick);
|
||||
mLoginNormalBtn.setOnClickListener(mLoginNormalClick);
|
||||
mLoginTokensBtn.setOnClickListener(mLoginTokensClick);
|
||||
mLoginBarcode.setOnClickListener(mBarcodeClick);
|
||||
mRegisterBtn.setOnClickListener(mRegisterClick);
|
||||
mLoginNormalBtn.setOnClickListener(mLoginNormalClick);
|
||||
mLoginTokensBtn.setOnClickListener(mLoginTokensClick);
|
||||
mLoginBarcode.setOnClickListener(mBarcodeClick);
|
||||
|
||||
HostConfig hc= PrefsActivity.fromContext(this);
|
||||
if(hc ==null) {
|
||||
hc = new HostConfig(getString(R.string.SP_address_default), "80", "", "");
|
||||
HostConfig hc = PrefsActivity.fromContext(this);
|
||||
if (hc == null) {
|
||||
hc = new HostConfig(getString(R.string.SP_address_default), "80", "", "");
|
||||
}
|
||||
mApiHelper = new APIHelper(this,hc);
|
||||
mApiHelper = new APIHelper(this, hc);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private void resetLayout() {
|
||||
//expand(mLoginBarcode);
|
||||
if(mRegisterBtn.getVisibility() == View.GONE)
|
||||
expand(mRegisterBtn);
|
||||
if(mLoginTokensBtn.getVisibility() == View.GONE)
|
||||
expand(mLoginTokensBtn);
|
||||
if(mLoginNormalBtn.getVisibility() == View.GONE)
|
||||
expand(mLoginNormalBtn);
|
||||
if(mLoginBarcode.getVisibility()==View.GONE)
|
||||
expand(mLoginBarcode);
|
||||
if(mLoginBtnContainer.getVisibility()==View.GONE)
|
||||
expand(mLoginBtnContainer);
|
||||
collapse(mLoginNormalLayout);
|
||||
collapse(mLoginTokensLayout);
|
||||
collapse(mRegisterLayout);
|
||||
private void resetLayout() {
|
||||
//expand(mLoginBarcode);
|
||||
if (mRegisterBtn.getVisibility() == View.GONE)
|
||||
expand(mRegisterBtn);
|
||||
if (mLoginTokensBtn.getVisibility() == View.GONE)
|
||||
expand(mLoginTokensBtn);
|
||||
if (mLoginNormalBtn.getVisibility() == View.GONE)
|
||||
expand(mLoginNormalBtn);
|
||||
if (mLoginBarcode.getVisibility() == View.GONE)
|
||||
expand(mLoginBarcode);
|
||||
if (mLoginBtnContainer.getVisibility() == View.GONE)
|
||||
expand(mLoginBtnContainer);
|
||||
collapse(mLoginNormalLayout);
|
||||
collapse(mLoginTokensLayout);
|
||||
collapse(mRegisterLayout);
|
||||
|
||||
}
|
||||
private View.OnClickListener mBarcodeClick = new View.OnClickListener() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View view) {
|
||||
IntentIntegrator integrator = new IntentIntegrator(LoginActivity.this);
|
||||
integrator.initiateScan();
|
||||
}
|
||||
};
|
||||
private View.OnClickListener mRegisterClick = new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
if(mLoginTokensBtn.getVisibility()==View.GONE && mLoginNormalBtn.getVisibility()==View.GONE) {
|
||||
String username, email,password,cpassword;
|
||||
username = String.valueOf(mRegUsername.getText());
|
||||
email = String.valueOf(mRegEmail.getText());
|
||||
password = String.valueOf(mRegPassword.getText());
|
||||
cpassword = String.valueOf(mRegConfirmPassword.getText());
|
||||
mApiHelper.registerUser(v,username,email,password,cpassword);
|
||||
}else {
|
||||
expand(mRegisterLayout);//.setVisibility(View.VISIBLE);
|
||||
collapse(mLoginNormalBtn);//.setVisibility(View.GONE);
|
||||
collapse(mLoginTokensBtn);//.setVisibility(View.GONE);
|
||||
}
|
||||
}
|
||||
};
|
||||
private View.OnClickListener mLoginNormalClick = new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
if(mRegisterBtn.getVisibility()==View.GONE && mLoginTokensBtn.getVisibility()==View.GONE) {
|
||||
String username,password;
|
||||
username = String.valueOf(mUsernameET.getText());
|
||||
password = String.valueOf(mPasswordET.getText());
|
||||
mApiHelper.connectUser(username,password, LoginActivity.this);
|
||||
} else {
|
||||
expand(mLoginNormalLayout);//.setVisibility(View.VISIBLE);
|
||||
collapse(mRegisterBtn);//.setVisibility(View.GONE);
|
||||
collapse(mLoginTokensBtn);//.setVisibility(View.GONE);
|
||||
}
|
||||
}
|
||||
};
|
||||
private View.OnClickListener mLoginTokensClick = new View.OnClickListener() {
|
||||
private View.OnClickListener mBarcodeClick = new View.OnClickListener() {
|
||||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
if (mRegisterBtn.getVisibility() == View.GONE && mLoginNormalBtn.getVisibility() == View.GONE) {
|
||||
mTmpUserToken = String.valueOf(mUserTokenET.getText());
|
||||
mTmpApiToken = String.valueOf(mApiTokenET.getText());
|
||||
HostConfig config = PrefsActivity.fromContext(LoginActivity.this);
|
||||
if(config==null) {
|
||||
@Override
|
||||
public void onClick(View view) {
|
||||
IntentIntegrator integrator = new IntentIntegrator(LoginActivity.this);
|
||||
integrator.initiateScan();
|
||||
}
|
||||
};
|
||||
private View.OnClickListener mRegisterClick = new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
if (mLoginTokensBtn.getVisibility() == View.GONE && mLoginNormalBtn.getVisibility() == View.GONE) {
|
||||
String username, email, password, cpassword;
|
||||
username = String.valueOf(mRegUsername.getText());
|
||||
email = String.valueOf(mRegEmail.getText());
|
||||
password = String.valueOf(mRegPassword.getText());
|
||||
cpassword = String.valueOf(mRegConfirmPassword.getText());
|
||||
mApiHelper.registerUser(v, username, email, password, cpassword);
|
||||
} else {
|
||||
expand(mRegisterLayout);//.setVisibility(View.VISIBLE);
|
||||
collapse(mLoginNormalBtn);//.setVisibility(View.GONE);
|
||||
collapse(mLoginTokensBtn);//.setVisibility(View.GONE);
|
||||
}
|
||||
}
|
||||
};
|
||||
private View.OnClickListener mLoginNormalClick = new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
if (mRegisterBtn.getVisibility() == View.GONE && mLoginTokensBtn.getVisibility() == View.GONE) {
|
||||
String username, password;
|
||||
username = String.valueOf(mUsernameET.getText());
|
||||
password = String.valueOf(mPasswordET.getText());
|
||||
mApiHelper.connectUser(username, password, LoginActivity.this);
|
||||
} else {
|
||||
expand(mLoginNormalLayout);//.setVisibility(View.VISIBLE);
|
||||
collapse(mRegisterBtn);//.setVisibility(View.GONE);
|
||||
collapse(mLoginTokensBtn);//.setVisibility(View.GONE);
|
||||
}
|
||||
}
|
||||
};
|
||||
private View.OnClickListener mLoginTokensClick = new View.OnClickListener() {
|
||||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
if (mRegisterBtn.getVisibility() == View.GONE && mLoginNormalBtn.getVisibility() == View.GONE) {
|
||||
mTmpUserToken = String.valueOf(mUserTokenET.getText());
|
||||
mTmpApiToken = String.valueOf(mApiTokenET.getText());
|
||||
HostConfig config = PrefsActivity.fromContext(LoginActivity.this);
|
||||
if (config == null) {
|
||||
config = new HostConfig(getString(R.string.SP_address_default), "80", mTmpApiToken, mTmpUserToken);
|
||||
} else {
|
||||
config.setApi(mTmpApiToken);
|
||||
config.setUser(mTmpUserToken);
|
||||
}
|
||||
APIHelper secApiHelper = new APIHelper(LoginActivity.this, config);
|
||||
secApiHelper.retrieveUser(new HabitRPGUserCallback(LoginActivity.this));
|
||||
APIHelper secApiHelper = new APIHelper(LoginActivity.this, config);
|
||||
secApiHelper.retrieveUser(new HabitRPGUserCallback(LoginActivity.this));
|
||||
|
||||
} else {
|
||||
expand(mLoginTokensLayout);
|
||||
collapse(mLoginNormalBtn);
|
||||
collapse(mRegisterBtn);
|
||||
}
|
||||
}
|
||||
};
|
||||
} else {
|
||||
expand(mLoginTokensLayout);
|
||||
collapse(mLoginNormalBtn);
|
||||
collapse(mRegisterBtn);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
private boolean layoutHasChanged() {
|
||||
return mRegisterBtn.getVisibility() == View.GONE || mLoginNormalBtn.getVisibility() == View.GONE || mLoginTokensBtn.getVisibility() == View.GONE;
|
||||
}
|
||||
|
||||
private boolean layoutHasChanged() {
|
||||
return mRegisterBtn.getVisibility() == View.GONE || mLoginNormalBtn.getVisibility() == View.GONE ||mLoginTokensBtn.getVisibility() == View.GONE;
|
||||
}
|
||||
@Override
|
||||
public boolean onKeyDown(int keyCode, KeyEvent event) {
|
||||
if (keyCode == KeyEvent.KEYCODE_BACK && layoutHasChanged()) {
|
||||
resetLayout();
|
||||
return true;
|
||||
}
|
||||
return super.onKeyDown(keyCode, event);
|
||||
}
|
||||
public static void expand(final View v) {
|
||||
v.measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||
final int targtetHeight = v.getMeasuredHeight();
|
||||
final int targtetWidth = v.getMeasuredWidth();
|
||||
Log.v("expanding ", "w:" + targtetWidth + " h:"+targtetHeight);
|
||||
//v.getLayoutParams().height = 0;
|
||||
//v.getLayoutParams().width=0;
|
||||
v.setVisibility(View.VISIBLE);//works when the setVisibility is outside the animationlistener.
|
||||
@Override
|
||||
public boolean onKeyDown(int keyCode, KeyEvent event) {
|
||||
if (keyCode == KeyEvent.KEYCODE_BACK && layoutHasChanged()) {
|
||||
resetLayout();
|
||||
return true;
|
||||
}
|
||||
return super.onKeyDown(keyCode, event);
|
||||
}
|
||||
|
||||
Animation a = new Animation()
|
||||
{
|
||||
public static void expand(final View v) {
|
||||
v.measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||
final int targtetHeight = v.getMeasuredHeight();
|
||||
final int targtetWidth = v.getMeasuredWidth();
|
||||
Log.v("expanding ", "w:" + targtetWidth + " h:" + targtetHeight);
|
||||
//v.getLayoutParams().height = 0;
|
||||
//v.getLayoutParams().width=0;
|
||||
v.setVisibility(View.VISIBLE);//works when the setVisibility is outside the animationlistener.
|
||||
|
||||
@Override
|
||||
protected void applyTransformation(float interpolatedTime, Transformation t) {
|
||||
v.getLayoutParams().height = interpolatedTime == 1
|
||||
? ViewGroup.LayoutParams.WRAP_CONTENT
|
||||
: (int)(targtetHeight * interpolatedTime);
|
||||
v.getLayoutParams().width = interpolatedTime == 1
|
||||
? ViewGroup.LayoutParams.WRAP_CONTENT
|
||||
: (int)(targtetWidth * interpolatedTime);
|
||||
v.requestLayout();
|
||||
}
|
||||
Animation a = new Animation() {
|
||||
|
||||
@Override
|
||||
public boolean willChangeBounds() {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
// 1dp/ms
|
||||
a.setDuration(500);
|
||||
v.startAnimation(a);
|
||||
}
|
||||
//
|
||||
@Override
|
||||
protected void applyTransformation(float interpolatedTime, Transformation t) {
|
||||
v.getLayoutParams().height = interpolatedTime == 1
|
||||
? ViewGroup.LayoutParams.WRAP_CONTENT
|
||||
: (int) (targtetHeight * interpolatedTime);
|
||||
v.getLayoutParams().width = interpolatedTime == 1
|
||||
? ViewGroup.LayoutParams.WRAP_CONTENT
|
||||
: (int) (targtetWidth * interpolatedTime);
|
||||
v.requestLayout();
|
||||
}
|
||||
|
||||
public static void collapse(final View v) {
|
||||
final int initialHeight = v.getMeasuredHeight();
|
||||
final int initialWidth = v.getMeasuredWidth();
|
||||
@Override
|
||||
public boolean willChangeBounds() {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
// 1dp/ms
|
||||
a.setDuration(500);
|
||||
v.startAnimation(a);
|
||||
}
|
||||
//
|
||||
|
||||
Animation a = new Animation()
|
||||
{
|
||||
@Override
|
||||
protected void applyTransformation(float interpolatedTime, Transformation t) {
|
||||
if(interpolatedTime == 1){
|
||||
v.setVisibility(View.GONE);
|
||||
}else{
|
||||
v.getLayoutParams().height = initialHeight - (int)(initialHeight * interpolatedTime);
|
||||
v.getLayoutParams().width = initialWidth - (int) (initialWidth*interpolatedTime);
|
||||
v.requestLayout();
|
||||
}
|
||||
}
|
||||
public static void collapse(final View v) {
|
||||
final int initialHeight = v.getMeasuredHeight();
|
||||
final int initialWidth = v.getMeasuredWidth();
|
||||
|
||||
@Override
|
||||
public boolean willChangeBounds() {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
Animation a = new Animation() {
|
||||
@Override
|
||||
protected void applyTransformation(float interpolatedTime, Transformation t) {
|
||||
if (interpolatedTime == 1) {
|
||||
v.setVisibility(View.GONE);
|
||||
} else {
|
||||
v.getLayoutParams().height = initialHeight - (int) (initialHeight * interpolatedTime);
|
||||
v.getLayoutParams().width = initialWidth - (int) (initialWidth * interpolatedTime);
|
||||
v.requestLayout();
|
||||
}
|
||||
}
|
||||
|
||||
// 1dp/ms
|
||||
a.setDuration(500);//targtetHeight / (v.getContext().getResources().getDisplayMetrics().density)));
|
||||
v.startAnimation(a);
|
||||
}
|
||||
@Override
|
||||
public boolean willChangeBounds() {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
private void startMainActivity() {
|
||||
startActivity(new Intent(LoginActivity.this, MainActivity.class));
|
||||
finish();
|
||||
// 1dp/ms
|
||||
a.setDuration(500);//targtetHeight / (v.getContext().getResources().getDisplayMetrics().density)));
|
||||
v.startAnimation(a);
|
||||
}
|
||||
|
||||
}
|
||||
private void saveTokens(String api, String user) throws Exception {
|
||||
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
|
||||
SharedPreferences.Editor editor = prefs.edit();
|
||||
private void startMainActivity() {
|
||||
startActivity(new Intent(LoginActivity.this, MainActivity.class));
|
||||
finish();
|
||||
|
||||
}
|
||||
|
||||
private void saveTokens(String api, String user) throws Exception {
|
||||
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
|
||||
SharedPreferences.Editor editor = prefs.edit();
|
||||
Log.v("login", "saving tokens");
|
||||
boolean ans = editor.putString(getString(R.string.SP_APIToken), api)
|
||||
.putString(getString(R.string.SP_userID), user)
|
||||
.putString(getString(R.string.SP_address),getString(R.string.SP_address_default))
|
||||
.commit();
|
||||
if(!ans) {
|
||||
throw new Exception("PB_string_commit");
|
||||
}
|
||||
boolean ans = editor.putString(getString(R.string.SP_APIToken), api)
|
||||
.putString(getString(R.string.SP_userID), user)
|
||||
.putString(getString(R.string.SP_address), getString(R.string.SP_address_default))
|
||||
.commit();
|
||||
if (!ans) {
|
||||
throw new Exception("PB_string_commit");
|
||||
}
|
||||
|
||||
}
|
||||
private void showHelpMMessage() {
|
||||
final SpannableString mess = new SpannableString(getString(R.string.helpString));
|
||||
Linkify.addLinks(mess, Linkify.ALL);
|
||||
AlertDialog d =new AlertDialog.Builder(this)
|
||||
.setTitle(R.string.pref_dialog_title)
|
||||
.setMessage(mess).setCancelable(false)
|
||||
.setPositiveButton(R.string.string_pref_dialog_positive, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
dialog.dismiss();
|
||||
}
|
||||
}
|
||||
|
||||
}).create();
|
||||
d.show();
|
||||
((TextView)d.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
|
||||
((TextView)d.findViewById(android.R.id.message)).setTextSize(13);
|
||||
private void showHelpMMessage() {
|
||||
final SpannableString mess = new SpannableString(getString(R.string.helpString));
|
||||
Linkify.addLinks(mess, Linkify.ALL);
|
||||
AlertDialog d = new AlertDialog.Builder(this)
|
||||
.setTitle(R.string.pref_dialog_title)
|
||||
.setMessage(mess).setCancelable(false)
|
||||
.setPositiveButton(R.string.string_pref_dialog_positive, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
dialog.dismiss();
|
||||
}
|
||||
|
||||
}
|
||||
}).create();
|
||||
d.show();
|
||||
((TextView) d.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
|
||||
((TextView) d.findViewById(android.R.id.message)).setTextSize(13);
|
||||
|
||||
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
|
||||
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
|
||||
if (scanResult != null) {
|
||||
try {
|
||||
Log.d("scanresult", scanResult.getContents());
|
||||
this.parse(scanResult.getContents());
|
||||
} catch(Exception e) {
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
|
||||
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
|
||||
if (scanResult != null) {
|
||||
try {
|
||||
Log.d("scanresult", scanResult.getContents());
|
||||
this.parse(scanResult.getContents());
|
||||
} catch (Exception e) {
|
||||
|
||||
private void parse(String contents) {
|
||||
String adr=null,user=null,key=null;
|
||||
try {
|
||||
JSONObject obj;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
obj = new JSONObject(contents);
|
||||
adr = obj.getString(TAG_ADDRESS);
|
||||
user = obj.getString(TAG_USERID);
|
||||
key = obj.getString(TAG_APIKEY);
|
||||
Log.d("", "adr" + adr + " user:" + user + " key" + key);
|
||||
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
|
||||
SharedPreferences.Editor editor = prefs.edit();
|
||||
boolean ans = editor.putString(getString(R.string.SP_address), adr)
|
||||
.putString(getString(R.string.SP_APIToken), key)
|
||||
.putString(getString(R.string.SP_userID), user)
|
||||
.commit();
|
||||
if(ans != true) {
|
||||
throw new Exception("PB_string_commit");
|
||||
}
|
||||
startMainActivity();
|
||||
} catch (JSONException e) {
|
||||
showSnackbar(getString(R.string.ERR_pb_barcode));
|
||||
e.printStackTrace();
|
||||
} catch(Exception e) {
|
||||
if("PB_string_commit".equals(e.getMessage())) {
|
||||
showSnackbar(getString(R.string.ERR_pb_barcode));
|
||||
}
|
||||
}
|
||||
}
|
||||
private void parse(String contents) {
|
||||
String adr = null, user = null, key = null;
|
||||
try {
|
||||
JSONObject obj;
|
||||
|
||||
private void showSnackbar(String content)
|
||||
{
|
||||
Snackbar snackbar = Snackbar
|
||||
.make(this.findViewById(R.id.login_linear_layout), content, Snackbar.LENGTH_LONG);
|
||||
obj = new JSONObject(contents);
|
||||
adr = obj.getString(TAG_ADDRESS);
|
||||
user = obj.getString(TAG_USERID);
|
||||
key = obj.getString(TAG_APIKEY);
|
||||
Log.d("", "adr" + adr + " user:" + user + " key" + key);
|
||||
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
|
||||
SharedPreferences.Editor editor = prefs.edit();
|
||||
boolean ans = editor.putString(getString(R.string.SP_address), adr)
|
||||
.putString(getString(R.string.SP_APIToken), key)
|
||||
.putString(getString(R.string.SP_userID), user)
|
||||
.commit();
|
||||
if (ans != true) {
|
||||
throw new Exception("PB_string_commit");
|
||||
}
|
||||
startMainActivity();
|
||||
} catch (JSONException e) {
|
||||
showSnackbar(getString(R.string.ERR_pb_barcode));
|
||||
e.printStackTrace();
|
||||
} catch (Exception e) {
|
||||
if ("PB_string_commit".equals(e.getMessage())) {
|
||||
showSnackbar(getString(R.string.ERR_pb_barcode));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
View snackbarView = snackbar.getView();
|
||||
snackbarView.setBackgroundColor(Color.RED);//change Snackbar's background color;
|
||||
snackbar.show(); // Don’t forget to show!
|
||||
}
|
||||
private void showSnackbar(String content) {
|
||||
Snackbar snackbar = Snackbar
|
||||
.make(this.findViewById(R.id.login_linear_layout), content, Snackbar.LENGTH_LONG);
|
||||
|
||||
@Override
|
||||
public boolean onCreateOptionsMenu(Menu menu) {
|
||||
getMenuInflater().inflate(R.menu.login, menu);
|
||||
return super.onCreateOptionsMenu(menu);
|
||||
}
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(MenuItem item) {
|
||||
switch(item.getItemId()) {
|
||||
case R.id.action_info:
|
||||
showHelpMMessage();
|
||||
break;
|
||||
}
|
||||
return super.onOptionsItemSelected(item);
|
||||
}
|
||||
View snackbarView = snackbar.getView();
|
||||
snackbarView.setBackgroundColor(Color.RED);//change Snackbar's background color;
|
||||
snackbar.show(); // Don’t forget to show!
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCreateOptionsMenu(Menu menu) {
|
||||
getMenuInflater().inflate(R.menu.login, menu);
|
||||
return super.onCreateOptionsMenu(menu);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(MenuItem item) {
|
||||
switch (item.getItemId()) {
|
||||
case R.id.action_info:
|
||||
showHelpMMessage();
|
||||
break;
|
||||
}
|
||||
return super.onOptionsItemSelected(item);
|
||||
}
|
||||
|
||||
|
||||
/* @Override
|
||||
public void onNewUser(String apiToken, String apiUser) {
|
||||
final String api = apiToken;
|
||||
final String user = apiUser;
|
||||
mMainHandler = new Handler(getMainLooper());
|
||||
Runnable myRunnable = new Runnable(){
|
||||
public void run() {
|
||||
afterResults();
|
||||
try {
|
||||
saveTokens(api,user);
|
||||
startMainActivity();
|
||||
finish();
|
||||
} catch (Exception e) {
|
||||
if("PB_string_commit".equals(e.getMessage()))
|
||||
Crouton.makeText(LoginActivity.this, getString(R.string.ERR_pb_accountCreation), Style.ALERT).show();
|
||||
}
|
||||
}
|
||||
};
|
||||
mMainHandler.post(myRunnable);
|
||||
}
|
||||
@Override
|
||||
public void onUserConnected(String api_t, String user_t) {
|
||||
final String api = api_t;
|
||||
final String user = user_t;
|
||||
mMainHandler = new Handler(getMainLooper());
|
||||
Log.v("user connected", "api:" +api_t+ " us" + user_t);
|
||||
Runnable myRunnable = new Runnable(){
|
||||
public void run() {
|
||||
afterResults();
|
||||
try {
|
||||
saveTokens(api,user);
|
||||
startMainActivity();
|
||||
} catch (Exception e) {
|
||||
if("PB_string_commit".equals(e.getMessage()))
|
||||
Crouton.makeText(LoginActivity.this, getString(R.string.ERR_pb_connection), Style.ALERT).show();
|
||||
}
|
||||
}
|
||||
};
|
||||
mMainHandler.post(myRunnable);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void onUserReceived(User user) {
|
||||
try {
|
||||
saveTokens(mTmpApiToken,mTmpUserToken);
|
||||
startMainActivity();
|
||||
finish();
|
||||
} catch(Exception e) {
|
||||
if("PB_string_commit".equals(e.getMessage()))
|
||||
Crouton.makeText(LoginActivity.this, getString(R.string.ERR_pb_connection), Style.ALERT).show();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onUserItemsReceived(UserLook.UserItems userLook, Reward.SpecialReward itemBought) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPostResult(double xp, double hp, double gold, double lvl, double delta) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPreResult() {
|
||||
mProgressBar.setVisibility(View.VISIBLE);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(HabitRPGException error) {
|
||||
final HabitRPGException err = error;
|
||||
mMainHandler = new Handler(getMainLooper());
|
||||
Runnable myRunnable = new Runnable(){
|
||||
public void run() {
|
||||
afterResults();
|
||||
String myMessage=err!=null ? err.getMessage() : null;
|
||||
if(myMessage == null)
|
||||
myMessage= getString(R.string.unknown_error);
|
||||
Crouton.makeText(LoginActivity.this, myMessage, Style.ALERT).show();
|
||||
}
|
||||
};
|
||||
mMainHandler.post(myRunnable);
|
||||
}*/
|
||||
|
||||
|
||||
private void afterResults() {
|
||||
mProgressBar.setVisibility(View.INVISIBLE);
|
||||
}
|
||||
private void afterResults() {
|
||||
mProgressBar.setVisibility(View.INVISIBLE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void success(UserAuthResponse userAuthResponse, Response response) {
|
||||
|
|
@ -475,7 +387,7 @@ public class LoginActivity extends AppCompatActivity
|
|||
@Override
|
||||
public void onUserReceived(HabitRPGUser user) {
|
||||
try {
|
||||
saveTokens(mTmpApiToken,mTmpUserToken);
|
||||
saveTokens(mTmpApiToken, mTmpUserToken);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
|
@ -484,6 +396,6 @@ public class LoginActivity extends AppCompatActivity
|
|||
|
||||
@Override
|
||||
public void onUserFail() {
|
||||
showSnackbar(getString(R.string.unknown_error));
|
||||
showSnackbar(getString(R.string.unknown_error));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -45,10 +45,10 @@ import com.magicmicky.habitrpgwrapper.lib.models.tasks.Task;
|
|||
import com.magicmicky.habitrpgwrapper.lib.models.tasks.TaskTag;
|
||||
import com.mikepenz.materialdrawer.Drawer;
|
||||
import com.mikepenz.materialdrawer.DrawerBuilder;
|
||||
import com.mikepenz.materialdrawer.interfaces.OnCheckedChangeListener;
|
||||
import com.mikepenz.materialdrawer.model.SectionDrawerItem;
|
||||
import com.mikepenz.materialdrawer.model.SwitchDrawerItem;
|
||||
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
|
||||
import com.mikepenz.materialdrawer.interfaces.OnCheckedChangeListener;
|
||||
import com.raizlabs.android.dbflow.runtime.FlowContentObserver;
|
||||
import com.raizlabs.android.dbflow.runtime.transaction.BaseTransaction;
|
||||
import com.raizlabs.android.dbflow.runtime.transaction.TransactionListener;
|
||||
|
|
@ -268,7 +268,7 @@ public class MainActivity extends AvatarActivityBase implements HabitRPGUserCall
|
|||
int currentHp = User.getStats().getHp().intValue();
|
||||
int maxHp = User.getStats().getMaxHealth();
|
||||
|
||||
if(currentHp == maxHp) {
|
||||
if (currentHp == maxHp) {
|
||||
showSnackbar("You don't need to buy an health potion", true);
|
||||
return;
|
||||
}
|
||||
|
|
@ -552,7 +552,7 @@ public class MainActivity extends AvatarActivityBase implements HabitRPGUserCall
|
|||
|
||||
@Override
|
||||
public void onModelStateChanged(Class<? extends Model> aClass, BaseModel.Action action, String s, String s1) {
|
||||
if(aClass != HabitRPGUser.class)
|
||||
if (aClass != HabitRPGUser.class)
|
||||
return;
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -52,7 +52,7 @@ public class PartyActivity extends AvatarActivityBase implements AppBarLayout.On
|
|||
|
||||
mAPIHelper = new APIHelper(this, hostConfig);
|
||||
|
||||
if(User == null)
|
||||
if (User == null)
|
||||
return;
|
||||
|
||||
updateUserAvatars();
|
||||
|
|
|
|||
|
|
@ -1,9 +1,8 @@
|
|||
package com.habitrpg.android.habitica;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.support.v7.app.AppCompatActivity;
|
||||
import android.os.Bundle;
|
||||
import android.util.Log;
|
||||
import android.support.v7.app.AppCompatActivity;
|
||||
import android.view.Menu;
|
||||
import android.view.MenuItem;
|
||||
import android.view.View;
|
||||
|
|
@ -106,8 +105,8 @@ public class TaskFormActivity extends AppCompatActivity implements AdapterView.O
|
|||
this.task = task;
|
||||
this.populate(task);
|
||||
setTitle(task);
|
||||
} else{
|
||||
setTitle((Task)null);
|
||||
} else {
|
||||
setTitle((Task) null);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -119,7 +118,7 @@ public class TaskFormActivity extends AppCompatActivity implements AdapterView.O
|
|||
String title = "";
|
||||
|
||||
if (task != null) {
|
||||
title = getResources().getString(R.string.action_edit)+ " " + task.getText();
|
||||
title = getResources().getString(R.string.action_edit) + " " + task.getText();
|
||||
} else {
|
||||
switch (taskType) {
|
||||
case "todo":
|
||||
|
|
@ -273,7 +272,7 @@ public class TaskFormActivity extends AppCompatActivity implements AdapterView.O
|
|||
if (this.dailyFrequencySpinner.getSelectedItemPosition() == 0) {
|
||||
task.setFrequency("weekly");
|
||||
Days repeat = task.getRepeat();
|
||||
if(repeat == null){
|
||||
if (repeat == null) {
|
||||
repeat = new Days();
|
||||
task.setRepeat(repeat);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -86,7 +86,7 @@ public class TavernActivity extends AppCompatActivity {
|
|||
fragmentTransaction.commit();
|
||||
}
|
||||
|
||||
public void onEvent(ToggledInnStateEvent evt){
|
||||
public void onEvent(ToggledInnStateEvent evt) {
|
||||
avatarInHeader.updateData(User);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -17,8 +17,9 @@ public class HabitRPGUserCallback implements Callback<HabitRPGUser> {
|
|||
private final OnUserReceived mCallback;
|
||||
|
||||
public HabitRPGUserCallback(OnUserReceived callback) {
|
||||
this.mCallback = callback;
|
||||
this.mCallback = callback;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void success(HabitRPGUser habitRPGUser, Response response) {
|
||||
Log.d("db", "saving");
|
||||
|
|
@ -38,6 +39,7 @@ public class HabitRPGUserCallback implements Callback<HabitRPGUser> {
|
|||
|
||||
public interface OnUserReceived {
|
||||
public void onUserReceived(HabitRPGUser user);
|
||||
|
||||
public void onUserFail();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ import retrofit.client.Response;
|
|||
/**
|
||||
* Created by magicmicky on 02/04/15.
|
||||
*/
|
||||
public class TaskDeletionCallback implements Callback<Void> {
|
||||
public class TaskDeletionCallback implements Callback<Void> {
|
||||
private final OnTaskDeleted callback;
|
||||
private final Task taskToDelete;
|
||||
|
||||
|
|
@ -20,6 +20,7 @@ public class TaskDeletionCallback implements Callback<Void> {
|
|||
this.callback = cb;
|
||||
this.taskToDelete = taskToDelete;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void success(Void aVoid, Response response) {
|
||||
callback.onTaskDeleted(taskToDelete);
|
||||
|
|
@ -36,5 +37,7 @@ public class TaskDeletionCallback implements Callback<Void> {
|
|||
|
||||
public interface OnTaskDeleted {
|
||||
public void onTaskDeleted(Task deleted);
|
||||
|
||||
public void onTaskDeletionFail();
|
||||
}}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ package com.habitrpg.android.habitica.callbacks;
|
|||
import android.util.Log;
|
||||
|
||||
import com.crashlytics.android.Crashlytics;
|
||||
import com.magicmicky.habitrpgwrapper.lib.models.HabitRPGUser;
|
||||
import com.magicmicky.habitrpgwrapper.lib.models.TaskDirectionData;
|
||||
import com.magicmicky.habitrpgwrapper.lib.models.tasks.Task;
|
||||
import com.raizlabs.android.dbflow.sql.builder.Condition;
|
||||
|
|
@ -19,10 +18,12 @@ import retrofit.client.Response;
|
|||
public class TaskScoringCallback implements Callback<TaskDirectionData> {
|
||||
private final OnTaskScored mCallback;
|
||||
private final String taskId;
|
||||
|
||||
public TaskScoringCallback(OnTaskScored callback, String taskId) {
|
||||
this.mCallback= callback;
|
||||
this.mCallback = callback;
|
||||
this.taskId = taskId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void success(TaskDirectionData taskDirectionData, Response response) {
|
||||
Task task = new Select().from(Task.class).where(Condition.column("id").eq(taskId)).querySingle();
|
||||
|
|
@ -34,13 +35,14 @@ public class TaskScoringCallback implements Callback<TaskDirectionData> {
|
|||
@Override
|
||||
public void failure(RetrofitError error) {
|
||||
Crashlytics.logException(error);
|
||||
|
||||
|
||||
this.mCallback.onTaskScoringFailed();
|
||||
Log.w("TaskScoring", "Task scoring failed " + error.getMessage());
|
||||
}
|
||||
|
||||
public interface OnTaskScored {
|
||||
public void onTaskDataReceived(TaskDirectionData data);
|
||||
|
||||
public void onTaskScoringFailed();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ package com.habitrpg.android.habitica.callbacks;
|
|||
import android.util.Log;
|
||||
|
||||
import com.crashlytics.android.Crashlytics;
|
||||
import com.habitrpg.android.habitica.events.TaskCreatedEvent;
|
||||
import com.habitrpg.android.habitica.events.TaskUpdatedEvent;
|
||||
import com.magicmicky.habitrpgwrapper.lib.models.tasks.Task;
|
||||
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import com.magicmicky.habitrpgwrapper.lib.models.tasks.Task;
|
|||
public class TaskCreatedEvent {
|
||||
public Task task;
|
||||
|
||||
public TaskCreatedEvent(Task t){
|
||||
public TaskCreatedEvent(Task t) {
|
||||
task = t;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import com.magicmicky.habitrpgwrapper.lib.models.tasks.Task;
|
|||
public class TaskUpdatedEvent {
|
||||
public Task task;
|
||||
|
||||
public TaskUpdatedEvent(Task t){
|
||||
public TaskUpdatedEvent(Task t) {
|
||||
task = t;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,5 +4,5 @@ package com.habitrpg.android.habitica.events.commands;
|
|||
* Created by Negue on 11.07.2015.
|
||||
*/
|
||||
public class AddNewTaskCommand {
|
||||
public String ClassType ;
|
||||
public String ClassType;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ public abstract class ChatMessageCommandBase {
|
|||
public String groupId;
|
||||
public ChatMessage chatMessage;
|
||||
|
||||
public ChatMessageCommandBase(String groupId, ChatMessage chatMessage){
|
||||
public ChatMessageCommandBase(String groupId, ChatMessage chatMessage) {
|
||||
this.groupId = groupId;
|
||||
this.chatMessage = chatMessage;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ package com.habitrpg.android.habitica.events.commands;
|
|||
public class CreateTagCommand {
|
||||
public String tagName;
|
||||
|
||||
public CreateTagCommand(String tagName){
|
||||
public CreateTagCommand(String tagName) {
|
||||
this.tagName = tagName;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ public class SendNewGroupMessageCommand {
|
|||
public String Message;
|
||||
public String TargetGroupId;
|
||||
|
||||
public SendNewGroupMessageCommand(String targetGroupId, String message){
|
||||
public SendNewGroupMessageCommand(String targetGroupId, String message) {
|
||||
TargetGroupId = targetGroupId;
|
||||
Message = message;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import com.magicmicky.habitrpgwrapper.lib.models.ChatMessage;
|
|||
/**
|
||||
* Created by Negue on 02.09.2015.
|
||||
*/
|
||||
public class ToggleLikeMessageCommand extends ChatMessageCommandBase {
|
||||
public class ToggleLikeMessageCommand extends ChatMessageCommandBase {
|
||||
public ToggleLikeMessageCommand(String groupId, ChatMessage chatMessage) {
|
||||
super(groupId, chatMessage);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ public class TagsHelper {
|
|||
}
|
||||
|
||||
public void setTags(List<String> tagsId) {
|
||||
this.tagsId= tagsId;
|
||||
this.tagsId = tagsId;
|
||||
}
|
||||
|
||||
public void addTags(String tags) {
|
||||
|
|
@ -34,7 +34,7 @@ public class TagsHelper {
|
|||
|
||||
public List<Task> filter(List<Task> tasks) {
|
||||
List<Task> filtered = new ArrayList<Task>();
|
||||
for(Task t : tasks) {
|
||||
for (Task t : tasks) {
|
||||
if (t.containsAllTagIds(this.tagsId)) {
|
||||
filtered.add(t);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
package com.habitrpg.android.habitica.prefs;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import android.app.AlertDialog.Builder;
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.DialogInterface.OnClickListener;
|
||||
|
|
@ -20,13 +19,13 @@ import android.widget.CompoundButton;
|
|||
import android.widget.EditText;
|
||||
import android.widget.RadioButton;
|
||||
import android.widget.TextView;
|
||||
import android.app.AlertDialog.Builder;
|
||||
|
||||
import com.habitrpg.android.habitica.R;
|
||||
|
||||
public class CustomListPreference extends ListPreference
|
||||
{
|
||||
private CustomListPreferenceAdapter customListPreferenceAdapter = null;
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class CustomListPreference extends ListPreference {
|
||||
private CustomListPreferenceAdapter customListPreferenceAdapter = null;
|
||||
private Context mContext;
|
||||
private LayoutInflater mInflater;
|
||||
private CharSequence[] entries;
|
||||
|
|
@ -34,10 +33,10 @@ public class CustomListPreference extends ListPreference
|
|||
private ArrayList<RadioButton> rButtonList;
|
||||
private SharedPreferences prefs;
|
||||
private SharedPreferences.Editor editor;
|
||||
private String value="";
|
||||
private String value = "";
|
||||
private EditText text;
|
||||
public CustomListPreference(Context context, AttributeSet attrs)
|
||||
{
|
||||
|
||||
public CustomListPreference(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
mContext = context;
|
||||
mInflater = LayoutInflater.from(context);
|
||||
|
|
@ -47,123 +46,108 @@ public class CustomListPreference extends ListPreference
|
|||
}
|
||||
|
||||
@Override
|
||||
protected void onPrepareDialogBuilder(Builder builder)
|
||||
{
|
||||
protected void onPrepareDialogBuilder(Builder builder) {
|
||||
entries = getEntries();
|
||||
entryValues = getEntryValues();
|
||||
|
||||
if (entries == null || entryValues == null || entries.length != entryValues.length )
|
||||
{
|
||||
if (entries == null || entryValues == null || entries.length != entryValues.length) {
|
||||
throw new IllegalStateException(
|
||||
"ListPreference requires an entries array and an entryValues array which are both the same length");
|
||||
}
|
||||
|
||||
customListPreferenceAdapter = new CustomListPreferenceAdapter(mContext);
|
||||
builder.setAdapter(customListPreferenceAdapter, new DialogInterface.OnClickListener()
|
||||
{
|
||||
public void onClick(DialogInterface dialog, int which)
|
||||
{
|
||||
builder.setAdapter(customListPreferenceAdapter, new DialogInterface.OnClickListener() {
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
|
||||
}
|
||||
});
|
||||
builder.setPositiveButton("OK", new OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface arg0, int arg1) {
|
||||
if(value != null && value.equals("custom")) {
|
||||
Log.d("commiting","custom value");
|
||||
value=text.getText().toString();
|
||||
}
|
||||
if(value == null || !value.startsWith("http")) {
|
||||
Log.v("Commiting", "changing values to default");
|
||||
value = mContext.getString(R.string.SP_address_default);
|
||||
}
|
||||
|
||||
Log.d("Commiting", "putting string: " + value);
|
||||
editor.putString(mContext.getString(R.string.SP_address), value);
|
||||
@Override
|
||||
public void onClick(DialogInterface arg0, int arg1) {
|
||||
if (value != null && value.equals("custom")) {
|
||||
Log.d("commiting", "custom value");
|
||||
value = text.getText().toString();
|
||||
}
|
||||
if (value == null || !value.startsWith("http")) {
|
||||
Log.v("Commiting", "changing values to default");
|
||||
value = mContext.getString(R.string.SP_address_default);
|
||||
}
|
||||
|
||||
Log.d("Commiting", "putting string: " + value);
|
||||
editor.putString(mContext.getString(R.string.SP_address), value);
|
||||
editor.commit();
|
||||
arg0.dismiss();
|
||||
}
|
||||
arg0.dismiss();
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
private class CustomListPreferenceAdapter extends BaseAdapter
|
||||
{
|
||||
public CustomListPreferenceAdapter(Context context)
|
||||
{
|
||||
|
||||
private class CustomListPreferenceAdapter extends BaseAdapter {
|
||||
public CustomListPreferenceAdapter(Context context) {
|
||||
|
||||
}
|
||||
|
||||
public int getCount()
|
||||
{
|
||||
public int getCount() {
|
||||
return entries.length;
|
||||
}
|
||||
|
||||
public Object getItem(int position)
|
||||
{
|
||||
public Object getItem(int position) {
|
||||
return position;
|
||||
}
|
||||
|
||||
public long getItemId(int position)
|
||||
{
|
||||
public long getItemId(int position) {
|
||||
return position;
|
||||
}
|
||||
|
||||
public View getView(final int position, View convertView, ViewGroup parent)
|
||||
{
|
||||
public View getView(final int position, View convertView, ViewGroup parent) {
|
||||
View row = convertView;
|
||||
|
||||
if(row == null)
|
||||
{
|
||||
if (row == null) {
|
||||
// do whatever you need here, for me I wanted the last item to be greyed out and unclickable
|
||||
if(position < 2)
|
||||
{
|
||||
if (position < 2) {
|
||||
NormalHolder holder = null;
|
||||
|
||||
row = mInflater.inflate(R.layout.normal_list_preference_row, parent, false);
|
||||
if(prefs.getString(mContext.getString(R.string.SP_address), "0").equals(entryValues[position])) {
|
||||
holder = new NormalHolder(row, position,true);
|
||||
Log.v("Prefs", entryValues[position] + " already exists at position " + position);
|
||||
value=entryValues[position].toString();
|
||||
row = mInflater.inflate(R.layout.normal_list_preference_row, parent, false);
|
||||
if (prefs.getString(mContext.getString(R.string.SP_address), "0").equals(entryValues[position])) {
|
||||
holder = new NormalHolder(row, position, true);
|
||||
Log.v("Prefs", entryValues[position] + " already exists at position " + position);
|
||||
value = entryValues[position].toString();
|
||||
} else {
|
||||
holder = new NormalHolder(row, position,false);
|
||||
holder = new NormalHolder(row, position, false);
|
||||
}
|
||||
|
||||
|
||||
|
||||
row.setTag(holder);
|
||||
// row.setClickable(true);
|
||||
row.setOnClickListener(new View.OnClickListener()
|
||||
{
|
||||
public void onClick(View v)
|
||||
{
|
||||
if(!rButtonList.get(position).isChecked()) {
|
||||
for(RadioButton rb : rButtonList)
|
||||
{
|
||||
if(rb.getId() == position) {
|
||||
Log.d("row.OnClickListener - " + position, "isChecked");
|
||||
if(!rb.isChecked())
|
||||
rb.setChecked(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
// row.setClickable(true);
|
||||
row.setOnClickListener(new View.OnClickListener() {
|
||||
public void onClick(View v) {
|
||||
if (!rButtonList.get(position).isChecked()) {
|
||||
for (RadioButton rb : rButtonList) {
|
||||
if (rb.getId() == position) {
|
||||
Log.d("row.OnClickListener - " + position, "isChecked");
|
||||
if (!rb.isChecked())
|
||||
rb.setChecked(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
row = mInflater.inflate(R.layout.custom_list_preference_row, parent, false);
|
||||
String fromPref = prefs.getString(mContext.getString(R.string.SP_address), "0");
|
||||
boolean flag=false;
|
||||
for(CharSequence entry : entryValues) {
|
||||
if(entry.toString().equals(fromPref)) {
|
||||
Log.v("ListPref", entry.toString() + " already exists");
|
||||
flag=true;
|
||||
}
|
||||
}
|
||||
CustomHolder holder;
|
||||
if(!flag && fromPref != null && !fromPref.equals("")) {
|
||||
holder = new CustomHolder(row, position, fromPref, true);
|
||||
value = "custom";
|
||||
row = mInflater.inflate(R.layout.custom_list_preference_row, parent, false);
|
||||
String fromPref = prefs.getString(mContext.getString(R.string.SP_address), "0");
|
||||
boolean flag = false;
|
||||
for (CharSequence entry : entryValues) {
|
||||
if (entry.toString().equals(fromPref)) {
|
||||
Log.v("ListPref", entry.toString() + " already exists");
|
||||
flag = true;
|
||||
}
|
||||
}
|
||||
CustomHolder holder;
|
||||
if (!flag && fromPref != null && !fromPref.equals("")) {
|
||||
holder = new CustomHolder(row, position, fromPref, true);
|
||||
value = "custom";
|
||||
} else {
|
||||
holder = new CustomHolder(row, position, "", false);
|
||||
holder = new CustomHolder(row, position, "", false);
|
||||
|
||||
}
|
||||
row.setTag(holder);
|
||||
|
|
@ -172,87 +156,77 @@ public class CustomListPreference extends ListPreference
|
|||
|
||||
return row;
|
||||
}
|
||||
class NormalHolder
|
||||
{
|
||||
private TextView text = null;
|
||||
private RadioButton rButton = null;
|
||||
|
||||
NormalHolder(View row, int position, boolean isCheked)
|
||||
{
|
||||
text = (TextView)row.findViewById(R.id.custom_list_view_row_text_view);
|
||||
text.setText(entries[position]);
|
||||
rButton = (RadioButton)row.findViewById(R.id.custom_list_view_row_radio_button);
|
||||
rButton.setId(position);
|
||||
rButton.setChecked(isCheked);
|
||||
|
||||
// also need to do something to check your preference and set the right button as checked
|
||||
|
||||
rButtonList.add(rButton);
|
||||
rButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
|
||||
{
|
||||
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
|
||||
{
|
||||
if(isChecked)
|
||||
{
|
||||
for(RadioButton rb : rButtonList)
|
||||
{
|
||||
if(rb.getId() != buttonView.getId())
|
||||
rb.setChecked(false);
|
||||
}
|
||||
|
||||
int index = buttonView.getId();
|
||||
value = entryValues[index].toString();
|
||||
Log.v("NormalHolder.onCheckedChanged", "putting string" + value);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
class CustomHolder
|
||||
{
|
||||
class NormalHolder {
|
||||
private TextView text = null;
|
||||
private RadioButton rButton = null;
|
||||
|
||||
CustomHolder(View row, int position, String pref, boolean checked)
|
||||
{
|
||||
rButton = (RadioButton)row.findViewById(R.id.custom_list_view_row_radio_button);
|
||||
NormalHolder(View row, int position, boolean isCheked) {
|
||||
text = (TextView) row.findViewById(R.id.custom_list_view_row_text_view);
|
||||
text.setText(entries[position]);
|
||||
rButton = (RadioButton) row.findViewById(R.id.custom_list_view_row_radio_button);
|
||||
rButton.setId(position);
|
||||
rButton.setChecked(isCheked);
|
||||
|
||||
// also need to do something to check your preference and set the right button as checked
|
||||
|
||||
rButtonList.add(rButton);
|
||||
rButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
|
||||
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
|
||||
if (isChecked) {
|
||||
for (RadioButton rb : rButtonList) {
|
||||
if (rb.getId() != buttonView.getId())
|
||||
rb.setChecked(false);
|
||||
}
|
||||
|
||||
int index = buttonView.getId();
|
||||
value = entryValues[index].toString();
|
||||
Log.v("NormalHolder.onCheckedChanged", "putting string" + value);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class CustomHolder {
|
||||
private RadioButton rButton = null;
|
||||
|
||||
CustomHolder(View row, int position, String pref, boolean checked) {
|
||||
rButton = (RadioButton) row.findViewById(R.id.custom_list_view_row_radio_button);
|
||||
rButton.setId(position);
|
||||
rButton.setChecked(checked);
|
||||
|
||||
text = (EditText)row.findViewById(R.id.ET_prefs_customText);
|
||||
text = (EditText) row.findViewById(R.id.ET_prefs_customText);
|
||||
text.setText(pref);
|
||||
text.setOnFocusChangeListener(new OnFocusChangeListener() {
|
||||
@Override
|
||||
public void onFocusChange(View v, boolean hasFocus) {
|
||||
if(hasFocus) {
|
||||
if(!rButton.isChecked())
|
||||
rButton.setChecked(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
getDialog().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
|
||||
@Override
|
||||
public void onFocusChange(View v, boolean hasFocus) {
|
||||
if (hasFocus) {
|
||||
if (!rButton.isChecked())
|
||||
rButton.setChecked(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
getDialog().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
|
||||
rButtonList.add(rButton);
|
||||
|
||||
// also need to do something to check your preference and set the right button as checked
|
||||
|
||||
rButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
|
||||
{
|
||||
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
|
||||
{
|
||||
if(isChecked)
|
||||
{
|
||||
for(RadioButton rb : rButtonList)
|
||||
{
|
||||
if(rb != buttonView)
|
||||
rButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
|
||||
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
|
||||
if (isChecked) {
|
||||
for (RadioButton rb : rButtonList) {
|
||||
if (rb != buttonView)
|
||||
rb.setChecked(false);
|
||||
}
|
||||
if(!text.hasFocus())
|
||||
text.requestFocus();
|
||||
if (!text.hasFocus())
|
||||
text.requestFocus();
|
||||
value = String.valueOf("custom");
|
||||
Log.v("CustomHolder.onCheckedChanged","putting string" + value);
|
||||
Log.v("CustomHolder.onCheckedChanged", "putting string" + value);
|
||||
} else {
|
||||
if(text.hasFocus())
|
||||
text.clearFocus();
|
||||
if (text.hasFocus())
|
||||
text.clearFocus();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,12 +1,5 @@
|
|||
package com.habitrpg.android.habitica.prefs;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
|
||||
import com.habitrpg.android.habitica.HostConfig;
|
||||
import com.habitrpg.android.habitica.R;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.Context;
|
||||
|
|
@ -19,30 +12,39 @@ import android.preference.PreferenceFragment;
|
|||
import android.preference.PreferenceManager;
|
||||
import android.view.MenuItem;
|
||||
|
||||
import com.habitrpg.android.habitica.HostConfig;
|
||||
import com.habitrpg.android.habitica.R;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
|
||||
public class PrefsActivity extends PreferenceActivity {
|
||||
protected Method mLoadHeaders = null;
|
||||
protected Method mHasHeaders = null;
|
||||
/**
|
||||
|
||||
/**
|
||||
* Checks to see if using new v11+ way of handling PrefsFragments.
|
||||
*
|
||||
* @return Returns false pre-v11, else checks to see if using headers.
|
||||
*/
|
||||
public boolean isNewV11Prefs() {
|
||||
if (mHasHeaders!=null && mLoadHeaders!=null) {
|
||||
if (mHasHeaders != null && mLoadHeaders != null) {
|
||||
try {
|
||||
return (Boolean)mHasHeaders.invoke(this);
|
||||
return (Boolean) mHasHeaders.invoke(this);
|
||||
} catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException ignored) {
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
|
||||
@SuppressWarnings("deprecation")
|
||||
@Override
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
|
||||
@SuppressWarnings("deprecation")
|
||||
@Override
|
||||
public void onCreate(Bundle aSavedState) {
|
||||
//onBuildHeaders() will be called during super.onCreate()
|
||||
try {
|
||||
mLoadHeaders = getClass().getMethod("loadHeadersFromResource", int.class, List.class );
|
||||
mLoadHeaders = getClass().getMethod("loadHeadersFromResource", int.class, List.class);
|
||||
mHasHeaders = getClass().getMethod("hasHeaders");
|
||||
} catch (NoSuchMethodException e) {
|
||||
}
|
||||
|
|
@ -59,11 +61,11 @@ public class PrefsActivity extends PreferenceActivity {
|
|||
});
|
||||
|
||||
|
||||
} else {
|
||||
if(this.getActionBar() != null) {
|
||||
} else {
|
||||
if (this.getActionBar() != null) {
|
||||
this.getActionBar().setDisplayHomeAsUpEnabled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
@ -74,11 +76,11 @@ public class PrefsActivity extends PreferenceActivity {
|
|||
@Override
|
||||
public void onBuildHeaders(List<Header> aTarget) {
|
||||
try {
|
||||
mLoadHeaders.invoke(this,new Object[]{R.xml.pref_headers,aTarget});
|
||||
mLoadHeaders.invoke(this, new Object[]{R.xml.pref_headers, aTarget});
|
||||
} catch (IllegalArgumentException e) {
|
||||
} catch (IllegalAccessException e) {
|
||||
} catch (InvocationTargetException e) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
@ -92,39 +94,39 @@ public class PrefsActivity extends PreferenceActivity {
|
|||
}
|
||||
|
||||
@SuppressLint("NewApi")
|
||||
static public class PrefsFragment extends PreferenceFragment {
|
||||
static public class PrefsFragment extends PreferenceFragment {
|
||||
@Override
|
||||
public void onCreate(Bundle aSavedState) {
|
||||
super.onCreate(aSavedState);
|
||||
Context anAct = getActivity().getApplicationContext();
|
||||
int thePrefRes = anAct.getResources().getIdentifier(getArguments().getString("pref-resource"),
|
||||
"xml",anAct.getPackageName());
|
||||
"xml", anAct.getPackageName());
|
||||
addPreferencesFromResource(thePrefRes);
|
||||
}
|
||||
}
|
||||
public static HostConfig fromContext(Context ctx) {
|
||||
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
|
||||
HostConfig config;
|
||||
String httpPort = "80";
|
||||
String address = prefs.getString(ctx.getString(R.string.SP_address), ctx.getString(R.string.SP_address_default));
|
||||
if(address.contains("http://habitrpg.com")) {
|
||||
address = "https://habitrpg.com";
|
||||
prefs.edit().putString(ctx.getString(R.string.SP_address), address).commit();
|
||||
} else if (address.contains("http://beta.habitrpg.com")) {
|
||||
address = "https://beta.habitrpg.com/";
|
||||
prefs.edit().putString(ctx.getString(R.string.SP_address), address).commit();
|
||||
|
||||
}
|
||||
if(address==null || address=="" || address.length()<2) {
|
||||
config=null;
|
||||
}
|
||||
else {
|
||||
String api=prefs.getString(ctx.getString(R.string.SP_APIToken), null);
|
||||
String userID=prefs.getString(ctx.getString(R.string.SP_userID), null);
|
||||
config = new HostConfig(address, httpPort, api, userID);
|
||||
}
|
||||
return config;
|
||||
}
|
||||
public static HostConfig fromContext(Context ctx) {
|
||||
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
|
||||
HostConfig config;
|
||||
String httpPort = "80";
|
||||
String address = prefs.getString(ctx.getString(R.string.SP_address), ctx.getString(R.string.SP_address_default));
|
||||
if (address.contains("http://habitrpg.com")) {
|
||||
address = "https://habitrpg.com";
|
||||
prefs.edit().putString(ctx.getString(R.string.SP_address), address).commit();
|
||||
} else if (address.contains("http://beta.habitrpg.com")) {
|
||||
address = "https://beta.habitrpg.com/";
|
||||
prefs.edit().putString(ctx.getString(R.string.SP_address), address).commit();
|
||||
|
||||
}
|
||||
if (address == null || address == "" || address.length() < 2) {
|
||||
config = null;
|
||||
} else {
|
||||
String api = prefs.getString(ctx.getString(R.string.SP_APIToken), null);
|
||||
String userID = prefs.getString(ctx.getString(R.string.SP_userID), null);
|
||||
config = new HostConfig(address, httpPort, api, userID);
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBackPressed() {
|
||||
|
|
|
|||
|
|
@ -16,13 +16,6 @@ package com.habitrpg.android.habitica.prefs.scanner;
|
|||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.AlertDialog;
|
||||
import android.content.ActivityNotFoundException;
|
||||
|
|
@ -34,22 +27,29 @@ import android.net.Uri;
|
|||
import android.os.Bundle;
|
||||
import android.util.Log;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* <p>A utility class which helps ease integration with Barcode Scanner via {@link Intent}s. This is a simple
|
||||
* way to invoke barcode scanning and receive the result, without any need to integrate, modify, or learn the
|
||||
* project's source code.</p>
|
||||
*
|
||||
* <p/>
|
||||
* <h2>Initiating a barcode scan</h2>
|
||||
*
|
||||
* <p/>
|
||||
* <p>To integrate, create an instance of {@code IntentIntegrator} and call {@link #initiateScan()} and wait
|
||||
* for the result in your app.</p>
|
||||
*
|
||||
* <p/>
|
||||
* <p>It does require that the Barcode Scanner (or work-alike) application is installed. The
|
||||
* {@link #initiateScan()} method will prompt the user to download the application, if needed.</p>
|
||||
*
|
||||
* <p/>
|
||||
* <p>There are a few steps to using this integration. First, your {@link Activity} must implement
|
||||
* the method {@link Activity#onActivityResult(int, int, Intent)} and include a line of code like this:</p>
|
||||
*
|
||||
* <p/>
|
||||
* <pre>{@code
|
||||
* public void onActivityResult(int requestCode, int resultCode, Intent intent) {
|
||||
* IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
|
||||
|
|
@ -60,41 +60,41 @@ import android.util.Log;
|
|||
* ...
|
||||
* }
|
||||
* }</pre>
|
||||
*
|
||||
* <p/>
|
||||
* <p>This is where you will handle a scan result.</p>
|
||||
*
|
||||
* <p/>
|
||||
* <p>Second, just call this in response to a user action somewhere to begin the scan process:</p>
|
||||
*
|
||||
* <p/>
|
||||
* <pre>{@code
|
||||
* IntentIntegrator integrator = new IntentIntegrator(yourActivity);
|
||||
* integrator.initiateScan();
|
||||
* }</pre>
|
||||
*
|
||||
* <p/>
|
||||
* <p>Note that {@link #initiateScan()} returns an {@link AlertDialog} which is non-null if the
|
||||
* user was prompted to download the application. This lets the calling app potentially manage the dialog.
|
||||
* In particular, ideally, the app dismisses the dialog if it's still active in its {@link Activity#onPause()}
|
||||
* method.</p>
|
||||
*
|
||||
* <p/>
|
||||
* <p>You can use {@link #setTitle(String)} to customize the title of this download prompt dialog (or, use
|
||||
* {@link #setTitleByID(int)} to set the title by string resource ID.) Likewise, the prompt message, and
|
||||
* yes/no button labels can be changed.</p>
|
||||
*
|
||||
* <p/>
|
||||
* <p>Finally, you can use {@link #addExtra(String, Object)} to add more parameters to the Intent used
|
||||
* to invoke the scanner. This can be used to set additional options not directly exposed by this
|
||||
* simplified API.</p>
|
||||
*
|
||||
* <p/>
|
||||
* <p>By default, this will only allow applications that are known to respond to this intent correctly
|
||||
* do so. The apps that are allowed to response can be set with {@link #setTargetApplications(List)}.
|
||||
* For example, set to {@link #TARGET_BARCODE_SCANNER_ONLY} to only target the Barcode Scanner app itself.</p>
|
||||
*
|
||||
* <p/>
|
||||
* <h2>Sharing text via barcode</h2>
|
||||
*
|
||||
* <p/>
|
||||
* <p>To share text, encoded as a QR Code on-screen, similarly, see {@link #shareText(CharSequence)}.</p>
|
||||
*
|
||||
* <p/>
|
||||
* <p>Some code, particularly download integration, was contributed from the Anobiit application.</p>
|
||||
*
|
||||
* <p/>
|
||||
* <h2>Enabling experimental barcode formats</h2>
|
||||
*
|
||||
* <p/>
|
||||
* <p>Some formats are not enabled by default even when scanning with {@link #ALL_CODE_TYPES}, such as
|
||||
* PDF417. Use {@link #initiateScan(java.util.Collection)} with
|
||||
* a collection containing the names of formats to scan for explicitly, like "PDF_417", to use such
|
||||
|
|
@ -108,312 +108,314 @@ import android.util.Log;
|
|||
*/
|
||||
public class IntentIntegrator {
|
||||
|
||||
public static final int REQUEST_CODE = 0x0000c0de; // Only use bottom 16 bits
|
||||
private static final String TAG = IntentIntegrator.class.getSimpleName();
|
||||
public static final int REQUEST_CODE = 0x0000c0de; // Only use bottom 16 bits
|
||||
private static final String TAG = IntentIntegrator.class.getSimpleName();
|
||||
|
||||
public static final String DEFAULT_TITLE = "Install Barcode Scanner?";
|
||||
public static final String DEFAULT_MESSAGE =
|
||||
"This application requires Barcode Scanner. Would you like to install it?";
|
||||
public static final String DEFAULT_YES = "Yes";
|
||||
public static final String DEFAULT_NO = "No";
|
||||
public static final String DEFAULT_TITLE = "Install Barcode Scanner?";
|
||||
public static final String DEFAULT_MESSAGE =
|
||||
"This application requires Barcode Scanner. Would you like to install it?";
|
||||
public static final String DEFAULT_YES = "Yes";
|
||||
public static final String DEFAULT_NO = "No";
|
||||
|
||||
private static final String BS_PACKAGE = "com.google.zxing.client.android";
|
||||
private static final String BSPLUS_PACKAGE = "com.srowen.bs.android";
|
||||
private static final String BS_PACKAGE = "com.google.zxing.client.android";
|
||||
private static final String BSPLUS_PACKAGE = "com.srowen.bs.android";
|
||||
|
||||
// supported barcode formats
|
||||
public static final Collection<String> PRODUCT_CODE_TYPES = list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "RSS_14");
|
||||
public static final Collection<String> ONE_D_CODE_TYPES =
|
||||
list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "CODE_39", "CODE_93", "CODE_128",
|
||||
"ITF", "RSS_14", "RSS_EXPANDED");
|
||||
public static final Collection<String> QR_CODE_TYPES = Collections.singleton("QR_CODE");
|
||||
public static final Collection<String> DATA_MATRIX_TYPES = Collections.singleton("DATA_MATRIX");
|
||||
// supported barcode formats
|
||||
public static final Collection<String> PRODUCT_CODE_TYPES = list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "RSS_14");
|
||||
public static final Collection<String> ONE_D_CODE_TYPES =
|
||||
list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "CODE_39", "CODE_93", "CODE_128",
|
||||
"ITF", "RSS_14", "RSS_EXPANDED");
|
||||
public static final Collection<String> QR_CODE_TYPES = Collections.singleton("QR_CODE");
|
||||
public static final Collection<String> DATA_MATRIX_TYPES = Collections.singleton("DATA_MATRIX");
|
||||
|
||||
public static final Collection<String> ALL_CODE_TYPES = null;
|
||||
|
||||
public static final List<String> TARGET_BARCODE_SCANNER_ONLY = Collections.singletonList(BS_PACKAGE);
|
||||
public static final List<String> TARGET_ALL_KNOWN = list(
|
||||
BS_PACKAGE, // Barcode Scanner
|
||||
BSPLUS_PACKAGE, // Barcode Scanner+
|
||||
BSPLUS_PACKAGE + ".simple" // Barcode Scanner+ Simple
|
||||
// What else supports this intent?
|
||||
);
|
||||
|
||||
private final Activity activity;
|
||||
private String title;
|
||||
private String message;
|
||||
private String buttonYes;
|
||||
private String buttonNo;
|
||||
private List<String> targetApplications;
|
||||
private final Map<String,Object> moreExtras;
|
||||
|
||||
public IntentIntegrator(Activity activity) {
|
||||
this.activity = activity;
|
||||
title = DEFAULT_TITLE;
|
||||
message = DEFAULT_MESSAGE;
|
||||
buttonYes = DEFAULT_YES;
|
||||
buttonNo = DEFAULT_NO;
|
||||
targetApplications = TARGET_ALL_KNOWN;
|
||||
moreExtras = new HashMap<String,Object>(3);
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
public static final Collection<String> ALL_CODE_TYPES = null;
|
||||
|
||||
public void setTitleByID(int titleID) {
|
||||
title = activity.getString(titleID);
|
||||
}
|
||||
public static final List<String> TARGET_BARCODE_SCANNER_ONLY = Collections.singletonList(BS_PACKAGE);
|
||||
public static final List<String> TARGET_ALL_KNOWN = list(
|
||||
BS_PACKAGE, // Barcode Scanner
|
||||
BSPLUS_PACKAGE, // Barcode Scanner+
|
||||
BSPLUS_PACKAGE + ".simple" // Barcode Scanner+ Simple
|
||||
// What else supports this intent?
|
||||
);
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
private final Activity activity;
|
||||
private String title;
|
||||
private String message;
|
||||
private String buttonYes;
|
||||
private String buttonNo;
|
||||
private List<String> targetApplications;
|
||||
private final Map<String, Object> moreExtras;
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public void setMessageByID(int messageID) {
|
||||
message = activity.getString(messageID);
|
||||
}
|
||||
|
||||
public String getButtonYes() {
|
||||
return buttonYes;
|
||||
}
|
||||
|
||||
public void setButtonYes(String buttonYes) {
|
||||
this.buttonYes = buttonYes;
|
||||
}
|
||||
|
||||
public void setButtonYesByID(int buttonYesID) {
|
||||
buttonYes = activity.getString(buttonYesID);
|
||||
}
|
||||
|
||||
public String getButtonNo() {
|
||||
return buttonNo;
|
||||
}
|
||||
|
||||
public void setButtonNo(String buttonNo) {
|
||||
this.buttonNo = buttonNo;
|
||||
}
|
||||
|
||||
public void setButtonNoByID(int buttonNoID) {
|
||||
buttonNo = activity.getString(buttonNoID);
|
||||
}
|
||||
|
||||
public Collection<String> getTargetApplications() {
|
||||
return targetApplications;
|
||||
}
|
||||
|
||||
public final void setTargetApplications(List<String> targetApplications) {
|
||||
if (targetApplications.isEmpty()) {
|
||||
throw new IllegalArgumentException("No target applications");
|
||||
public IntentIntegrator(Activity activity) {
|
||||
this.activity = activity;
|
||||
title = DEFAULT_TITLE;
|
||||
message = DEFAULT_MESSAGE;
|
||||
buttonYes = DEFAULT_YES;
|
||||
buttonNo = DEFAULT_NO;
|
||||
targetApplications = TARGET_ALL_KNOWN;
|
||||
moreExtras = new HashMap<String, Object>(3);
|
||||
}
|
||||
this.targetApplications = targetApplications;
|
||||
}
|
||||
|
||||
public void setSingleTargetApplication(String targetApplication) {
|
||||
this.targetApplications = Collections.singletonList(targetApplication);
|
||||
}
|
||||
|
||||
public Map<String,?> getMoreExtras() {
|
||||
return moreExtras;
|
||||
}
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public final void addExtra(String key, Object value) {
|
||||
moreExtras.put(key, value);
|
||||
}
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initiates a scan for all known barcode types.
|
||||
*/
|
||||
public final AlertDialog initiateScan() {
|
||||
return initiateScan(ALL_CODE_TYPES);
|
||||
}
|
||||
public void setTitleByID(int titleID) {
|
||||
title = activity.getString(titleID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initiates a scan only for a certain set of barcode types, given as strings corresponding
|
||||
* to their names in ZXing's {@code BarcodeFormat} class like "UPC_A". You can supply constants
|
||||
* like {@link #PRODUCT_CODE_TYPES} for example.
|
||||
*
|
||||
* @return the {@link AlertDialog} that was shown to the user prompting them to download the app
|
||||
* if a prompt was needed, or null otherwise
|
||||
*/
|
||||
public final AlertDialog initiateScan(Collection<String> desiredBarcodeFormats) {
|
||||
Intent intentScan = new Intent(BS_PACKAGE + ".SCAN");
|
||||
intentScan.addCategory(Intent.CATEGORY_DEFAULT);
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
// check which types of codes to scan for
|
||||
if (desiredBarcodeFormats != null) {
|
||||
// set the desired barcode types
|
||||
StringBuilder joinedByComma = new StringBuilder();
|
||||
for (String format : desiredBarcodeFormats) {
|
||||
if (joinedByComma.length() > 0) {
|
||||
joinedByComma.append(',');
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public void setMessageByID(int messageID) {
|
||||
message = activity.getString(messageID);
|
||||
}
|
||||
|
||||
public String getButtonYes() {
|
||||
return buttonYes;
|
||||
}
|
||||
|
||||
public void setButtonYes(String buttonYes) {
|
||||
this.buttonYes = buttonYes;
|
||||
}
|
||||
|
||||
public void setButtonYesByID(int buttonYesID) {
|
||||
buttonYes = activity.getString(buttonYesID);
|
||||
}
|
||||
|
||||
public String getButtonNo() {
|
||||
return buttonNo;
|
||||
}
|
||||
|
||||
public void setButtonNo(String buttonNo) {
|
||||
this.buttonNo = buttonNo;
|
||||
}
|
||||
|
||||
public void setButtonNoByID(int buttonNoID) {
|
||||
buttonNo = activity.getString(buttonNoID);
|
||||
}
|
||||
|
||||
public Collection<String> getTargetApplications() {
|
||||
return targetApplications;
|
||||
}
|
||||
|
||||
public final void setTargetApplications(List<String> targetApplications) {
|
||||
if (targetApplications.isEmpty()) {
|
||||
throw new IllegalArgumentException("No target applications");
|
||||
}
|
||||
joinedByComma.append(format);
|
||||
}
|
||||
intentScan.putExtra("SCAN_FORMATS", joinedByComma.toString());
|
||||
this.targetApplications = targetApplications;
|
||||
}
|
||||
|
||||
String targetAppPackage = findTargetAppPackage(intentScan);
|
||||
if (targetAppPackage == null) {
|
||||
return showDownloadDialog();
|
||||
public void setSingleTargetApplication(String targetApplication) {
|
||||
this.targetApplications = Collections.singletonList(targetApplication);
|
||||
}
|
||||
intentScan.setPackage(targetAppPackage);
|
||||
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
|
||||
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
|
||||
attachMoreExtras(intentScan);
|
||||
startActivityForResult(intentScan, REQUEST_CODE);
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start an activity.<br>
|
||||
* This method is defined to allow different methods of activity starting for
|
||||
* newer versions of Android and for compatibility library.
|
||||
*
|
||||
* @param intent Intent to start.
|
||||
* @param code Request code for the activity
|
||||
* @see android.app.Activity#startActivityForResult(Intent, int)
|
||||
* @see android.app.Fragment#startActivityForResult(Intent, int)
|
||||
*/
|
||||
protected void startActivityForResult(Intent intent, int code) {
|
||||
activity.startActivityForResult(intent, code);
|
||||
}
|
||||
|
||||
private String findTargetAppPackage(Intent intent) {
|
||||
PackageManager pm = activity.getPackageManager();
|
||||
List<ResolveInfo> availableApps = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
|
||||
if (availableApps != null) {
|
||||
for (ResolveInfo availableApp : availableApps) {
|
||||
String packageName = availableApp.activityInfo.packageName;
|
||||
if (targetApplications.contains(packageName)) {
|
||||
return packageName;
|
||||
public Map<String, ?> getMoreExtras() {
|
||||
return moreExtras;
|
||||
}
|
||||
|
||||
public final void addExtra(String key, Object value) {
|
||||
moreExtras.put(key, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initiates a scan for all known barcode types.
|
||||
*/
|
||||
public final AlertDialog initiateScan() {
|
||||
return initiateScan(ALL_CODE_TYPES);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initiates a scan only for a certain set of barcode types, given as strings corresponding
|
||||
* to their names in ZXing's {@code BarcodeFormat} class like "UPC_A". You can supply constants
|
||||
* like {@link #PRODUCT_CODE_TYPES} for example.
|
||||
*
|
||||
* @return the {@link AlertDialog} that was shown to the user prompting them to download the app
|
||||
* if a prompt was needed, or null otherwise
|
||||
*/
|
||||
public final AlertDialog initiateScan(Collection<String> desiredBarcodeFormats) {
|
||||
Intent intentScan = new Intent(BS_PACKAGE + ".SCAN");
|
||||
intentScan.addCategory(Intent.CATEGORY_DEFAULT);
|
||||
|
||||
// check which types of codes to scan for
|
||||
if (desiredBarcodeFormats != null) {
|
||||
// set the desired barcode types
|
||||
StringBuilder joinedByComma = new StringBuilder();
|
||||
for (String format : desiredBarcodeFormats) {
|
||||
if (joinedByComma.length() > 0) {
|
||||
joinedByComma.append(',');
|
||||
}
|
||||
joinedByComma.append(format);
|
||||
}
|
||||
intentScan.putExtra("SCAN_FORMATS", joinedByComma.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private AlertDialog showDownloadDialog() {
|
||||
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(activity);
|
||||
downloadDialog.setTitle(title);
|
||||
downloadDialog.setMessage(message);
|
||||
downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialogInterface, int i) {
|
||||
String packageName = targetApplications.get(0);
|
||||
Uri uri = Uri.parse("market://details?id=" + packageName);
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
|
||||
try {
|
||||
activity.startActivity(intent);
|
||||
} catch (ActivityNotFoundException anfe) {
|
||||
// Hmm, market is not installed
|
||||
Log.w(TAG, "Google Play is not installed; cannot install " + packageName);
|
||||
String targetAppPackage = findTargetAppPackage(intentScan);
|
||||
if (targetAppPackage == null) {
|
||||
return showDownloadDialog();
|
||||
}
|
||||
}
|
||||
});
|
||||
downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialogInterface, int i) {}
|
||||
});
|
||||
return downloadDialog.show();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* <p>Call this from your {@link Activity}'s
|
||||
* {@link Activity#onActivityResult(int, int, Intent)} method.</p>
|
||||
*
|
||||
* @return null if the event handled here was not related to this class, or
|
||||
* else an {@link IntentResult} containing the result of the scan. If the user cancelled scanning,
|
||||
* the fields will be null.
|
||||
*/
|
||||
public static IntentResult parseActivityResult(int requestCode, int resultCode, Intent intent) {
|
||||
if (requestCode == REQUEST_CODE) {
|
||||
if (resultCode == Activity.RESULT_OK) {
|
||||
String contents = intent.getStringExtra("SCAN_RESULT");
|
||||
String formatName = intent.getStringExtra("SCAN_RESULT_FORMAT");
|
||||
byte[] rawBytes = intent.getByteArrayExtra("SCAN_RESULT_BYTES");
|
||||
int intentOrientation = intent.getIntExtra("SCAN_RESULT_ORIENTATION", Integer.MIN_VALUE);
|
||||
Integer orientation = intentOrientation == Integer.MIN_VALUE ? null : intentOrientation;
|
||||
String errorCorrectionLevel = intent.getStringExtra("SCAN_RESULT_ERROR_CORRECTION_LEVEL");
|
||||
return new IntentResult(contents,
|
||||
formatName,
|
||||
rawBytes,
|
||||
orientation,
|
||||
errorCorrectionLevel);
|
||||
}
|
||||
return new IntentResult();
|
||||
intentScan.setPackage(targetAppPackage);
|
||||
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
|
||||
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
|
||||
attachMoreExtras(intentScan);
|
||||
startActivityForResult(intentScan, REQUEST_CODE);
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Defaults to type "TEXT_TYPE".
|
||||
* @see #shareText(CharSequence, CharSequence)
|
||||
*/
|
||||
public final AlertDialog shareText(CharSequence text) {
|
||||
return shareText(text, "TEXT_TYPE");
|
||||
}
|
||||
|
||||
/**
|
||||
* Shares the given text by encoding it as a barcode, such that another user can
|
||||
* scan the text off the screen of the device.
|
||||
*
|
||||
* @param text the text string to encode as a barcode
|
||||
* @param type type of data to encode. See {@code com.google.zxing.client.android.Contents.Type} constants.
|
||||
* @return the {@link AlertDialog} that was shown to the user prompting them to download the app
|
||||
* if a prompt was needed, or null otherwise
|
||||
*/
|
||||
public final AlertDialog shareText(CharSequence text, CharSequence type) {
|
||||
Intent intent = new Intent();
|
||||
intent.addCategory(Intent.CATEGORY_DEFAULT);
|
||||
intent.setAction(BS_PACKAGE + ".ENCODE");
|
||||
intent.putExtra("ENCODE_TYPE", type);
|
||||
intent.putExtra("ENCODE_DATA", text);
|
||||
String targetAppPackage = findTargetAppPackage(intent);
|
||||
if (targetAppPackage == null) {
|
||||
return showDownloadDialog();
|
||||
/**
|
||||
* Start an activity.<br>
|
||||
* This method is defined to allow different methods of activity starting for
|
||||
* newer versions of Android and for compatibility library.
|
||||
*
|
||||
* @param intent Intent to start.
|
||||
* @param code Request code for the activity
|
||||
* @see android.app.Activity#startActivityForResult(Intent, int)
|
||||
* @see android.app.Fragment#startActivityForResult(Intent, int)
|
||||
*/
|
||||
protected void startActivityForResult(Intent intent, int code) {
|
||||
activity.startActivityForResult(intent, code);
|
||||
}
|
||||
intent.setPackage(targetAppPackage);
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
|
||||
attachMoreExtras(intent);
|
||||
activity.startActivity(intent);
|
||||
return null;
|
||||
}
|
||||
|
||||
private static List<String> list(String... values) {
|
||||
return Collections.unmodifiableList(Arrays.asList(values));
|
||||
}
|
||||
|
||||
private void attachMoreExtras(Intent intent) {
|
||||
for (Map.Entry<String,Object> entry : moreExtras.entrySet()) {
|
||||
String key = entry.getKey();
|
||||
Object value = entry.getValue();
|
||||
// Kind of hacky
|
||||
if (value instanceof Integer) {
|
||||
intent.putExtra(key, (Integer) value);
|
||||
} else if (value instanceof Long) {
|
||||
intent.putExtra(key, (Long) value);
|
||||
} else if (value instanceof Boolean) {
|
||||
intent.putExtra(key, (Boolean) value);
|
||||
} else if (value instanceof Double) {
|
||||
intent.putExtra(key, (Double) value);
|
||||
} else if (value instanceof Float) {
|
||||
intent.putExtra(key, (Float) value);
|
||||
} else if (value instanceof Bundle) {
|
||||
intent.putExtra(key, (Bundle) value);
|
||||
} else {
|
||||
intent.putExtra(key, value.toString());
|
||||
}
|
||||
private String findTargetAppPackage(Intent intent) {
|
||||
PackageManager pm = activity.getPackageManager();
|
||||
List<ResolveInfo> availableApps = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
|
||||
if (availableApps != null) {
|
||||
for (ResolveInfo availableApp : availableApps) {
|
||||
String packageName = availableApp.activityInfo.packageName;
|
||||
if (targetApplications.contains(packageName)) {
|
||||
return packageName;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private AlertDialog showDownloadDialog() {
|
||||
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(activity);
|
||||
downloadDialog.setTitle(title);
|
||||
downloadDialog.setMessage(message);
|
||||
downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialogInterface, int i) {
|
||||
String packageName = targetApplications.get(0);
|
||||
Uri uri = Uri.parse("market://details?id=" + packageName);
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
|
||||
try {
|
||||
activity.startActivity(intent);
|
||||
} catch (ActivityNotFoundException anfe) {
|
||||
// Hmm, market is not installed
|
||||
Log.w(TAG, "Google Play is not installed; cannot install " + packageName);
|
||||
}
|
||||
}
|
||||
});
|
||||
downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialogInterface, int i) {
|
||||
}
|
||||
});
|
||||
return downloadDialog.show();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* <p>Call this from your {@link Activity}'s
|
||||
* {@link Activity#onActivityResult(int, int, Intent)} method.</p>
|
||||
*
|
||||
* @return null if the event handled here was not related to this class, or
|
||||
* else an {@link IntentResult} containing the result of the scan. If the user cancelled scanning,
|
||||
* the fields will be null.
|
||||
*/
|
||||
public static IntentResult parseActivityResult(int requestCode, int resultCode, Intent intent) {
|
||||
if (requestCode == REQUEST_CODE) {
|
||||
if (resultCode == Activity.RESULT_OK) {
|
||||
String contents = intent.getStringExtra("SCAN_RESULT");
|
||||
String formatName = intent.getStringExtra("SCAN_RESULT_FORMAT");
|
||||
byte[] rawBytes = intent.getByteArrayExtra("SCAN_RESULT_BYTES");
|
||||
int intentOrientation = intent.getIntExtra("SCAN_RESULT_ORIENTATION", Integer.MIN_VALUE);
|
||||
Integer orientation = intentOrientation == Integer.MIN_VALUE ? null : intentOrientation;
|
||||
String errorCorrectionLevel = intent.getStringExtra("SCAN_RESULT_ERROR_CORRECTION_LEVEL");
|
||||
return new IntentResult(contents,
|
||||
formatName,
|
||||
rawBytes,
|
||||
orientation,
|
||||
errorCorrectionLevel);
|
||||
}
|
||||
return new IntentResult();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Defaults to type "TEXT_TYPE".
|
||||
*
|
||||
* @see #shareText(CharSequence, CharSequence)
|
||||
*/
|
||||
public final AlertDialog shareText(CharSequence text) {
|
||||
return shareText(text, "TEXT_TYPE");
|
||||
}
|
||||
|
||||
/**
|
||||
* Shares the given text by encoding it as a barcode, such that another user can
|
||||
* scan the text off the screen of the device.
|
||||
*
|
||||
* @param text the text string to encode as a barcode
|
||||
* @param type type of data to encode. See {@code com.google.zxing.client.android.Contents.Type} constants.
|
||||
* @return the {@link AlertDialog} that was shown to the user prompting them to download the app
|
||||
* if a prompt was needed, or null otherwise
|
||||
*/
|
||||
public final AlertDialog shareText(CharSequence text, CharSequence type) {
|
||||
Intent intent = new Intent();
|
||||
intent.addCategory(Intent.CATEGORY_DEFAULT);
|
||||
intent.setAction(BS_PACKAGE + ".ENCODE");
|
||||
intent.putExtra("ENCODE_TYPE", type);
|
||||
intent.putExtra("ENCODE_DATA", text);
|
||||
String targetAppPackage = findTargetAppPackage(intent);
|
||||
if (targetAppPackage == null) {
|
||||
return showDownloadDialog();
|
||||
}
|
||||
intent.setPackage(targetAppPackage);
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
|
||||
attachMoreExtras(intent);
|
||||
activity.startActivity(intent);
|
||||
return null;
|
||||
}
|
||||
|
||||
private static List<String> list(String... values) {
|
||||
return Collections.unmodifiableList(Arrays.asList(values));
|
||||
}
|
||||
|
||||
private void attachMoreExtras(Intent intent) {
|
||||
for (Map.Entry<String, Object> entry : moreExtras.entrySet()) {
|
||||
String key = entry.getKey();
|
||||
Object value = entry.getValue();
|
||||
// Kind of hacky
|
||||
if (value instanceof Integer) {
|
||||
intent.putExtra(key, (Integer) value);
|
||||
} else if (value instanceof Long) {
|
||||
intent.putExtra(key, (Long) value);
|
||||
} else if (value instanceof Boolean) {
|
||||
intent.putExtra(key, (Boolean) value);
|
||||
} else if (value instanceof Double) {
|
||||
intent.putExtra(key, (Double) value);
|
||||
} else if (value instanceof Float) {
|
||||
intent.putExtra(key, (Float) value);
|
||||
} else if (value instanceof Bundle) {
|
||||
intent.putExtra(key, (Bundle) value);
|
||||
} else {
|
||||
intent.putExtra(key, value.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -22,73 +22,73 @@ package com.habitrpg.android.habitica.prefs.scanner;
|
|||
*/
|
||||
public final class IntentResult {
|
||||
|
||||
private final String contents;
|
||||
private final String formatName;
|
||||
private final byte[] rawBytes;
|
||||
private final Integer orientation;
|
||||
private final String errorCorrectionLevel;
|
||||
private final String contents;
|
||||
private final String formatName;
|
||||
private final byte[] rawBytes;
|
||||
private final Integer orientation;
|
||||
private final String errorCorrectionLevel;
|
||||
|
||||
IntentResult() {
|
||||
this(null, null, null, null, null);
|
||||
}
|
||||
IntentResult() {
|
||||
this(null, null, null, null, null);
|
||||
}
|
||||
|
||||
IntentResult(String contents,
|
||||
String formatName,
|
||||
byte[] rawBytes,
|
||||
Integer orientation,
|
||||
String errorCorrectionLevel) {
|
||||
this.contents = contents;
|
||||
this.formatName = formatName;
|
||||
this.rawBytes = rawBytes;
|
||||
this.orientation = orientation;
|
||||
this.errorCorrectionLevel = errorCorrectionLevel;
|
||||
}
|
||||
IntentResult(String contents,
|
||||
String formatName,
|
||||
byte[] rawBytes,
|
||||
Integer orientation,
|
||||
String errorCorrectionLevel) {
|
||||
this.contents = contents;
|
||||
this.formatName = formatName;
|
||||
this.rawBytes = rawBytes;
|
||||
this.orientation = orientation;
|
||||
this.errorCorrectionLevel = errorCorrectionLevel;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return raw content of barcode
|
||||
*/
|
||||
public String getContents() {
|
||||
return contents;
|
||||
}
|
||||
/**
|
||||
* @return raw content of barcode
|
||||
*/
|
||||
public String getContents() {
|
||||
return contents;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return name of format, like "QR_CODE", "UPC_A". See {@code BarcodeFormat} for more format names.
|
||||
*/
|
||||
public String getFormatName() {
|
||||
return formatName;
|
||||
}
|
||||
/**
|
||||
* @return name of format, like "QR_CODE", "UPC_A". See {@code BarcodeFormat} for more format names.
|
||||
*/
|
||||
public String getFormatName() {
|
||||
return formatName;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return raw bytes of the barcode content, if applicable, or null otherwise
|
||||
*/
|
||||
public byte[] getRawBytes() {
|
||||
return rawBytes;
|
||||
}
|
||||
/**
|
||||
* @return raw bytes of the barcode content, if applicable, or null otherwise
|
||||
*/
|
||||
public byte[] getRawBytes() {
|
||||
return rawBytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return rotation of the image, in degrees, which resulted in a successful scan. May be null.
|
||||
*/
|
||||
public Integer getOrientation() {
|
||||
return orientation;
|
||||
}
|
||||
/**
|
||||
* @return rotation of the image, in degrees, which resulted in a successful scan. May be null.
|
||||
*/
|
||||
public Integer getOrientation() {
|
||||
return orientation;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return name of the error correction level used in the barcode, if applicable
|
||||
*/
|
||||
public String getErrorCorrectionLevel() {
|
||||
return errorCorrectionLevel;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder dialogText = new StringBuilder(100);
|
||||
dialogText.append("Format: ").append(formatName).append('\n');
|
||||
dialogText.append("Contents: ").append(contents).append('\n');
|
||||
int rawBytesLength = rawBytes == null ? 0 : rawBytes.length;
|
||||
dialogText.append("Raw bytes: (").append(rawBytesLength).append(" bytes)\n");
|
||||
dialogText.append("Orientation: ").append(orientation).append('\n');
|
||||
dialogText.append("EC level: ").append(errorCorrectionLevel).append('\n');
|
||||
return dialogText.toString();
|
||||
}
|
||||
/**
|
||||
* @return name of the error correction level used in the barcode, if applicable
|
||||
*/
|
||||
public String getErrorCorrectionLevel() {
|
||||
return errorCorrectionLevel;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder dialogText = new StringBuilder(100);
|
||||
dialogText.append("Format: ").append(formatName).append('\n');
|
||||
dialogText.append("Contents: ").append(contents).append('\n');
|
||||
int rawBytesLength = rawBytes == null ? 0 : rawBytes.length;
|
||||
dialogText.append("Raw bytes: (").append(rawBytesLength).append(" bytes)\n");
|
||||
dialogText.append("Orientation: ").append(orientation).append('\n');
|
||||
dialogText.append("EC level: ").append(errorCorrectionLevel).append('\n');
|
||||
return dialogText.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -33,13 +33,12 @@ public class AvatarWithBarsViewModel {
|
|||
|
||||
private TextView lvlText, goldText, silverText, gemsText;
|
||||
|
||||
public AvatarWithBarsViewModel(Context context, View v){
|
||||
public AvatarWithBarsViewModel(Context context, View v) {
|
||||
this.context = context;
|
||||
|
||||
res = context.getResources();
|
||||
|
||||
if(v == null)
|
||||
{
|
||||
if (v == null) {
|
||||
Log.w("AvatarWithBarsViewModel", "View is null");
|
||||
return;
|
||||
}
|
||||
|
|
@ -62,8 +61,7 @@ public class AvatarWithBarsViewModel {
|
|||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
|
||||
public void updateData(HabitRPGUser user)
|
||||
{
|
||||
public void updateData(HabitRPGUser user) {
|
||||
Stats stats = user.getStats();
|
||||
char classShort;
|
||||
String userClass = "";
|
||||
|
|
@ -74,14 +72,14 @@ public class AvatarWithBarsViewModel {
|
|||
setValueBar(mpBar, stats.getMp().floatValue(), stats.getMaxMP(), context.getString(R.string.MP_default), context.getResources().getColor(R.color.mpColor), R.drawable.ic_header_magic);
|
||||
new UserPicture(user, this.context).setPictureOn(image);
|
||||
|
||||
if(user.getStats().get_class()!=null) {
|
||||
userClass+=user.getStats().get_class().name();
|
||||
if (user.getStats().get_class() != null) {
|
||||
userClass += user.getStats().get_class().name();
|
||||
}
|
||||
lvlText.setText("Lv" + user.getStats().getLvl() + " " + userClass);
|
||||
Drawable drawable;
|
||||
switch(stats.get_class()) {
|
||||
switch (stats.get_class()) {
|
||||
case warrior:
|
||||
drawable = ResourcesCompat.getDrawable(res, R.drawable.ic_header_warrior, null);
|
||||
drawable = ResourcesCompat.getDrawable(res, R.drawable.ic_header_warrior, null);
|
||||
|
||||
break;
|
||||
case rogue:
|
||||
|
|
@ -106,18 +104,16 @@ public class AvatarWithBarsViewModel {
|
|||
|
||||
// binding.setClassShort(classShort);
|
||||
|
||||
goldText.setText(gp+"");
|
||||
silverText.setText(sp+"");
|
||||
goldText.setText(gp + "");
|
||||
silverText.setText(sp + "");
|
||||
|
||||
Double gems = new Double(user.getBalance()*4);
|
||||
gemsText.setText(gems.intValue()+"");
|
||||
Double gems = new Double(user.getBalance() * 4);
|
||||
gemsText.setText(gems.intValue() + "");
|
||||
}
|
||||
|
||||
public static void setHpBarData(ValueBarBinding valueBar, Stats stats, Context ctx)
|
||||
{
|
||||
public static void setHpBarData(ValueBarBinding valueBar, Stats stats, Context ctx) {
|
||||
int maxHP = stats.getMaxHealth();
|
||||
if(maxHP == 0)
|
||||
{
|
||||
if (maxHP == 0) {
|
||||
maxHP = 50;
|
||||
}
|
||||
|
||||
|
|
@ -126,17 +122,13 @@ public class AvatarWithBarsViewModel {
|
|||
|
||||
// Layout_Weight don't accepts 0.7/0.3 to have 70% filled instead it shows the 30% , so I had to switch the values
|
||||
// but on a 1.0/0.0 which switches to 0.0/1.0 it shows the blank part full size...
|
||||
private static void setValueBar(ValueBarBinding valueBar, float value, float valueMax, String description, int color, int icon)
|
||||
{
|
||||
private static void setValueBar(ValueBarBinding valueBar, float value, float valueMax, String description, int color, int icon) {
|
||||
double percent = Math.min(1, value / valueMax);
|
||||
|
||||
if(percent == 1)
|
||||
{
|
||||
if (percent == 1) {
|
||||
valueBar.setWeightToShow(1);
|
||||
valueBar.setWeightToHide(0);
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
valueBar.setWeightToShow((float) percent);
|
||||
valueBar.setWeightToHide((float) (1 - percent));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,17 +1,13 @@
|
|||
package com.habitrpg.android.habitica.ui;
|
||||
|
||||
import android.content.Context;
|
||||
import android.support.v7.widget.RecyclerView;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.Button;
|
||||
import android.widget.EditText;
|
||||
|
||||
import com.habitrpg.android.habitica.R;
|
||||
import com.habitrpg.android.habitica.events.commands.CreateTagCommand;
|
||||
import com.habitrpg.android.habitica.ui.helpers.ViewHelper;
|
||||
import com.mikepenz.materialdrawer.model.BaseDrawerItem;
|
||||
import com.mikepenz.materialdrawer.model.BasePrimaryDrawerItem;
|
||||
import com.mikepenz.materialdrawer.model.utils.ViewHolderFactory;
|
||||
|
||||
|
|
@ -42,22 +38,6 @@ public class EditTextDrawer extends BasePrimaryDrawerItem<EditTextDrawer> {
|
|||
|
||||
}
|
||||
|
||||
/*@Override
|
||||
public View convertView(LayoutInflater inflater, View convertView, ViewGroup parent) {
|
||||
Context ctx = parent.getContext();
|
||||
|
||||
//get the viewHolder
|
||||
ViewHolder viewHolder;
|
||||
if (convertView == null) {
|
||||
convertView = inflater.inflate(getLayoutRes(), parent, false);
|
||||
viewHolder = new ViewHolder(convertView);
|
||||
convertView.setTag(viewHolder);
|
||||
} else {
|
||||
viewHolder = (ViewHolder) convertView.getTag();
|
||||
}
|
||||
|
||||
return convertView;
|
||||
}*/
|
||||
|
||||
@Override
|
||||
public ViewHolderFactory getFactory() {
|
||||
|
|
@ -93,7 +73,7 @@ public class EditTextDrawer extends BasePrimaryDrawerItem<EditTextDrawer> {
|
|||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
if(editText.getText().equals(""))
|
||||
if (editText.getText().equals(""))
|
||||
return;
|
||||
|
||||
EventBus.getDefault().post(new CreateTagCommand(editText.getText().toString()));
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ import android.app.Activity;
|
|||
import android.content.Intent;
|
||||
import android.support.v7.widget.Toolbar;
|
||||
import android.view.View;
|
||||
import android.widget.AdapterView;
|
||||
|
||||
import com.habitrpg.android.habitica.AboutActivity;
|
||||
import com.habitrpg.android.habitica.GemPurchaseActivity;
|
||||
|
|
|
|||
|
|
@ -25,8 +25,8 @@ import com.habitrpg.android.habitica.events.commands.ToggleLikeMessageCommand;
|
|||
import com.habitrpg.android.habitica.ui.helpers.DataBindingUtils;
|
||||
import com.habitrpg.android.habitica.ui.helpers.ViewHelper;
|
||||
import com.magicmicky.habitrpgwrapper.lib.models.ChatMessage;
|
||||
import com.mikepenz.iconics.Iconics;
|
||||
import com.mikepenz.fontawesome_typeface_library.FontAwesome;
|
||||
import com.mikepenz.iconics.Iconics;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.List;
|
||||
|
|
@ -98,7 +98,7 @@ public class ChatRecyclerViewAdapter extends RecyclerView.Adapter<ChatRecyclerVi
|
|||
|
||||
@Override
|
||||
public void onBindViewHolder(ChatRecyclerViewHolder holder, int position) {
|
||||
if(!isTavern && position > 0){
|
||||
if (!isTavern && position > 0) {
|
||||
holder.bind(messages.get(position - 1));
|
||||
return;
|
||||
}
|
||||
|
|
@ -215,7 +215,7 @@ public class ChatRecyclerViewAdapter extends RecyclerView.Adapter<ChatRecyclerVi
|
|||
|
||||
DataBindingUtils.setRoundedBackgroundInt(userBackground, msg.getContributorColor());
|
||||
|
||||
if(msg.user == null || msg.user.equals("")){
|
||||
if (msg.user == null || msg.user.equals("")) {
|
||||
msg.user = "system";
|
||||
}
|
||||
|
||||
|
|
@ -341,7 +341,7 @@ public class ChatRecyclerViewAdapter extends RecyclerView.Adapter<ChatRecyclerVi
|
|||
|
||||
String text = textNewMessage.getText().toString();
|
||||
|
||||
if(!text.equals("")) {
|
||||
if (!text.equals("")) {
|
||||
EventBus.getDefault().post(new SendNewGroupMessageCommand(groupId, text));
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -53,8 +53,7 @@ public class HabitItemRecyclerViewAdapter<THabitItem extends Task>
|
|||
implements FlowContentObserver.OnModelStateChangedListener, IReceiveNewEntries {
|
||||
|
||||
|
||||
public interface IAdditionalEntries
|
||||
{
|
||||
public interface IAdditionalEntries {
|
||||
void GetAdditionalEntries(IReceiveNewEntries callBack);
|
||||
}
|
||||
|
||||
|
|
@ -114,16 +113,16 @@ public class HabitItemRecyclerViewAdapter<THabitItem extends Task>
|
|||
|
||||
}
|
||||
|
||||
public void onEvent(TaskUpdatedEvent evnt){
|
||||
if(!taskType.equals(evnt.task.getType()))
|
||||
public void onEvent(TaskUpdatedEvent evnt) {
|
||||
if (!taskType.equals(evnt.task.getType()))
|
||||
return;
|
||||
|
||||
this.filter();
|
||||
notifyDataSetChanged();
|
||||
}
|
||||
|
||||
public void onEvent(TaskCreatedEvent evnt){
|
||||
if(!taskType.equals(evnt.task.getType()))
|
||||
public void onEvent(TaskCreatedEvent evnt) {
|
||||
if (!taskType.equals(evnt.task.getType()))
|
||||
return;
|
||||
|
||||
observableContent.add(0, evnt.task);
|
||||
|
|
@ -501,7 +500,7 @@ public class HabitItemRecyclerViewAdapter<THabitItem extends Task>
|
|||
.orderBy(OrderBy.columns("dateCreated").descending())
|
||||
.queryList());
|
||||
|
||||
if(additionalEntries != null){
|
||||
if (additionalEntries != null) {
|
||||
additionalEntries.GetAdditionalEntries(this);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,6 @@ import com.magicmicky.habitrpgwrapper.lib.models.tasks.Task;
|
|||
|
||||
import java.util.List;
|
||||
|
||||
public interface IReceiveNewEntries{
|
||||
public interface IReceiveNewEntries {
|
||||
void GotAdditionalItems(List<Task> items);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,63 +20,71 @@ import java.util.Map;
|
|||
public class TagAdapter extends BaseAdapter {
|
||||
|
||||
|
||||
private Context mContext;
|
||||
private Map<String, String> mTags;
|
||||
private String[] mKeySet;
|
||||
public TagAdapter(Context c) {
|
||||
this(c, new HashMap<String, String>());
|
||||
}
|
||||
public TagAdapter(Context c, Map<String, String> tags) {
|
||||
this.mContext = c;
|
||||
this.mTags = tags;
|
||||
if(this.mTags!=null)
|
||||
this.mKeySet = this.mTags.keySet().toArray(new String[mTags.size()]);
|
||||
else {
|
||||
mKeySet = new String[0];
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public int getCount() {
|
||||
return mTags.size();
|
||||
}
|
||||
private Context mContext;
|
||||
private Map<String, String> mTags;
|
||||
private String[] mKeySet;
|
||||
|
||||
@Override
|
||||
public String getItem(int i) {
|
||||
public TagAdapter(Context c) {
|
||||
this(c, new HashMap<String, String>());
|
||||
}
|
||||
|
||||
return mTags.get(mKeySet[i]);
|
||||
}
|
||||
@Override
|
||||
public boolean isEnabled(int position) {
|
||||
public TagAdapter(Context c, Map<String, String> tags) {
|
||||
this.mContext = c;
|
||||
this.mTags = tags;
|
||||
if (this.mTags != null)
|
||||
this.mKeySet = this.mTags.keySet().toArray(new String[mTags.size()]);
|
||||
else {
|
||||
mKeySet = new String[0];
|
||||
}
|
||||
}
|
||||
|
||||
return super.isEnabled(position);
|
||||
}
|
||||
@Override
|
||||
public long getItemId(int i) {
|
||||
return i;
|
||||
}
|
||||
@Override
|
||||
public int getCount() {
|
||||
return mTags.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getItem(int i) {
|
||||
|
||||
return mTags.get(mKeySet[i]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled(int position) {
|
||||
|
||||
return super.isEnabled(position);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getItemId(int i) {
|
||||
return i;
|
||||
}
|
||||
|
||||
public String getTagId(int i) {
|
||||
return mKeySet[i];
|
||||
}
|
||||
|
||||
@Override
|
||||
public View getView(int i, View convertView, ViewGroup parent) {
|
||||
String tag = getItem(i);
|
||||
TextView tv = (TextView) LayoutInflater.from(mContext).inflate(R.layout.drawer_list_item, parent, false);
|
||||
tv.setText(tag);
|
||||
convertView = tv;
|
||||
return convertView;
|
||||
}
|
||||
|
||||
public void updateTags(Map<String, String> tags) {
|
||||
this.mTags.clear();
|
||||
if (tags != null)
|
||||
this.mTags.putAll(tags);
|
||||
this.mKeySet = this.mTags.keySet().toArray(new String[mTags.size()]);
|
||||
}
|
||||
|
||||
public String getTagId(int i) {
|
||||
return mKeySet[i];
|
||||
}
|
||||
@Override
|
||||
public View getView(int i, View convertView, ViewGroup parent) {
|
||||
String tag = getItem(i);
|
||||
TextView tv = (TextView)LayoutInflater.from(mContext).inflate(R.layout.drawer_list_item, parent, false);
|
||||
tv.setText(tag);
|
||||
convertView = tv;
|
||||
return convertView;
|
||||
}
|
||||
public void updateTags(Map<String, String> tags) {
|
||||
this.mTags.clear();
|
||||
if(tags!=null)
|
||||
this.mTags.putAll(tags);
|
||||
this.mKeySet = this.mTags.keySet().toArray(new String[mTags.size()]);
|
||||
}
|
||||
//TODO: Nooooooooooo! this is kinda ugly to do it like that.
|
||||
public void updateTags(List<Tag> tags) {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
for(Tag tag : tags) {
|
||||
map.put(tag.getId(),tag.getName());
|
||||
for (Tag tag : tags) {
|
||||
map.put(tag.getId(), tag.getName());
|
||||
}
|
||||
this.updateTags(map);
|
||||
|
||||
|
|
|
|||
|
|
@ -23,31 +23,33 @@ public class AboutFragment extends Fragment {
|
|||
private String twitterLink = "https://twitter.com/habitica";
|
||||
|
||||
@OnClick(R.id.sourceCodeLink)
|
||||
public void openSourceCodePageByLabel(){
|
||||
public void openSourceCodePageByLabel() {
|
||||
openBrowserLink(androidSourceCodeLink);
|
||||
}
|
||||
|
||||
@OnClick(R.id.twitter)
|
||||
public void openTwitterPage(){
|
||||
public void openTwitterPage() {
|
||||
openBrowserLink(twitterLink);
|
||||
}
|
||||
|
||||
@OnClick(R.id.sourceCodeButton)
|
||||
public void openSourceCodePageByButton(){
|
||||
public void openSourceCodePageByButton() {
|
||||
openBrowserLink(androidSourceCodeLink);
|
||||
}
|
||||
|
||||
@OnClick(R.id.reportBug)
|
||||
public void sendBugReport(){ sendEmail("[Android] Bugreport"); }
|
||||
public void sendBugReport() {
|
||||
sendEmail("[Android] Bugreport");
|
||||
}
|
||||
|
||||
@OnClick(R.id.sendFeedback)
|
||||
public void sendFeedback(){
|
||||
public void sendFeedback() {
|
||||
sendEmail("[Android] Feedback");
|
||||
}
|
||||
|
||||
|
||||
@OnClick(R.id.googlePlayStoreButton)
|
||||
public void openGooglePlay(){
|
||||
public void openGooglePlay() {
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW);
|
||||
intent.setData(Uri.parse("market://details?id=com.habitrpg.android.habitica"));
|
||||
startActivity(intent);
|
||||
|
|
@ -72,7 +74,7 @@ public class AboutFragment extends Fragment {
|
|||
ButterKnife.inject(this, view);
|
||||
}
|
||||
|
||||
private void openBrowserLink(String url){
|
||||
private void openBrowserLink(String url) {
|
||||
Uri uriUrl = Uri.parse(url);
|
||||
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
|
||||
startActivity(launchBrowser);
|
||||
|
|
|
|||
|
|
@ -47,7 +47,7 @@ public class ChatListFragment extends Fragment implements SwipeRefreshLayout.OnR
|
|||
private String userId;
|
||||
private boolean isTavern;
|
||||
|
||||
public ChatListFragment(Context ctx, String groupId, APIHelper apiHelper, HabitRPGUser user, boolean isTavern){
|
||||
public ChatListFragment(Context ctx, String groupId, APIHelper apiHelper, HabitRPGUser user, boolean isTavern) {
|
||||
|
||||
this.ctx = ctx;
|
||||
this.groupId = groupId;
|
||||
|
|
@ -100,7 +100,7 @@ public class ChatListFragment extends Fragment implements SwipeRefreshLayout.OnR
|
|||
}
|
||||
|
||||
public void setRefreshEnabled(boolean enable) {
|
||||
if(swipeRefreshLayout != null){
|
||||
if (swipeRefreshLayout != null) {
|
||||
swipeRefreshLayout.setEnabled(enable);
|
||||
}
|
||||
}
|
||||
|
|
@ -122,7 +122,7 @@ public class ChatListFragment extends Fragment implements SwipeRefreshLayout.OnR
|
|||
for (int i = chatMessages.size() - 1; i >= 0; i--) {
|
||||
ChatMessage msg = chatMessages.get(i);
|
||||
|
||||
if(msg.flagCount >= 2){
|
||||
if (msg.flagCount >= 2) {
|
||||
chatMessages.remove(msg);
|
||||
}
|
||||
}
|
||||
|
|
@ -140,7 +140,7 @@ public class ChatListFragment extends Fragment implements SwipeRefreshLayout.OnR
|
|||
}
|
||||
|
||||
|
||||
private void showSnackbar(String msg, boolean negative){
|
||||
private void showSnackbar(String msg, boolean negative) {
|
||||
Snackbar snackbar = Snackbar.make(mRecyclerView, msg, Snackbar.LENGTH_LONG);
|
||||
|
||||
if (negative) {
|
||||
|
|
@ -153,7 +153,7 @@ public class ChatListFragment extends Fragment implements SwipeRefreshLayout.OnR
|
|||
snackbar.show();
|
||||
}
|
||||
|
||||
public void onEvent(final FlagChatMessageCommand cmd){
|
||||
public void onEvent(final FlagChatMessageCommand cmd) {
|
||||
apiHelper.apiService.flagMessage(cmd.groupId, cmd.chatMessage.id, new Callback<Void>() {
|
||||
@Override
|
||||
public void success(Void aVoid, Response response) {
|
||||
|
|
@ -167,7 +167,7 @@ public class ChatListFragment extends Fragment implements SwipeRefreshLayout.OnR
|
|||
});
|
||||
}
|
||||
|
||||
public void onEvent(final ToggleLikeMessageCommand cmd){
|
||||
public void onEvent(final ToggleLikeMessageCommand cmd) {
|
||||
apiHelper.apiService.likeMessage(cmd.groupId, cmd.chatMessage.id, new Callback<List<Void>>() {
|
||||
@Override
|
||||
public void success(List<Void> aVoid, Response response) {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,5 @@
|
|||
package com.habitrpg.android.habitica.ui.fragments;
|
||||
|
||||
import java.util.Calendar;
|
||||
|
||||
import android.app.DatePickerDialog;
|
||||
import android.app.DatePickerDialog.OnDateSetListener;
|
||||
import android.app.Dialog;
|
||||
|
|
@ -11,28 +9,30 @@ import android.content.DialogInterface.OnDismissListener;
|
|||
import android.os.Bundle;
|
||||
import android.support.v4.app.DialogFragment;
|
||||
|
||||
import java.util.Calendar;
|
||||
|
||||
public class DatePickerFragment extends DialogFragment {
|
||||
@Override
|
||||
public Dialog onCreateDialog(Bundle savedInstanceState) {
|
||||
// Use the current time as the default values for the picker
|
||||
final Calendar c = Calendar.getInstance();
|
||||
int year = c.get(Calendar.YEAR);
|
||||
int month = c.get(Calendar.MONTH);
|
||||
int day = c.get(Calendar.DAY_OF_MONTH);
|
||||
// Create a new instance of TimePickerDialog and return it
|
||||
Dialog d = new DatePickerDialog(getActivity(), (OnDateSetListener) getTargetFragment(), year, month, day);
|
||||
d.setOnDismissListener(new OnDismissListener() {
|
||||
|
||||
@Override
|
||||
public void onDismiss(DialogInterface dialog) {
|
||||
}
|
||||
});
|
||||
d.setOnCancelListener(new OnCancelListener() {
|
||||
@Override
|
||||
public void onCancel(DialogInterface dialog) {
|
||||
}
|
||||
});
|
||||
return d;
|
||||
}
|
||||
@Override
|
||||
public Dialog onCreateDialog(Bundle savedInstanceState) {
|
||||
// Use the current time as the default values for the picker
|
||||
final Calendar c = Calendar.getInstance();
|
||||
int year = c.get(Calendar.YEAR);
|
||||
int month = c.get(Calendar.MONTH);
|
||||
int day = c.get(Calendar.DAY_OF_MONTH);
|
||||
// Create a new instance of TimePickerDialog and return it
|
||||
Dialog d = new DatePickerDialog(getActivity(), (OnDateSetListener) getTargetFragment(), year, month, day);
|
||||
d.setOnDismissListener(new OnDismissListener() {
|
||||
|
||||
@Override
|
||||
public void onDismiss(DialogInterface dialog) {
|
||||
}
|
||||
});
|
||||
d.setOnCancelListener(new OnCancelListener() {
|
||||
@Override
|
||||
public void onCancel(DialogInterface dialog) {
|
||||
}
|
||||
});
|
||||
return d;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,7 +10,6 @@ import android.view.ViewGroup;
|
|||
|
||||
import com.habitrpg.android.habitica.R;
|
||||
import com.habitrpg.android.habitica.databinding.FragmentPartyInfoBinding;
|
||||
import com.habitrpg.android.habitica.ui.helpers.DataBindingUtils;
|
||||
import com.magicmicky.habitrpgwrapper.lib.models.Group;
|
||||
import com.magicmicky.habitrpgwrapper.lib.models.QuestContent;
|
||||
|
||||
|
|
@ -37,20 +36,20 @@ public class PartyInformationFragment extends Fragment {
|
|||
|
||||
viewBinding = DataBindingUtil.bind(view);
|
||||
|
||||
if(group != null){
|
||||
if (group != null) {
|
||||
setGroup(group);
|
||||
}
|
||||
|
||||
return view;
|
||||
}
|
||||
|
||||
public void setGroup(Group group){
|
||||
public void setGroup(Group group) {
|
||||
if (viewBinding != null) {
|
||||
viewBinding.setParty(group);
|
||||
}
|
||||
}
|
||||
|
||||
public void setQuestContent(QuestContent quest){
|
||||
public void setQuestContent(QuestContent quest) {
|
||||
if (viewBinding != null) {
|
||||
viewBinding.setQuest(quest);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ public class PartyMemberListFragment extends Fragment {
|
|||
|
||||
private PartyMemberRecyclerViewAdapter viewAdapter;
|
||||
|
||||
public PartyMemberListFragment(Context ctx, Group group){
|
||||
public PartyMemberListFragment(Context ctx, Group group) {
|
||||
this.ctx = ctx;
|
||||
this.group = group;
|
||||
|
||||
|
|
@ -60,12 +60,12 @@ public class PartyMemberListFragment extends Fragment {
|
|||
mRecyclerView.setLayoutManager(new LinearLayoutManager(ctx));
|
||||
mRecyclerView.setAdapter(viewAdapter);
|
||||
|
||||
if(group != null){
|
||||
if (group != null) {
|
||||
setMemberList(group.members);
|
||||
}
|
||||
}
|
||||
|
||||
public void setMemberList(ArrayList<HabitRPGUser> members){
|
||||
public void setMemberList(ArrayList<HabitRPGUser> members) {
|
||||
viewAdapter.setMemberList(members);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ public class DataBindingUtils {
|
|||
|
||||
@BindingAdapter("bind:imageName")
|
||||
public static void loadImage(ImageView view, String imageName) {
|
||||
if(view.getVisibility() == View.VISIBLE) {
|
||||
if (view.getVisibility() == View.VISIBLE) {
|
||||
Picasso.with(view.getContext())
|
||||
.load("https://habitica-assets.s3.amazonaws.com/mobileApp/images/" + imageName + ".png")
|
||||
.into(view);
|
||||
|
|
@ -73,7 +73,7 @@ public class DataBindingUtils {
|
|||
|
||||
@BindingAdapter("app:layout_weight")
|
||||
public static void setLayoutWeight(View view, float weight) {
|
||||
LinearLayout.LayoutParams layout = (LinearLayout.LayoutParams)view.getLayoutParams();
|
||||
LinearLayout.LayoutParams layout = (LinearLayout.LayoutParams) view.getLayoutParams();
|
||||
|
||||
layout.weight = weight;
|
||||
|
||||
|
|
@ -82,7 +82,7 @@ public class DataBindingUtils {
|
|||
|
||||
@BindingAdapter("app:layout_weight_anim")
|
||||
public static void setLayoutWeightAnim(View view, float weight) {
|
||||
if(weight == 0.0f || weight == 1.0f){
|
||||
if (weight == 0.0f || weight == 1.0f) {
|
||||
setLayoutWeight(view, weight);
|
||||
return;
|
||||
}
|
||||
|
|
@ -97,7 +97,7 @@ public class DataBindingUtils {
|
|||
public static void setRoundedBackground(View view, int color) {
|
||||
Drawable drawable = view.getResources().getDrawable(R.drawable.layout_rounded_bg);
|
||||
drawable.setColorFilter(color, PorterDuff.Mode.MULTIPLY);
|
||||
if(Build.VERSION.SDK_INT < 16) {
|
||||
if (Build.VERSION.SDK_INT < 16) {
|
||||
view.setBackgroundDrawable(drawable);
|
||||
} else {
|
||||
view.setBackground(drawable);
|
||||
|
|
@ -106,7 +106,7 @@ public class DataBindingUtils {
|
|||
|
||||
@BindingAdapter("app:rounded_background_int")
|
||||
public static void setRoundedBackgroundInt(View view, int color) {
|
||||
if(color != 0){
|
||||
if (color != 0) {
|
||||
setRoundedBackground(view, view.getResources().getColor(color));
|
||||
}
|
||||
}
|
||||
|
|
@ -122,7 +122,7 @@ public class DataBindingUtils {
|
|||
this.view = view;
|
||||
this.targetWeight = targetWeight;
|
||||
|
||||
layoutParams = (LinearLayout.LayoutParams)view.getLayoutParams();
|
||||
layoutParams = (LinearLayout.LayoutParams) view.getLayoutParams();
|
||||
initializeWeight = layoutParams.weight;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -18,9 +18,9 @@ public abstract class Debounce {
|
|||
this.checkDelay = checkDelay;
|
||||
}
|
||||
|
||||
public void hit(){
|
||||
public void hit() {
|
||||
lastHit = System.currentTimeMillis();
|
||||
if(this.timer != null){
|
||||
if (this.timer != null) {
|
||||
this.timer.cancel();
|
||||
this.timer = null;
|
||||
}
|
||||
|
|
@ -28,8 +28,8 @@ public abstract class Debounce {
|
|||
this.timer.schedule(new DebounceTask(this), 0, checkDelay);
|
||||
}
|
||||
|
||||
private void checkExecute(){
|
||||
if((System.currentTimeMillis() - lastHit) > debounceDelay){
|
||||
private void checkExecute() {
|
||||
if ((System.currentTimeMillis() - lastHit) > debounceDelay) {
|
||||
this.timer.cancel();
|
||||
this.timer = null;
|
||||
execute();
|
||||
|
|
|
|||
|
|
@ -15,15 +15,17 @@ public class BitmapUtils {
|
|||
} else {
|
||||
path = Environment.getDownloadCacheDirectory().getAbsolutePath();
|
||||
}
|
||||
return path+"/HabiticaImageCache";
|
||||
return path + "/HabiticaImageCache";
|
||||
}
|
||||
|
||||
public static Bitmap loadFromFile(String filename) {
|
||||
try {
|
||||
filename = getSavePath() +"/"+ filename;
|
||||
filename = getSavePath() + "/" + filename;
|
||||
|
||||
File f = new File(filename);
|
||||
if (!f.exists()) { return null; }
|
||||
if (!f.exists()) {
|
||||
return null;
|
||||
}
|
||||
Bitmap tmp = BitmapFactory.decodeFile(filename);
|
||||
return tmp;
|
||||
} catch (Exception e) {
|
||||
|
|
@ -31,18 +33,19 @@ public class BitmapUtils {
|
|||
}
|
||||
}
|
||||
|
||||
public static void saveToFile(String filename,Bitmap bmp) {
|
||||
public static void saveToFile(String filename, Bitmap bmp) {
|
||||
try {
|
||||
File myDir = new File(getSavePath());
|
||||
boolean res = myDir.mkdirs();
|
||||
|
||||
filename = getSavePath() +"/"+ filename;
|
||||
filename = getSavePath() + "/" + filename;
|
||||
|
||||
FileOutputStream out = new FileOutputStream(filename);
|
||||
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
|
||||
out.flush();
|
||||
out.close();
|
||||
} catch(Exception e) {}
|
||||
} catch (Exception e) {
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean hasSDCard() {
|
||||
|
|
|
|||
|
|
@ -41,12 +41,12 @@ public class UserPicture {
|
|||
this.context = context;
|
||||
}
|
||||
|
||||
public void removeTask(){
|
||||
public void removeTask() {
|
||||
numOfTasks.decrementAndGet();
|
||||
}
|
||||
|
||||
public void allTasksComplete(){
|
||||
if(this.numOfTasks.get() == 0){
|
||||
public void allTasksComplete() {
|
||||
if (this.numOfTasks.get() == 0) {
|
||||
BitmapFactory.Options o = new BitmapFactory.Options();
|
||||
o.inScaled = false;
|
||||
|
||||
|
|
@ -95,7 +95,7 @@ public class UserPicture {
|
|||
// get layer hash value
|
||||
String fullLayerString = "";
|
||||
|
||||
for(String l : layerNames){
|
||||
for (String l : layerNames) {
|
||||
fullLayerString = fullLayerString.concat(l);
|
||||
}
|
||||
|
||||
|
|
@ -106,7 +106,7 @@ public class UserPicture {
|
|||
Bitmap cache = BitmapUtils.loadFromFile(currentCacheFileName);
|
||||
|
||||
// yes => load image to bitmap
|
||||
if(cache != null){
|
||||
if (cache != null) {
|
||||
imageView.setImageBitmap(cache);
|
||||
return;
|
||||
}
|
||||
|
|
@ -117,19 +117,19 @@ public class UserPicture {
|
|||
for (String layer : layerNames) {
|
||||
layers.add(0);
|
||||
SpriteTarget target = new SpriteTarget(layerNumber, layer);
|
||||
Picasso.with(this.context).load("https://habitica-assets.s3.amazonaws.com/mobileApp/images/"+ layer +".png").into(target);
|
||||
Picasso.with(this.context).load("https://habitica-assets.s3.amazonaws.com/mobileApp/images/" + layer + ".png").into(target);
|
||||
layerNumber = layerNumber + 1;
|
||||
}
|
||||
}
|
||||
|
||||
private static String generateHashCode(String value){
|
||||
private static String generateHashCode(String value) {
|
||||
|
||||
MessageDigest md = null;
|
||||
byte[] digest = new byte[0];
|
||||
try {
|
||||
md = MessageDigest.getInstance("MD5");
|
||||
|
||||
md.update(value.getBytes());
|
||||
md.update(value.getBytes());
|
||||
digest = md.digest();
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
|
|
@ -139,9 +139,10 @@ public class UserPicture {
|
|||
}
|
||||
|
||||
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
|
||||
|
||||
public static String bytesToHex(byte[] bytes) {
|
||||
char[] hexChars = new char[bytes.length * 2];
|
||||
for ( int j = 0; j < bytes.length; j++ ) {
|
||||
for (int j = 0; j < bytes.length; j++) {
|
||||
int v = bytes[j] & 0xFF;
|
||||
hexChars[j * 2] = hexArray[v >>> 4];
|
||||
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
|
||||
|
|
@ -149,7 +150,7 @@ public class UserPicture {
|
|||
return new String(hexChars);
|
||||
}
|
||||
|
||||
private void modifyCanvas(Bitmap img, Canvas canvas, Integer layerNumber) {
|
||||
private void modifyCanvas(Bitmap img, Canvas canvas, Integer layerNumber) {
|
||||
Paint paint = new Paint();
|
||||
paint.setFilterBitmap(false);
|
||||
|
||||
|
|
@ -162,21 +163,21 @@ public class UserPicture {
|
|||
}
|
||||
|
||||
if (this.hasMount && !((this.hasBackground && layerNumber == 1) ||
|
||||
(!this.hasBackground && layerNumber == 0) ||
|
||||
(this.hasPet && layerNumber == this.layers.size()-2) ||
|
||||
(!this.hasPet && layerNumber == this.layers.size()-1)
|
||||
(!this.hasBackground && layerNumber == 0) ||
|
||||
(this.hasPet && layerNumber == this.layers.size() - 2) ||
|
||||
(!this.hasPet && layerNumber == this.layers.size() - 1)
|
||||
)) {
|
||||
yOffset = 0;
|
||||
}
|
||||
|
||||
if (this.hasPet && layerNumber == this.layers.size()-1) {
|
||||
if (this.hasPet && layerNumber == this.layers.size() - 1) {
|
||||
xOffset = 0;
|
||||
yOffset = 43;
|
||||
}
|
||||
|
||||
canvas.drawBitmap(img, new Rect(0, 0, img.getWidth(), img.getHeight()),
|
||||
new Rect(xOffset, yOffset, img.getWidth()+xOffset, img.getHeight()+yOffset), paint);
|
||||
}
|
||||
new Rect(xOffset, yOffset, img.getWidth() + xOffset, img.getHeight() + yOffset), paint);
|
||||
}
|
||||
|
||||
private class SpriteTarget implements Target {
|
||||
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ public class SimpleWidget extends AppWidgetProvider {
|
|||
|
||||
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
|
||||
@Override
|
||||
public void onAppWidgetOptionsChanged (Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions) {
|
||||
public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions) {
|
||||
Log.v(LOG, "onAppWidgetOptionChanged call");
|
||||
Bundle options = appWidgetManager.getAppWidgetOptions(appWidgetId);
|
||||
|
||||
|
|
@ -59,6 +59,7 @@ public class SimpleWidget extends AppWidgetProvider {
|
|||
/**
|
||||
* Determine appropriate view based on width provided.<br/>
|
||||
* see http://stackoverflow.com/questions/14270138/dynamically-adjusting-widgets-content-and-layout-to-the-size-the-user-defined-t
|
||||
*
|
||||
* @param minWidth
|
||||
* @param minHeight
|
||||
* @return
|
||||
|
|
@ -97,7 +98,4 @@ public class SimpleWidget extends AppWidgetProvider {
|
|||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,13 +4,9 @@ import android.app.PendingIntent;
|
|||
import android.app.Service;
|
||||
import android.appwidget.AppWidgetManager;
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.res.Resources;
|
||||
import android.graphics.Bitmap;
|
||||
import android.os.IBinder;
|
||||
import android.util.Log;
|
||||
import android.util.TypedValue;
|
||||
import android.widget.RemoteViews;
|
||||
|
||||
import com.habitrpg.android.habitica.APIHelper;
|
||||
|
|
@ -19,11 +15,11 @@ import com.habitrpg.android.habitica.MainActivity;
|
|||
import com.habitrpg.android.habitica.R;
|
||||
import com.habitrpg.android.habitica.callbacks.HabitRPGUserCallback;
|
||||
import com.habitrpg.android.habitica.prefs.PrefsActivity;
|
||||
import com.habitrpg.android.habitica.userpicture.UserPicture;
|
||||
import com.magicmicky.habitrpgwrapper.lib.models.HabitRPGUser;
|
||||
|
||||
/**
|
||||
* The service that should update the simple widget
|
||||
*
|
||||
* @see com.habitrpg.android.habitica.widget.SimpleWidget
|
||||
* Created by Mickael on 01/11/13.
|
||||
*/
|
||||
|
|
@ -45,7 +41,7 @@ public class UpdateWidgetService extends Service implements HabitRPGUserCallback
|
|||
Log.w(LOG, "Direct" + String.valueOf(allWidgetIds2.length));
|
||||
|
||||
HostConfig hc = PrefsActivity.fromContext(this);
|
||||
if(hc!=null && hc.getApi()!=null && !hc.getApi().equals("") && hc.getUser()!=null && !hc.getUser().equals("") ) {
|
||||
if (hc != null && hc.getApi() != null && !hc.getApi().equals("") && hc.getUser() != null && !hc.getUser().equals("")) {
|
||||
this.apiHelper = new APIHelper(this, hc);
|
||||
apiHelper.retrieveUser(new HabitRPGUserCallback(this));
|
||||
for (int widgetId : allWidgetIds) {
|
||||
|
|
@ -53,23 +49,23 @@ public class UpdateWidgetService extends Service implements HabitRPGUserCallback
|
|||
appWidgetManager.updateAppWidget(widgetId, remoteViews);
|
||||
}
|
||||
} else {
|
||||
Log.w(LOG,"HostConfig is null");
|
||||
Log.w(LOG, "HostConfig is null");
|
||||
for (int widgetId : allWidgetIds) {
|
||||
RemoteViews remoteViews = new RemoteViews(this.getPackageName(), R.layout.simple_widget);
|
||||
RemoteViews textConnect = new RemoteViews(this.getPackageName(),R.layout.simple_textview);
|
||||
textConnect.setTextViewText(R.id.TV_simple_textview,getString(R.string.please_connect));
|
||||
RemoteViews textConnect = new RemoteViews(this.getPackageName(), R.layout.simple_textview);
|
||||
textConnect.setTextViewText(R.id.TV_simple_textview, getString(R.string.please_connect));
|
||||
remoteViews.removeAllViews(R.id.LL_header);
|
||||
remoteViews.addView(R.id.LL_header, textConnect);
|
||||
|
||||
|
||||
Intent clickIntent = new Intent(this.getApplicationContext(),SimpleWidget.class);
|
||||
Intent clickIntent = new Intent(this.getApplicationContext(), SimpleWidget.class);
|
||||
clickIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
|
||||
clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);
|
||||
PendingIntent updateIntent = PendingIntent.getBroadcast(this, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
remoteViews.setOnClickPendingIntent(R.id.BT_refresh, updateIntent);
|
||||
|
||||
Intent openAppIntent = new Intent(this.getApplicationContext(), MainActivity.class);
|
||||
PendingIntent openApp = PendingIntent.getActivity(this,0,openAppIntent,PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
PendingIntent openApp = PendingIntent.getActivity(this, 0, openAppIntent, PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
remoteViews.setOnClickPendingIntent(R.id.widget_main_view, openApp);
|
||||
appWidgetManager.updateAppWidget(widgetId, remoteViews);
|
||||
|
||||
|
|
@ -81,18 +77,18 @@ public class UpdateWidgetService extends Service implements HabitRPGUserCallback
|
|||
}
|
||||
|
||||
private void updateData(HabitRPGUser user, AppWidgetManager appWidgetManager) {
|
||||
ComponentName thisWidget = new ComponentName(this,SimpleWidget.class);
|
||||
ComponentName thisWidget = new ComponentName(this, SimpleWidget.class);
|
||||
int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
|
||||
for (int widgetId : allWidgetIds) {
|
||||
RemoteViews remoteViews = new RemoteViews(this.getPackageName(),R.layout.simple_widget);
|
||||
RemoteViews remoteViews = new RemoteViews(this.getPackageName(), R.layout.simple_widget);
|
||||
remoteViews.setTextViewText(R.id.TV_HP, "" + user.getStats().getHp().intValue() + "/" + (int) user.getStats().getMaxHealth() + " " + this.getString(R.string.HP_default));
|
||||
remoteViews.setTextViewText(R.id.TV_XP, "" + user.getStats().getExp().intValue() + "/" + (int) user.getStats().getToNextLevel() + " " + this.getString(R.string.XP_default));
|
||||
//remoteViews.setImageViewBitmap(R.id.IMG_ProfilePicture, dealWithUserPicture(user,this));
|
||||
remoteViews.setProgressBar(R.id.V_HPBar,(int)user.getStats().getMaxHealth(), user.getStats().getHp().intValue(), false);
|
||||
remoteViews.setProgressBar(R.id.V_XPBar,(int)user.getStats().getToNextLevel(),user.getStats().getExp().intValue(), false);
|
||||
remoteViews.setProgressBar(R.id.V_HPBar, (int) user.getStats().getMaxHealth(), user.getStats().getHp().intValue(), false);
|
||||
remoteViews.setProgressBar(R.id.V_XPBar, (int) user.getStats().getToNextLevel(), user.getStats().getExp().intValue(), false);
|
||||
|
||||
// If user click on refresh: refresh
|
||||
Intent clickIntent = new Intent(this.getApplicationContext(),SimpleWidget.class);
|
||||
Intent clickIntent = new Intent(this.getApplicationContext(), SimpleWidget.class);
|
||||
clickIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
|
||||
clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);
|
||||
PendingIntent updateIntent = PendingIntent.getBroadcast(this, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
|
|
@ -100,11 +96,11 @@ public class UpdateWidgetService extends Service implements HabitRPGUserCallback
|
|||
|
||||
//If user click on life and xp: open the app
|
||||
Intent openAppIntent = new Intent(this.getApplicationContext(), MainActivity.class);
|
||||
PendingIntent openApp = PendingIntent.getActivity(this,0,openAppIntent,PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
PendingIntent openApp = PendingIntent.getActivity(this, 0, openAppIntent, PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
remoteViews.setOnClickPendingIntent(R.id.LL_header, openApp);
|
||||
remoteViews.setOnClickPendingIntent(R.id.IMG_ProfilePicture, openApp);
|
||||
|
||||
appWidgetManager.updateAppWidget(widgetId, remoteViews);
|
||||
appWidgetManager.updateAppWidget(widgetId, remoteViews);
|
||||
|
||||
|
||||
//If user click on the
|
||||
|
|
@ -120,7 +116,7 @@ public class UpdateWidgetService extends Service implements HabitRPGUserCallback
|
|||
|
||||
@Override
|
||||
public void onUserReceived(HabitRPGUser user) {
|
||||
this.updateData(user,appWidgetManager);
|
||||
this.updateData(user, appWidgetManager);
|
||||
|
||||
}
|
||||
|
||||
|
|
@ -128,30 +124,4 @@ public class UpdateWidgetService extends Service implements HabitRPGUserCallback
|
|||
public void onUserFail() {
|
||||
//TODO
|
||||
}
|
||||
|
||||
/*
|
||||
private Bitmap dealWithUserPicture(HabitRPGUser look, Context c) {
|
||||
UserPicture up = new UserPicture(look);
|
||||
Resources r = getResources();
|
||||
int w = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, r.getDimension(R.dimen.avatar_width), r.getDisplayMetrics());
|
||||
int h = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, r.getDimension(R.dimen.avatar_height), r.getDisplayMetrics());
|
||||
Bitmap img = up.getPicture();
|
||||
return Bitmap.createScaledBitmap(img, w,h,false);
|
||||
}
|
||||
*/
|
||||
//
|
||||
//
|
||||
// @Override public void onNewUser(String s, String s2) {}
|
||||
// @Override public void onUserReceived(User user) {
|
||||
// Log.i(LOG,"User received");
|
||||
// updateData(user, appWidgetManager);
|
||||
// }
|
||||
// @Override public void onUserItemsReceived(UserLook.UserItems userItems, Reward.SpecialReward specialReward) {}
|
||||
// @Override public void onPostResult(double v, double v2, double v3, double v4, double v5) {}
|
||||
// @Override public void onPreResult() {}
|
||||
// @Override public void onError(HabitRPGException e) {}
|
||||
// @Override public void onPostTaskAnswer(Task habitItem) {}
|
||||
// @Override public void onDeletedTask(Task habitItem) {}
|
||||
// @Override public void onEditTaskAnswer(Task habitItem) {}
|
||||
// @Override public void onUserConnected(String s, String s2) {}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue