getLocationOnScreen crashes - java

I need to get the coordinates of my app on screen to use them as an offset for a popout.
View tempView = (View) findViewById(R.layout.main);
int[] loc = {0,0};
tempView.getLocationOnScreen(loc); /// crashes here!
Tried this code, but the last line of it makes the app crash. Maybe the tempView I'm getting from the main layout somehow doesn't correspond with the layout on screen?
Any suggestions... thanks! :)
added:
solved
int[] loc = new int[2];
View tempView = (View) findViewById(R.id.LL_whole);
tempView.getLocationOnScreen(loc);
post( String.valueOf(loc[1]) );
works! :)

Try checking to see if tempView is null. I suspect findViewById() is failing to find the id you've given it.
int[] loc = {0,0};
View tempView = (View) findViewById(R.layout.main);
if (tempView != null) {
tempView.getLocationOnScreen(loc);
} else {
Log.d("YourComponent", "tempView was null.");
}
In your XML you have something like this:
<SomeLayout android:id="#+id/myLayout" ... >
<SomeView android:id="#+id/myView" ... />
<SomeOtherView android:id="#+id/myOtherView" .../>
</SomeLayout>
So you want to say:
SomeView v = (SomeView)findViewById(R.id.myView);
Or perhaps:
SomeLayout l = (SomeLayout)findViewById(R.id.myLayout);

findViewById(R.layout.main)
You should place here R.id.something not R.layout.something.

Related

Iterating over drawables in Android

In Android, I have only found answers as to how to open a single specific Drawable from MainActivity.java, but not how to iterate over each Drawable from res/drawables. The Drawables names do not follow any patterns (e.g. being numbered from 0 to 25), so the answer suggested here sadly doesn't solve my problem. Does anyone know how to do the latter?
Thank you in advance :)
First, put your drawables into an arrays
<array name="dashboard_item_menu_drawable">
<item>#drawable/ic_file_green</item>
<item>#drawable/ic_email_green</item>
<item>#drawable/ic_linear_scale_green</item>
<item>#drawable/ic_undo_green</item>
<item>#drawable/ic_check_circle_green</item>
<item>#drawable/ic_archive_green</item>
</array>
Then, iterate your array drawables
val icons = ArrayList<Int>()
val arr = resources.obtainTypedArray(R.array.dashboard_item_menu_drawable)
(0 until arr.length()).forEach {
// get resource id of each drawable
val icon = arr.getResourceId(it, -1)
icons.add(icon)
}
Next, recycles resource
arr.recycle()
Then you can use your drawable
iconView.setImageDrawable(ContextCompat.getDrawable(this, icons[index]))
If you want to iterate through drawables that have similar names like: image1, image2, ..., image10 you can do it like this:
for (int i = 0; i < 10; i++) {
int id = getResources().getIdentifier("image" + i, "drawable", getPackageName());
Drawable d = ContextCompat.getDrawable(this, id);
// your code here
}
The easiest way to do it is to put the names of your drawables in a String array:
String[] symbols = {"first_img", "second_img", "third_img", "fourth_img"};
Then iterate over them like this (I put the images into a GridLayout):
for(String symbol : symbols) {
int id = getResources().getIdentifier(symbol, "drawable", getPackageName());
ImageView img = new ImageView(this);
LinearLayout.LayoutParams imgParams = new LinearLayout.LayoutParams(300, 300);
imgParams.setMargins(30, 30, 30, 30);
img.setLayoutParams(imgParams);
img.setBackgroundResource(id);
symbolGrid.addView(img);
}

Dynamically Generate and show Table in Android Studio

I'm creating my first app on android, accordingly I have low experience to develop android apps and I'm fist time use java too.
What I want ?
I want to generate table from ArrayList
What's the problem ?
I have problem when I generate table. When "for" loop finished debugger stands in catch block (but when I mouse over "e", it writes - "local variable e is not defined" and I can not read some error) after that I see on phone screen -"unfortunately app is closed"
What's happen without For Loop ?
Without For loop everything works well, when I try to show only one object.
Please help and give me suggestions, Thanx.
Hare is Java code:
try {
ArrayList<Persons> otherPersons = new ArrayList<Persons>();
otherPerosons = GetPersonsList();//from service
// /* Find Tablelayout defined in main.xml */
TableLayout tl = (TableLayout) findViewById(R.id.dynamictable);
TextView[] title = new TextView[1000];
TableRow[] tr = new TableRow[1000];
LinearLayout.LayoutParams trparams;
LinearLayout.LayoutParams titleparams;
for (int y=0; y < otherPersons.size(); y++) {
/* Create a new row to be added. */
tr[y] = new TableRow(this);
tr[y].setId(y+100);
tr[y].setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
trparams = (LinearLayout.LayoutParams) tr[y].getLayoutParams();
trparams.setMargins(0, 8, 0, 5); //substitute parameters for left, top, right, bottom
tr[y].setLayoutParams(trparams);
/* Create a TextView to be the row-content. */
title[y] = new TextView(this);
title[y].setText(otherPersons.get(y).Name);
title[y].setId(y +200);
title[y].setTextColor(Color.parseColor("#000000"));
title[y].setGravity(Gravity.LEFT);
title[y].setLayoutParams(new TableLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 34));
titleparams = (LinearLayout.LayoutParams) title[y].getLayoutParams();
titleparams.setMargins(5, 0, 0, 0); //substitute parameters for left, top, right, bottom
title[y].setLayoutParams(titleparams);
tr[y].addView(title[y]);
/* Add row to TableLayout. */
tl.addView(tr[y], new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
}
} catch (Exception e) {
e.printStackTrace();
}
Hare is my Design XML:
<TableLayout
android:id="#+id/dynamictable"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:shrinkColumns="*"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="39dp"
android:stretchColumns="*"
android:background="#ffB224">
</TableLayout>
I don't know the answer, but try to put your exception-output in your logcat output with
try{
}catch(Exception e){
Log.e("ClassName", e.toString());
}
Maybe you see more information about the exception.
Here you can find more information about Android Logging

findViewById with getIdentifier not working

I'm looping through an array, in that for-loop I'm also using this array to get IDs for a couple of spinners:
Integer[] ids;
ids = new Integer[8];
ids[0] = R.id.nr_area;
ids[1] = R.id.nr_municipality;
ids[2] = R.id.nr_method;
ids[3] = R.id.nr_bait;
ids[4] = R.id.nr_sessionhours;
ids[5] = R.id.nr_bifangst_art;
ids[6] = R.id.nr_bifangst_released;
ids[7] = R.id.nr_name;
In the for loop:
for (int i = 0; i < fields.length; i++) {
if(fields[i].contains("*") || fields[i].matches("")){
String test = ids[i].toString();
int resID = getResources().getIdentifier(test, "id", getPackageName());
Spinner spnr = (Spinner) findViewById(resID); //error is on this row
spnr.setBackgroundColor(Color.GREEN);
}
}
Now the error I get is as follows:
android.support.v7.internal.widget.TintEditText cannot be cast to android.widget.Spinner
So I guess this can't be used with a spinner as I found the example code for a EditText.. but how can I do what I'm trying to do with a spinner?
I would appreciate any help! Been fighting with this for hours. Thanks alot..
I think the problem is that either one of the ids is of EditText or id was of EditText and you have changed it to Spinner in your xml lately. Make sure that ids are correct, relate them from xml, if still problem persists, try cleaning your project for indexing again, that should do it.
Hope this helps ...

Why File.exists returns false positive

I have a weird problem with my android File.exists functionality. Below is my code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_file_browser, container);
DataBaseHelper tmpHelper = new DataBaseHelper(getActivity());
ButtonInfoContainer infoContainer = tmpHelper.getVideoWithId(videoId);
//Tmp way to use this. When UX is finished will create a better way.
File f = new File(Environment.getExternalStorageDirectory() + "/aslkfj");
Log.i(StaticValues.TAG, Environment.getExternalStorageDirectory() + "/aslkfj");
LinearLayout tmpView2 = (LinearLayout) view.findViewById(R.id.custom_recordings);
if(f.exists());
{
Log.i(StaticValues.TAG, "f exists");
String[] tmp = f.list();
View tmpView = null;
if(tmp != null)
{
for(int i = 0; i < tmp.length; i ++)
{
tmpView = inflater.inflate(R.layout.list_item, null);
TextView tmpText = (TextView) tmpView.findViewById(R.id.product_name);
tmpText.setText(tmp[i]);
tmpView2.addView(tmpView);
}
}
}
return view;
}
Everything is cool but the weird part is that File.exists returns a false positive for me. It always says that the file exists (just in this app though). the path given above /aslkfj does not exist but when I run this code my logcat outputs f exists. Why would something like that happen.
You have a semi-colon at the end of your if condition: -
if(f.exists()); <-- Semi-colon here is causing problem
Due to this, the following block is just a local block, which will be executed regardless of what your if condition evaluate to.
You have a critical typo:
if(f.exists());
The ; basically ignores the if statement.
This is very handy for quick conditionals like:
if(f.exists())
Log.i(StaticValues.TAG, "f exists");
But an oopies here.

Inflater and loop not working as it should

I am having a problem with a custom view I am currently doing for an app on android, I know there are many questions related with inflaters, but I cannot get around this problem.
the inflater i working just fine, but it should be doing the loop 3 times and is only doing it 1 so I only get one view on my final layout.
the relevant part of the code is this one
void populate(String strcline, String url){
lLfD = (LinearLayout)findViewById(R.id.lLfD);
try{
JSONArray a1 = new JSONArray(strcline);
for(int i = 0; i < a1.length(); i++){
JSONArray a2 = a1.getJSONArray(i);
final String fUserId = a2.getString(0);
String userName = a2.getString(1);
String userPicture = url + a2.getString(2);
View child = getLayoutInflater().inflate(R.layout.cellevery, lLfD);
ImageView avatar = (ImageView)findViewById(R.id.cellAvatar);
downloadFile(userPicture, avatar);
TextView cellName = (TextView)findViewById(R.id.cellName);
cellName.setText(userName);
lLfD.addView(child);
}
}catch(Exception e){
}
pDialog.dismiss();
}
You look like you need to run findViewById only on the inflated view, otherwise it will just find the first one which is only the first one in your loop:
View child = getLayoutInflater().inflate(R.layout.cellevery, lLfD);
ImageView avatar = (ImageView)child.findViewById(R.id.cellAvatar);
downloadFile(userPicture, avatar);
TextView cellName = (TextView)child.findViewById(R.id.cellName);
cellName.setText(userName);
Here's an explanation of findViewById in your loop:
Loop 1:
1LfD->child1->R.id.cellAvatar (findViewById(R.id.cellAvatar) finds this one)
Loop 2:
1Lfd->
child1->R.id.cellAvatar
child2->R.id.cellAvatar (findViewById(R.id.cellAvatar) finds the child1.cellAvatar again)
Loop 3:
1LfD->
child1->R.id.cellAvatar
child2->R.id.cellAvatar
child3->R.id.cellAvatar (findViewById(R.id.cellAvatar) finds the child1.cellAvatar again)
by using child.findViewById(R.id.cellAvatar), it ensures that you find the correct R.id.cellAvatar for each run of the loop.
Does that make sense?
Update 2:
When you call:
getLayoutInflater().inflate(R.layout.cellevery, lLfD);
You are already setting the parent view as the second argument so you don't need to call:
lLfD.addView(child);

Categories