Android Reading Assets depending on selected Activity - android

I'm developing an app which consists on different tests and for each test (activity) it is needes to read a different txt file. I know doing this but changing it manually. How could be possible to read the proper txt when an specific activity is running. For example for activity 1 I need to read 1.txt and so on.
Here is the code where i read the txts.
String questionFile = "";
questionFile = "1.txt";
questionCount = 20;
Log.i("Question", questionFile + ": " + questionCount);
try {
InputStream is = context.getAssets().open(questionFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
// Skips lines
for (i = 0; i< questionNumber; i++) {
reader.readLine();
}
question = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}

you will need to put current code inside separate class and create a method for reading file from Assets depend on Activity currently running as:
public class GetFileAssets {
Context context;
public GetFileAssets(Context context){
this.context=context;
}
public String readFilefromAssets(String str_file_id){
String questionFile = "";
questionFile = str_file_id;
questionCount = 20;
//... your code here
return question;
}
}
and now pass file accoding to Activity .like from Actiivty 1:
GetFileAssets obj=new GetFileAssets(Activity1.this);
String str=obj.readFilefromAssets("1.txt");
same from Activity 2 :
GetFileAssets obj=new GetFileAssets(Activity2.this);
String str=obj.readFilefromAssets("2.txt");

Related

How to create a string / string array from a .txt/.xml file?

I know it has been asked a million times, but I just can't find anything that Works, and I just started learning to code
I'm trying to use regex to tell when the user types any of 118 different patterns, so you can guess it'd be a really long string, and I have all the patterns in a .txt/.xml file and I want to create a string or array with these patterns
The code:
public class MainActivity extends AppCompatActivity {
private TextView tv1;
private EditText et3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView)findViewById(R.id.tv1);
et3 = (EditText)findViewById(R.id.et3);
}
public void boton (View view){
String text = et3.getText().toString();
//String[] symbolsArr = {"He|","H|","Os|","O"};
//StringBuffer sb = new StringBuffer();
//for(int i = 0; i < symbolsArr.length; i++) { //all of this is just to convert an array to a single string
// sb.append(symbolsArr[i]);
//
String symbols = "Zr|Zn|Yb|Y|Xe|W|V|U|Ts|Tm|Tl|Ti|Th|Te|Tc|Tb|Ta|Sr|Sn|Sm|Si|Sg|Se|Sc|Sb|S|Ru|Rn|Rh|Rg|Rf|Re|Rb|Ra|Pu|Pt|Pr|Po|Pm|Pd|Pb|Pa|P|Os|Og|O|Np|No|Ni|Nh|Ne|Nd|Nb|Na|N|Mt|Mo|Mn|Mg|Md|Mc|Lv|Lu|Lr|Li|La|Kr|K|Ir|In|I|Hs|Ho|Hg|Hf|He|H|Ge|Gd|Ga|Fr|Fm|Fl|Fe|F|Eu|Es|Er|Dy|Ds|Db|Cu|Cs|Cr|Co|Cn|Cm|Cl|Cf|Ce|Cd|Ca|C|Br|Bk|Bi|Bh|Be|Ba|B|Au|At|As|Ar|Am|Al|Ag|Ac";
//The really long string with all the patterns
Pattern p = Pattern.compile(symbols);
Matcher m = p.matcher(text);
tv1.setText("");
while (m.find()){
tv1.append("found " + m.group() + "\n");
}
}
}
It depends of how do you want to storage the file.
For example let`s use assets.
Put file data.txt in assets(you can create this in File/New/Folder/Assets Folder)
After that you can create method, wich help you to get string from assetFile
public String getStringFromAssetFile(Context context, String nameFile)
{
String str = "";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(context.getAssets().open(nameFile)));
String line;
while ((line = reader.readLine()) != null) {
str += line;
}
} catch (IOException ex) {
ex.printStackTrace();
}
return str;
}
Now you can use this method to create a string or array with these patterns
String symbols = getStringFromAssetFile(MainActivity.this, "data.txt");

Android, how to get app on foreground

I'm trying to develop a service that whenever an user opens an app my service will identify it. I'm using the files: /proc/[pid]/cgroup,/proc/[pid]/cmdline,/proc/[pid]/oom_score,/proc/[pid]/oom_score_adj to check if it's an user app running on foreground. Actually it's working but when I try to open any game the service won't recognize it all the time. (The service only identify the files (oom_score) that has the lowest value).
Example: oom_score for "com.google.android.googlequicksearchbox:interactor" is 75, but for "com.king.candycrushsaga" will be >150, so it will never be detected by the code (as it follows).
Service code:
scheduler.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
s=appManager.getAppRunningForeground();
System.out.println(s);
}
},1,2,SECONDS);
Function that gets the app running:
private ReadWriteFile readWriteFile = new ReadWriteFile();
public String getAppRunningForeground(){
int pid;
File[] files = new File("/proc").listFiles();
int lowestOomScore = Integer.MAX_VALUE;
String foregroundProcess = null;
for (File file : files) {
if (!file.isDirectory() || (!file.getName().matches(("\\d+"))))
continue;
pid = Integer.parseInt(file.getName());
try {
String cgroup = readWriteFile.read(String.format("/proc/%d/cgroup", pid));
String[] lines = cgroup.split("\n");
if (lines.length != 2)
continue;
String cpuSubsystem = lines[0];
String cpuaccctSubsystem = lines[1];
if (!cpuaccctSubsystem.endsWith(Integer.toString(pid)) || cpuSubsystem.endsWith("bg_non_interactive"))
continue;
String cmdline = readWriteFile.read(String.format("/proc/%d/cmdline", pid));
if (cmdline.contains("com.android.systemui")||cmdline.contains("com.google.android.googlequicksearchbox:interactor")) {
continue;
}
int uid = Integer.parseInt(cpuaccctSubsystem.split(":")[2].split("/")[1].replace("uid_", ""));
if (uid > 1000 && uid <= 1038)//System process
continue;
File oomScoreAdj = new File(String.format("/proc/%d/oom_score_adj", pid));
if (oomScoreAdj.canRead()) {
int oomAdj = Integer.parseInt(readWriteFile.read(oomScoreAdj.getAbsolutePath()));
if (oomAdj != 0) {
continue;
}
}
int oomscore = Integer.parseInt(readWriteFile.read(String.format("/proc/%d/oom_score", pid)));
if (oomscore < lowestOomScore) {
lowestOomScore = oomscore;
foregroundProcess = cmdline.replaceAll("\\p{Cntrl}", "");
}
} catch (IOException e) {
e.printStackTrace();
}
}
return foregroundProcess;
}
Class that reads a file.
public class ReadWriteFile{
File file;
StringBuilder teste3 = new StringBuilder();
FileOutputStream outputStream;
public static String read(String path) throws IOException {
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(new FileReader(path));
output.append(reader.readLine());
for (String line = reader.readLine(); line != null; line = reader.readLine())
output.append('\n').append(line);
reader.close();
return output.toString();
}
}
P.S: getRunningTasks is deprecated, so please, don't suggest it.
You can use UsageStatsManager class added in android api 21. See this
question raised and answered by me.
The above answer will provide you an sorted applications ArrayList, required foreground application will the first one in the ArrayList on the index number 0.
Hope this will help.
This methods help you
void checkForegroundAppCompat()
{
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
final List<ActivityManager.RunningTaskInfo> taskInfo = activityManager.getRunningTasks(1);
final ComponentName componentName = taskInfo.get(0).topActivity;
if(!getWhiteListedPackages().contains(componentName.getPackageName()) &&
SecurityStatusManager.isAppsBlockingEnabled(this))
{
int pid = android.os.Process.getUidForName(componentName.getPackageName());
// Kill blick APP here
GRLog.w("KILL Blacklist App Package: " + componentName.getPackageName() + " with pid: " + pid);
killApp(componentName.getPackageName(), pid);
}
}

Android: display sentence from text file stored in res/raw folder

I am new to android and i Struck at this point.My text file contains wordings with number like
1abcd efg hij klmn opqrs.
2hdgh eydg ieuyhd gdhdgl.
3hdgf dhgfhs fhghs dhghj. and so on.
Now i need to display full sentence start with 1. please help me out from this problem.
You can save your text file in "Assets" folder of project and use following code to retrieve that file in java class
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("YOUR_TEXT_FILE.txt")));
StringBuilder total = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
total.append(line);
}
message=total.toString();
System.out.println(message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
After that you have that file in String message and you can retrieve string starting from "1" from that.
EDIT
TO RETRIEVE STRING STARTING WITH 1
use can use following code-
String newString;
for (int i = 0; i < message.length(); i++){
char c = message.charAt(i);
if(c=='1'){
for (int j = i; j < message.length(); j++){
if(c=='2'){
break;
}
else{
newString += message.charAt(j);
}
}
break;
}
}
Now String newString will contain String starting with '1'.
Good Luck

Load textfiles to android app - Out of memory despite not heavy files

I cannot, by now, understand why I got an out-of-memory exception when I load 9 different textfiles into my android app. The total size of the textfiles is about 10 MB. And I hade to change to large-heapsize in the manifest file to be able to load these files. Its not a good solution, so I wonder if someone could help me to understand what causes the heapsize to rize over 100 MB.
Another thing, could be a clue of something??, is that when heapsize has climed a bit over 100 MB and allocated memory is sligtly below - all loading is done, something happends:
The garbagecollector makes something immediately when loading is finished - the allocated space falls dramatically from 100 MB to 35 MB.
SO I wonder - what is happening? Why is the loading so memory consuming?
I can say that I have a class called FileManager where all loading taking place.
And because FileManager do not extend Activity, I have to pass a context to this class.
Could it be the context that is memory consuming? I think It may be and I have to move the loading when the app starts app at first.
Here is the FileManager-class
public class FileManager {
private String[][] solarObj,, celestObj, stars, sun, moon, venus, march, jupiter, saturn;
private ArrayList <String[][]> stringObjects = new ArrayList <String[][]> () ;
private String[] textFile;
private Context context;
private AssetManager assetManager;
public FileManager(Context context) {
this.context = context;
assetManager = context.getResources().getAssets();
instanciateStrings();
putStringsToList();
initializeTextFile();
for (int array_index = 0; array_index < 9; array_index++) {
read(this.textFile[array_index], this.stringObjects.get(array_index).length, array_index);
//printString(array_index);
}
}
private void instanciateStrings() {
this.solarObj = new String[98][4];
this.celestObj = new String[7][3];
this.stars = new String[92][7];
this.sun = new String[14246][15];
this.moon = new String[14246][15];
this.venus = new String[14246][15];
this.march = new String[14246][15];
this.jupiter = new String[14246][15];
this.saturn = new String[14246][15];
}
/**
* Lägger in de tvådimensionella strängvektorerna i en arraylist.
*/
private void putStringsToList() {
this.stringObjects.add(this.celestObj);
this.stringObjects.add(this.solarObj);
this.stringObjects.add(this.stars);
this.stringObjects.add(this.sun);
this.stringObjects.add(this.moon);
this.stringObjects.add(this.venus);
this.stringObjects.add(this.march);
this.stringObjects.add(this.jupiter);
this.stringObjects.add(this.saturn);
}
/**
* Filnamnen läses in i en strängvektor
*/
private void initializeTextFile() {
this.textFile = new String[9];
this.textFile[0] = "celestobj_txt.txt";
this.textFile[1] = "solarObj_txt.txt";
this.textFile[2] = "stars_txt.txt";
this.textFile[3] = "sun_txt.txt";
this.textFile[4] = "moon_txt.txt";
this.textFile[5] = "venus_txt.txt";
this.textFile[6] = "march_txt.txt";
this.textFile[7] = "jupiter_txt.txt";
this.textFile[8] = "saturn_txt.txt";
}
private void read(String text_file, int len, int index) {
String[] stringBuffer = new String[len]; // temporär textsträng som read-objektet returnerar textraden till.
BufferedReader br;
try {
InputStream input = assetManager.open(text_file);
br = new BufferedReader(new InputStreamReader(input, "UTF-8"));
//bufferedReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(text_file)));
String line;
int i = 0;
while ( (line = br.readLine()) != null) {
stringBuffer[i] = line; // läs in rader från textfilen
i++;
}
br.close();
} catch (FileNotFoundException fnde) {
//fnde.printStackTrace();
System.out.println("filerna kunde inte hittas");
} catch (Exception e) {
e.printStackTrace();
}
splitString(stringBuffer, index);
}
private void splitString(String[] str, int index) {
int nCols = this.stringObjects.get(index)[0].length; // antal kolumner
for (int i = 0; i < str.length; i++) {
StringTokenizer st = new StringTokenizer(str[i]);
for (int j = 0; j < nCols; j++) {
this.stringObjects.get(index)[i][j] = st.nextToken();
}
}
}
since its 9 files that is to be loaded this read-method are called 9 times. Could this be the source to te memory leak?
Greatful for answer
EDIT: I choosed to show the whole class. Thanks again!!!
I think it's because of the String[] you are using to store read lines. Can you try it with a StringBuilder instead of String[] ?
// stringBuffer[i] = line;
stringBuilder.append(line);

Android: Reading from a file and increasing the readed lines not working

I have a file with different questions and I need to read them one after another when the user clicks the "Next Button". However, I can only read the first line and the following one and after that one the layout remains the same and doesn't work. I will appreciate some help in order to read total questions. Here is part of my code:
public class Questions {
int i = 0;
int questionCount = 0;
int category;
String question;
int questionNumber=1;
void currentQuestion(Context context, int cat) {
category = cat;
String questionFile = "";
questionFile = "VerbalSup1.txt";
questionCount = 25;
Log.i("Question", questionFile + ": " + questionCount);
try {
InputStream is = context.getAssets().open(questionFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
// Skips lines
for (i = 0; i< questionNumber; i++) {
reader.readLine();
}
question = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
void Next(){
questionNumber=questionNumber + 1;
}
Here is the next button:
bNext.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
questions.Next();
questions = new Questions();
questions.Next();
currentQuestion();
}
});
The issue is that you are resetting the questions object so it will get only the first line..
Here:
questions.Next();
questions = new Questions(); // this is wrong as the counts will be reset to defaults
questions.Next();
currentQuestion();
You should have:
questions.Next();
currentQuestion();
currentQuestion();
I hope it helps.

Categories

Resources