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");
Related
I'm trying to read a file which consists of some lines and each line has 3 parts: id , name and surname. There is also an EditText where the user needs to enter his id and in case it matches with one of the ones read from the file it should show a dialog like this one: Are you "Name", "Username"?
I've tried doing the following thing but unfortunately it doesn't work.
public String getDNI() {
String[] parts = fichero.split("\\,");
String DNI = parts[0];
return DNI;
}
public String getNombre() {
String[] parts = fichero.split("\\,");
String Nombre = parts[1];
return Nombre;
}
public String getEnunciado() {
String[] parts = fichero.split("\\,");
String Apellido = parts[2];
return Apellido;
}
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.identificacion);
Button bSiguiente = (Button) findViewById(R.id.btn_siguiente);
dniText = (EditText) findViewById(R.id.dni_candidato);
try {
InputStream is = getAssets().open(File);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
// Skips lines
for (i = 0; i<= 100; i++) {
reader.readLine();
}
fichero = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
bSiguiente.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
try{
longitud = dniText.getText().toString();
user = Integer.parseInt(dniText.getText().toString());
DNIWord(user);
for (i = 0; i<= 100; i++) {
if (longitud.equals(getDNI())){
// (longitud.length()==8){
showDialog(DIALOG_CONFIRMAR_CANDIDATO);}
else{
showDialog(DIALOG_ERROR_DNI);
}
}
}
catch (NumberFormatException e)
{}
}
A better approach is to create a class to represent your user:
class User{
public String nombre;
public String enunciado;
public String dni;
public User(String nombre, String enunciado, String dni){
this.nombre = nombre;
this.enunciado = enunciado;
this.dni = dni;
}
public User(String csvLine){
String[] values = csvLine.split(",");
this(values[0], values[1], values[2]);
}
}
I prefer the first constructor because it's easier to read.
Use like this:
ArrayList<User> users = new ArrayList<User>();
...
String s;
while ((s = reader.readLine()) != null) {
users.add(new User(s));
}
or
String s;
String[] value;
while ((s = reader.readLine()) != null) {
values = s.split(",");
users.add(new User(values[0], values[1], values[2])); <-- prefer this one
}
To make it even better:
public static final int DNI = 0;
public static final int NOMBRE = 1;
public static final int ENUNCIADO = 2;
...
String s;
String[] value;
while ((s = reader.readLine()) != null) {
values = s.split(",");
users.add(new User(values[DNI], values[NOMBRE], values[ENUNCIADO]));
}
Now you can work with your users collection using users.contains, users.getElementAt, Collections.sort, Collections.binarySearch etc.
Here is another question helpful for parsing CVS in C++: How can I read and parse CSV files in C++?
If you are open to other languages, like python, it might be much easier. For example, python has build-in csv tools:
http://docs.python.org/2/library/csv.html
I'm wanting to create an array of all keys within an object does anyone know how to do this in Android? in iOS I have done this
NSDictionary *variablesDictionary = [[NSDictionary alloc] init];
// ^^ full of variables and keys...
NSString *finalString = #"";
if(variablesDictionary != nil){
NSArray *keysArray = [variablesDictionary allKeys];
for(NSString *singleKey in keysArray) {
finalString = [finalString stringByAppendingString:[NSString stringWithFormat:#"&%#=%#", singleKey, [variablesDictionary objectForKey:singleKey]]];
}
}
//final string will = '&key=variable&key=variable&key=variable&key=variable' etc...
heres what i have tried so far. heres my global actions
public final static void startAPICallRequest(Context activityContext, String request, String apiLocation, Object postVarsObj, Object getVarsObj){
long unixTimeStamp = System.currentTimeMillis() / 1000L;
if(getVarsObj != null){
Array keysArray = getVarsObj.keySet().toArray();
StringBuilder sb = new StringBuilder();
for (String key : getVarsObj.keySet()) {
sb.append("&");
sb.append(key);
sb.append("=");
sb.append(getVarsObj.get(key).toString());
}
final String will = sb.toString();
}
}
// for Map<String, Object>
StringBuilder sb = new StringBuilder();
for (String key : map.keySet()) {
sb.append("&");
sb.append(key);
sb.append("=");
sb.append(map.get(key).toString());
}
final String will = sb.toString();
If using a map, you'll want to take a look at the keySet() functionality. Here is an example
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");
Im making question and answer. my question generate randomly but, the question repeated again.
im using txt file as my database when the int array generate randomly my holder get what is string line in my database. supposed to be int array = x, and string line = y;
{y==x}. my question is when i generate again the question get again, what supposed i will do guys?.
private void question() {
InputStreamReader inputStream = new InputStreamReader
(getResources().openRawResource(R.raw.question1));
BufferedReader br = new BufferedReader(inputStream);
ArrayList<Integer> ar= new ArrayList<Integer>();
int[] number= {1,2,3,4,5,6,7,8,9,10};
for (int i : number) {
ar.add(i);
}
Random r = new Random();
int select = r.nextInt(ar.size());
int random = ar.get(select);
ar.remove(select);
String theLine="";
int lineCtr = 0;
try {
while ((theLine = br.readLine()) != null) {
if (lineCtr == select) {
StringTokenizer st = new StringTokenizer(theLine,",");
while(st.hasMoreTokens())
{
//reading and getting data from the database","
String a = st.nextToken();
String b = st.nextToken();
String c = st.nextToken();
String d = st.nextToken();
String e = st.nextToken();
String f = st.nextToken();
//button setText
question.setText(a);
ca.setText(f);
firstbutton.setText(e);
secondbutton.setText(d);
thirdbutton.setText(b);
fourthbutton.setText(c);
//assigning
firstholder =e;
secondholder =d;
thirdholder=b;
fourthholder =c;
break;
}
}lineCtr++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Have you try below code for solve repeating question problem :-
Collections.shuffle(Arrays.asList(number));
I wanted to show the whole c program on screen which should be visible to user.
I used textView but i am getting errors as the code contains special symbols.
for example:
android:text=" #include <stdio.h>
int main()
{
int x, y, temp;
printf("Enter the value of x and y\n");
scanf("%d%d", &x, &y);
printf("Before Swapping\nx = %d\ny = %d\n",x,y);
temp = x;
x = y;
y = temp;
printf("After Swapping\nx = %d\ny = %d\n",x,y);
return 0;
}" />
I also want that the user should be able to scroll the code as the codes may be larger than the example.I am a noob so please suggest me any alternate for the textView to display the code.
Save your C code in a file in assets folder, for example "res/assets/code.c".
Write a function that reads the content of a file to a String:
private String readFileInAssetsDir(String filename) {
BufferedReader br = null;
StringBuffer sb = new StringBuffer();
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(filename)));
String line;
while((line = br.readLine()) != null)
sb.append(line + "\n");
} catch(Exception e) {
// TODO
}
return sb.toString();
}
And now define a WebView (not a TextView) in your layout (the advantages are that you can show any character, and WebView provides zoom and scroll directly):
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1" />
And finally I would enclose all C code in a <pre></pre> tag and then show it inside the WebView widget:
String plainCode = readFileInAssetsDir("code.c");
String htmlCode = "<pre>" + plainCode + "</pre>";
webView.loadDataWithBaseURL("", htmlCode, "text/html", "utf-8", "");
EDIT: THIS WORKS BUT READS ONLY A SINGLE LINE OF THE TEXT IN THE TXT FILE
String line;
TextView view;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addingprogrammultipletimes);
AssetManager am = getAssets();
try {
InputStream is = am.open("add.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
line = reader.readLine();
view = (TextView) findViewById(R.id.textView);
view.setText(line);
} catch (Exception e) {
e.printStackTrace();
}
}