Android app crashes when trying to add an imageview in another class - android

i recently started programming in Android and i came across a little problem.
What i'm trying to do is:
I have NewsActivity and a NewsRows.class (in the same package). So the news activites just creates a new NewsRows object and tells it to fill the TableLayout with new rows.
It works fine as long as i try to add an image from a resource... The app just keeps crashing.
The debugger tells me it can't find the resource but i can't find out why!
My code is here:
News Acitivty
package de.myapp.app.activites.news;
import de.myapp.app.R;
import android.app.Activity;
import android.os.Bundle;
public class News extends Activity {
NewsRows rowClass = new NewsRows();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news);
NewsRows.createNewsEntries(this);
}
}
NewsRows.class
package de.myapp.app.activites.news;
import de.myapp.app.R;
import android.app.Activity;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class NewsRows {
static TextView title;
static TableRow tRow;
static TableLayout tLayout;
public NewsRows() {
}
public static void createNewsEntries(Activity contextActivity) {
ImageView image = new ImageView(contextActivity);
image.setBackgroundColor(R.drawable.myimage);
tLayout = (TableLayout) contextActivity.findViewById(R.id.NewsTable);
for(int a = 0; a < 100; a++) {
tRow = new TableRow(contextActivity);
title = new TextView(contextActivity);
//tRow.addView(image);
title.setText("This is a test.");
tRow.addView(title);
tLayout.addView(tRow);
}
}
}
EDIT:
The line
image.setBackgroundColor(R.drawable.myimage);<br />
Is actually supposed to be:
image.setImageResource(R.drawable.myimage);

You're trying to set an image into a background color:
Change this:
image.setBackgroundColor(R.drawable.myimage);
to this:
image.setBackgroundResource(R.drawable.myimage);

Fun fact:
TableLayout tLayout = (TableLayout) findViewById(R.id.NewsTable);
TableRow tRow = new TableRow(this);
ImageView image = new ImageView(this);
image.setImageResource(R.drawable.myimage);
tRow.addView(image);
tLayout.addView(tRow);
If i put this code right in the News.Activity it works...

You can't set a drawable for as a background color of your ImageView, that's why you have the resource not found exception on your logcat!!
image.setBackgroundColor(R.drawable.myimage);
change it to this:
image.setBackgroundResource(R.drawable.myimage);
Also try to change this
public static void createNewsEntries(Activity contextActivity)
with
public static void createNewsEntries(Context contextActivity)

Related

Android OnClickListener infinite button use problem

I am trying to make an simple button that will cooperate with TextView, array and method changer (in public class Change). However the application uses the method changer only twice (below). It should work on every click. The changer method is used for the change in displayed array.
1-click: 1 |
2-click: 4 |
3-click: 1 |
4-click: 1 |
...-click: 1 |
I don't know where is the problem.
My target solution should be 1,4,1,4,1,4 ...
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
String[] numbers = {"1", "2","3","4"};
private Button mButton;
int i = 0;
Change ch = new Change();
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.button2);
text = (TextView) findViewById(R.id.tv1);
ch = new Change();
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text.setText(numbers[0]);
numbers = ch.changer(numbers);
i++;
}
});
}
}
Change.java
public class Change {
String[] arraynew = new String[4];
public String[] changer(String[] array){
arraynew[0]=array[3];
arraynew[1]=array[2];
arraynew[2]=array[1];
arraynew[3]=array[0];
return arraynew;
}
}
The arraynew variable in your code is global - so it will not create a new array every time you call the changer method, only rearranges its contents.
Here comes the tricky part: When you call the method for the second time, the parameter is the same object as arraynew. So when you do arraynew[0]=array[3] it changes 4 to 1 on the first slot; but arraynew[3]=array[0] will copy that newly changed 1 to the third index (where it is still the same 1 you put there). It basically eliminates the 4, making it impossible to recover.
Solution: Make arraynew local. If you declare it in the method, it will never be the same array, so the issue won't appear.

Last Button added Dictatorship in android

I know that title is fancy but this is going on in my android app.
I am storing the names of websites which user wants to open in an arraylist of strings. Then an array of buttons is made whose size depends on the size of arraylist.
Then I set the text of the buttons using the arraylist. This works perfectly and all the buttons are assigned correct text.
Then I set the on click listeners of each button and create an implicit intent to open the web site.
Problem that is occuring is that despite the fact the text of the buttons are set perfectly , There is some problem with the listener because no matter which button i press, always the site of last button is opened and hence last button dictatorship.
Here is my code.
package com.example.hp.myproject;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created #CreativeLabsworks
*/
public class Act3 extends Activity
{
LinearLayout ll1; Button[] bt_arr; String s;
LinearLayout.LayoutParams params1;
ArrayList<String> sites;TextView t1;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent intent=getIntent();
sites= intent.getStringArrayListExtra("arraylist");
/*Creating a linear layout to hold editTexts*/
ll1=new LinearLayout(this);
ll1.setOrientation(LinearLayout.VERTICAL);
/*set the width and height of the linear layout*/
params1=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
setContentView(ll1, params1);
/*Initializing the button array*/
bt_arr = new Button[sites.size()];
/*Initialize each button*/
for(int i=0;i<bt_arr.length;++i)
{
bt_arr[i] = new Button(this);
ll1.addView(bt_arr[i]);
}
setText();
attach_listeners();
}
public void attach_listeners()
{
/*this function attaches listeners with all buttons in the button array*/
for(int i=0;i<bt_arr.length;++i)
{
s=sites.get(i);
bt_arr[i].setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent i=new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://"+s));
startActivity(i);
}
});
}
}
public void setText()
{
/*This function sets the text of the various buttons*/
int j;
for(int i=0;i<bt_arr.length;++i)
{
j=sites.get(i).indexOf(".com");
bt_arr[i].setText(sites.get(i).substring(4,j));
}
}
}
The problem that you have is that
s=sites.get(i);
S is being set by the last element.
Whenever a button is clicked it is taking the S from the last element since S is outside the onClickListener instance that you have.
I would suggest to save the url in the Button tag and then use it When the button is clicked.
for (int i = 0; i < bt_arr.length; ++i) {
s = sites.get(i);
bt_arr[i].setTag(s);
bt_arr[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String website = (String)v.getTag();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://" + website));
startActivity(i);
}
});
}
Intent i=new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://"+s));
startActivity(i);
Maybe you do not write i.setclass()?

Call different String from Res to .java

First, I'm new with android. I've trying to make a survey on android. My problem is that i want that the next question and possible answers appear when radiobutton is selected, and the same thing for all the question i have. I make it function but accidentally i erased the project. Here is the code i developed
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView texto1;
TextView texto2;
RadioGroup Selecopc;
int i=1;
private TextView num;
private TextView pregu;
private TextView rep1;
private TextView rep2;
private TextView rep3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.area_de_preguntas);
num = (TextView)findViewById(R.id.Numero);
pregu = (TextView)findViewById(R.id.Pregunta);
rep1 = (TextView)findViewById(R.id.Respuesta1);
rep2 = (TextView)findViewById(R.id.Respuesta2);
rep3 = (TextView)findViewById(R.id.Respuesta3);
Selecopc = (RadioGroup)findViewById(R.id.opcion);
Selecopc.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
public void onCheckedChanged(RadioGroup group, int checkedId)
{
i++;
String n = String.valueOf(i);
num.setText(n);
String pregseg ="R.string."+"preg"+i;
pregu.setText(pregseg);
}
});
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="action_settings">Settings</string>
<string name="numero">1</string>
<string name="preg1">Cua...</string>
<string name="preg2">Cu..</string>
<string name="preg3">...</string>
<string name="preg4">...</string>
<string name="preg5">...</string>
<string name="preg6">...</string>
String id resource names is just a static field. I suppose you can do it using reflection but it's not the better choice in your case. The better way is to predefine array of identifiers and use them. Sample:
private int[] pregs = new int[]{
R.string.preg1,
R.string.preg2,
R.string.preg3
};
And use it later like this:
public void onCheckedChanged(RadioGroup group, int checkedId)
{
i++;
String n = String.valueOf(i);
num.setText(n);
pregu.setText(pregs[i]);
}

TextView with HTML content - Hide images/empty squares

I have html content and setting this into (android) textbox as follows
textbox.setText(Html.fromHtml(myhtml));
HTML content contains some img tags as well, I do not want display images, currently it displays empty square boxes where ever there is a img tag. How do I hide those square boxes?
You could do a regex replace <img.+?> on htmlString.
textView.setText(Html.fromHtml(htmlString.replaceAll("<img.+?>", "")));
Untested
Update:
since images can look like:
<img ...></img>
and
<img... />
This solution will match both cases:
String htmlBody = htmlString.replaceAll("<img.+/(img)*>", "");
textView.setText(Html.fromHtml(htmlBody));
This works
Create Html.ImageGetter to return empty image as follows
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.text.Html;
public class EmptyImageGetter implements Html.ImageGetter {
private static final Drawable TRANSPARENT_DRAWABLE = new ColorDrawable(Color.TRANSPARENT);
#Override
public Drawable getDrawable(String source) {
return TRANSPARENT_DRAWABLE;
}
}
and then create a static instance
private static final EmptyImageGetter EMPTY_IMAGE_GETTER = new EmptyImageGetter();
set this into text view
textView.setText(Html.fromHtml(myhtml, EMPTY_IMAGE_GETTER, null));

How Do I Load Images From SD Card One At A Time?

Ok, I am able to load a specific image into ImageView from my SD card...no problem. But I need to take a step further and add a button load the next image (move/copy/delete previous image). I can add the button, etc but how do I retreive the 'next' image without knowing filenames? Here is the code so far. I would have liked to use Gallery but it has been deprecated and I can't seem to make anything else work. Thank You
package com.demo.ShowSDImages;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
public class AndroidBitmap extends Activity
{private final String imageInSD = "/sdcard/er.PNG";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bitmap bitmap = BitmapFactory.decodeFile(imageInSD);
ImageView myImageView = (ImageView)findViewById(R.id.imageview);
myImageView.setImageBitmap(bitmap);
}
}
i think you can give a try to this sample here..Check this link
here i think the below code can help you in getting the images .
int imageCount = sdcardPath.listFiles().length;
for (int count = 0; count < imageCount - 1; count++) {
Bitmap bmp = BitmapFactory.decodeFile(sdcardPath.listFiles()[count]
.getAbsolutePath());
In the sample instead of using the thread or timer use the the same logic that is using of the showNext() in the button click event
Give a try. Happy Coding

Categories

Resources