How to get elements from array list in android - android

Hi all in my application by using web service i get the data from database and stored that data in hash table.I took that data from hast table to array.this array data can be displayed in button.My array contains 10 elements.For animation i used view flipper.Now i want to do is display that array elements on button one after another for every 10sec.But in Updater method i didn't get all array elements.How to solve this one
i am sending my code
//in on create method i wore this one
user_advertise is the hash table
System.out.println(""+user_advertise.size());
array=new String[user_advertise.size()];
e= user_advertise.keys();
int i = 0;
int j=0;
for(i=user_advertise.size();;i++){
array[j]=e.nextElement().toString();
LinearLayout layout = (LinearLayout) findViewById(R.id.LinearLayout01);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
Button buttonView = new Button(this);
buttonView.setText("" +array[i]);
Timer timing = new Timer();
timing.schedule(new Updater(buttonView), 3000, 3000);
ViewFlipper flipper = new ViewFlipper (this);
flipper.addView(buttonView);
layout.addView(flipper,p);
flipper.startFlipping();
flipper.setClickable(true);
flipper.setFlipInterval(10000);
flipper.setInAnimation(AnimationUtils.loadAnimation(this,R.anim.push_left_in));
flipper.setOutAnimation(AnimationUtils.loadAnimation(this,R.anim.push_left_out));
}
}catch(Exception e)
{
Log.v("Add",e.toString());
}
}
private class Updater extends TimerTask {
private final Button buttonView;
public Updater(Button buttonView) {
this.buttonView = buttonView;
}
public void run() {
buttonView.post(new Runnable() {
public void run() {
int k=0;
buttonView.setText(" ");
buttonView.setText(""+array[k].toString()+"");
if(array[++k]!= null)
{
k++;
}
}

You have defined and initialized int k=0; within the thread block so everytime it will run, k will always be 0 so you will have to define it outside.
Also
if(array[++k]!= null)
{
k++;
}
will increment k twice : one for the if test and one in the block
What you want is:
if(k != array.length - 1) k++;

Related

Android issue with programatically created buttons

Well im trying to get the text on each button, it displays the text correctly on each but when i try to print it, it shows the same text. The text of optionD
private void displayQuestion() {
final ArrayList<String> options = new ArrayList<>();
for (int i = 0; i < questions.size(); i++){
Questions diaplayQuestion = questions.get(i);
question.setText(diaplayQuestion.getQuestion());
options.add(0, diaplayQuestion.getOptionA());
options.add(1, diaplayQuestion.getOptionB());
options.add(2, diaplayQuestion.getOptionC());
options.add(3, diaplayQuestion.getOptionD());
correctOption = diaplayQuestion.getCorrectOption();
}
for (int i = 0; i < options.size(); i++) {
btn = new Button(GameplayActivity.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(10, 10, 10, 0);
btn.setLayoutParams(params);
btn.setText(options.get(i));
btn.setId(i);
linearLayout.addView(btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.out.println(view.getId());
}
});
}
}
If you want to store some information inside View use tags. From official docs:
Unlike IDs, tags are not used to identify views. Tags are essentially an extra piece of information that can be associated with a view. They are most often used as a convenience to store data related to views in the views themselves rather than by putting them in a separate structure.
So in your case it'll be like this:
btn = new Button(GameplayActivity.this);
...
btn.setTag(options.get(i)); // I assume that value is String
...
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.out.println((String) view.getTag());
}
});

setText on TextViews created using a for loop - android

I have created a set of TextViews programmatically using a for loop. This what i have tried.
for(int i=1; i<5; i++){
valueTV = new TextView(AddMyVehicle.this);
linearLayout.addView(valueTV);
vehicleModelReturned = myVehicleData.getString("VehicleModel"+x, "");
valueTV.setText(vehicleModelReturned);
valueTV.setGravity(Gravity.CENTER_HORIZONTAL);
valueTV.setTextSize(TypedValue.COMPLEX_UNIT_SP,22);
valueTV.setTextColor(Color.parseColor("#333333"));
i++;
}
this.valueTV.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
valueTV.setText("Hello");
}
});
I need to change the text of clicked TextView to "Hello". How can i achieve this?
You have to add a listener to all your TextView created.
And be careful, you incremented i twice : one in the first line of the for and another one in the end of the for.
for (int i = 1; i < 5; i++)
{
final TextView valueTV = new TextView(AddMyVehicle.this);
linearLayout.addView(valueTV);
vehicleModelReturned = myVehicleData.getString("VehicleModel" + x, "");
valueTV.setText(vehicleModelReturned);
valueTV.setGravity(Gravity.CENTER_HORIZONTAL);
valueTV.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
valueTV.setTextColor(Color.parseColor("#333333"));
valueTV.setId("test");
valueTV.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
TextView tv = (TextView) v;
tv.setText("Hello");
}
});
}
First, set the OnClickListener to all the TextViews you create, not just the last one. That is, move the setOnClickListener() inside the for loop.
Second, in onClick(), change the text of the clicked view and not again the last one you created. The View v param is the view that was clicked. You can cast it to TextView.

Hopefully Simple Error in Thread Android

I'm a little new to Android. Working on an app that let's user input a number and then calculates the Fibonacci Sequence and then displays each element in the sequence at 1 second intervals. But I have an issue when I try to display using a thread inside a for loop. I try print from an array list but it gives me an error with my counter variable (j). I tried running this same exact method in a much simpler app and the array list worked just fine. I don't know why it doesn't work this time. I hope this is a simple obvious error. Can anyone tell me why? Code is posted below:
public class MainActivity extends Activity {
// primary widgets
private EditText editText;
private TextView textView;
private Button button1;
Thread thread;
static ArrayList<Integer> fibList = new ArrayList<Integer>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText1);
textView = (TextView) findViewById(R.id.textView2);
button1 = (Button) findViewById(R.id.button1);
//Attempt to clear TextView
textView.setText("");
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Clear Textview
String array = " ";
fibList.clear();
textView.setText(array);
final String input = editText.getText().toString();
int number = Integer.parseInt(input);
int tmp = 0;
// confirm input
if (number < 20) {
Toast.makeText(getApplicationContext(),
"You entered: " + number, Toast.LENGTH_LONG).show();
for (int i = 0; i <= number; i++) {
fibList.add(fib(i));
// sum even numbers
if (fib(i) % 2 == 0) {
tmp += fib(i);
}
}
} else {
Toast.makeText(getApplicationContext(),
"Number is too Large: " + number, Toast.LENGTH_LONG)
.show();
}
Log.i("TEST", "ARRAY"+fibList);
thread = new Thread(new Runnable(){
#Override
public void run(){
for(int j = 0; j < fibList.size(); j++){
runOnUiThread(new Runnable(){
#Override
public void run(){
//ERROR OCCURS HERE: Cannot refer to a non-final variable j
//inside an inner class defined in a different method
textView.append(fibList.get(j).toString());
textView.append("");
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //wait one second
}
}
});
thread.start();
}
});
}
// run fibonacci sequence
public static int fib(int n) {
if (n < 2) {
return n;
} else {
return fib(n - 1) + fib(n - 2);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
a simple workaround to solve your issue is to declare a temp final variable in this way:
for(int j = 0; j < fibList.size(); j++){
final int finalJ = j;
runOnUiThread(new Runnable(){
#Override
public void run(){
//ERROR OCCURS HERE: Cannot refer to a non-final variable j
//inside an inner class defined in a different method
textView.append(fibList.get(finalJ).toString());
textView.append("");
}
});
You have a more serious problem.
You are attempting to manipulate a texView from a thread. That's not permitted. Only the GUI thread can manipulate screen objects or else Bad Things Happen.
Take a look at AsyncTask. It is designed to address exactly the problem you are trying to solve.
http://developer.android.com/reference/android/os/AsyncTask.html

UI Block on creating imageview at runtime

I want to create 600 imageview at runtime and add it to linear layout at runtime.It cause block my user interface. My activity appear when all imageview created and added to linear layout. How to resolve this.
Please help for this.
for(int index = 0; index < ProductItemArray.Image_URL.length; index++)
{
ImageView bottomImageView = new ImageView(context);
bottomImageView.setTag(index);
if(Helper.isTablet(context))
bottomImageView.setLayoutParams(new Gallery.LayoutParams(VirtualMirrorActivity.convertDpToPixel(100, context), VirtualMirrorActivity.convertDpToPixel(100, context)));
else
bottomImageView.setLayoutParams(new Gallery.LayoutParams(VirtualMirrorActivity.convertDpToPixel(80, context), VirtualMirrorActivity.convertDpToPixel(80, context)));
UrlImageViewHelper.setUrlDrawable(bottomImageView, ProductItemArray.Image_URL[index]);
bottomImageView.setBackgroundResource(R.layout.border);
linearLayout3.addView(bottomImageView);
bottomImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final int position = (Integer) v.getTag();
linearLayout.removeAllViews();
Thread newThread = new Thread(new Runnable() {
public void run() {
isAlreadyExistInWishlist = true;
URL url_1 = null;
try {
VMProductListPaging.productUrl = ProductItemArray.Image_small_URL[position];
VMProductListPaging.productId = ProductItemArray.productId[position];
VMProductListPaging.productName = ProductItemArray.product_Name[position];
url_1 = new URL(ProductItemArray.Image_small_URL[position]);
bmp = BitmapFactory.decodeStream(url_1.openConnection().getInputStream());
isExecuted = true;
bitmapModelsHandler.sendMessage(bitmapModelsHandler.obtainMessage());
}
catch (Exception e) {
//Toast.makeText(context,"Sorry!! This link appears to be broken",Toast.LENGTH_LONG).show();
}
}
});
newThread.start();
}
});
}
Having 600 images in memory in the same time is probably not a good idea.
You should consider using some lazy loading via an adapter (with a ListView, a Gallery, a GridView, a Spinner,etc...) which will manage recycling/releasing of views.

Regarding android Development

I am doing an application in which I have to display the numbers on TextView randomly and automatically with the help of Timer. I am able to get the random Numbers in the log without repeating, but I am not able to print the same on device please help me...
Regards,
Akki
Source:
//RandomNumber.java
public class RandomNumber extends Activity{
static Random randGen = new Random();
int tambolanum,count=0;
private Button previousbutton;
private Button startbutton;
private Button nextbutton;
int bingonum[]=new int[90];
boolean fill;
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.numbers);
LinearLayout number=(LinearLayout)findViewById(R.id.numbersview);
final TextView randomnum=(TextView)findViewById(R.id.numberstext);
previousbutton=(Button)findViewById(R.id.previous);
nextbutton=(Button)findViewById(R.id.next);
startbutton=(Button)findViewById(R.id.start);
startbutton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on click
//--- Initialize the array to the ints 0-90
do{
fill = true;
//Get new random number
tambolanum = randGen.nextInt(90) + 1;
//If the number exists in the array already, don't add it again
for(int i = 0; i < bingonum.length; i++)
{
if(bingonum == tambolanum)
{
fill = false;
}
}
//If the number didn't already exist, put it in the array and move
//To the next position
if(fill == true)
{
bingonum[count] = tambolanum;
count++;
}
} while(count < 90);
for(i=0;i
{
randomnum.setText(Integer.toString(bingonum[i]);
}
}
setText(CharSequence text)
The problem you're having is that you're overwriting your text in every itteration of this loop:
for(i=0;i
{
randomnum.setText(Integer.toString(bingonum[i]);
}
You need to build your string first then set it. Something like:
StringBuilder sb = new StringBuilder();
for(i=0;i /* where's the rest of this for-statement? */
{
sb.append(Integer.toString(bingonum[i]);
}
randomnum.setText(sb.toString());

Categories

Resources