how to not get the integer array again - android

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));

Related

compare multiplication of JSONObjects

So, I have at this point a collections.sort of java values as you can see
and I have two keys that are integers (let's say for the sake of the example that the values of tipo are 1,2 and the values of id are 3 and 4) and I want to sort the result of theyr multiplication:
Something like this:
valA = a.get(KEY_ONE)*a.get(KEY_TWO);
valB = b.get(KEY_ONE)*b.get(KEY_TWO);
Then compare them.
How can I do it??
here is the code that I have at this point.
Collections.sort( jsonValues, new Comparator<JSONObject>() {
private static final String KEY_ONE = "tipo";
private static final String Key_TWO = "id";
#Override
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = (String) a.get(KEY_ONE.toString());
valB = (String) b.get(KEY_ONE.toString());
}
catch (JSONException e) {
//do something
}
return valA.compareTo(valB);
}
});
for (int i = 0; i < jsonArray.length(); i++) {
sortedJsonArray.put(jsonValues.get(i));
}
tvJson.setText(sortedJsonArray.toString());
}
}
Thanks in advance !

How to parse a CSV file

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

database textfile random without repeating the data?

I want to display the data of my database which is in txt file randomly one at a time, and it cannot repeat the data.
private void question() {
// TODO Auto-generated method stub
InputStreamReader inputStream = new InputStreamReader
(getResources().openRawResource(R.raw.question1));
BufferedReader br = new BufferedReader(inputStream);
//number of lines in the database numLines
int numLines= 10;
Random r = new Random();
int desiredLine = r.nextInt(numLines);
String theLine="";
int lineCtr = 0;
try {
while ((theLine = br.readLine()) != null) {
if (lineCtr == desiredLine) {
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();
}
}

I'm not understanding the following code

I have to understand this code to create my own app(almost based on this function):
public static String[][] ReadFilePerLine(Context context, String nom) {
int i = 0;
try {
FileInputStream fIn = context.openFileInput(nom);
InputStreamReader ipsr = new InputStreamReader(fIn);
BufferedReader b = new BufferedReader(ipsr);
i = getLineNumber(context, nom);
String[][] s = new String[2][i/2];
i = 0;
String ligne;
int j = 0;
while ((ligne = b.readLine()) != null) {
if (i % 2 == 0)
s[0][j] = ligne;
else {
s[1][j] = ligne;
j++;
}
i++;
}
fIn.close();
ipsr.close();
return s;
}
catch (Exception e)
{}
I'm not understanding why the using of a 2D array? and with two rows ?(String[][] s = new String[2][i/2];)
here is the data that it will be stored in the file:
data = date + " : " + y + "L/100KM"+ " " + value1 + "L "+ value2 + "KM\n";
Necessary functions:
public void updatelv(Activity activity) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String fileName = getResources().getString(R.string.fileName);
fileDir = "" + preferences.getString("login", "") + "."+ preferences.getString("marque", "") + ".";
s = myIO.ReadFilePerLine(getApplicationContext(), fileDir+fileName);
ListView L = (ListView) findViewById(R.id.lv);
L.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, s[0]));
for (int i = 0; i< s[0].length; i++) {
Log.d("Saves",s[0][i]);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.histo);
context = getApplicationContext();
activity = this;
final SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(context);
String fileName = getResources().getString(R.string.fileName);
fileDir = "" + preferences.getString("login", "") + "."+ preferences.getString("marque", "") + ".";
s = myIO.ReadFilePerLine(getApplicationContext(), fileDir + fileName);
updatelv(this);
ListView L = (ListView) findViewById(R.id.lv);
L.setTextFilterEnabled(true);
L.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
String tmp = s[1][position];
if (tmp == null)
tmp = "Aucun fichier trouvé!";
Toast.makeText(getApplicationContext(), tmp, Toast.LENGTH_SHORT)
.show();
}
});
ReadFilePerLine function:
public static String[][] ReadFilePerLine(Context context, String nom) {
int i = 0;
try {
FileInputStream fIn = context.openFileInput(nom);
InputStreamReader ipsr = new InputStreamReader(fIn);
BufferedReader b = new BufferedReader(ipsr);
i = getLineNumber(context, nom);
String[][] s = new String[2][i/2];
i = 0;
String ligne;
int j = 0;
while ((ligne = b.readLine()) != null) {
if (i % 2 == 0)
s[0][j] = ligne;
else {
s[1][j] = ligne;
j++;
}
i++;
}
fIn.close();
ipsr.close();
return s;
}
catch (Exception e)
{
}
Thank you for you help.
The code is clearly reading from a file whose format consists of pairs of lines; it puts the first line of each pair in s[0][...] and the second line of each pair in s[1][...]. If your format doesn't have that peculiarity -- which it doesn't sound as if it does -- then you don't need to do that. Just make an ordinary 1-dimensional array of Strings.
It appears that what they are doing is breaking the file down into two lists (or String arrays, in this case), one which contains all the even-numbered lines, and one which contains all the odd-numbered lines. I'll comment up the code for you:
public static String[][] ReadFilePerLine(Context context, String nom) {
int i = 0;
try {
//open the specified input file and create a reader
FileInputStream fIn = context.openFileInput(nom);
InputStreamReader ipsr = new InputStreamReader(fIn);
BufferedReader b = new BufferedReader(ipsr);
//get the total number of lines in the file, and allocate
//a buffer large enough to hold them all
i = getLineNumber(context, nom);
String[][] s = new String[2][i/2];
i = 0; //set the current line to 0
String ligne;
int j = 0; //set the section index to 0
//now read through the lines in the file, and place every
//even-numbered line in the first section ('s[0]'), and every
//odd-numbered line in the second section ('s[1]')
while ((ligne = b.readLine()) != null) {
if (i % 2 == 0)
//even-numbered line, it goes into the first section
s[0][j] = ligne;
else {
//odd-numbered line, it goes into the second section
s[1][j] = ligne;
j++; //increment the section index
}
i++; //increment the line count
}
//done, cleanup and return
fIn.close();
ipsr.close();
return s;
}
catch (Exception e) {
//should at least log an error here...
}
}
As to why they chose to use a String[][], I cannot say. Probably for convenience, since they want a single object that they can return from this function that contains both lists. Personally I would use a Map that has two List instances in it, but the String[][] works just as well and is probably marginally more efficient.
Judging from your example data it does not appear that you need to use this format. But if you want to use it, you need to structure your data so that the key is on one line, and its associated value is on the next, like:
date
2011-03-19
userName
someGuy
it seems to read from a file, split it into the two dimensional array (based on row count).
Why it does it? I have no idea why you'd want that. Check out the function that it returns s to and find out!

Fail to split downloaded txt file

I have a String that I try to split. The following code works
lsSagor = "some text\n Some more text\n More text~Text again\n Text\n text~Some text ..."
final String[] laList = lsSagor.split("~");
String[] laSaga = laList[0].split("\n");
Gives:
laSaga[0] => some text
laSaga[1] => some more text
laSaga[2] => More text
But if I download the textfile, it fails to split and gives:
laSaga[0] => "some text\n Some more text\n More text"
So it seems the first split works, but not the second.
Here is the code I use to download the file
String lsSagor = getFileFromUrl(BASEURL+"/sagor.txt");
public static String getFileFromUrl(String url)
{
InputStream content = null;
try
{
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
// Execute HTTP Get Request
HttpResponse response = httpclient.execute(httpGet);
content = response.getEntity().getContent();
}
catch (Exception e)
{
//handle the exception !
}
BufferedReader rd = new BufferedReader(new InputStreamReader(content), 4096);
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
From the documentation
I don't think you will find your string contains any newline character to split on, you would need to do
while ((line = rd.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
to get that and I'm sure there is an easier way to just read it newlines and all in the first place.
Hi I think the problem is in String.split() function
Old method but work :)
public static String[] splitString(String str, char separator)
{
String[] retVal = null;
int length = str.length();
int size = 1;
int jIndx = 0;
int expressionLength = 0;
while ((jIndx = str.indexOf(separator, jIndx + 1)) != -1)
{
size++;
}
retVal = new String[size];
jIndx = 0;
char[] charArray = str.toCharArray() ;
for (int index = 0; index < length; index++)
{
if (charArray[index] == separator)
{
retVal[jIndx] = str.substring(index - expressionLength, index);
jIndx++;
expressionLength = 0;
}
else
expressionLength++;
if (index + 1 == length)
{
retVal[jIndx] = str.substring(index + 1 - expressionLength, index + 1);
}
}
return retVal;
}
This is the (not so beautiful) solution
lsSagor = "some text# Some more text# More text~Text again\n Text# text~Some text ..."
String lsSagor = getFileFromUrl(BASEURL+"/sagor.txt");
final String[] laList = lsSagor.split("~");
giAntalSagor = laList.length;
String[] laSaga = laList[0].split("#");
final String[] guiLaList = new String[giAntalSagor];
for (int i = 0; i < giAntalSagor; i++)
{
guiLaList[i] = laList[i].replaceAll("#", "\n");
}
guiLaList is used for layout with "\n" and the other list laList to get the information I wanted.

Categories

Resources