How to dynamically add images from server to a linear layout - java

Hi i am trying to load images from server and add them dynamically into a linearlayout which is inside a scroll view
protected void onPostExecute(ArrayList<RssItem> result) {
Log.i("Async-Example", "onPostExecute Called");
horview = (HorizontalScrollView) aview.findViewById(R.id.homesection);
LinearLayout ll = (LinearLayout) aview.findViewById(R.id.sectionid);
for(int i = 0; i < rssItems.size(); i++){
try{
image = new ImageView(getActivity());
image.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
//text.setText(data.get(position).getTitle());
aview.setTag(rssItems.get(i).getLink());
image.setFocusable(true);
imageLoader.DisplayImage(rssItems.get(i).getLink(), image);
ll.addView(image);
}catch(Exception e) {
}
}
The problem I am facing is: if I am declaring ImageView inside my LinearLayout in xml, then only the last image from the server is added. But if i don't declare the ImageView inside linear layout and instead instantiate and add to it, none of the images from the server replace my actual default icon

You should not add the ImageView with XML inside the LinearLayout, as this will only result in a single view being inflated. Initiating ImageViews on the go as you do should work, but to me it sounds like you are trying to load a list of images fetched from a website, in which case you would normally use a ListView with a custom adapter. There are a lot of tutorials online for this:
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
I think the problem in your code is related to the imageLoader. If you are having problems it, you can always try another one like http://square.github.io/picasso/ and call
Picasso.with(getActivity()).load(rssItems.get(i).getLink()).into(image);

Related

Registering multiple click events programatically (Android/Java)

So i have this program which create my list of cards which are relative layouts and they look like this.
Here is the code of it creation. Ps its in a for loop
LayoutInflater mInflater = (LayoutInflater) atv.getSystemService(atv.LAYOUT_INFLATER_SERVICE);
LinearLayout relativeLayoutz = (LinearLayout) mInflater.inflate(R.layout.rtl_enterprise, parent);
RelativeLayout rl = (RelativeLayout) relativeLayoutz.findViewById(R.id.rl_empresa);
rl.setId(i);
ImageView img = (ImageView) rl.getChildAt(0);
//
//Performance bottleneck needs fixing/ not loading all images and overloading thread
//
//loadImageByUrl(atv, enterprises.getEnterprises().get(k).getPhoto().toString(), img);
TextView txt = (TextView) rl.getChildAt(1);
txt.setText(enterprises.getEnterprises().get(i).getEnterpriseName());
TextView txt2 = (TextView) rl.getChildAt(2);
txt2.setText(enterprises.getEnterprises().get(i).getEnterpriseType().getEnterpriseTypeName());
TextView txt3 = (TextView) rl.getChildAt(3);
txt3.setText(enterprises.getEnterprises().get(i).getCountry());
LinearLayout relativeLayout = (LinearLayout) mInflater.inflate(R.layout.rtl_enterprise, parent);
relativeLayout.setId(i);
everything there works kinda ok, but i have a problem, i need to create a
onClick listener
Why?
I would call a method which needs some info about the card that has been clicked, and then redirect to a new activity which contains the info about the card that he clicked.
But i would need that onclick listener for each of these relative layouts, and i assume it would need to be initialized when the card is created since it create + 50 cards, but i have no idea of how to setup each listener.
Why do you create it like that?
a better solution to use RecyclerView.
and in the adapter, you can listen for the item click. write the code one time and when any item clicked. you will know the position of the clicked item.
see this tutorial
https://developer.android.com/guide/topics/ui/layout/recyclerview
https://www.androidhive.info/2016/01/android-working-with-recycler-view/

App crashes when setting background colour

Every time I run my app it crashes giving me a nullpointerexception, I want to programatically change my background depending on the scenario, here is my code:
Main Activity:
public class Activity extends AppCompatActivity {
ConstraintLayout layout;
String messageSafe = "Item is Safe for Consumption";
String messageUnSafe = "Item is NOT Safe for Consumption";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information);
layout = new ConstraintLayout(this);
if (matched.length == 0) {
layout.setBackgroundResource(R.drawable.background_safe);
setContentView(layout);
changeColor("#00FF00");
messageView.setText(messageSafe);
}
else{
layout.setBackgroundResource(R.drawable.background_unsafe);
setContentView(layout);
changeColor("#FF0000");
messageView.setText(messageUnSafe);
}
ListView listContains = (ListView) findViewById(R.id.lvItemsFound);
ArrayAdapter<String> contains = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, foundItems);
listContains.setAdapter(contains);
ListView listRestricted = (ListView) findViewById(R.id.lvItemsRestricted);
ArrayAdapter<String> found = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, matched);
listRestricted.setAdapter(found);
}
You are losing reference to your old view because you changed the layout to a new ConstraintLayout object. This means you now don't have your ListView objects and other items in your XML because that View is gone. It's not the ContentView anymore. If you want to work on the existing layout, you need to give the root view an ID.
<constraintlayout android:id="#+id/container" ... />
Then you can reference that ID with findViewById(R.id.container) and use the object you get from it to change your background like you are doing.
Try this:
1. Give your root view an ID
2. Set a ConstraintLayout object with ConstraintLayout layout = findViewById(R.id.container) (Note: You can call it anything, not just container, I am just going off my example from above, since I gave it the ID 'container')
3. call setBackgroundResource() like you are doing.
4. No need to call setContentView() again, this was set in the beginning, and you do not want to reset it to a new view you just constructed like you were initially doing.
5. You shouldn't crash when trying to call setAdapter() to your ListView now because you don't have a reference to an object that isn't in your content view.
layout = (ConstraintLayout)findViewById(R.id.container);
if (matched.length == 0) {
layout.setBackgroundResource(R.drawable.background_safe);
changeColor("#00FF00"); //assuming this is some local function?
messageView.setText(messageSafe);
}
else{
layout.setBackgroundResource(R.drawable.background_unsafe);
changeColor("#FF0000");
messageView.setText(messageUnSafe);
}
You are trying to set the background by replacing the view of your activity (this is what setContentView() does). This causes a null pointer exception later because the old layout (defined in the XML) has been replaced, so your list view no longer exists.
Instead, you should get a reference to the existing root view (the ConstraintLayout, although if you're just setting background you can just reference it as a View, no need to be so specific), and set the background on it, like so:
findViewById(R.id.container).setBackgroundResource(R.drawable.unsafe);
You'll also need to give the containing layout an id in the existing layout XML:
<android.support.constraint.ConstraintLayout
android:id="#+id/container"
... etc.

Adding a webview programmatically

I have had no trouble adding a web view to my layout on click with a button, but when it comes to adding a web view on create of my main activity it just does nothing. I need the program to create certain web views based on data stored when I run it. It just really gets me that the same exact code runs perfectly when I put it inside an onClick button, but in the main method it does absolutely nothing. No error, no anything.
tickerLinearLayout = (LinearLayout) findViewById(R.id.TickerLinearLayout);
currency = new WebView(this);
currency.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, btcUp.getMeasuredHeight()));
tickerLinearLayout.addView(currency);
currency.getSettings().setJavaScriptEnabled(true);
disableScroll(currency);
currency.loadUrl("file:///android_asset/btc.html");
To create a Webview programatically in an Activity, you will first have to add your Webview into a RelativeLayout. I am choosing a RelativeLayout because my use case needs the Webview to be positioned on different locations on the Parent View time to time.
public class CustomRelativeLayout extends RelativeLayout {
private WebView mWebView;
public CustomRelativeLayout(Context context) {
super(context);
mWebView = new WebView(context);
mWebView.setId(View.NO_ID);
mWebView.setScrollContainer(false);
mWebView.loadData("<html><body>TEST</body></html>", "text/html", "utf-8");
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
context.getResources().getDisplayMetrics().widthPixels, context.getResources().getDisplayMetrics().heightPixels);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
mWebView.setLayoutParams(params);
addView(mWebView);
}
public WebView getTheWebView() {
return mWebView;
}
}
You can modify the CustomRelativeLayout class to accept URL.
In your MainActivity class, you will have to add a new instance of CustomRelativeLayout and add it to the contentView as shown below:
setContentView(new CustomRelativeLayout(this));
To make adjustments to the size of the webview play around with the width and height of the LayoutParams added to the Webview.
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
<width>, <height>);

Programatically add LinearLayout with Text and Image

I'm trying to add a LinearLayout for each item in a varying Array. I need each item to have an image and text horizontally, but for now I am testing with the text.
Keeping in mind this code is in a Fragment.
I think the error is with the getContext() but not to sure.
The code I currently have is:
List<PaymentOption> paymentOptions = aTradeItem.getPaymentOptions();
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(ImageUtils.dpToPx(16), ImageUtils.dpToPx(4), ImageUtils.dpToPx(16), ImageUtils.dpToPx(4));
LinearLayout.LayoutParams lineparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ImageUtils.dpToPx(1));
lineparams.setMargins(0, ImageUtils.dpToPx(4), 0, ImageUtils.dpToPx(4));
if (paymentOptions != null && paymentOptions.size() > 0) {
for (PaymentOption t : paymentOptions) {
LinearLayout paymentOptionLayout = new LinearLayout(getContext());
paymentOptionLayout.setOrientation(LinearLayout.HORIZONTAL);
paymentOptionLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
TextView heading = new TextView(getContext());
heading.setText(t.getDescription());
heading.setTextColor(getResources().getColor(R.color.light_text));
heading.setLayoutParams(lp);
paymentOptionLayout.addView(heading);
}
}
There are no errors, the data just doesnt populate on the screen. I have tried Hardcoding random text in the setText() but with no success.
Thank you
You're not adding your paymentOptionLayout to the layout which is set as your content View. Basically what you're doing is programatically creating the layout, but then doing nothing with it.
By default your activity_main.xml file will come with some type of layout depending on how you setup your code, for example a blank activity's xml file would be
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity"
android:id="#+id/RelativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
However when you create layouts programmatically the way you did, you must append them to the layout which is the parent layout in your XML file.
So I think what you need to do is the following.
RelativeLayout rl=(RelativeLayout)findViewById(R.id.RelativeLayout); //getting the view from the xml file. Keep in mind that the id is defiend in the xml file by you
List<PaymentOption> paymentOptions = aTradeItem.getPaymentOptions();
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(ImageUtils.dpToPx(16), ImageUtils.dpToPx(4), ImageUtils.dpToPx(16), ImageUtils.dpToPx(4));
LinearLayout.LayoutParams lineparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ImageUtils.dpToPx(1));
lineparams.setMargins(0, ImageUtils.dpToPx(4), 0, ImageUtils.dpToPx(4));
if (paymentOptions != null && paymentOptions.size() > 0) {
for (PaymentOption t : paymentOptions) {
LinearLayout paymentOptionLayout = new LinearLayout(getContext());
paymentOptionLayout.setOrientation(LinearLayout.HORIZONTAL);
paymentOptionLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
TextView heading = new TextView(getContext());
heading.setText(t.getDescription());
heading.setTextColor(getResources().getColor(R.color.light_text));
heading.setLayoutParams(lp);
paymentOptionLayout.addView(heading);
rl.addView(paymentOptionLayout); //adding the view to the parent view
}
}
Please note that from the looks of your code, you're really just reimplementing listView which is an available layout in android. I think you should take a look at that.
getContext() is a method of activity class. It returns the context view only for currently running activity.
For Fragment either pass the instance of current activity class via constructor or use getActivity() method or this instead of getContext()
See here for help
Using context in a fragment
How to add view into LinearLayout of Fragment by onClick?
Also add paymentOptionLayout to the parent layout view right after for loop.

Create ImageView and TextView in HorizontalScrollView

I want to create a TextView over an ImageView in my Android-App. I know I need a RelativeLayout for this, but I don't know how to create this in my main.java (NOT in XML).
It should be dynamic, so I want to create a for-loop which creates many ImageViews with a TextView over it in a HorizontalScrollView.
This is my approach
LinearLayout sv = (LinearLayout) findViewById (R.id.LinearLayout1);
for (int i=1 ; i<=3; i++){
String uri = "drawable/test"; //only one picture several times
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
ImageView iv = new ImageView (this);
iv.setBackgroundResource (imageResource);
sv.addView(iv);
}
This only add ImageViews to my HorizontalScrollView (LinearLayout is located in the HorizontalScrollView), but now I also want to add TextViews over my ImageViews. I tried lot of things but nothing works.. I despair.
Hopefully someone can help me
PS: Sorry for my spelling mistakes, I'm from Germany
If you know it to design in xml, create a XML and inflate it.
Below is the code that explains, How to use it.
Code Snippet
//Parent View
LinearLayout sv = (LinearLayout) findViewById (R.id.LinearLayout1);
//infalter service
LayoutInflater inflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Loop to create all the child views
for (int i=0; i<=3; i++) {
//Refrence your layout xml here
LinearLayout childView= inflater. inflates (R. layout. your_xml, null);
//Get refrence to your button and imageview using childView
//add child view
sv.addView(childView);
}
//add sv to horizontal scroll view
Dude try custom views. Create one XML file and create one basic layout . And then inflate that view as many time as u want don't do with for loop. I thnk u r new in android.
http://androidexample.com/Dynamically_Create_View_Elements__-_Android_Example/index.php?view=article_discription&aid=115&aaid=137

Categories