What ActivityProxyHelper class actually do? - android

I need help to understand what is going on in the following two classes. The first activity class is the launching activity.
public class UnityPlayerNativeActivity
extends com.unity3d.player.UnityPlayerNativeActivity
{
private ActivityProxyObjectHelper _proxyHelper;
protected void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
try
{
this._proxyHelper = new ActivityProxyObjectHelper(this);
this._proxyHelper.onCreate(paramBundle);
return;
}
catch (Exception paramBundle)
{
Log.i("Prime31", "Failed to create proxyHelper: " + paramBundle.getMessage());
}
}
}
And the second class is :
public class ActivityProxyObjectHelper
{
private Activity _context;
private List<Class<?>> _proxyClasses = new ArrayList();
public ActivityProxyObjectHelper(Activity paramActivity)
{
this._context = paramActivity;
}
protected void onCreate(Bundle paramBundle)
{
for (;;)
{
try
{
localObject1 = this._context.getPackageManager().getApplicationInfo(this._context.getPackageName(), 128).metaData;
localObject2 = ((Bundle)localObject1).keySet().iterator();
bool = ((Iterator)localObject2).hasNext();
if (bool) {
continue;
}
}
catch (PackageManager.NameNotFoundException localNameNotFoundException)
{
Object localObject1;
boolean bool;
String str;
Log.i("Prime31", "Failed to load meta-data, NameNotFound: " + localNameNotFoundException.getMessage());
continue;
}
catch (NullPointerException localNullPointerException)
{
Log.e("Prime31", "Failed to load meta-data, NullPointer: " + localNullPointerException.getMessage());
continue;
Object localObject2 = (Class)localNullPointerException.next();
try
{
((Class)localObject2).getMethod("onCreate", new Class[] { Bundle.class }).invoke(null, new Object[] { paramBundle });
}
catch (Exception localException1) {}
continue;
}
if (((Iterator)localObject1).hasNext()) {
continue;
}
return;
str = (String)((Iterator)localObject2).next();
}
}
}
I need to understand what is that ActivityProxyObjectHelper class doing initially after the launching activity gets called. What is the purpose of this class? Why it is trying to get metadata? What is localObject1 and localObject2 trying to do?

Related

Why NullPointerException occurs when calling getColor from single instance?

google play crash log:
Caused by: java.lang.NullPointerException:
at com.manager.loader.SkinManager.getColor (SkinManager.java:28)
at base.util.ui.titlebar.BaseTitlebarFragmentActivity.getImmersiveColor (BaseTitlebarFragmentActivity.java:6)
at base.util.ui.titlebar.BaseTitlebarFragmentActivity.onCreate (BaseTitlebarFragmentActivity.java)
activity:
public abstract class BaseTitlebarFragmentActivity extends FragmentActivity {
public void onCreate(Bundle savedInstanceState) {
setImmersive(getImmersiveColor());
super.onCreate(savedInstanceState);
}
protected int getImmersiveColor(){
return SkinManager.getInstance().getColor(R.color.v8_common_title_bg);
}
SkinManager:
public class SkinManager implements ISkinLoader {
private static final Object synchronizedLock = new Object();
private static SkinManager instance;
private SkinManager() { }
public static SkinManager getInstance() {
if (instance == null) {
synchronized (synchronizedLock) {
if (instance == null){
instance = new SkinManager();
}
}
}
return instance;
}
public int getColor(int resId){
int originColor;
if(mResources == null || isDefaultSkin){
try {
originColor = context.getResources().getColor(resId);
return originColor;
} catch (Exception e) {
}
}
int trueColor = 0;
try{
trueColor = mResources.getColor(resId);
}catch(Exception e){
originColor = context.getResources().getColor(resId);
trueColor = originColor;
}
return trueColor;
}
App:
public class App extends BaseApplication {
public void onCreate() {
super.onCreate();
initSkins();
}
private void initSkins() {
AttrFactory.addSupportAttr("iiv_background_color", new IconicsImageViewBgColorAttr());
AttrFactory.addSupportAttr("iiv_color", new IconicsImageViewColorAttr());
AttrFactory.addSupportAttr("matProg_barColor", new ProgressWheelBarColorAttr());
AttrFactory.addSupportAttr("progressDrawable", new ProgressBarDrawableAttr());
AttrFactory.addSupportAttr("indeterminateDrawable", new ProgressBar2DrawableAttr());
AttrFactory.addSupportAttr("button", new CheckBoxButtonDrawableAttr());
SkinManager.getInstance().init(this);
SkinManager.getInstance().setUpSkinFile();
if (!ProcessManager.isMainProcess(getContext())) {
SkinManager.getInstance().registerProcessSkinLoadReceiver();
}
}
Although it's impossible as crash log shows, I will refactoring getColor to this and have a look:
public int getColor(int resId){
if(mResources == null || isDefaultSkin){
try {
int originColor = context.getResources().getColor(resId);
return originColor;
} catch (Exception ignored) {
}
}
try{
int trueColor = mResources.getColor(resId);
return trueColor;
} catch(Exception ignored) {
}
try {
int originColor = context.getResources().getColor(resId);
return originColor;
} catch (Exception ignored) {
}
return 0;
}

Retrofit enqueue gets dismissed on orientation change

I am trying to upload plain text and image to the api using RetroFit. I want make sure the request continues to execute on orientation change. To do this, I have encapsulated the RetroFit api call inside a Headless fragment. This works fine when I try to upload an image. The request stops and resumes on device rotation. However it just gets cancelled on a text upload.
The only difference between the two uploads is that for image upload I use execute() and for text I use enqueue(). However, if I try to use execute() with the text, it still does not work.
Below is some code :-
UpdateTaskHelper (Headless fragment)
public static class UploadTaskHelper extends Fragment
{
private UploadAsync uploadTask;
private ProgressDialog m_loadingp;
public static UploadTaskHelper newInstance()
{
return new UploadTaskHelper();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public void onDestroy()
{
Log.d(getClass().getName(), "[onDestroy]");
super.onDestroy();
if (uploadTask != null)
{
uploadTask.cancel(true);
}
}
public void startUpload(ActionActivity actionActivity, boolean shouldTakePhoto, boolean isTextNote, String noteContent)
{
uploadTask = new UploadAsync(actionActivity, shouldTakePhoto, isText, noteContent);
uploadTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private static class UploadAsync extends AsyncTask<Void, Void, Void>
{
private Bitmap m_bitmap = null;
private Pair<Boolean, String> m_errorPair;
private File m_uploadedFile = null;
private WeakReference<ActionActivity> m_weakActivity;
private boolean shouldTakePhoto;
private boolean isTextNote;
private java.io.File m_capturedImageFile;
UploadAsync(#NonNull ActionActivity activity, boolean shouldTakePhoto, boolean isTextNote, String textNoteContent)
{
this.m_weakActivity = new WeakReference<>(activity);
this.shouldTakePhoto = shouldTakePhoto;
this.isTextNote = isTextNote;
}
#Override
protected Void doInBackground(Void... params)
{
try
{
final ActionActivity activity = this.m_weakActivity.get();
activity.m_fileAPIWrapper = new FileAPIWrapper(new IHttpEventTracker<File>()
{
#Override
public void getCallProgress(int progress) {}
#Override
public void onCallFail(#NonNull String cause, #NonNull Throwable t, #Nullable ResponseBody responseBody)
{
m_errorPair = new Pair<>(true, t.getLocalizedMessage());
}
#Override
public void onCallSuccess(#NonNull RealmList<File> models)
{
m_errorPair = new Pair<>(false, AppConstants.EMPTY_STRING);
m_uploadedFile = models.get(0);
}
});
if(!isTextNote)
{
final java.io.File storageDir = new java.io.File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + java.io.File.separator + activity.getPackageName()
+ java.io.File.separator + "-" + java.io.File.separator);
if (!storageDir.exists())
{
storageDir.mkdirs();
}
this.m_capturedImageFile = java.io.File.createTempFile("IMG_" + System.currentTimeMillis(), ".jpg", storageDir);
final FileOutputStream outStream = new FileOutputStream(this.m_capturedImageFile);
this.m_bitmap.compress(Bitmap.CompressFormat.JPEG, 50, outStream);
outStream.flush();
outStream.close();
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
this.m_bitmap.compress(Bitmap.CompressFormat.JPEG, 50, stream);
activity.m_fileAPIWrapper.postImage(RequestBody.create(MediaType.parse("image/jpeg"), stream.toByteArray()));
stream.flush();
stream.close();
}
else
{
activity.m_fileAPIWrapper.postTextNote(RequestBody.create(MediaType.parse("multipart/raw"), activity.m_addContentNoteEdit.getText()
.toString()));
}
}
catch (Exception e)
{
e.printStackTrace();
this.m_errorPair = new Pair<>(true, e.toString());
}
return null;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
activity.m_loading.show();
}
#Override
protected void onPostExecute(Void aVoid)
{
super.onPostExecute(aVoid);
}
}
}
Network calls :-
public void postImage(#NonNull RequestBody reqFile) {
if (m_eventTracker != null) {
final ResponseToken token = NetworkUtil.getAccessToken();
if (getService() != null && m_httpOperationWrapper != null && token != null) {
m_call = getService().postImage(token.getTokenType() + " " + token.getAccessToken(), NetworkUtil.X_VERSION,
"filename=IMG_" + System.currentTimeMillis(), "image/jpeg", reqFile);
m_httpOperationWrapper.initCall(m_call, this, true);
} else {
m_eventTracker.onCallFail(AppConstants.BAD_REQUEST, new Throwable("Something went wrong, Try again later!"), null);
}
}
}
/**
* Execute HTTP call to post a new text note.
*/
public void postTextNote(#NonNull RequestBody requestBody) {
if (m_eventTracker != null) {
final ResponseToken token = NetworkUtil.getAccessToken();
if (getService() != null && m_httpOperationWrapper != null && token != null) {
m_call = getService().postFile(token.getTokenType() + " " + token.getAccessToken(), NetworkUtil.X_VERSION,
"filename=" + token.getOwnerId() + "_text_note_" + System.currentTimeMillis(), "text/plain",
requestBody);
m_httpOperationWrapper.initCall(m_call, this);
} else {
m_eventTracker.onCallFail(AppConstants.BAD_REQUEST, new Throwable("Something went wrong, Try again later!"), null);
}
}
}
public void initCall(#NonNull Call<ContentResponse> call, #NonNull IHttpOperationCallback callback, final boolean isSynchronousCall) {
m_callback = callback;
try {
if (NetworkUtil.isNetworkAvailable()) {
if (isSynchronousCall) {
m_executeRequest(call);
} else {
m_enqueueRequest(call);
}
} else {
m_callback.onFailure(call, new Throwable(AppConstants.NO_INTERNET), null);
}
} catch (Exception e) {
m_callback.onFailure(call, e.fillInStackTrace(), null);
}
}
private void m_enqueueRequest(#NonNull Call<ContentResponse> call) {
call.enqueue(new Callback<ContentResponse>() {
#SuppressWarnings("ConstantConditions")
#Override
public void onResponse(#NonNull Call<ContentResponse> call, #NonNull Response<ContentResponse> response) {
if (m_callback != null) {
if (!Util.isValidResponse(response)) {
String error = "Status: " + response.code() + " " + response.message();
m_callback.onFailure(call, new Throwable(
response.code() == HttpURLConnection.HTTP_UNAUTHORIZED ? AppConstants.UNAUTHORIZED : error), response.errorBody());
return;
}
m_callback.onSuccess(call, response.body());
}
}
#Override
public void onFailure(#NonNull Call<ContentResponse> call, #NonNull Throwable t) {
if (m_callback != null) {
m_callback.onFailure(call, t, null);
}
}
});
}
#WorkerThread
private void m_executeRequest(#NonNull Call<ContentResponse> call) {
try {
Response<ContentResponse> response = call.execute();
if (m_callback != null) {
if (!Util.isValidResponse(response)) {
String error = "Status: " + response.code() + " " + response.message();
m_callback.onFailure(call,
new Throwable(response.code() == HttpURLConnection.HTTP_UNAUTHORIZED ? AppConstants.UNAUTHORIZED : error),
response.errorBody());
return;
}
//noinspection ConstantConditions
m_callback.onSuccess(call, response.body());
}
} catch (IOException | RuntimeException e) {
e.printStackTrace();
if (m_callback != null) {
m_callback.onFailure(call, e.fillInStackTrace(), null);
}
}
}
How can I get the same behaviour for the text note? Any help is appreciated.
When you use enqueue your request sent async, and the orientation change destroys the activity and cancels your response code scope.
You should consider move the request code into a ViewModel class which is part of the MVVM architecture. The ViewModel would make the request even after orientation change and keep the data inside it, then you could access its data after the activity is re-created.

Android Database in AsyncTask in Fragment

I have a DbHelper Class which extends SQLiteOpenHelper.
I do Some Download and update the Database inside an Asynctask.
Inside an activity i got no problem and code works fine,
but when i use the ASynctask class inside a fragment problems occurs.
usually wherever i use a context an Exception happened, Especially with dbHelper.ClearDB()
Error:
DB Read ERROR:java.lang.NullPointerException:
Attempt to invoke virtual method 'java.util.ArrayList x.database.DBHelper.getAllItems()' on a null object reference
Here's the code :
public class StaggeredFragment extends Fragment
{
private DBHelper dbHelper;
private SharedPreferences preferences;
private ArrayList<DisItem> savedData;
private final String LINK1 = "myLink";
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dbHelper = new DBHelper(getActivity().getApplicationContext());
preferences = getActivity().getSharedPreferences("pid", Context.MODE_PRIVATE);
new LoaderAsyncTask("ALL").execute();
}
class LoaderAsyncTask extends AsyncTask<Void, Void, Boolean> {
String brand;
LoaderAsyncTask(String brand) {
this.brand = brand;
}
#Override
protected Boolean doInBackground(Void... params) {
Log.d(TAG,"RUnning");
String fetched;
InputStream is = null;
//Store Current Data before Sync
try {
savedData = dbHelper.getAllItems();
}catch (Exception e)
{
Log.d(TAG,"DB Read ERROR:"+e.toString());
return false;
}
try {
dbHelper.ClearDB();
}catch (Exception e)
{
Log.d(TAG,"DB Clear ERROR:"+e.toString());
return false;
}
// Open connection to server for html
try {
is = urlStream(LINK1);
} catch (Exception e) {
Log.e(TAG, "HTTP Error " + e.toString());
return false;
}
// Fetch HTML Data
try {
fetched = readIt(is);
// Log.d("fetched", fetched);
} catch (Exception e) {
Log.e(TAG, "Buffer Error " + e.toString());
return false;
}
// Parsing JSON
try {
if (!fetched.isEmpty())
InitialsJson(fetched);
}catch (JSONException e) {
Log.e(TAG, "JSON Error " + e.toString());
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if(!aBoolean)
RestoreData();
}
}
private void InitialsJson(String fetched) throws JSONException
{
JSONObject jsonObject = new JSONObject(fetched);
if (jsonObject.getInt("success") == 1) {
JSONArray array = jsonObject.getJSONArray("data");
for (int i = 0; i<array.length() ; i++) {
JSONObject object = array.getJSONObject(i);
DisItem disItem = new DisItem();
disItem.setPid(object.getString("pid"));
disItem.setLiked(preferences.getBoolean(String.valueOf(disItem.getPid()), false));
Log.d(TAG, disItem.toString());
dbHelper.insert(disItem);
}
}
}
This is Databace getallItems function
public ArrayList<DisItem> getAllItems()
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + DIS_TABLE_NAME + "", null);
ArrayList<DisItem> arrayList = new ArrayList<>();
cursor.moveToFirst();
while (! cursor.isAfterLast())
{
DisItem disItem = new DisItem(cursor);
arrayList.add(disItem);
cursor.moveToNext();
}
return arrayList;
}
I tried your code with same scenario in a small JUnit Test and it shows me that you have not initialized your ArrayList<DisItem> correctely in getAllItems() method may be thats why you are getting nullPointerException that is
Replace
ArrayList<DisItem> arrayList = new ArrayList<>();
With
ArrayList<DisItem> arrayList = new ArrayList<DisItem>();'
I corrected this thing and run the test again with some dummy values and it showed me correct result like:
public class Test
{
private ArrayList<DisItem> savedData;
#org.junit.Test
public void test() throws Exception
{
savedData = getAllData();
for(int a = 0; a < savedData.size(); a++){
System.out.println("ArrayList Data A= " + savedData.get(a).getA() + " B = " + savedData.get(a).getB());
}
}
}
private ArrayList<DisItem> getAllData()
{
ArrayList<DisItem> arrayList = new ArrayList<DisItem>();
DisItem disItem = new DisItem();
disItem.setA("AAAAAA");
disItem.setB("BBBB");
arrayList.add(disItem);
return arrayList;
}
private class DisItem
{
String a, b;
public void setA(String a)
{
this.a = a;
}
public void setB(String b)
{
this.b = b;
}
public String getA()
{
return this.a;
}
public String getB()
{
return this.b;
}
}
Output:
ArrayList Data A= AAAAAA B = BBBB
you cant access more than one SharedPreferences or SQLiteOpenHelper in Parallel.

How to use returned arraylist?How to retrieve data from arraylist?

In the following code,i am saving the three values fun_id,fun_logo,fun_req with the help of another class Use.In the code an arraylist is returned,now i want to retrieve the fun_id,fun_logo,fun_req.I want to add fun_logo into imagearray.I would like to know how to use the Class Use for retreving data.I am learning currently so only small idea bout android.
ArrayList<Use> stringArrayList = null;
ArrayList<Use> res = null;
ArrayList<String> linklist = null;
String getdetailsurl;
String link [];
String[] ar;
Use[] getalldet;
public String imagearray[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Getdetailsfromweb().execute();
list=(ListView)findViewById(R.id.listView1);
// adapter=new myadpter(this, imagearray);
list.setAdapter(adapter);
}
public class Getdetailsfromweb extends AsyncTask<String,Void,String>
{
String result = "";
#Override
protected String doInBackground(String... params) {
getdetailsurl=Webcall.getdet();
if(getdetailsurl!=null)
{
result = "Success";
}
else
{
result = "Failure";
}
return result;
}
#Override
protected void onPostExecute(String result) {
res = new ArrayList<Use>();
try {
if (result.contentEquals("Success"))
{
res=passdetails();
System.out.println("lsize is " + res.size());
for(int i=0;i<res.size();i++)
{
// To retreive value what should i do here
imagearray[i]=obj.funlogo;
System.out.println("logo is " + imagearray[i]);
}
}
else
{
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
public ArrayList<Use> passdetails()
{
JSONArray array = null;
stringArrayList = new ArrayList<Use>();
linklist= new ArrayList<String>();
Use usee;
try {
array = new JSONArray(getdetailsurl);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i = 0;i <array.length() ;i++ )
{
String fun_id= null;
String fun_logo= null;
String fun_req = null;
try {
fun_id = array.getJSONObject(i).getString("up_id");
System.out.println("up_id is " + fun_id);
fun_logo=array.getJSONObject(i).getString("logo");
System.out.println("logo is " + fun_logo);
fun_req=array.getJSONObject(i).getString("requirements");
System.out.println("req is " + fun_req);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
usee=new Use();
usee.funid=fun_id;
System.out.println("fun is " + usee.funid);
usee.funlogo=fun_logo;
System.out.println("fun is " + usee.funlogo);
usee.funreq=fun_req;
System.out.println("fun is " + usee.funreq);
linklist.add(fun_logo);
stringArrayList.add(usee);
}
return stringArrayList;
}
}
Use.java
public class Use {
public static String funid;
public String funlogo;
public String funreq;
}
I would like to know how to use the Class Use for retrieving data
All fields are public in Use and res is ArrayList of object of Use class. access values from each object as :
for(int i=0;i<res.size();i++)
Use useObj=res.get(i);
String funlogo=useObj.funlogo;
String funreq=useObj.funreq;
...
}
Define a Use class with getter and setter methods.
Define a method getFunLogos() in Use class which would return the image array of all the fun logos. Access this method from wherever you want.
protected String[] getFunLogos(ArrayList<Use> listFunLogos) {
for(int i=0;i<res.size();i++)
{
// To retreive value what should i do here
imagearray[i]=obj.funlogo;
System.out.println("logo is " + imagearray[i]);
}
}
I want to add fun_logo into imagearray
//linklist : as you are adding fun_log in it
imagearray=new String[linklist.size()];
linklist.toArray(imageArray);

How to test my dbmanager class in android?

In my android app I am using ormlite. Now I want to create some testcases for the db helper methods. I do not know how this should work properly. The database need to be created in my testcase before the concrete test can start. For example I want to test if a user will be created as expected. For this I have a addUser Method which should be tested, but how can this be done?
Currently I created a TestProject with a TestCase for my DBManager-Class.
Here is my DBHelper class
public class DBHelper extends OrmLiteSqliteOpenHelper{
private static final String DATABASE_NAME = "pdixattach.db";
private static final int DATABASE_VERSION = 4;
private static final String TAG = DBHelper.class.getSimpleName();
private static DBHelper _helperInstance;
private Dao<Attachment, Integer> attachmentDao = null;
private Dao<User, Integer> userDao = null;
private Dao<Comment, Integer> commentDao = null;
private Dao<Job, Integer> jobDao = null;
private Dao<Target, Integer> targetDao = null;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db, ConnectionSource source) {
Log.i(TAG, "onCreate");
try{
dropTables(source);
TableUtils.createTable(source, Attachment.class);
TableUtils.createTable(source, User.class);
TableUtils.createTable(source, Comment.class);
TableUtils.createTable(source, Target.class);
TableUtils.createTable(source, Job.class);
TableUtils.createTable(source, ConfigurationParameter.class);
} catch (Exception e){
Log.e(TAG, "error while creating tables " + e.getMessage());
throw new RuntimeException(e);
}
}
#Override
public void onUpgrade(final SQLiteDatabase db, final ConnectionSource connectionSource, final int oldVersion, final int newVersion) {
Log.i(TAG, "onUpgrade");
try {
dropTables(connectionSource);
onCreate(db, connectionSource);
} catch (SQLException e) {
Log.e(TAG, "error while upgrading tables " + e.getMessage());
throw new RuntimeException(e);
}
// after we drop the old databases, we create the new ones
onCreate(db, connectionSource);
}
private void dropTables(final ConnectionSource connectionSource)
throws SQLException {
TableUtils.dropTable(connectionSource, Attachment.class, true);
TableUtils.dropTable(connectionSource, User.class, true);
TableUtils.dropTable(connectionSource, Target.class, true);
TableUtils.dropTable(connectionSource, Job.class, true);
TableUtils.dropTable(connectionSource, Comment.class, true);
TableUtils.dropTable(connectionSource, ConfigurationParameter.class, true);
}
public Dao<Attachment, Integer> getAttachmentDao() throws SQLException {
if (this.attachmentDao == null) {
this.attachmentDao = getDao(Attachment.class);
}
return this.attachmentDao;
}
public Dao<User, Integer> getUserDao() throws SQLException {
if (this.userDao == null) {
this.userDao = getDao(User.class);
}
return this.userDao;
}
public Dao<Comment, Integer> getCommentDao() throws SQLException {
if (this.commentDao == null) {
this.commentDao = getDao(Comment.class);
}
return this.commentDao;
}
public Dao<Target, Integer> getTargetDao() throws SQLException {
if (this.targetDao == null) {
this.targetDao = getDao(Target.class);
}
return this.targetDao;
}
public Dao<Job, Integer> getJobDao() throws SQLException {
if (this.jobDao == null) {
this.jobDao = getDao(Job.class);
}
return this.jobDao;
}
/**
* Close the database connections and clear any cached DAOs.
*/
#Override
public void close() {
super.close();
_helperInstance = null;
this.attachmentDao = null;
this.commentDao = null;
this.jobDao = null;
this.targetDao = null;
this.userDao = null;
}
}
and my DBManager which I want to test, for example the storeUser Method
public class DBManager {
private DBHelper helper;
private static DBManager uniqueInstance;
private static final String TAG = DBManager.class.getSimpleName();
public DBManager(Context context) {
helper = new DBHelper(context);
}
public static void init(Context context) {
if (uniqueInstance == null) {
uniqueInstance = new DBManager(context);
}
}
public static DBManager getInstance() {
return uniqueInstance;
}
public boolean addUser(User u) {
boolean retVal = false;
if (u == null) {
throw new IllegalArgumentException("user must not be null");
}
try {
helper.getUserDao().create(u);
retVal = true;
} catch (SQLException e) {
Log.e(TAG, "error while adding user to db " + e.getMessage());
}
return retVal;
}
public boolean addServiceEndpoint(String endpoint) {
Log.d(TAG, "adding Service Endpoint " + endpoint);
boolean retVal = false;
if (endpoint == null) {
throw new IllegalArgumentException("endpoint must not be null");
}
try {
Target t = new Target(endpoint);
int result = helper.getTargetDao().create(t);
Log.d(TAG, "creating target entry resulted with value " + result);
retVal = (result == 1);
} catch (SQLException e) {
Log.e(TAG,"error while adding target to db, with service endpoint " + endpoint + "error" + e.getMessage());
}
return retVal;
}
public List<Target> getAllTargets() {
List<Target> retVal = new ArrayList<Target>();
try {
retVal = helper.getTargetDao().queryForAll();
} catch (SQLException e) {
Log.e(TAG,
"error while retrieving service endpoints, error" + e.getMessage());
}
return retVal;
}
public User storeUser(String username, String hashedPw, Target target,
boolean storeLogin) {
User loggedInUser = null;
int loginState = (storeLogin) ? 1 : 0;
if (username == null || hashedPw == null || target == null) {
throw new IllegalArgumentException(
"cannot store login with empty/null values");
}
try {
QueryBuilder<User, Integer> queryBuilder = helper.getUserDao().queryBuilder();
Where<User, Integer> where = queryBuilder.where();
where.eq(User.USERNAME, username)
.and().eq(User.TARGET_ID, target.getServiceEndpoint());
PreparedQuery<User> prepareStmt = queryBuilder.prepare();
List<User> userList = helper.getUserDao().query(prepareStmt);
if (userList.isEmpty()) {
Log.d(TAG, "no user found with this name in the db, need to store it");
User newUser = new User(username, hashedPw, target);
newUser.setStored(loginState);
addUser(newUser);
userList = helper.getUserDao().query(prepareStmt);
loggedInUser = userList.get(0);
} else {
Log.d(TAG, "found at least one user with username " + username + " target " + target);
for (User u : userList) {
if (u.getPassword().equals(hashedPw)) {
Log.d(TAG, "password is equal to the one in db");
}
else {
u.setPassword(hashedPw);
}
// setze diesen User als aktiv!
u.setStatus(1);
u.setStored(loginState);
helper.getUserDao().update(u);
loggedInUser = u;
}
}
} catch (SQLException e) {
Log.d(TAG, "error while storing login" + e.getMessage());
}
return loggedInUser;
}
public Comment addComment(Comment cmt) {
Comment retVal = null;
if (cmt == null) {
throw new IllegalArgumentException("cannot create a comment entry in database without comment");
}
try {
retVal = helper.getCommentDao().createIfNotExists(cmt);
} catch (SQLException e) {
e.printStackTrace();
}
return retVal;
}
public Attachment addAttachment(Attachment att) {
if (att == null) {
throw new IllegalArgumentException(
"cannot create attachment entry in database without attachment");
}
Attachment dbAttach = null;
try {
dbAttach = helper.getAttachmentDao().createIfNotExists(att);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dbAttach;
}
public Job addJob(Job job) {
Job dbJob = null;
if (job == null) {
throw new IllegalArgumentException(
"no job given, cannot create an entry");
}
try {
QueryBuilder<Job, Integer> queryBuilder = helper.getJobDao()
.queryBuilder();
Where<Job, Integer> where = queryBuilder.where();
if (job.getInstanceId() == null)
where.isNull(Job.INSTANCE_ID);
else
where.eq(Job.INSTANCE_ID, job.getInstanceId());
where.and().eq(Job.COMMENT_ID, job.getComment().getComment()).and()
.eq(Job.ATTACH_ID, job.getAtach().getAttUri()).and()
.eq(Job.STATUS, "0").and()
.eq(Job.TARGET_ID, job.getTarget().getServiceEndpoint());
PreparedQuery<Job> prepareStmt = queryBuilder.prepare();
Log.d(TAG, "querystring is " + prepareStmt.getStatement());
List<Job> jobList = helper.getJobDao().query(prepareStmt);
if (jobList.isEmpty()) {
Log.d(TAG, "no job with these parameters given, need to create one");
Log.d(TAG, "job id is " + job.getId());
dbJob = helper.getJobDao().createIfNotExists(job);
Log.d(TAG, "dbJob id is " + dbJob.getId());
} else {
Log.d(TAG,
"job does already exists for this parameters, wont create new");
dbJob = jobList.get(0);
// hier comment und status usw updaten
}
} catch (SQLException e) {
Log.d(TAG, "Exception during adding a job to db: " + e.getMessage());
}
return dbJob;
}
public void attachInstanceIdToJob(String instanceId, long jobId) {
Log.d(TAG, "attaching instance id " + instanceId + " to job with id " + jobId);
try {
Job job = helper.getJobDao().queryForId((int) jobId);
if (job != null){
job.setInstanceId(instanceId);
helper.getJobDao().update(job);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
Log.d(TAG, "error while attaching instance id " + instanceId + " to job with id " + jobId);
}
}
public List<Job> getAllOpenJobs() {
List<Job> jobList = null;
QueryBuilder<Job, Integer> queryBuilder;
try {
queryBuilder = helper.getJobDao()
.queryBuilder();
Where<Job, Integer> where = queryBuilder.where();
where.eq(Job.STATUS, JobStatusEnum.OPEN.getState())
.or().eq(Job.STATUS, JobStatusEnum.RETRY.getState());
;
PreparedQuery<Job> prepareStmt = queryBuilder.prepare();
Log.d(TAG, "querystring is " + prepareStmt.getStatement());
jobList = helper.getJobDao().query(prepareStmt);
} catch (SQLException e) {
Log.d(TAG, "error while retrieving open jobs from db" + e.getMessage());
}
return jobList;
}
public void getDataForJob(Job j, User u, Attachment att, Target target, Comment comment) {
try {
if (j != null){
helper.getUserDao().refresh(j.getUser());
helper.getAttachmentDao().refresh(j.getAtach());
helper.getTargetDao().refresh(j.getTarget());
helper.getCommentDao().refresh(j.getComment());
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public User getCurrentStoredUser(){
try {
List<User> users = helper.getUserDao().queryForAll();
for (User u: users){
if (u.getStored() == 1){
return u;
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public void updateJob(Job j) {
if (j != null){
try {
helper.getJobDao().update(j);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* The status of the given user will be configured to stored. All others will be set to unstored
* #param loggedInUser
*/
public void setUserStatusToStored(User loggedInUser) {
List<User> listOfUsers;
try {
listOfUsers = helper.getUserDao().queryForAll();
for (User u: listOfUsers){
if (u.equals(loggedInUser)){
u.setStatus(UserStatusEnum.STORED.getState());
}
else{
u.setStatus(UserStatusEnum.UNSTORED.getState());
}
helper.getUserDao().update(u);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and my TestClass
public class DBManagerTest
extends TestCase
{
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testDBManager() {
fail( "Not yet implemented" );
}
}
Can someone help me with shat, I guess once the first test is running the others should be clear.
Thanks

Categories

Resources