I'm trying to get different ID with for. What I have is a CardView with diferent IDs for each card and I would like to get data when clicked.
I have done this:
public void setToggleEvent(final GridLayout mainGrid) {
for ( int i = 0; i < mainGrid.getChildCount(); i++){
count = i;
final CardView cardView = (CardView)mainGrid.getChildAt(i);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(cardView.getCardBackgroundColor().getDefaultColor() == -1) {
for (int f = 0; f < mainGrid.getChildCount(); f++){
if (f == count) {
int index = f;
String idFood = "food" + index;
int resID = getResources().getIdentifier(idFood, "id", getPackageName());
foodName = findViewById(resID);
foodName.getText();
}
}
//canvi color de fons
cardView.setCardBackgroundColor(Color.parseColor("#FF6F00"));
foodData = foodName.toString();
selectedVegetables.add(foodData);
} else {
cardView.setBackgroundColor(Color.parseColor("#FFFFFF"));
Toast.makeText(VegetablesActivity.this, "Food Selected", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Each card has a ID called: food0, food1, food2....
As you can see in the code I did this to get the IDs:
String idFood = "food" + index;
int resID = getResources().getIdentifier(idFood, "id", getPackageName());
foodName = findViewById(resID);
foodName.getText();
and then:
foodData = foodName.toString();
selectedVegetables.add(foodData);
But when I run it says that foodName is null ( java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference)
and is in this line where the error shows up
foodName.getText();
Any idea?
Sorry for my bad english, it's not my native lenguage, hope everyone could understand this.
I surprised! this is not actually logical!
foodName = findViewById(resID);
int resID not provide you like this: "R.id.exampleId" type of id.
resID Only provide you a integer value.
Related
I am designing UI and for that need to populate some dummy content for recyclerview. So I thought to create using for loop so it makes life easier if I want to change the number.
I have drawable resources (images) that suffix with numbers. for instance
avatar_1, avatar_2, avatar_3, ...
featured_1, featured_2, featured_3, ...
I have tried setting R.drwable.featured_ + i and as expected it didn't work and end up with an error.
This is what I am using
...
for (int i = 0; i <= 11; i++) {
int username = random.nextInt(userNames.length);
int catInt = random.nextInt(categories.length);
int time = random.nextInt(times.length);
mBlogs.add(new Blog(
R.drawable.featured_ + i, // this
R.drawable.avatar_ + i, // this
getString(R.string.blog_title),
categories[catInt],
getString(R.string.blog_excerpt),
userNames[username],
times[time],
random.nextBoolean(),
random.nextBoolean()
));
}
...
Question: How can I get resource within the loop by loop index?
Try as below.
//find drawable resource id
public int getDrawableId(Context context, String name)
{
try {
return getResources().getIdentifier(name, "drawable", context.getPackageName());
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
...
for (int i = 0; i <= 11; i++) {
int username = random.nextInt(userNames.length);
int catInt = random.nextInt(categories.length);
int time = random.nextInt(times.length);
int featuredRes = getDrawableId(context, "featured_" + i);
int avatarRes = getDrawableId(context, "avatar_" + i);
// if not found any resource
if (featuredRes == 0) featuredRes = R.drawable.featured_default
if (avatarRes == 0) avatarRes = R.drawable.avatar_default
mBlogs.add(new Blog(
featuredRes,
avatarRes,
getString(R.string.blog_title),
categories[catInt],
getString(R.string.blog_excerpt),
userNames[username],
times[time],
random.nextBoolean(),
random.nextBoolean()
));
}
...
You can use getIdentifier
for (int i = 0; i <= 11; i++) {
int featuredResId = getResources().getIdentifier("featured_" + i, "drawable", getPackageName())
int avatarResId = getResources().getIdentifier("avatar_" + i, "drawable", getPackageName())
//...
mBlogs.add(new Blog(
featuredResId,
avatarResId,
//...
));
}
I'm new to android and I am currently having this problem on onClick():
I have dynamically created textViews within a TableLayout() and each textviews have onClickListener. The code is like this:
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//change the color of tapped textview
text.setTextColor(Color.WHITE);
text.setBackgroundColor(Color.parseColor("#c04485ed"));
String a = view.getTag().toString();
String b = text.getText().toString();
uTxt.setText(""+uTxt.getText().toString() + b);
if(uTxt.length() == 4){
if(checkAns(uTxt, list)){
Log.e("OUTPUT: " , uTxt.getText().toString().toLowerCase() + " IS ON THE ARRAY!");
}
else if (!checkAns(uTxt, list))
{
Log.e("OUTPUT: " , uTxt.getText().toString() + " IS NOT ON THE ARRAY!");
}
}
}
});
I also initialized a method called checkAns() and it goes like this:
private boolean checkAns(TextView uTxt, List<String> list) {
String word = uTxt.getText().toString().toLowerCase();
if (list.contains(word)) {
return true;
}
else {
return false;
}
}
The purpose of that method is to catch the created word and check if the formed word is on the array.
But that method always returns false. Is there anything wrong with my logic?
Any help, comments, and suggestions are welcome. :)
EDIT:
#k3b ask me where the list is populated. So here is the full code of the textView grid that i created:
RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
final TableLayout table = (TableLayout) findViewById(R.id.mainLayout);
table.setTag(1);
final Typeface font = Typeface.createFromAsset(getAssets(), "kg.ttf");
final Typeface font2 = Typeface.createFromAsset(getAssets(), "futura.ttf");
final String[] wordArray = new String[Category.size];
final TextView uTxt = (TextView)findViewById(R.id.userTxt);
for(int i = 0; i < Category.size; i++){
wordArray[i] = listahan[i];
}
final List<String> list = Arrays.asList(wordArray);
for (int i = 0; i < input.length; i++) {
final LinearLayout rowLayout = new LinearLayout(this);
rowLayout.setOrientation(LinearLayout.HORIZONTAL);
rowLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
final TableRow row = new TableRow(this);
row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
row.setGravity(Gravity.CENTER_HORIZONTAL);
row.setTag(i);
int k = 0;
for (int j = 0; j < input.length; j++) {
final TextView text = new TextView(this);
Character temp = input[i][j];
text.setText(temp.toString());
text.setPadding(20, 20, 20, 20);
text.setTag(i + " " + j);
text.setTextSize(txtSize);
text.setTypeface(font);
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//change the color of tapped textview
text.setTextColor(Color.WHITE);
text.setBackgroundColor(Color.parseColor("#c04485ed"));
String a = view.getTag().toString();
String b = text.getText().toString();
uTxt.setText(""+uTxt.getText().toString() + b);
if(uTxt.length() == 4){
if(checkAns(uTxt, list)){
Log.e("OUTPUT: " , uTxt.getText().toString().toLowerCase() + " IS ON THE ARRAY!");
}
else if (!checkAns(uTxt, list))
{
Log.e("OUTPUT: " , uTxt.getText().toString() + " IS NOT ON THE ARRAY!");
}
}
}
});
text.setGravity(Gravity.CENTER);
row.addView(text);
}
Thanks for all the help guys. I managed to fix the error. It seems that the code that initialized my array of words is not properly coded! Thanks guys!
I use the debugger to find that the value of townHallLvl stays 1 at the end
Please help
int townHallLvl = 1;
public void addTownHall(View v){
if (townHallLvl == 11) {
Toast.makeText(this, "You can't have more than Town Hall lvl 11!!!", Toast.LENGTH_SHORT).show();
return;
}
add(townHallLvl);
TextView townHallText = (TextView) findViewById(R.id.town_hall_lvl);
townHallText.setText(String.valueOf(townHallLvl));
}
public int add(int lvl){
int ans = lvl + 1;
return ans;
}
townHallLvl = add(townHallLvl);
You probably missed to assign back the value to townHallLvl.
I have receipt and logs model in android app. Receipt hasMany logs.
I made query for group_by logs by sortID and grade.
//recieve RecepitID and query to group logs
final long forwardedId = (long) getIntent().getExtras().get(String.valueOf("recepitID"));
List<Logs> logsList = new Select().from(Logs.class).where("Receipt = " + forwardedId).groupBy("SortID, Grade").execute();
This grouping works fine. Problem is next. I need to have output like this (part in red circle):
but I get it like this:
And this is part of code how I done this.
public class LogsRecapitulation extends AppCompatActivity {
private ListView mainListView;
private BaseAdapter listAdapter;
private TextView logsCount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recapitulation_listview);
mainListView = (ListView) findViewById(R.id.ListViewItem);
//recieve RecepitID and query to group logs
final long forwardedId = (long) getIntent().getExtras().get(String.valueOf("recepitID"));
List<Logs> logsList = new Select().from(Logs.class).where("Receipt = " + forwardedId).groupBy("SortID, Grade").execute();
TextView result = (TextView) findViewById(R.id.LogMassResult);
double sum = 0.0;
for (int i = 0; i < logsList.size(); i++) {
sum += logsList.get(i).getM3();
}
result.setText(String.format("%.2f m3", sum));
for (int i = 0; i < logsList.size(); i++) {
if (logsList.get(i).receipt.priceType.equals("Na panju")) {
TextView stumpPriceKN = (TextView) findViewById(R.id.sumPriceKN);
double sumPricekn = 0.0;
for (int j = 0; j < logsList.size(); j++) {
sumPricekn += logsList.get(j).price.stumpPrice_kn * logsList.get(j).getM3();
}
stumpPriceKN.setText(String.format("%.2f KN", sumPricekn));
} else {
TextView roadKN = (TextView) findViewById(R.id.sumPriceKN);
double roadPrKn = 0.0;
for (int j = 0; j < logsList.size(); j++) {
roadPrKn += logsList.get(j).price.roadPrice_kn * logsList.get(j).getM3();
}
roadKN.setText(String.format("%.2f KN", roadPrKn));
}
}
for (int i = 0; i < logsList.size(); i++) {
if (logsList.get(i).receipt.priceCorrection > 0 && logsList.get(i).receipt.priceType.equals("Na panju")) {
TextView corecctionPriceKn = (TextView) findViewById(R.id.correctionPriceKN);
double correcSumKN = 0.0;
for (int j = 0; j < logsList.size(); j++) {
correcSumKN += (logsList.get(j).price.stumpPrice_kn * logsList.get(j).getM3()) + ((logsList.get(j).price.stumpPrice_kn * logsList.get(j).getM3()) * logsList.get(j).receipt.priceCorrection / 100);
}
corecctionPriceKn.setText(String.format("%.2f KN", correcSumKN));
} else if (logsList.get(i).receipt.priceCorrection > 0 && logsList.get(i).receipt.priceType.equals("Šumska cesta")) {
TextView corecctionPriceKn = (TextView) findViewById(R.id.correctionPriceKN);
double correcSumKN = 0.0;
for (int j = 0; j < logsList.size(); j++) {
correcSumKN += (logsList.get(j).price.roadPrice_kn * logsList.get(j).getM3()) + ((logsList.get(j).price.roadPrice_kn * logsList.get(j).getM3()) * logsList.get(j).receipt.priceCorrection / 100);
}
corecctionPriceKn.setText(String.format("%.2f KN", correcSumKN));
} else {
TextView priceHolder = (TextView) findViewById(R.id.KorekcijaCijene);
TextView corecctionPriceKn = (TextView) findViewById(R.id.correctionPriceKN);
priceHolder.setText("");
corecctionPriceKn.setText("");
}
}
listAdapter = new RecapitulationArrayAdapter(logsList);
mainListView.setAdapter(listAdapter);
//display logs count
logsCount = (TextView) findViewById(R.id.logsCount);
logsCount.setText(String.valueOf(logsList.size()));
}
private class RecapitulationArrayAdapter extends BaseAdapter {
private LayoutInflater inflater;
private List<Logs> logsList;
public RecapitulationArrayAdapter(List<Logs> logsList) {
inflater = LayoutInflater.from(LogsRecapitulation.this);
this.logsList = logsList;
}
#Override
public int getCount() {
return logsList.size();
}
#Override
public Object getItem(int position) {
return logsList.get(position);
}
#Override
public long getItemId(int position) {
return logsList.get(position).getId();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.logs_recapitulation, parent, false);
}
Logs log = logsList.get(position);
((TextView) convertView.findViewById(R.id.rec_log_sort)).setText(log.sort_id);
((TextView) convertView.findViewById(R.id.rec_log_class)).setText(log.grade);
((TextView) convertView.findViewById(R.id.rec_log_count)).setText(String.valueOf(logsList.size()));
((TextView) convertView.findViewById(R.id.rec_logs_mass)).setText(String.format("%.2f m3", log.getM3()));
if (log.receipt.priceType.equals("Na panju")) {
((TextView) convertView.findViewById(R.id.rec_log_price_default)).setText(String.valueOf(log.price.stumpPrice_kn));
} else {
((TextView) convertView.findViewById(R.id.rec_log_price_default)).setText(String.valueOf(log.price.roadPrice_kn));
}
if (log.receipt.priceType.equals("Na panju")) {
((TextView) convertView.findViewById(R.id.rec_calculated_price)).setText(String.format("%.2f KN", log.price.stumpPrice_kn * log.getM3()));
} else {
((TextView) convertView.findViewById(R.id.rec_calculated_price)).setText(String.format("%.2f KN", log.price.roadPrice_kn * log.getM3()));
}
return convertView;
}
}
}
I'm using ActiveAndroid and displaying this in listview.
PROBLEM is with displaying these grouped items. I’m displaying them in BaseAdapter listView and it shows me only one item per group but it needs to show me multiple items (because it has more than 4 items in each group).
Can anyone give me advice what should I do to get output like on first image?
It looks like you are trying to get results similar to the following SQL:
select sort, grade, count(grade), sum(mass), price from logs where receiptid = forwardedId group by sort, grade;
You show the displayed count computed as logList.size(). Instead, if you are going to have the database group the records, you will want to get the count from the database as well.
A couple of things may also help.
1. Verify the SQL query directly against the database to verify you are starting with the intended result set. You can use the sqlite3 client to test assuming you are using an SQLite db.
2. Enable ActiveAndroid logging in ActiveAndroid.initialize
Also you might double check the parameter spelling to make sure you are referencing the intended intent parameter.
Once you verify that the query results are correct, you can focus on whether you are rendering it in the list as you wish.
Finally be wary of doing work on the UI thread.
User 'user650881' is right (I cannot vote since repo < 50).
Additionally to achieve the summary for the total table you may execute the following SQL query:
select /*sort, grade,*/ count(grade), sum(mass), price from logs where receiptid = forwardedId /*group by sort, grade*/;
if you would like to have the items grouped by different fields you may also try widow functions i.e.:
select count(grade) over(partition by fieldName)
and group by is eventually not necessary
In my activity, I am creating a dynamic radiogroup. I have some questions and answers in Sqlite database, retrieving them in activity and then set in RadioGroup. This is working fine. But after that, I want to get all ID of selected radio button by user to store them in database. In general, we do something like this when we have option's ID :
id1=rdgroup1.getCheckedRadioButtonId();
que1=(RadioButton)findViewById(id1);
ans1=que1.getId()+""; // so here I will get radio button's ID.
So my questions is, how will I get selected radio button's ID. Here's my code for dynamically creating radiogroup.
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linear1);
c1=db.rawQuery("SELECT * FROM QueTable WHERE AgeGroup='10-20'", null);
c1.moveToFirst();
int i = c1.getCount();
if(i > 0)
{
Log.w("START", "start");
while (i > 0)
{
TextView title = new TextView(this);
questions = c1.getString(1);
title.setText(questions);
title.setTextColor(Color.BLACK);
mLinearLayout.addView(title);
// create radio button
answers=c1.getString(2);
String[] answer = answers.split(",");
rb = new RadioButton[5];
rg = new RadioGroup(this);
rg.setOrientation(RadioGroup.VERTICAL);
int k = answer.length;
for (int j = 0; j < k; j++)
{
rb[j] = new RadioButton(this);
rg.addView(rb[j]);
rb[j].setText(answer[j]);
}
mLinearLayout.addView(rg);
c1.moveToNext();
i--;
}
}
The place where you create RadioButton set and Id to it
for (int j = 0; j < k; j++)
{
RadioButton rb = new RadioButton(this);
rb.setId(Somenumber + j)
rb[j] = rb;
rg.addView(rb[j]);
rb[j].setText(answer[j]);
}
Like this you can setId or also if you want you can add tag to process.
rb.setTag(SomeObject)
You need to set an ID for your programmatically created RadioButton in order to find it using findViewById as you show in your first code.
To set the ID for your RadioButton, you can use View.setId(). The documentation says:
Sets the identifier for this view. The identifier does not have to be
unique in this view's hierarchy. The identifier should be a positive
number.
The identifier does not have to be unique, but if it's not unique, findViewById will return the first occurence, so you can use the static method View.generateViewId added on API level 17.
If you are using lower APIs, you may want to write your own function to find a suitable (unused) ID. You can take a look at Android: View.setID(int id) programmatically - how to avoid ID conflicts?
Ok..So finally I got the solution. I am going to share complete code here that will create dynamically radiogroup and radiobuttons from database. Here is code below :
private static final int RB_ID = 100;
int k=0,len=0,r=0,p = 0,q=0, len = 0;
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linear1);
c1 = db.rawQuery("SELECT * FROM QueMotion WHERE AgeGroup ='"+Age+"' LIMIT 5", null);
c1.moveToFirst();
int i = c1.getCount();
rg = new RadioGroup[i];
rb = new RadioButton[i*5];
if (i > 0) {
Log.w("START", "start");
while (i > 0)
{
TextView title = new TextView(this);
questions = c1.getString(1);// retrive from database
title.setText(questions);
title.setTextColor(Color.BLACK);
title.setTypeface(null, Typeface.BOLD);
title.setPadding(0, 0, 0, 10);
mLinearLayout.addView(title);
answers = c1.getString(2);// retrive from database
String[] answer = answers.split(",");// will create options for radio button.
rg[p] = new RadioGroup(this);
rg[p].setOrientation(RadioGroup.VERTICAL);
len=len+answer.length;
for (int j = 0; j < answer.length; j++)
{
rb[q] = new RadioButton(this);
rg[p].addView(rb[q]);
rb[q].setId(k + RB_ID);
rb[q].setText(answer[j]);
k++;
q++;
}
mLinearLayout.addView(rg[p]);
c1.moveToNext();
i--;
p++;
}
//Submit button click
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (rg[0].getCheckedRadioButtonId() == -1)
{
Log.e("Nothing selected", "Nothing selected");
}
else
{
for (r = 0; r < len; r++) {
if (rb[r].isChecked()) {
RadioButton id = (RadioButton) findViewById(rb[r].getId());
String radioText = id.getText().toString();
c3.moveToFirst();
Log.e("RadioString", radioText);
} else {
Log.e("RadioString", "nothing");
}
}
}
}
});