I got this following method in an non Activity class, My code is below.
public class ReadTextByLineNo {
public void setContext(Context _context) {
if (context == null) {
context = _context;
}
}
public String getTextByLine(int Filename,int LineNumber)
{
String output="";
String line="";
int counter=1;
try
{
InputStream in = context.getResources().openRawResource(Filename);
//InputStream in = assetManager.open(Filename);
if(in!=null)
{
InputStreamReader input = new InputStreamReader(in);
BufferedReader buff = new BufferedReader(input);
while((line=buff.readLine())!=null)
{
if(counter ==LineNumber){
output=line;
}counter++;
}in.close();
}else{
Log.e("Input STREAM PROBLEM", "TEXT IS NULL NULL NULL NULL NULL");
}
}catch(Exception e)
{
//log
}
return output;
}
**I am calling this method from an NON_ACTIVITY CLASS LIKE THIS **
class sample implements Isample
{
ReadTextByLineNo read = new ReadTextByLineNo();
String subMsg = read.getTextByLine(R.raw.subtitle, storySceneId);
//the above string is to called from an activity called Layout
}
How do I use resources/context from an non activity class? I cannot use the context in constructor since I'm also calling the method from an non Activity class.
so I can't set read.setContent(this); where I got setContext method in my ReadtextByLineNo class, thanks for the help .
Please help me to get the context/resourse in the class sample and example by code is appreciated
public class ReadTextByLineNo {
private static Context context;
public static void setContext(Context mcontext) {
if (context == null)
context = mcontext;
}
}
when your application start, just initialize this context, by calling
ReadTextByLineNo.setContext(getApplicationContext());
from your main activity..
Enjoy...
Related
I have AsyncTask class as shown below in the code, and I am trying to test it.
I coded the test cases of the AsyncTask as shown below in the testing section, but as shown in the testing code, I just tested whether or not the AsyncTask
methods was called or not, and I did not tested the code in doInBackground() for example, because I do not know how to test it
Please let me know how to test AsyncTask class any guideline or hints are highly appreciated
code
public class AsyncTaskImageLoader extends AsyncTask<String, Void, RequestCreator> {
RequestCreator requCreator = null;
String picUrl = null;
private ImageView mImageView = null;
private UserAdapter.MyViewHolder mHolder = null;
ProgressBar mProgressBar = null;
Validation mValidation = null;
private Context mCtx = null;
public AsyncTaskImageLoader(Context ctx, UserAdapter.MyViewHolder holder) {
mHolder = holder;
mCtx = ctx;
mValidation = new Validation(ctx);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mHolder.progressBar.setVisibility(View.VISIBLE);
}
#Override
protected RequestCreator doInBackground(String... params) {
picUrl = params[0];
if (mValidation.isValidUrl(picUrl)) {
while (!isCancelled() && requCreator == null) {
try {
requCreator = mValidation.requestCreatorFromUrl(picUrl);
} catch (Exception e) {
}
//the value of the delay could be changed preferably
SystemClock.sleep(100);
}
}
return requCreator;
}
#Override
protected void onPostExecute(RequestCreator requestCreator) {
super.onPostExecute(requestCreator);
mHolder.progressBar.setVisibility(View.GONE);
//requestCreator.into(mHolder.imageViewAvatarOfOwner);
mValidation.setImageOnImageView(requestCreator, mHolder.imageViewAvatarOfOwner);
}
testing:
public class AsyncTaskImageLoaderTest {
#Mock
ProgressBar mockProgressBar = null;
#Mock
AsyncTaskImageLoader mockAsyncTaskImageLoader = null;
#Mock
Context mCtx = null;
#Before
public void setUp() {
mCtx = mock(Context.class);
mockProgressBar = mock(ProgressBar.class);
mockAsyncTaskImageLoader = mock(AsyncTaskImageLoader.class);
}
#Test
public void whenProgreeBarISSetToVisibleInOnPreExecute() throws Exception {
mockProgressBar.setVisibility(View.VISIBLE);
verify(mockProgressBar).setVisibility(View.VISIBLE);
}
#Test
public void whenOnDoInBackgroundIsCalled() throws Exception {
String str = new String();
mockAsyncTaskImageLoader.execute(str);
verify(mockAsyncTaskImageLoader).execute(str);
}
#Test
public void whenOnPostExecuteIsCalled() throws Exception {
RequestCreator mockRequestCreator = mock(RequestCreator.class);
mockAsyncTaskImageLoader.onPostExecute(mockRequestCreator);
}
}
I have 2 Java files (CreateMyDb.java,ReadfromAssets.java).
In ReadfromAssets.java, I have the code below.
If I want to call ReadFileFromAssets method from CreateMyDb.java, How should I call,What is the context param I should pass? I am trying it make it work but in vain.
Thanks
public class ReadFromAssets extends Activity {
private static final String splitBy = ",";
private static int ID_Count = 6;
private static final String ObjName = "Question";
private static String NewObjName = "";
public void ReadFileFromAssets(Context myContext) {
//read from assets
myContext.getAssets();
AssetManager assetManager = myContext.getAssets();
InputStreamReader is = null;
try {
is = new InputStreamReader(assetManager.open("questions.csv"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(is);
try {
reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String line;
try {
while ((line = reader.readLine()) != null) {
NewObjName = ObjName+ID_Count;
String[] QDetails = line.split(splitBy);
Question NewObjName=new Question(QDetails[0],QDetails[1],QDetails[2],QDetails[3],QDetails[4],QDetails[5], QDetails[6]);
CreateMyDb db=new CreateMyDb (this);
db.AddToDB(NewObjName);
ID_Count = ID_Count+1;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//use assets however
}
}
In the CreateMyDb.java file, I am calling the same method as ,
private void addQuestions(){
ReadFromAssets ReadCsv = new ReadFromAssets();
ReadCsv.ReadFileFromAssets();//what should I pass as context here?
}
pass the context of that class where you are accessing this class method
ReadCsv.ReadFileFromAssets(CreateMyDb.this);
if the CreateMyDb class extend from activity or fragementactivity it obviously have the context of that activity too so pass the context of the class where you are accessing this thank you may be its help you
The most inmediate solution is pass the context of your activity to this class. Is that possible?
If you don't want to pass parameters, you can create an Application class to get the context of the application wherever you want.
public class ApplicationClass extends Application
{
private static ApplicationClass myAppClass;
#Override
public void onCreate()
{
super.onCreate();
myAppClass = this;
}
public static ApplicationClass getMyAppClass()
{
return myAppClass;
}
}
Then you must add the next line in the ManifestFile under the label
android:name="com.yourapp.ApplicationClass"
Now, you can call in you method ApplicationClass.getMyAppCLass().getAssets() without passing any context.
I must say that in this case the Application class is not used in the correct way. This class type is used to keep the application state, but is the only way I can think to do what you want without passing any parameter.
Basically I have a stand alone class, which does not use Activity OR Service.
A function in the class starts a new Authenticator.
I have a string in the strings.xml file, which I want to access
Looking for the best method
Example code
class MyConnection(){
String username;
String pwd;
String strurl;
public MyConnection(String usernameIN, String pwdIN, String urlIN){
this.username = usernameIN;
this.pwd = pwdIN;
this.strurl = urlIN
}
public void
URL url = null;
try {
url = new URL(this.strURL);
URLConnection urlConn = null;
Authenticator.setDefault(new Authenticator()){
protected PasswordAuthentication getPasswordAuthentication()(
// I want my vars from strings.xml here
return new PasswordAuthentication(strUsername, strPwd.toCharArray());
}
});
urlCOnn = url.openConnection();
//Rest of the code, including CATCH
}
I passed the vars through into the class BUT how do I access them When I set the PasswordAuthentication. OR Can I access them direct from strings.xml ???
How do you create an instance of the MyConnection class?
It should be through an Activity or a Service, right?
Then when you create it, pass the current Activity
public class MyConnection {
private Activity activity;
public MyConnection(Activity a) {
this.activity = a;
}
//....
private void method() {
activity.getResources().getString(R.string....);
}
}
edit: I did not see you already had a constructor. Then add a parameter to the existing one.
You can add a final modificator to your MyConnection() constructor's parameters, this way you can use them as parameters in the call to PasswordAuthentication(). Hope this helps.
You'll need to pass a Context instance to your class or individual methods. The Context instance can be an instance of Activity or Service or anything else which is a subclass of Context. You can then use this to access system resources:
class MyConnection
{
private final Context context;
public MyConnection( Context context )
{
this.context = context;
}
.
.
.
public void someMethod()
{
String str = context.getResources().getString ( R.string.myString );
}
}
I'm trying to to key on the drawable ID to check if it is already available in memory before loading drawables again. I'm retrieving the theme from the theme apk package and retrieving them by String as seen in the getDrawable method. For the life of me I cant see why I get a nullpointer on this line and why it wont work.
" if (!mDrawables.containsKey(name)) {"
This is how I'm calling it to display images in my Activities.
/* Custom theme */
auxDrw = ThemeManager.getDrawable(ThemeID.FONDO);
// Fondo
if(auxDrw!=null)((LinearLayout)findViewById(R.id.about_layout)).setBackgroundDrawable(auxDrw);
This is the ThemeManager:
public static Resources themeResources = null;
public static String themePackage = null;
public static void setTheme(Context ctx, String themePack){
PackageManager pm = ctx.getPackageManager();
themePackage = themePack;
themeResources = null;
try{
themeResources = pm.getResourcesForApplication(themePackage);
}catch(NameNotFoundException e){
Log.d("tag", "Theme not found: "+e.getMessage());
}
}
public static void setTheme(Context ctx){
String themePackageName = Utils.preferencias.getString("themePackageName", "");
ThemeManager.setTheme(ctx, themePackageName);
}
private static boolean mActive = true;
private static HashMap<String, Drawable> mDrawables;
private Context ctx;
public ThemeManager(Context c) {
mDrawables = new HashMap<String, Drawable>();
ctx = c;
}
public static Drawable getDrawable(String name) {
if (mActive) {
if (!mDrawables.containsKey(name)) {
try {
int resource_id = themeResources.getIdentifier(name,
"drawable", themePackage);
if (resource_id != 0) {
mDrawables.put(name,
themeResources.getDrawable(resource_id));
}
} catch (NullPointerException e) {
}
return mDrawables.get(name);
}
}
return null;
}
Are you calling the constructor to ThemeManager elsewhere in your code? It appears that you are attempting to implement a static singleton class, something along those lines? I'm curious what the bigger picture here is, are you just attempting to load resources by a string filename instead of a resource ID?
friends,
i am using following code to write Serializable object to external storage.
it throws me error java.io.NotSerializableException
even my object is serializable any one guide me what mistake am i doing?
public class MyClass implements Serializable
{
// other veriable stuff here...
public String title;
public String startTime;
public String endTime;
public boolean classEnabled;
public Context myContext;
public MyClass(Context context,String title, String startTime, boolean enable){
this.title = title;
this.startTime = startTime;
this.classEnabled = enable;
this.myContext = context;
}
public boolean saveObject(MyClass obj) {
final File suspend_f=new File(cacheDir, "test");
FileOutputStream fos = null;
ObjectOutputStream oos = null;
boolean keep = true;
try {
fos = new FileOutputStream(suspend_f);
oos = new ObjectOutputStream(fos);
oos.writeObject(obj); // exception throws here
}
catch (Exception e) {
keep = false;
}
finally {
try {
if (oos != null) oos.close();
if (fos != null) fos.close();
if (keep == false) suspend_f.delete();
}
catch (Exception e) { /* do nothing */ }
}
return keep;
}
}
and calling from activity class to save it
MyClass m= new MyClass(this, "hello", "abc", true);
boolean result =m.saveObject(m);
any help would be appreciated.
This fails due to the Context field in your class. Context objects are not serializable.
Per the Serializable documentation - "When traversing a graph, an object may be encountered that does not support the Serializable interface. In this case the NotSerializableException will be thrown and will identify the class of the non-serializable object."
You can either remove the Context field entirely, or apply the transient attribute to the Context field so that it is not serialized.
public class MyClass implements Serializable
{
...
public transient Context myContext;
...
}