is it possible to loop through the ids to findViewById android [duplicate] - java

This question already has answers here:
Android getResources/getIdentifier not returning ID
(2 answers)
Closed 7 years ago.
I Have a table created on the GUI but I'm stuck on looping through the IDs of the views as it is not a string that goes in the path. HELP anyone please!
for example IDs are tMon9, tMon10, tMon11 etc...
String classgroup = "CO.DNET3";
int semester = 2;
Timetable t = null;
try {
t = new Timetable(classgroup, semester);
} catch (IOException e) {
e.printStackTrace();
}
if(t!=null)
{
TextView tv;
for (int i = 9; i < 18; i++) {
if (t.getModule("wednesday", i + ":00") != null) {
tv=(TextView)findViewById(R.id. (LOOP HERE) ); // I want to loop through ids
String s = "";
s+= t.getModule("wednesday", i + ":00") + "\n";
s+= t.getRoomNumber("wednesday", i + ":00") + "\n";
tv.setText(s);
}
}
}

Use getIdentifier to get id of View using String name:
int textViewID = getResources().getIdentifier("tMon"+i, "id", getPackageName());
tv=(TextView)findViewById(textViewID);

Related

Cannot generate url image with AsyncTask [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I have a list of number of url and its name is listOfUrlSources,
I passed it inside class GenerateUrlImages the task of this class is to come out with a picture link and it works if you use it and pass a link to one site it gives out a picture link, but now I'm trying to pass more than one site for it and also give me links to photos I tried, but I didn't make it through a list.
//
for (int i = 0; i < sources.size(); i++) {
item = new GenerateImage(sources.get(i).getUrl());
// networkImagesLiveData.setValue(createLiveDataForLoadingImage(sources.get(i).getUrl()));
listOfUrlSources.add(item);
}
new GenerateUrlImages().execute(listOfUrlSources);
//---------
//
public class GenerateUrlImages extends AsyncTask<List<GenerateImage>, Void, List<GenerateImage>>{
public GenerateUrlImages(){
}
#Override
protected List<GenerateImage> doInBackground(List<GenerateImage>... arrayLists) {
List<String> result = new ArrayList<String>();
List<GenerateImage> passed = new ArrayList<GenerateImage>();
passed = arrayLists[0];
//get passed arraylist
//urlImages
String src="";
try {
org.jsoup.nodes.Document doc1;
Elements img2;
GenerateImage Item;
for(int i=0; i<passed.size(); i++) {
doc1 = Jsoup.connect(passed.get(i).getUrl()).get();
//Elements img = doc1.getElementsByTag("img");
img2 = doc1.getElementsByTag("meta");
for(Element element : img2) {
if("og:image".equals(element.attr("property"))) {
src = element.attr("content");
Item = new GenerateImage(src);
urlImages.add(Item);
}
}
for (int j = 0; j < urlImages.size(); j++) {
Log.d("getUrlImage:", "" + urlImages(j));
}
}
//InputStream in = new java.net.URL(src).openStream();
// bmp = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error :", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute(){
}
protected void onPostExecute(ArrayList<String> result){
}
}
In for loop you did a mistake
for (int j = 0; j < urlImages.size(); j++) {
Log.d("getUrlImage: ", "" + urlImages[j]); // add this line also
}
You have printed the Arraylist without index value using the ArraylistName.get(index) in your case Log.d("getUrlImage: ", "" + urlImages); it should be like Log.d("getUrlImage: ", "" + urlImages.get(j));
after this change in your code, you will be able to see the required result.
for (int j = 0; j < urlImages.size(); j++) {
Log.d("getUrlImage: ", "" + urlImages.get(j));
}

Create ordered Arrays with JSONObject

Let me explain my problem.
(I'm new to java so maybe this type of thing might be easy but I can't figure it out !)
I have a JSONObject which looks like :
{
notes:[
{
"scolaryear":2013,
"codemodule":"B-CPE-042",
"titlemodule":"B1 - Unix & C Lab Seminar",
"codeinstance":"NCE-1-1",
"codeacti":"acti-134315",
"title":"Piscine Jour 1",
"date":"2013-10-04 13:33:51",
"correcteur":"ramassage-tek",
"final_note":0,
"comment":"Ex_00 -> output differs"
},
{} // And so on ..
]
}
For now I can get all the data doing something like :
try {
// Pulling items from the array
JSONArray notesArr = jsonObject.getJSONArray("notes");
try {
ListView lv = (ListView) _modulesActivity.findViewById(R.id.listView);
List < String > notesList = new ArrayList < String > ();
for (int i = 0; i < notesArr.length(); i++) {
JSONObject tmp = notesArr.getJSONObject(i);
String code_module = tmp.getString("codemodule");
String module = tmp.getString("titlemodule");
String title = tmp.getString("title");
String final_note = tmp.getString("final_note");
String year = tmp.getString("scolaryear");
String comment = tmp.getString("comment");
String display = year + " | " + title + " | " + final_note;
notesList.add(display);
}
ArrayAdapter < String > arrayAdapter = new ArrayAdapter < String > (
_mainContext, android.R.layout.simple_list_item_1, notesList);
lv.setAdapter(arrayAdapter);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(_mainContext, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(_mainContext, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
So with that technique I got all my data in one array and an only listView which looks like :
2014 | PROJECT #1 | 13/20
2015 | PROJECT #2 | 20/20
But I need to order my data with year, and module.
It would look like :
> YEAR (year)
> TITLE OF MODULE (module) - MODULE CODE (codemodule)
> PROJECT NAME (title) | MARK (final_note)
- COMMENT (comment)
You have a first header with the year, when you click on a year, you can see all the module :
> MODULE #1
> MODULE #2
...
And when you click on a module you can see all project :
> PROJECT #1 | MARK : 20
> PROJECT #2 | MARK : 13
...
And finally when you click on a project you can see the comment !
^ PROJECT #1 | MARK : 20
- Great project .. bla bla bla
(or maybe display a popup window which contains the comments if it's possible)
I know it may be a complexe thing but I really want to achieve that !
Thanks in advance for your help !
In my opinion you have two possibilities:
Implement a Note Java object, during the form initialize this objects and put them in an ArrayList. In the end sort it with some algorithm.
For example it would look like:
List<Note> notesList = new ArrayList<Note>();
for (int i = 0; i < notesArr.length(); i++) {
JSONObject tmp = notesArr.getJSONObject(i);
noteListe.add(new Note(tmp.getString("codemodule"), tmp.getString("titlemodule"),...);
}
Now sort it with a proper method and in the end print it maybe overriding toString() Note method.
If possible sort the JsonObjectArray when you create it.
Hope it can help you
So I found a solution !
I used this library : https://github.com/bmelnychuk/AndroidTreeView
Here is my Code :
try {
// Pulling items from the array
TreeNode root = TreeNode.root();
TreeNode child;
String year = "YEAR";
String moduleName = "";
YearHolder.IconTreeItem nodeItem = new YearHolder.IconTreeItem(1, year);
ModuleHolder.IconTreeItem nodeModule = new ModuleHolder.IconTreeItem(1, moduleName);
TreeNode parent = new TreeNode(nodeItem).setViewHolder(new YearHolder(_mainContext));
TreeNode parentModule = new TreeNode(nodeModule).setViewHolder(new ModuleHolder(_mainContext));
JSONArray modArr = jsonObject.getJSONArray("notes");
try {
for (int i = 0; i < modArr.length(); i++) {
JSONObject tmp = modArr.getJSONObject(i);
/*String title = tmp.getString("title");*/
String final_note = tmp.getString("final_note");
String newModuleName = tmp.getString("titlemodule");
String newYear = tmp.getString("scolaryear");
if (!(newYear.equals(year))) {
year = newYear;
nodeItem = new YearHolder.IconTreeItem(1, year);
parent = new TreeNode(nodeItem).setViewHolder(new YearHolder(_mainContext));
root.addChild(parent);
}
if (!(newModuleName.equals(moduleName))) {
moduleName = newModuleName;
nodeModule = new ModuleHolder.IconTreeItem(1, moduleName);
parentModule = new TreeNode(nodeModule).setViewHolder(new ModuleHolder(_mainContext));
parent.addChild(parentModule);
}
NoteHolder.IconTreeItem nodeNote = new NoteHolder.IconTreeItem(1, final_note);
child = new TreeNode(nodeNote).setViewHolder(new NoteHolder(_mainContext));
parentModule.addChildren(child);
/*String display = year + " | " + title + " | " + final_note;*/
}
AndroidTreeView tView = new AndroidTreeView(_notesActivity, root);
_notesActivity.setContentView(tView.getView());
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(_mainContext, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(_mainContext, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
YearHolder class looks like this :
public class YearHolder extends TreeNode.BaseNodeViewHolder<YearHolder.IconTreeItem> {
public YearHolder (Context context ) {
super(context);
}
#Override
public View createNodeView(TreeNode node, IconTreeItem value) {
final LayoutInflater inflater = LayoutInflater.from(context);
final View view = inflater.inflate(R.layout.custom_notes_view, null, false);
TextView tvValue = (TextView) view.findViewById(R.id.text_title);
tvValue.setText(value.text);
return view;
}
public static class IconTreeItem {
public int icon;
public String text;
IconTreeItem(int icon_, String text_) {
this.icon = icon_;
this.text = text_;
}
}
}
Super easy to use !

J2ME , Quizz using choiceGroups

I am working on a driving licence project on j2Me wich is including Tests like quizz , well and i am having a problem after parsing the questions and moving them into choiceGroups just like that :
if (questions.length > 0) {
for (int i = 0; i < questions.length; i++) {
ChoiceGroup reponses = new ChoiceGroup("Reponses" + i, Choice.EXCLUSIVE);
reponses.append(questions[i].getReponse1(), null);
reponses.append(questions[i].getReponse2(), null);
reponses.append(questions[i].getReponse3(), null);
pass.append(questions[i].getContenu());
pass.append(reponses);
}
}
} catch (Exception e) {
System.out.println("Exception:" + e.toString());
}
disp.setCurrent(pass);
and the next step is the command who's controlling the choiceGroups to test them if they are like the true answer or not .
so i am blocked here .
if (c == valider) {
int result = 0;
for (int i = 0; i < pass.size(); i++) {
String ch = pass.get(i).getLabel();
System.out.println(ch);
}
}
I don't know how to get the choice from the choicegroup
any help
Actually, I am not sure what totally you want for:
This code will help you get selected items from choicegroup that i did long time before:
//get a selected array in choicegroup
private String[] choiceGroupSelected(ChoiceGroup cg) {
String selectedArray[] = new String[cg.size()];
int k = 0;
for (int i = 0; i < cg.size(); i++) {
if (cg.isSelected(i)) {
selectedArray[k] = cg.getString(i);
k++;
}
}
return selectedArray;
}
That function will help me get all selected items for deleting action below:
private void deleteSpecificItem() {
try {
String temp = null;
int index;
//get ChoiceGroup size
int numbers = cgTrip.size();
String selectedItems[] = choiceGroupSelected(cgTrip);
//
rs = services.RecordStoreManager.openRecordStoreByName("TripRS");
re = rs.enumerateRecords(null, null, true);
String[] tripList = new String[2];
for (int i = 0; i < numbers; i++) {
temp = selectedItems[i];
if (temp != null) {
while (re.hasNextElement()) {
try {
index = re.nextRecordId();
System.out.println("RecordID: " + index);
byte[] byteBuff = rs.getRecord(index);
String source = new String(byteBuff);
tripList = services.StringManager.getItems(source, ";", 2);
String strProcess = tripList[0] + "-" + tripList[1];
//inspect all of items in choicegroup and if they are selecting then compare with record
//If comparison is true then delete this record
if (temp.equals(strProcess)) {
System.out.println("Delete RecordID: " + index);
rs.deleteRecord(index);
re.keepUpdated(true);
break;
}
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}
}
}
try {
rs.closeRecordStore();
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
rs = null;
re.destroy();
this.LoadTripItem();
} catch (RecordStoreNotOpenException ex) {
ex.printStackTrace();
}
}

Java - NumberFormatException at linear search

I am having this issue with the NumberFormatException in my program. Basically, I am asked to read a .csv file separated by ; and it looks like this:
// Column Explanation (not in .csv file)
id; Summary; Number; Employee1; Employee2; ....... Employee7;
"1";"Sony";"1600";"Markos";"Nikos";"Antonis";"Nikolas";"Vaggelis";"Markos";"Thanasis";
"2";"HP";"1000";"Marios";"Dimitra";"Nikolia";"Spiros";"Thomas";"Kostas";"Manolis";
"3";"Dell";"1100";"Antonis";"Aggelos";"Baggelis";"Nikos";"Kuriakos";"Panagiotis";"Rafail";
"4";"Acer";"2000";"Marina";"Aggelos";"Spiros";"Marinos";"Xristos";"Antreas";"Basilis";
What I have already done is create a String 2-d array or the .csv file called temp_arr and I am asked to write a method that will run a linear search by id and return that company. So here is the thing.
At first, I thought I should convert the input key from int -> String since my temp_arr is a String and compares the strings (which at that time they would be int but read as Strings) using temp_arr[value][value2].equals(string_key). But I had a NullPointerException.
Then I thought I should better convert my Id's from the temp_arr from String -> Int and then compare with the integer key using == operand. This action returned me a NumberFormatException.
The process is this:
System.out.println("Enter id :");
Scanner input = new Scanner(System.in);
int item = input.nextInt(); // read the key which is an Integer
int id_int; // temp_arr is String and item is int, must convert ids from String -> int
for (int i = 0; i < temp_arr.length; i++)
{
id_int = Integer.parseInt(temp_arr[i][0]); // Convert from String to int
if (id_int == item) // If the Array's Id's are == item
{
System.out.println(item+" is present at location " + (i+1) );
break;
}
if (i == temp_arr.length)
System.out.println(item + " does not exist");
}
My error appears at line 7 and I do not know why.
Read File process:
String csvFile = "sam.csv"; // .csv file to be placed in the project file!
BufferedReader br = null; // ini
String line = "",cvsSplitBy = ";"; // columns asked to be split by ";"
String[] arr = null;
String[][] temp_arr = new String[1000][10];
int temp = 0;
try
{
br = new BufferedReader(new FileReader(csvFile)); //start reading the file
while ((line = br.readLine()) != null) // while the line has words
{
arr = line.split(cvsSplitBy); // creating the array
System.out.println(arr[0] + "\t" + arr[1] + "\t" + arr[2] + "\t" + arr[3] + "\t" + arr[4] + "\t" + arr[5] + "\t" + arr[6] + "\t" + arr[7] + "\t" + arr[8] + "\t" + arr[9] );
for (int i = 0; i<=9; i++)
{
temp_arr[temp][i] = arr[i]; // temp_arr represents (is a copy of) the .csv file
}
temp++;
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
if (br != null)
{
try
{
br.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
System.out.println("Done!\n");
Output (Image) :
Line 106 which is causing the issue is :
id_int = Integer.parseInt(temp_arr[i][0]); // Convert from String to int
Your issue is that your Integer.parseInt() is trying to parse a "2" WITH QUOTATION MARKS. That's the problem.
A quick solution would be to replace this line:
temp_arr[temp][i] = arr[i];
To this:
temp_arr[temp][i] = arr[i].replaceAll("\"", "");
Anyway, I'd like to suggest using a different data structure for your case, because I've done something like this before for a client. Have you ever heard of HashMaps? You can do something like a HashMap with an int key and String[] values to store your data in, and the key can be your id_int. Maybe you can try this implementation next time. It's a lot more elegant.
Hope I was able to help!
Cheers,
Justin
Would help if you also posted some of your data file and how you are reading it in.
But, my guess from what is presented is if you add System.out.println(temp_arr[i][0]) prior to the 7th line or run this code through a debugger you will see that temp_arr[i][0] is not an integer value as that is what the error is telling you.

Finish the logic of search on java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
When the array argi has more than one partition, its only begins to find word from the second url of the array, but why? Correct it please in code. Here the part of it:
I make regular expresion for search by title in url:
private final Pattern TITLE = Pattern.compile("\\<title\\>(.*)\\<\\/title\\>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
And searh logic here:
public String search(String url, String someword) {
try {
InputStreamReader in = new InputStreamReader(new URL(url).openStream(),"UTF-8");
StringBuilder input = new StringBuilder();
int ch;
while ((ch = in.read()) != -1) {
input.append((char) ch);
}
if (Pattern.compile(someword, Pattern.CASE_INSENSITIVE).matcher(input).find()) {
Matcher title = TITLE.matcher(input);
if (title.find()) {
return title.group(1);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (PatternSyntaxException e) {
e.printStackTrace();
}
return null;
}
String[] argi = {"http://localhost:8080/site/dipnagradi","http://localhost:8080/site/contacts"};
for (int i = 0; i < argi.length; i++) {
String result = search(argi[i], word);
if (result != null) {
str = "Search phrase " + "<b>"+ word + "</b>" + " have found " + "" + result + ""+ "<p></p>";
}
else{
str="Search word not found!";
}
if (word == null||word=="") {
str = "Enter a search word!";
}
}
return null;
}
Use if (word == null || word.isEmpty()), (for beginners) never use == in Object comparison in java.
Also, for a more detailed answer, you really need to post your input and expected output. And also what`search() does.
Do not use '==' operator with String as String is an Object and is compared using equals method.. Instead use : if(!"".equals(word){}

Categories