I'm new to Android. I want to create a group of radiobuttons in application that I'm working on, but I want to define the number of radiobuttons from csv file or database.
In a way that if I have two options in the csv file, show me 2 radiobutton and If I have 3 options in the csv file show me 3 radiobuttons.
How can i achieve this?
I'm using eclipse
1) read the csv file:
How to read csv file in android?
2) in your application add for each option a radiobutton dynamically:
how to set dynamically created Radio buttons into a RadioGroup?
Peace on you
to set dynamically created Radio buttons into a RadioGroupfor I find this solution
http://androiddesk.wordpress.com/2012/08/05/creating-dynamic-views-in-android/
and to parce the csv file I've used this fonction
private String[] loadArrayFromFileName(){
String[] liste=null;
String[] liste2=null;
String liste3=null;
int s=0;
try {
// Get input stream and Buffered Reader for our data file.
InputStream is = FocusTow.this.getAssets().open("Test.csv");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
//Read each line
while ((line = reader.readLine()) != null) {
liste2=line.split("\n");
for(int i=0; i< liste2.length;i++){
if(s==0) {
liste3=liste2[i];
s=1;
}
else liste3=liste3+","+liste2[i];
}
}
liste=liste3.split(",");
//Read each line
} catch (IOException e) {
e.printStackTrace();
}
return liste;
}
and this is the code of my button listener
mybutton.setOnClickListener(new OnClickListener() {
int j=0;
final String[] liste=loadArrayFromFileName();
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for( j=0;j<liste.length/2;j++){
RadioButton radiobutton=new RadioButton(getApplicationContext());
radiobutton.setText(liste[j*2+1]);
radioGroup.addView(radiobutton);
}
}
});
I hope this help u,
Thanks.
Related
i want create a book in android stodio
for example: i want when i click on first_season button open text1.txt file and when click on second_season button open text2.txt file and the rest as I said.
and i dont want make a activity for each page.
and i want use switch case for get button id and based on that id open the text file.
i just want to know how use switch case for create this application.
i use this code for open txt file:
TextView txtView = (TextView)findViewById(R.id.hellotxt);
InputStream inputStream = getResources().openRawResource(R.raw.nitish);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
txtView.setText(byteArrayOutputStream.toString());
consider names of my buttons are
season1, season2, season3, season4
and name of my text files are
txt1, txt2, txt3, txt4
thank for helping
Something like this you mean?
Map<Int, String> lookupTable = new HashMap<>();
lookupTable.put(R.id.season1, "txt1");
lookupTable.put(R.id.season2, "txt2");
// etc
for (Map.Entry<String,String> entry : lookupTable.entrySet()) {
findViewById(entry.getKey()).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtView.setText(readBookPageFromFile(entry.getValue());
}
})
}
Where readBookPageFromFile is your above code with the filename as a parameter.
I am working on a simple word processing app, and I'm close to the point of being able to release it, except that I have one problem. When I click on an item in a ListView that displays the file names of all the text files the user has created with my app, I would like to open the file that corresponds with the item name, and place the text from that file inside the main EditText that the user uses to input data. However, when the item is clicked, nothing happens. Here is my code for that action.
filesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemName = filesListView.getItemAtPosition(position).toString();
FileInputStream fis;
String content = null;
try {
fis = openFileInput(itemName);
byte[] input = new byte[fis.available()];
while (fis.read(input) != -1) {
content += new String(input);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
textEntryEditText = (EditText) findViewById(R.id.textEntryEditText);
textEntryEditText.setText(content);
}
});
Please help. Thanks!
EDIT: SOLVED, check my Answer to see what I did.
There might be a problem with the focusable of your listView items.Set the focusable to false for the editText in the ListView.
Try to get the file or path object from the Listview adapter not file name.
when using openFileInput(String) method it creates or get the file from application files folder not from that file location. so use BaseAdapter and get File object using getItem(int) method
I believe you are using any a dapter for binding data to your listView,
So in custom adapter class
if(convertView==null){
convertView.setTag(holder);
convertView.setTag(R.string.fileName, array.get(position).getfileName());
}else {
holder = (ViewHolder) convertView.getTag();
}
then on item click try to fetch file name like this
fileName = view.getTag(R.string.fileName).toString();
Never mind, I solved it. After several hours of tears, rage, and frustration, I finally solved it, lol. But thank you everyone who responded. As for anyone else who has a similar problem, here's what I did.
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemName = filesListView.getItemAtPosition(position).toString();
StringBuffer fileRead = new StringBuffer("");
try {
FileInputStream fileInputStream = new FileInputStream(new File(getDir("FOLDER", Context.MODE_APPEND), itemName));
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String readString = bufferedReader.readLine();
while (readString != null) {
fileRead.append(readString);
readString = bufferedReader.readLine();
}
fileInputStream.close();
inputStreamReader.close();
bufferedReader.close();
textEntryEditText.setText(fileRead);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
My previous method of using the openFileInput was flawed, because I was trying to locate the file inside the default directory that openFileInput looks in, which is not where my file was. After, I tried referencing it directly, and found out that openFileInput does not allow this. So, I eventually tried just making a new FileInputStream, and telling it to make a new File object that uses the getDir method to reference the directory FOLDER, and the name of the file as determined by itemName. Hopefully this helps other who were struggling as I was, so that they don't have to suffer like I did. Thanks again to those who responded, even if I didn't use your advice!
Keep getting ArrayIndexOutOfBoundsException when trying to display a specific item form array list data displays fine in logcat but then after displaying throws exception at top please help is the code kind of new to android
public void loadData(){
InputStream file = ourContext.getResources().openRawResource(R.raw.cashpot);
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
String line ="";
ArrayList<String> values = new ArrayList<String>();
try {
while((line = reader.readLine()) != null) {
values.add(line);
// String[] strings = line.split(",");
/*for(String s : strings) {
values.add(s);
}*/
}
reader.close();
//for(String s : values) Log.d("CSV Test", s);
for(int i = 0; i < values.size();i++){
String[] data = values.get(i).split(",");
Log.d("Test String",data[2] );
}
} catch (IOException e) {
e.printStackTrace();
}
}
Your some lines do not have comma(,)(or 1 comma) and you are trying to split them by comma and storing it in to data array. and you are accessing data[2] location. which might not been created that's why you are getting this exception.
There might not be a 3rd element in your array ,that is created after the split on ",".
You can print value of data before accessing data[2](that might not exist).
Or you can Debug your program and proceed step by step and monitoring the value of each variable.
I'm trying to read excel contents in android, but always get file not found exception
The project is in:
C:\AndroidWorkSpace\AntenaProject
And the code is:
public void TestClick(View view)
{
File inputWorkbook = new File("shidur.xls");
Workbook w;
StringBuilder sb = new StringBuilder("starting");
try {
w = Workbook.getWorkbook(inputWorkbook);
// Get the first sheet
Sheet sheet = w.getSheet(0);
// Loop over first 10 column and lines
for (int j = 0; j < sheet.getColumns(); j++) {
for (int i = 0; i < sheet.getRows(); i++) {
Cell cell = sheet.getCell(j, i);
//CellType type = cell.getType();
sb.append(cell.getContents());
}
}
} catch (Exception e) {
e.printStackTrace();
}
TextView tv = (TextView)findViewById(R.id.testText);
tv.setText(sb.toString());
}
i tried to put shidur.xls in the following folders:
C:\AndroidWorkSpace\AntenaProject\res\raw
C:\AndroidWorkSpace\AntenaProject\res
but still getting this exception.
i'm using jxl.jar from http://jexcelapi.sourceforge.net/
thanks for the help
The path that you provide to the File constructor needs to be the absolute path of the file, or you need to use the overload that takes another File object as the first parameter which represents the directory the file lives in.
That being said, constructing a file in this way is for files that are either in local storage (ie. phone's main memory) or external storage (ie. SD card).
To open a file from the res/raw directory, get an InputStream in the following way
InputStream in = getResources().openRawResource(R.raw.file_name);
Then, you will need code that reads the contents of your input stream. I use a static helper method that looks like this, but this could run you into problems if the file is huge. Hasn't happened to me yet, but in principle that's always a risk when loading the entire content of a file into memory
public static String readStream(InputStream in)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch(Exception ex) { }
finally
{
// NOTE: you don't have my IOUtils class,
// but all these methods do is check for null and catch the exceptions that Closeable.close() can throw
IOUtils.safeClose(in);
IOUtils.safeClose(reader);
}
return sb.toString();
}
You should use the following code to open file in the /res/raw
getResources().openRawResource(R.raw.shidur.xls)
I have a CSV file in drawable/asset folder. In the CSV file there are four columns. First one is for date and rest three are for integer data.
I need to parse this CSV file and save the data in separate arrays.
I have searched for a solution, but I don't get proper idea on how to do this.
I like this csv reader: https://mvnrepository.com/artifact/net.sf.opencsv/opencsv/2.3
Just add it to your project.
Example code (assuming there is the file assets/test.csv):
String next[] = {};
List<String[]> list = new ArrayList<String[]>();
try {
CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("test.csv")));
while(true) {
next = reader.readNext();
if(next != null) {
list.add(next);
} else {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
You can access the imported data with, for example,
list.get(1)[1]
That would return a string.