Problem of multiply two spinners in calculation length,area and temperature - java

The problem i'm having is the inability for the app to perform the task i designed it to.
i run the app successfully but when i click any of the spinners the list doesn't drop down at all. None of the spinners is responding at all and i don't know the problem.
I've tried everything to sort this out but i can't.
i run the code many times i don't get an error message but still the spinners don't work.
please can anyone help out?
This app is suppose to convert length, area and temperature.
String.xml file
<resources>
<string name="spinner_1">From</string>
<string name="spinner_2">To</string>
<string-array name="conversion_type">
<item>Length</item>
<item>Area</item>
<item>Temperature</item>
</string-array>
<string-array name="area">
<item>Square kilometre</item>
<item>Square metre</item>
<item>Square yard</item>
<item>Square foot</item>
<item>Square inch</item>
<item>Square mile</item>
<item>Hectare</item>
<item>Acre</item>
</string-array>
<string-array name="length">
<item>Kilometre</item>
<item>Metre</item>
<item>Centimetre</item>
<item>Millimetre</item>
<item>Micrometer</item>
<item>Mile</item>
<item>Yard</item>
<item>Foot</item>
<item>Inch</item>
<item>Nautical Mile</item>
</string-array>
<string-array name="temperature">
<item>Celsius</item>
<item>Kelvin</item>
<item>Fahrenheit</item>
</string-array>
</resources>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Conversion Type"
android:layout_marginTop="10dp"
android:layout_marginLeft="12dp"
android:textSize="16sp"
android:textColor="#607D8B"
android:textStyle="bold"
android:id="#+id/text"/>
<LinearLayout
android:layout_below="#+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="10dp"
android:layout_marginLeft="8dp"
android:id="#+id/first_linear"
android:layout_marginRight="8dp">
<TextView
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="20dp"
android:background="#cbcbcb"/>
<Spinner
android:id="#+id/conversion_type"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_height="wrap_content" />
<TextView
android:layout_width="match_parent"
android:layout_marginTop="20dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_height="1dp"
android:id="#+id/text_some"
android:background="#cbcbcb"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_below="#id/first_linear"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
android:id="#+id/second_linear"
android:layout_marginLeft="8dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/text_from"
android:layout_marginTop="20dp"
android:layout_marginLeft="4dp"
android:text="From"
android:textStyle="bold"
android:textSize="16sp"
android:textColor="#607D8B"
android:layout_below="#id/first_linear"/>
<Spinner
android:id="#+id/from_spinner"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="18dp"
android:layout_marginBottom="20dp"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:hint="edit_text_from"
android:id="#+id/from_edit"
android:layout_width="0dp"
android:layout_weight="3"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:inputType="numberSigned|numberDecimal"
android:layout_marginLeft="30dp" />
<Button
android:layout_width="0dp"
android:layout_height="45dp"
android:layout_gravity="bottom"
android:layout_weight="1"
android:text="Clear"
android:layout_marginBottom="2dp"
android:id="#+id/clear_text_unit"
android:onClick="clear_unit"
/>
</LinearLayout>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="30dp"
android:id="#+id/third_text"
android:layout_below="#+id/second_linear"
android:layout_marginBottom="0dp"
android:background="#FFCBCBCB"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/third_text"
android:id="#+id/fourth_linear"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/text_to"
android:layout_marginTop="20dp"
android:layout_marginLeft="6dp"
android:text="To"
android:textStyle="bold"
android:textSize="16sp"
android:textColor="#607D8B" />
<Spinner
android:id="#+id/to_spinner"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_marginLeft="50dp"
android:layout_marginRight="30dp"
android:layout_marginTop="18dp"
android:layout_marginBottom="10dp"
android:layout_height="wrap_content" />
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="33dp"
android:background="#e6e5e5"
android:paddingLeft="10dp"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:maxLines="1"
android:scrollHorizontally="true"
android:layout_marginTop="20dp"
android:id="#+id/to_text"
android:textSize="20sp"
android:textColor="#000"
android:layout_marginRight="30dp"/>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="40dp"
android:layout_below="#+id/fourth_linear"
android:layout_marginBottom="10dp"
android:background="#FFCBCBCB"/>
</RelativeLayout>
MainActivity.java file
package com.example.learnspinner;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class MainActivity extends AppCompatActivity {
int spinner_cycle_pos = 0, spinner_duration_pos = 0;
Spinner from_spinner, to_spinner, conversion_type, duration_spinner, cycle_spinner;
String from_spinner_string, to_spinner_string, choice_spinner;
int from_spinner_position, to_spinner_position, choice_spinner_pos;
Button btnConvert;
TextView result;
EditText quantity;
ArrayAdapter<CharSequence> adapter_length, adapter_temperature, adapter_area;
BigDecimal[][] array = {{new BigDecimal("1"), new BigDecimal("1000000.0"), new BigDecimal("1195990.05"), new BigDecimal("10763910.4"), new BigDecimal("1550000000"), new BigDecimal("0.386102"), new BigDecimal("100"), new BigDecimal("247.105")},
{new BigDecimal("1"), new BigDecimal("0.125"), new BigDecimal("0.000122073125"), new BigDecimal("0.00000011920992"), new BigDecimal("0.0000000001164153"), new BigDecimal("0.0000000000001136868377"), new BigDecimal("0.000000000000001110223024")},
{new BigDecimal("1"), new BigDecimal("0.001"), new BigDecimal("0.000239006"), new BigDecimal("0.00000027778"), new BigDecimal("0.737562")},
{new BigDecimal("1"), new BigDecimal("0.001"), new BigDecimal("0.000001"), new BigDecimal("0.000000001")},
{new BigDecimal("1"), new BigDecimal("1000"), new BigDecimal("1000000"), new BigDecimal("1000000000"), new BigDecimal("1000000000000"), new BigDecimal("157.473"), new BigDecimal("2204.62"), new BigDecimal("35274")},
{new BigDecimal("1"), new BigDecimal("1000"), new BigDecimal("100000"), new BigDecimal("10000000000"), new BigDecimal("10000000000000"), new BigDecimal("0.621371"), new BigDecimal("1093.61"), new BigDecimal("3280.84"), new BigDecimal("39370.1"), new BigDecimal("0.539953")},
{new BigDecimal("1"), new BigDecimal("1.1111111300619"), new BigDecimal("0.0174533"), new BigDecimal("17.453300")},
{new BigDecimal("1"), new BigDecimal("1.01325"), new BigDecimal("101325"), new BigDecimal("760")},
{new BigDecimal("1"), new BigDecimal("1.46667"), new BigDecimal("0.44704"), new BigDecimal("1.60934"), new BigDecimal("0.868976")},
{}, // keep blank for temperature
{new BigDecimal("1"), new BigDecimal("0.001"), new BigDecimal("0.000016667"), new BigDecimal("0.00000027778"), new BigDecimal("0.000000011574"), new BigDecimal("0.0000000016534"), new BigDecimal("0.00000000038052"), new BigDecimal("0.00000000003171"), new BigDecimal("0.000000000003171"), new BigDecimal("0.0000000000003171")},
{new BigDecimal("1"), new BigDecimal("1000"), new BigDecimal("0.219969"), new BigDecimal("0.879877"), new BigDecimal("3.51951"), new BigDecimal("0.0353147"), new BigDecimal("61.0237"), new BigDecimal("61023.7")}};
String val = "0";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private void initialise_adapters() {
adapter_temperature = ArrayAdapter.createFromResource(getApplication(), R.array.temperature, android.R.layout.simple_spinner_item);
adapter_length = ArrayAdapter.createFromResource(getApplication(), R.array.length, android.R.layout.simple_spinner_item);
adapter_area = ArrayAdapter.createFromResource(getApplication(), R.array.area, android.R.layout.simple_spinner_item);
}
private void unit_converter() {
from_spinner = findViewById(R.id.from_spinner);
to_spinner = findViewById(R.id.to_spinner);
result = findViewById(R.id.to_text);
quantity = findViewById(R.id.from_edit);
conversion_type = (Spinner) findViewById(R.id.conversion_type);
// Initialise the main spinner
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getApplication(), R.array.conversion_type, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
conversion_type.setAdapter(adapter);
conversion_type.setOnItemSelectedListener(new spinner());
from_spinner = (Spinner) findViewById(R.id.from_spinner);
to_spinner = (Spinner) findViewById(R.id.to_spinner);
initialise_adapters();
//initally set default to area adapter
adapter_area.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
from_spinner.setAdapter(adapter_area);
to_spinner.setAdapter(adapter_area);
from_spinner_string = "Square kilometer";
to_spinner_string = "Square kilometer";
choice_spinner = "Area";
//Default values
from_spinner_position = 0;
to_spinner_position = 0;
choice_spinner_pos = 0;
int spinner_cycle_pos = 0, spinner_duration_pos = 0;
from_spinner.setOnItemSelectedListener(new spinner());
to_spinner.setOnItemSelectedListener(new spinner());
quantity.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
val = s.toString();
int flag = 0;
if (val.equals("")) {
flag = 1;
val = "0";
}
if (val.equals("-") || val.equals(".")) flag = 1;
if (choice_spinner.equals("Temperature")) {
if (flag == 0) {
double celcius = Double.parseDouble(val);
if (from_spinner_position == 2) {
celcius = celcius - Double.parseDouble("32");
celcius = celcius * Double.parseDouble("0.55555");
} else if (from_spinner_position == 1)
celcius = celcius - Double.parseDouble("273.15");
if (to_spinner_position == 2) {
celcius = celcius * Double.parseDouble("1.8");
celcius = celcius + Double.parseDouble("32");
} else if (to_spinner_position == 1)
celcius = celcius + Double.parseDouble("273.15");
print_exponent(result, celcius);
} else {
result.setText("");
}
} else {
if (flag == 0) {
double temp = Double.parseDouble(val);
temp = temp / Double.parseDouble(array[choice_spinner_pos][from_spinner_position].toString());
temp = temp * Double.parseDouble(array[choice_spinner_pos][to_spinner_position].toString());
temp = temp / Double.parseDouble(array[choice_spinner_pos][0].toString());
print_exponent(result, temp);
} else {
result.setText("");
}
}
}
});
}
//Method to print the numbers in exponent form
public void print_exponent(TextView view, double temp) {
String temp1 = "" + temp;
String temp2 = "";
int bds = 0;
for (char c : temp1.toCharArray()) {
if (c == 'E') {
temp2 += " e ";
bds = 1;
} else {
if (bds == 1) {
if (c == '-')
temp2 += c;
else
temp2 = temp2 + "+" + c;
} else
temp2 += c;
bds = 0;
}
}
view.setText(temp2);
}
//This method takes a big decimal number and convert that to the exponent from and scale is mantissa
private static String format(BigDecimal x, int scale) {
NumberFormat formatter = new DecimalFormat("0.0E0");
formatter.setRoundingMode(RoundingMode.HALF_UP);
formatter.setMinimumFractionDigits(scale);
return formatter.format(x);
}
//Spinner class to select spinner and also add gender
class spinner implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getId() == R.id.conversion_type) {
quantity.getText().clear();
result.setText("");
choice_spinner = parent.getItemAtPosition(position).toString();
choice_spinner_pos = position;
from_spinner.setEnabled(true);
to_spinner.setEnabled(true);
if (choice_spinner.equals("Area") == true) {
adapter_area.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
from_spinner.setAdapter(adapter_area);
to_spinner.setAdapter(adapter_area);
} else if (choice_spinner.equals("Length") == true) {
adapter_length.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
from_spinner.setAdapter(adapter_length);
to_spinner.setAdapter(adapter_length);
} else if (choice_spinner.equals("Temperature") == true) {
adapter_temperature.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
from_spinner.setAdapter(adapter_temperature);
to_spinner.setAdapter(adapter_temperature);
} else if (parent.getId() == R.id.from_spinner) {
quantity.getText().clear();
result.setText("");
from_spinner_string = parent.getItemAtPosition(position).toString();
from_spinner_position = position;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(getApplicationContext(), "Please Select a category", Toast.LENGTH_SHORT).show();
from_spinner.setEnabled(false);
to_spinner.setEnabled(false);
}
public void clear_unit (View view){
quantity.setText("");
result.setText("");
val = "";
}
}
}

Root cause
In the MainActivity, the unit_converter() method is responsible for initializing Spinner, set adapters, set listeners for the Spinner, but you forgot to call this method when the activity is starting.
Solution
Call the unit_converter() method when the activity is starting.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
unit_converter();
}
Update
When users select from_spinner and to_spinner, you do not update from_spinner_position and to_spinner_position value. Change your code to:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getId() == R.id.conversion_type) {
quantity.getText().clear();
result.setText("");
choice_spinner = parent.getItemAtPosition(position).toString();
choice_spinner_pos = position;
from_spinner.setEnabled(true);
to_spinner.setEnabled(true);
if (choice_spinner.equals("Area") == true) {
adapter_area.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
from_spinner.setAdapter(adapter_area);
to_spinner.setAdapter(adapter_area);
} else if (choice_spinner.equals("Length") == true) {
adapter_length.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
from_spinner.setAdapter(adapter_length);
to_spinner.setAdapter(adapter_length);
} else if (choice_spinner.equals("Temperature") == true) {
adapter_temperature.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
from_spinner.setAdapter(adapter_temperature);
to_spinner.setAdapter(adapter_temperature);
} else if (parent.getId() == R.id.from_spinner) {
quantity.getText().clear();
result.setText("");
from_spinner_string = parent.getItemAtPosition(position).toString();
from_spinner_position = position;
}
} else if (parent.getId() == R.id.from_spinner) {
from_spinner_position = position;
} else if (parent.getId() == R.id.to_spinner) {
to_spinner_position = position;
}
}

Related

Cant find Exact Error Line Number in the Console

here console show ClassCastException but not show error line Number? Any one help me here?
if any one has idea about to find exact errorline number then suggest me plz?
here xml where i used ListView.
i have tried
1) removed Params which set by programatically
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:fitsSystemWindows="true"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/adlayout"
android:background="#color/md_white_0">
<com.os.folder.and.file.locker.files.widget.BGridView
android:id="#+id/hide_view_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:numColumns="3"
android:stretchMode="columnWidth" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/hide_btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_marginRight="16dp"
android:layout_marginBottom="16dp"
android:background="#color/file_add"
android:onClick="onClick"
android:src="#drawable/ic_action_new" />
<LinearLayout
android:id="#+id/file_bottom_layout_tips"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/unrecord" />
<TextView
android:id="#+id/file_bottom_txt_tips"
android:layout_width="match_parent"
android:layout_height="64dp"
android:gravity="center"
android:text=""
android:textColor="#color/md_black_2"
android:textSize="14sp" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:id="#+id/pic_hide_btn_edit"
android:layout_width="match_parent"
android:layout_height="#dimen/title_height"
android:layout_above="#+id/adlayout"
android:layout_alignParentRight="true"
android:background="#color/md_black_1"
android:visibility="visible"
android:weightSum="4">
<LinearLayout
android:id="#+id/pic_hide_img_cancel"
android:layout_width="0dp"
android:layout_height="#dimen/title_height"
android:layout_weight="1"
android:gravity="center"
android:onClick="onClick">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/close" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="#dimen/title_height"
android:layout_weight="1"
android:gravity="center">
<CheckBox
android:id="#+id/item_file_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="#drawable/checkbox_selector" />
</LinearLayout>
<LinearLayout
android:id="#+id/pic_hide_img_recovery"
android:layout_width="0dp"
android:layout_height="#dimen/title_height"
android:layout_weight="1"
android:gravity="center"
android:onClick="onClick">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/unlock" />
</LinearLayout>
<LinearLayout
android:id="#+id/pic_hide_img_del"
android:layout_width="0dp"
android:layout_height="#dimen/title_height"
android:layout_weight="1"
android:gravity="center"
android:onClick="onClick">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/delete" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/adlayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:orientation="horizontal" />
</RelativeLayout>
here Java file, i have implemented from here listView
package com.os.folder.and.file.locker.files.activity;
import android.content.Intent;
import com.os.folder.and.file.locker.R;
import com.os.folder.and.file.locker.data.GroupImage;
import com.os.folder.and.file.locker.data.HideImage;
import com.os.folder.and.file.locker.files.adapter.BaseHideAdapter.OnListener;
import com.os.folder.and.file.locker.files.adapter.PicHideAdapter;
import com.os.folder.and.file.locker.files.entity.HideImageExt;
import com.os.folder.and.file.locker.files.widget.BGridView;
import com.os.folder.and.file.locker.service.GroupImageService;
import com.os.folder.and.file.locker.service.ImageService;
import java.util.List;
public class PicHideActivity extends BaseHideActivity implements OnListener {
protected static final String TAG = "PicHideActivity";
private int itemSize;
protected GroupImageService mGroupImageService;
protected ImageService mImageService;
protected void initUI() {
setContentView((int) R.layout.activity_file_hide_group);
setUI();
setTitleRID(R.string.pic_preview_title, R.string.pic_preview_title_edit);
setGridView();
this.mFile_bottom_txt_tips.setText(R.string.file_hide_txt_add_pic);
this.rid_string_type = R.string.pic_preview;
}
private void setGridView() {
this.itemSize = ((BGridView) findViewById(R.id.hide_view_list)).setGridView(getWindowManager(), 4, 4);
}
void initAdapter() {
BGridView adapterView = findViewById(R.id.hide_view_list);
this.mGroupImageService = new GroupImageService(this);
this.mImageService = new ImageService(this);
this.mBaseHideAdapter = new PicHideAdapter(this, this, this.itemSize);
adapterView.setAdapter(this.mBaseHideAdapter);
}
boolean delFolder() {
return false;
}
void addFolder() {}
public void addFile() {
Intent intent = new Intent(this, PicPreViewActivity.class);
intent.putExtra("beyondGroupId", this.mBaseHideAdapter.getGruopID());
startActivity(intent);
}
protected void recoveryFiles() {
for (Object imageModelView: this.mBaseHideAdapter.getHitFiles()) {
this.mImageService.unHideImage((HideImageExt) imageModelView);
}
}
protected void delFiles() {
for (Object hideImageExt: this.mBaseHideAdapter.getHitFiles()) {
this.mImageService.deleteAudioByPath((HideImageExt)
hideImageExt);
}
}
protected void openHolder(int groupID) {
List < GroupImage > groupList = this.mGroupImageService.getGroupFiles(groupID);
List < HideImage > list = this.mImageService.getHideImages(groupID);
this.mBaseHideAdapter.setHitFiles(groupList, list, groupID);
setHasData(groupList, list);
}
public void openHolder(Object object) {
GroupImage data = (GroupImage) object;
int groupID = -1;
if (data != null) {
groupID = data.getId().intValue();
}
openHolder(groupID);
}
}
and here is adapter code,
package com.os.folder.and.file.locker.files.adapter;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
//import android.widget.AbsListView.LayoutParams;
import android.widget.ImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.DisplayImageOptions.Builder;
import com.nostra13.universalimageloader.core.ImageLoader;
import
com.nostra13.universalimageloader.core.download.ImageDownloader.Scheme;
import com.os.folder.and.file.locker.R;
import com.os.folder.and.file.locker.data.GroupImage;
import com.os.folder.and.file.locker.data.HideImage;
import com.os.folder.and.file.locker.files.activity.PhotoPreViewActivity;
import com.os.folder.and.file.locker.files.entity.GroupImageExt;
import com.os.folder.and.file.locker.files.entity.HideImageExt;
import java.util.ArrayList;
import java.util.List;
public class PicHideAdapter extends BaseHideAdapter {
private static final String TAG = "PicHideAdapter";
protected ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new Builder().showStubImage(R.drawable.default_picture).showImageForEmptyUri((int) R.drawable.default_picture).showImageOnFail((int) R.drawable.default_picture).cacheInMemory(true).cacheOnDisc(true).build();
private ViewGroup.LayoutParams params;
class PicHolder {
Object mData;
ImageView mImg_pre_preview;
View mItem_file_ok;
View mItem_file_pic;
PicHolder() {}
}
public PicHideAdapter(Context context, OnListener onListern, int itemSize) {
super(context, onListern);
this.params = new ViewGroup.LayoutParams(itemSize, itemSize);
}
public void clear() {
super.clear();
if (this.imageLoader != null) {
this.imageLoader.stop();
this.imageLoader = null;
}
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = this.mInflater.inflate(R.layout.item_file_hide_pic, null);
PicHolder picHolder = new PicHolder();
picHolder.mItem_file_pic = convertView.findViewById(R.id.item_file_pic);
picHolder.mItem_file_ok = convertView.findViewById(R.id.item_file_ok);
picHolder.mImg_pre_preview = (ImageView)
convertView.findViewById(R.id.img_pre_preview);
convertView.setTag(picHolder);
// convertView.setLayoutParams(this.params);
}
initView(convertView, position);
return convertView;
}
protected void initView(View view, final int position) {
int i = 8;
final PicHolder fileHolder = (PicHolder) view.getTag();
fileHolder.mImg_pre_preview.setImageBitmap(null);
Object data = getItem(position);
fileHolder.mData = data;
if (data instanceof HideImageExt) {
final HideImageExt hideImageView = (HideImageExt) data;
this.imageLoader.displayImage(Scheme.THUMBNAIL.wrap(hideImageView.getNewPathUrl()), fileHolder.mImg_pre_preview, this.options);
if (this.edit) {
View view2 = fileHolder.mItem_file_ok;
if (hideImageView.isEnable()) {
i = 0;
}
view2.setVisibility(i);
view.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
boolean z;
int i = 0;
HideImageExt hideImageExt = hideImageView;
if (hideImageView.isEnable()) {
z = false;
} else {
z = true;
}
hideImageExt.setEnable(z);
View view = fileHolder.mItem_file_ok;
if (!hideImageView.isEnable()) {
i = 8;
}
view.setVisibility(i);
PicHideAdapter.this.updateSelect();
}
});
view.setOnLongClickListener(null);
return;
}
fileHolder.mItem_file_ok.setVisibility(8);
view.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(PicHideAdapter.this.context, PhotoPreViewActivity.class);
intent.putParcelableArrayListExtra("list", (ArrayList)
PicHideAdapter.this.mList_HideFile);
intent.putExtra("id", position);
PicHideAdapter.this.context.startActivity(intent);
}
});
view.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View v) {
PicHideAdapter.this.doVibrator(PicHideAdapter.this.context);
PicHideAdapter.this.mOnListern.onLongClick(hideImageView);
return false;
}
});
} else if (data instanceof GroupImageExt) {
final GroupImageExt groupImageView = (GroupImageExt) data;
fileHolder.mItem_file_ok.setVisibility(8);
fileHolder.mImg_pre_preview.setImageResource(R.drawable.folder);
view.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (PicHideAdapter.this.edit) {
PicHolder fileHolder = (PicHolder) v.getTag();
groupImageView.setEnable(!groupImageView.isEnable());
} else if (PicHideAdapter.this.mOnListern != null) {
PicHideAdapter.this.mOnListern.openHolder(groupImageView);
}
}
});
}
}
public void setHitFiles(List < ?>listGroup, List < ?>listFile, int groupID) {
this.mList_Group = GroupImageExt.transList((List < GroupImage > ) listGroup);
this.mList_HideFile = HideImageExt.transList((List < HideImage > ) listFile);
setGroup(groupID);
notifyDataSetChanged();
}
}
LayoutParams lp = new LayoutParams(-2, -2);
lp.setMargins(margin, margin, margin, margin);
setLayoutParams(lp);
resolved..by removing this param

code for image run in arraylist

i do array list with images thet i want them to run with 2 buttons thet go next pic and beck pic i dont know the code for this i thx all for the time you spend for help.
ackage com.example.hanansanag.mytourneyccreator;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.util.ArrayList;
/**
* Created by ssh on 25/12/2016.
*/
public class Players extends AppCompatActivity implements View.OnClickListener {
protected Button btnNext, btnBack;
protected String fname;
protected String Lname;
protected String team;
protected ImageView iv;
protected ArrayList array_image;
int i = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.team_pic);
ArrayList<Integer> array_image = new ArrayList<Integer>();
array_image.add(R.drawable.bacelona);
array_image.add(R.drawable.athlethiko);
array_image.add(R.drawable.arsenak);
array_image.add(R.drawable.chelsea);
array_image.add(R.drawable.dortmond);
array_image.add(R.drawable.city);
array_image.add(R.drawable.bayernunchen);
array_image.add(R.drawable.intermilan);
array_image.add(R.drawable.psj);
array_image.add(R.drawable.realmadrid);
array_image.add(R.drawable.leverpool);
array_image.add(R.drawable.milan);
array_image.add(R.drawable.juventus);
array_image.add(R.drawable.ashkelon);
array_image.add(R.drawable.macabiheifa);
array_image.add(R.drawable.macabitelaviv);
array_image.add(R.drawable.beitaryeroshlaim);
array_image.add(R.drawable.apoelbersheva);
iv = (ImageView) findViewById(R.id.imageView);
btnNext = (Button) findViewById(R.id.btnNextPic);
btnBack = (Button) findViewById(R.id.btnBeckPic);
btnBack.setOnClickListener(this);
btnNext.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (i <= 0 || i >= array_image.length) {
return;
}
if (btnNext == v) {
iv.setImageResource(array_image.get(i++));
} else if (btnBack == v) {
iv.setBackgroundResource(array_image.get(i--));
}
}
}
**what can i do here in this line of code thet the pic will move : **
#Override
public void onClick(View v) {
if (i <= 0 || i >= array_image.length) {
return;
}
if (btnNext == v) {
iv.setImageResource(array_image.get(i++));
} else if (btnBack == v) {
iv.setBackgroundResource(array_image.get(i--));
}
}
this is the xml;
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/teamimage">
<GridLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:text="Fname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/imageView"
android:layout_marginTop="12dp"
android:id="#+id/textView2" />
<ImageView
android:layout_height="80dp"
android:id="#+id/imageView"
android:layout_width="80dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<TextView
android:text="Lname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:id="#+id/Lname"
android:layout_below="#+id/textView2"
android:layout_toEndOf="#+id/imageView" />
<TextView
android:text="Fname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/imageView"
android:layout_marginTop="12dp"
android:id="#+id/textView3" />
<GridLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true">
<Button
android:layout_width="20dp"
android:layout_height="15dp"
android:id="#+id/btnBeckPic"
android:background="#drawable/btnbeck"
android:layout_marginStart="30dp"
android:layout_alignBottom="#+id/Lname"
android:layout_toEndOf="#+id/textView2" />
<Button
android:background="#drawable/btnnext"
android:layout_width="20dp"
android:layout_height="15dp"
android:id="#+id/btnNextPic"
android:layout_below="#+id/imageView"
android:layout_toEndOf="#+id/btnBeckPic"
android:layout_marginStart="14dp" />
</GridLayout>
</RelativeLayout>
int currentImage = 0;
String[] strArr = new String[array_image.size()];
strArr = array_image.toArray(stockArr);
#Override
public void onClick(View v) {
if (btnNext == v) {
currentImage++;
currentImage = currentImage % strArr .length;
iv.setImageResource(strArr .length[currentImage]);
} else if (btnBack == v) {
currentImage--;
currentImage = (currentImage + strArr .length) % strArr .length;
iv.setImageResource(strArr[currentImage]);
}
}

Why are my views widening and then returning to normal during running of this code?

This is the code.
What more information do i need to put here?
I'm trying to find out why my text and button views are widening and then returning to normal during running of this code.
It keeps saying i need more details so i guess im just gonna talk about some nonsense here.
package com.notesquirrel.johnald.memorymagic;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
public class GameActivity extends AppCompatActivity implements View.OnClickListener {
Animation wobble;
SharedPreferences prefs;
SharedPreferences.Editor editor;
String dataName = "MyData";
String intName = "MyInt";
int defaultInt = 0;
int highScore;
TextView textScore;
TextView textDifficulty;
TextView textWatchGo;
Button button1;
Button button2;
Button button3;
Button button4;
Button buttonRestart;
int difficultyLevel = 3;
int[] sequenceToCopy = new int[100];
private Handler myHandler;
boolean playSequence = false;
int elementToPlay = 0;
int playerResponses;
int playerScore;
boolean isResponding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
wobble = AnimationUtils.loadAnimation(this, R.anim.wobble);
prefs = getSharedPreferences(dataName, MODE_PRIVATE);
editor = prefs.edit();
highScore = prefs.getInt(intName, defaultInt);
final MediaPlayer powerup7 = MediaPlayer.create(this, R.raw.poweru);
final MediaPlayer powerup8 = MediaPlayer.create(this, R.raw.poweru2);
final MediaPlayer powerup9 = MediaPlayer.create(this, R.raw.poweru3);
final MediaPlayer powerup10 = MediaPlayer.create(this, R.raw.poweru4);
textScore = (TextView) findViewById(R.id.textScore);
assert textScore != null;
textScore.setText("Score: " + playerScore);
textDifficulty = (TextView) findViewById(R.id.textDifficulty);
assert textDifficulty != null;
textDifficulty.setText("Level: " + difficultyLevel);
textWatchGo = (TextView) findViewById(R.id.textWatchGo);
button1 = (Button) findViewById(R.id.button21);
button2 = (Button) findViewById(R.id.button32);
button3 = (Button) findViewById(R.id.button43);
button4 = (Button) findViewById(R.id.button54);
buttonRestart = (Button) findViewById(R.id.buttonRestart);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
button4.setOnClickListener(this);
buttonRestart.setOnClickListener(this);
//thread
myHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (playSequence) {
button1.setVisibility(View.VISIBLE);
button2.setVisibility(View.VISIBLE);
button3.setVisibility(View.VISIBLE);
button4.setVisibility(View.VISIBLE);
switch (sequenceToCopy[elementToPlay]) {
case 1:
// button1.setVisibility(View.INVISIBLE);
button1.startAnimation(wobble);
powerup7.start();
break;
case 2:
//button2.setVisibility(View.INVISIBLE);
button2.startAnimation(wobble);
powerup8.start();
break;
case 3:
//button3.setVisibility(View.INVISIBLE);
button3.startAnimation(wobble);
powerup9.start();
break;
case 4:
// button4.setVisibility(View.INVISIBLE);
button4.startAnimation(wobble);
powerup10.start();
break;
}
elementToPlay++;
if (elementToPlay == difficultyLevel) {
sequenceFinished();
}
}
myHandler.sendEmptyMessageDelayed(0, 900);
}
};
myHandler.sendEmptyMessage(0);
playASequence();
}
#Override
public void onClick(View v) {
final MediaPlayer powerup7 = MediaPlayer.create(this, R.raw.poweru);
final MediaPlayer powerup8 = MediaPlayer.create(this, R.raw.poweru2);
final MediaPlayer powerup9 = MediaPlayer.create(this, R.raw.poweru3);
final MediaPlayer powerup10 = MediaPlayer.create(this, R.raw.poweru4);
if (!playSequence) {
switch (v.getId()) {
case R.id.button21:
powerup7.start();
checkElement(1);
break;
case R.id.button32:
powerup8.start();
checkElement(2);
break;
case R.id.button43:
powerup9.start();
checkElement(3);
break;
case R.id.button54:
powerup10.start();
checkElement(4);
break;
case R.id.buttonRestart:
difficultyLevel = 3;
playerScore = 0;
textScore.setText("Score: " + playerScore);
playASequence();
break;
}
}
}
public void createSequence() {
//For choosing a random button
Random randInt = new Random();
int ourRandom;
for (int i = 0; i < difficultyLevel; i++) {
//get a random number between 1 and 4
ourRandom = randInt.nextInt(4);
ourRandom++;//make sure it is not zero
//Save that number to our array
sequenceToCopy[i] = ourRandom;
}
}
public void playASequence() {
createSequence();
isResponding = false;
elementToPlay = 0;
playerResponses = 0;
textWatchGo.setText("WATCH!");
playSequence = true;
}
public void sequenceFinished() {
playSequence = false;
//make sure all the buttons are made visible
// button1.setVisibility(View.VISIBLE);
// button2.setVisibility(View.VISIBLE);
// button3.setVisibility(View.VISIBLE);
// button4.setVisibility(View.VISIBLE);
textWatchGo.setText("GO!");
isResponding = true;
}
public void checkElement(int thisElement) {
if (isResponding) {
playerResponses++;
if (sequenceToCopy[playerResponses - 1] == thisElement) {//Correct
playerScore = playerScore + ((thisElement + 1) * 2);
textScore.setText("Score: " + playerScore);
if (playerResponses == difficultyLevel) {//got the whole sequence
//don't checkElelment anymore
isResponding = false;
//now raise the difficulty
difficultyLevel++;
//and play another sequence
playASequence();
}
} else {//wrong answer
textWatchGo.setText("FAILED!");
//don't checkElelment anymore
isResponding = false;
if (playerScore > highScore) {
highScore = playerScore;
editor.putInt(intName, highScore);
editor.commit();
Toast.makeText(getApplicationContext(), "New high score!!", Toast.LENGTH_LONG).show();
}
}
}
}
}
XML layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.notesquirrel.johnald.memorymagic.GameActivity"
android:background="#000000">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Score: 999"
android:textSize="40sp"
android:id="#+id/textScore"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Difficulty: 4"
android:textSize="25sp"
android:id="#+id/textDifficulty"
android:layout_below="#+id/textScore"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Watch/Go"
android:id="#+id/textWatchGo"
android:layout_marginTop="48dp"
android:textSize="25sp"
android:layout_below="#+id/textDifficulty"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:id="#+id/button21"
android:layout_marginTop="50dp"
android:layout_below="#+id/textWatchGo"
android:layout_alignRight="#+id/textScore"
android:layout_alignEnd="#+id/textScore"
android:layout_alignLeft="#+id/textScore"
android:layout_alignStart="#+id/textScore" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2"
android:id="#+id/button32"
android:layout_marginTop="10dp"
android:layout_below="#+id/button21"
android:layout_alignRight="#+id/button21"
android:layout_alignEnd="#+id/button21"
android:layout_alignLeft="#+id/button21"
android:layout_alignStart="#+id/button21" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3"
android:layout_marginTop="10dp"
android:id="#+id/button43"
android:layout_below="#+id/button32"
android:layout_alignRight="#+id/button32"
android:layout_alignEnd="#+id/button32"
android:layout_alignLeft="#+id/button32"
android:layout_alignStart="#+id/button32" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4"
android:layout_marginTop="10dp"
android:id="#+id/button54"
android:layout_below="#+id/button43"
android:layout_alignRight="#+id/button43"
android:layout_alignEnd="#+id/button43"
android:layout_alignLeft="#+id/button43"
android:layout_alignStart="#+id/button43" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Restart"
android:id="#+id/buttonRestart"
android:layout_marginTop="10dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
I have no problem with my device. But I removed some constraints.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.notesquirrel.johnald.memorymagic.GameActivity"
android:background="#000000">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Score: 999"
android:textSize="40sp"
android:id="#+id/textScore"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Difficulty: 4"
android:textSize="25sp"
android:id="#+id/textDifficulty"
android:layout_below="#+id/textScore"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Watch/Go"
android:id="#+id/textWatchGo"
android:layout_marginTop="48dp"
android:textSize="25sp"
android:layout_below="#+id/textDifficulty"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:id="#+id/button21"
android:layout_marginTop="50dp"
android:layout_below="#+id/textWatchGo"
android:layout_alignRight="#+id/textScore"
android:layout_alignLeft="#+id/textScore"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2"
android:id="#+id/button32"
android:layout_marginTop="10dp"
android:layout_below="#+id/button21"
android:layout_alignRight="#+id/button21"
android:layout_alignLeft="#+id/button21"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3"
android:layout_marginTop="10dp"
android:id="#+id/button43"
android:layout_below="#+id/button32"
android:layout_alignRight="#+id/button32"
android:layout_alignLeft="#+id/button32"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4"
android:layout_marginTop="10dp"
android:id="#+id/button54"
android:layout_below="#+id/button43"
android:layout_alignRight="#+id/button43"
android:layout_alignLeft="#+id/button43"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Restart"
android:id="#+id/buttonRestart"
android:layout_marginTop="10dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
/>
</RelativeLayout>

How to randomly create and assign variables and shorten an if-else statement (Java android)

I was wondering how to shorten my code by automatically creating and assigning variables for TextViews. Also, how do you shorten these if-else statements? I have looked at other threads, but they haven't fulfilled my needs. I am using Android Studio for this.
Here is my Java code:
package com.example.ani.testproject;
import android.graphics.Color;
import android.os.SystemClock;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainScreen extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
final TextView spot1 = (TextView) findViewById(R.id.spot1);
final TextView spot2 = (TextView) findViewById(R.id.spot2);
final TextView spot3 = (TextView) findViewById(R.id.spot3);
final TextView spot4 = (TextView) findViewById(R.id.spot4);
final TextView spot5 = (TextView) findViewById(R.id.spot5);
final TextView spot6 = (TextView) findViewById(R.id.spot6);
final TextView spot7 = (TextView) findViewById(R.id.spot7);
final TextView spot8 = (TextView) findViewById(R.id.spot8);
final TextView spot9 = (TextView) findViewById(R.id.spot9);
final TextView spot10 = (TextView) findViewById(R.id.spot10);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick (View v) {
int loopnum = 1;
while(loopnum<4){
Random r = new Random();
int spotnumber = r.nextInt(11-1) + 1;
if(spotnumber==1){
spot1.setBackgroundColor(Color.RED);
}
else if(spotnumber==2){
spot2.setBackgroundColor(Color.RED);
}
else if(spotnumber==3){
spot3.setBackgroundColor(Color.RED);
}
else if(spotnumber==4){
spot4.setBackgroundColor(Color.RED);
}
else if(spotnumber==5){
spot5.setBackgroundColor(Color.RED);
}
else if(spotnumber==6){
spot6.setBackgroundColor(Color.RED);
}
else if(spotnumber==7){
spot7.setBackgroundColor(Color.RED);
}
else if(spotnumber==8){
spot8.setBackgroundColor(Color.RED);
}
else if(spotnumber==9){
spot9.setBackgroundColor(Color.RED);
}
else if(spotnumber==10){
spot10.setBackgroundColor(Color.RED);
}
loopnum += 1;
SystemClock.sleep(5000);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main_screen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I was not really able to show this clearly, but the last bracket corresponds to the bracket in:
public class MainScreen extends ActionBarActivity {
Here is my XML code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation = "horizontal">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="170dp"
android:layout_height="match_parent"
android:orientation = "vertical"
android:layout_marginTop = "5dp"
android:layout_marginRight = "5dp"
android:id="#+id/linearLayout">
<TextView
android:layout_width="90dp"
android:layout_height="90dp"
android:id = "#+id/spot1"
android:layout_marginTop="10dp"
android:background="#ffffff"/>
<TextView
android:layout_width="90dp"
android:layout_height="90dp"
android:id = "#+id/spot2"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:background="#ffffff"/>
<TextView
android:layout_width="90dp"
android:layout_height="90dp"
android:id = "#+id/spot3"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:background="#ffffff"/>
<TextView
android:layout_width="90dp"
android:layout_height="90dp"
android:id = "#+id/spot4"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:background="#ffffff"/>
<TextView
android:layout_width="90dp"
android:layout_height="90dp"
android:id = "#+id/spot5"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:background="#ffffff"/>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="170dp"
android:layout_height="match_parent"
android:orientation = "vertical"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginTop = "5dp"
android:id="#+id/LinearLayout2">
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Press Me"
android:id="#+id/button"
android:layout_gravity="right" />
<TextView
android:layout_width="90dp"
android:layout_height="90dp"
android:id = "#+id/spot6"
android:layout_marginTop="10dp"
android:layout_alignParentRight = "true"
android:background="#ffffff"/>
<TextView
android:layout_width="90dp"
android:layout_height="90dp"
android:id = "#+id/spot7"
android:layout_marginTop="10dp"
android:layout_alignParentRight = "true"
android:background="#ffffff"/>
<TextView
android:layout_width="90dp"
android:layout_height="90dp"
android:id = "#+id/spot8"
android:layout_marginTop="10dp"
android:layout_alignParentRight = "true"
android:background="#ffffff"/>
<TextView
android:layout_width="90dp"
android:layout_height="90dp"
android:id = "#+id/spot9"
android:layout_marginTop="10dp"
android:layout_alignParentRight = "true"
android:background="#ffffff"/>
<TextView
android:layout_width="90dp"
android:layout_height="90dp"
android:id = "#+id/spot10"
android:layout_marginTop="10dp"
android:layout_alignParentRight = "true"
android:background="#ffffff"/>
</LinearLayout>
Please help me! I am new to Android and Java.
It looks like keeping a List of TextViews, rather than individual variables for each, would be appropriate in your case. We can use an ArrayList, and populate it by retrieving the IDs for the TextViews from their names specified in the layout xml.
ArrayList<TextView> spots = new ArrayList<TextView>();
for(int i = 1; i < 11; i++) {
int id = getResources().getIdentifier("spot" + i, "id", getPackageName());
spots.add((TextView) findViewById(id));
}
This will greatly simplify the other section of code, in that we now don't need any ifs at all.
Random r = new Random();
int spotnumber = r.nextInt(10);
spots.get(spotnumber).setBackgroundColor(Color.RED);
If you want to shorten you if => else if statements, you can use a switch statement.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Basically you give the switch a variable and then a set of case scenarios depending of the value of the given variable. In your case it would look like this :
switch (spotnumber) {
case 1 : //case scenario with spotnumber = 1
spot1.setBackgroundColor(Color.RED);
break;
case 2 : //case scenario with spotnumber = 2
spot2.setBackgroundColor(Color.RED);
break;
}
Don't forget the "break" otherwise each statement after the matching scenario will be executed.
A possible solution could be using Dependency Injection.You could look into RoboGuice.
However Android best practices does not recommen this method.You could maybe just automate your function and store the textViews using an arraylist.
List<TextView> spotList= new ArrayList<TextView>();
for(int i = 1; i <= 10; i++) {
int id = getResources().getIdentifier("spot" + i, "id", getPackageName());
spotList.add((TextView) findViewById(id));
}
and the if-else statement would be modified by using a switch case:
switch (spotnumber) {
case 1 : //equivalent of spotnumber==1
spot1.setBackgroundColor(Color.RED);
break;
case 2 : //equivalent of if spotnumber==2
spot2.setBackgroundColor(Color.RED);
break;
.
.
.
}

Can't setText of a TextView using a String with data from db

I have a TextView and a String randomWord. When the app starts I open my db and call a method db.open() which opens it and then the db.randomize() which calls the randomize() method and queries the db for random entry and returns it as a String. Thereafter I just want to MyTextView.setText (randomWord); but when app is running nothing is displaying. I have tried to hardcode in setText ("whatever") and that is shown.
So I guess I have done wrong in the randomize or something because I don't get a word from the db.
This is what I try to do:
db.open();
db.randomize(generatedWord);
//text = new SpannableString(generatedWord);
//text.setSpan(new ForegroundColorSpan(Color.WHITE), 0, text.length(), 0);
wordHolder.setText("" + generatedWord);
db.close();
This is my random method:
public Cursor randomize(String word) {
#SuppressWarnings("unused")
Cursor cursor;
return cursor = this.db.query("tblnames ORDER BY RANDOM() LIMIT 1", new String[] { "*" }, null, null, null, null, null);
}
My DB has two columns: "_id" and "word"
"create table tblnames (_id integer primary key autoincrement, "
+ "words text not null);"
Can it have to do that I don't specify the _id and word somewhere in the randomize()?
ALSO: I tried setText (generatedWord) as well as setText (" +generatedWord);
ALSO: no errors while running.
You aren't returning a String with your randomize() method.
This should give you the desired affect
db.open();
//text = new SpannableString(generatedWord);
//text.setSpan(new ForegroundColorSpan(Color.WHITE), 0, text.length(), 0);
wordHolder.setText(db.randomize());
db.close();
And in your DB you need to return the string value of the column you want from your cursor, not the cursor itself. http://developer.android.com/reference/android/database/Cursor.html#getString(int)
public String randomize() {
Cursor cursor;
cursor = this.db.query("tblnames ORDER BY RANDOM() LIMIT 1", new String[] { "*" }, null, null, null, null, null);
if(cursor.moveToFirst()) {
return cursor.getString(cursor.getColumnIndexOrThrow( "word" ));
}
return "";
}
SOLUTION FOR SHOWING WORD: instead of a spannable string (to hide and to show parts of the randomWord) i found StringBuilder, together with indexOf and userinput i was able to put in correct letters after a guess from the user. Like this:
public void guess()
{
char guess = userInput.getText().charAt(0);
StringBuilder builder = new StringBuilder(hiddenWord);
String j = ""+guess;
int index = randomedWord.indexOf(guess);
if (randomedWord.contains(j))
{
while (index >= 0)
{
builder.setCharAt(index*2, guess);
index = randomedWord.indexOf(guess, index + 1);
hiddenWord = builder.toString().trim();
wordHolder.setText(hiddenWord);
if (!(hiddenWord.toString().contains("_".toString())) )
{
winner();
}
}
}
else
{
showImages();
}
}
SOLUTION FOR RANDOMWORD(generate it): just look at James answer, I had return the cursor itself on my DB and not the string value of the column i wanted which is the correct way
db.open();
wordHolder.setText(db.randomize());
db.close();
public String randomize() {
Cursor cursor;
cursor = this.db.query("tblnames ORDER BY RANDOM() LIMIT 1", new String[] { "*" }, null, null, null, null, null);
if(cursor.moveToFirst()) {
return cursor.getString(cursor.getColumnIndexOrThrow( "word" ));
}
return "";
}
FULL CODE:
// MainActivity.java
package com.emanuelolsson.simplehangman;
import database.DBAdapter;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class HangMan extends Activity {
// DECLARE NEEDED VARIABLES
private Button newGameButton, enterLetterButton;
private EditText userInput;
private TextView wordHolder;
private ImageView imageOne, imageTwo, imageThree, imageFour, imageFive, imageSix, imageSeven, imageEight, winner, hanged;
private String hiddenWord, randomedWord;
private int count = 0;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hang_man);
DBAdapter db = new DBAdapter(this);
// ASSIGN OBJECTS
newGameButton = (Button) findViewById(R.id.newGame);
enterLetterButton = (Button) findViewById(R.id.enter);
wordHolder = (TextView) findViewById(R.id.wordHolder);
userInput = (EditText) findViewById(R.id.userInput);
imageOne = (ImageView) findViewById(R.id.imageView1);
imageTwo = (ImageView) findViewById(R.id.imageView2);
imageThree = (ImageView) findViewById(R.id.imageView3);
imageFour = (ImageView) findViewById(R.id.imageView4);
imageFive = (ImageView) findViewById(R.id.imageView5);
imageSix = (ImageView) findViewById(R.id.imageView6);
imageSeven = (ImageView) findViewById(R.id.imageView7);
imageEight = (ImageView) findViewById(R.id.imageView8);
winner = (ImageView) findViewById(R.id.winner);
hanged = (ImageView) findViewById(R.id.hanged);
imageOne.setVisibility(View.INVISIBLE);
imageTwo.setVisibility(View.INVISIBLE);
imageThree.setVisibility(View.INVISIBLE);
imageFour.setVisibility(View.INVISIBLE);
imageFive.setVisibility(View.INVISIBLE);
imageSix.setVisibility(View.INVISIBLE);
imageSeven.setVisibility(View.INVISIBLE);
imageEight.setVisibility(View.INVISIBLE);
winner.setVisibility(View.INVISIBLE);
hanged.setVisibility(View.INVISIBLE);
wordHolder.setVisibility(View.VISIBLE);
// ADD LISTENERS
newGameButton.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
newGame();
}
});
enterLetterButton.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
if (!(userInput.getText().toString().isEmpty()) )
{
guess();
} else if (userInput.getText().toString().isEmpty())
{
Toast toast = Toast.makeText(getApplicationContext(), "You need to insert a letter", Toast.LENGTH_SHORT);
toast.show();
}
}
});
db.open();
db.fill();
randomedWord = db.randomize();
invWord();
wordHolder.setText(hiddenWord);
db.clear();
db.close();
}
public void newGame() {
DBAdapter db = new DBAdapter(this);
count = 0;
imageOne.setVisibility(View.INVISIBLE);
imageTwo.setVisibility(View.INVISIBLE);
imageThree.setVisibility(View.INVISIBLE);
imageFour.setVisibility(View.INVISIBLE);
imageFive.setVisibility(View.INVISIBLE);
imageSix.setVisibility(View.INVISIBLE);
imageSeven.setVisibility(View.INVISIBLE);
imageEight.setVisibility(View.INVISIBLE);
winner.setVisibility(View.INVISIBLE);
hanged.setVisibility(View.INVISIBLE);
db.open();
db.fill();
randomedWord = db.randomize();
invWord();
wordHolder.setText(hiddenWord);
db.clear();
db.close();
}
public void invWord()
{
hiddenWord = randomedWord;
hiddenWord = hiddenWord.replaceAll(".", "_" +" ");
}
public void guess()
{
char guess = userInput.getText().charAt(0);
StringBuilder builder = new StringBuilder(hiddenWord);
String j = ""+guess;
int index = randomedWord.indexOf(guess);
if (randomedWord.contains(j))
{
while (index >= 0)
{
builder.setCharAt(index*2, guess);
index = randomedWord.indexOf(guess, index + 1);
hiddenWord = builder.toString().trim();
wordHolder.setText(hiddenWord);
if (!(hiddenWord.toString().contains("_".toString())) )
{
winner();
}
}
}
else
{
showImages();
}
}
private void winner()
{
imageOne.setVisibility(View.INVISIBLE);
imageTwo.setVisibility(View.INVISIBLE);
imageThree.setVisibility(View.INVISIBLE);
imageFour.setVisibility(View.INVISIBLE);
imageFive.setVisibility(View.INVISIBLE);
imageSix.setVisibility(View.INVISIBLE);
imageSeven.setVisibility(View.INVISIBLE);
imageEight.setVisibility(View.INVISIBLE);
winner.setVisibility(View.VISIBLE);
}
private void showImages() {
count ++;
if (count == 1)
{
imageOne.setVisibility(View.VISIBLE);
}
else if (count == 2)
{
imageTwo.setVisibility(View.VISIBLE);
}
else if (count == 3)
{
imageThree.setVisibility(View.VISIBLE);
}
else if (count == 4)
{
imageFour.setVisibility(View.VISIBLE);
}
else if (count == 5)
{
imageFive.setVisibility(View.VISIBLE);
}
else if (count == 6)
{
imageSix.setVisibility(View.VISIBLE);
}
else if (count == 7)
{
imageSeven.setVisibility(View.VISIBLE);
}
else if (count == 8)
{
gameEnd();
}
}
private void gameEnd()
{
imageOne.setVisibility(View.INVISIBLE);
imageTwo.setVisibility(View.INVISIBLE);
imageThree.setVisibility(View.INVISIBLE);
imageFour.setVisibility(View.INVISIBLE);
imageFive.setVisibility(View.INVISIBLE);
imageSix.setVisibility(View.INVISIBLE);
imageSeven.setVisibility(View.INVISIBLE);
imageEight.setVisibility(View.VISIBLE);
hanged.setVisibility(View.VISIBLE);
wordHolder.setText(randomedWord);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_hang_man, menu);
return true;
}
}
// XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp"
android:contentDescription="#string/picOne"
android:src="#drawable/one" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp"
android:contentDescription="#string/picTwo"
android:src="#drawable/two" />
<ImageView
android:id="#+id/imageView3"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp"
android:contentDescription="#string/picThree"
android:src="#drawable/three" />
<ImageView
android:id="#+id/imageView4"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp"
android:contentDescription="#string/picFour"
android:src="#drawable/four" />
<ImageView
android:id="#+id/imageView5"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp"
android:contentDescription="#string/picFive"
android:src="#drawable/five" />
<ImageView
android:id="#+id/imageView6"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp"
android:contentDescription="#string/picSix"
android:src="#drawable/six" />
<ImageView
android:id="#+id/imageView7"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp"
android:contentDescription="#string/picSeven"
android:src="#drawable/seven" />
<ImageView
android:id="#+id/imageView8"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp"
android:contentDescription="#string/picEight"
android:src="#drawable/eight" />
<ImageView
android:id="#+id/winner"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignTop="#+id/imageView1"
android:layout_centerHorizontal="true"
android:contentDescription="#string/winner"
android:src="#drawable/winner" />
<ImageView
android:id="#+id/hanged"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignTop="#+id/imageView1"
android:layout_centerHorizontal="true"
android:contentDescription="#string/hanged"
android:src="#drawable/hanged" />
<TextView
android:id="#+id/wordHolder"
android:layout_width="175dp"
android:layout_height="40dp"
android:layout_centerInParent="true"
android:layout_alignTop="#+id/imageView1"
android:layout_marginTop="134dp"
android:layout_marginLeft="50dp"
android:ems="10"
android:textSize="30dp" />
<Button
android:id="#+id/newGame"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/wordHolder"
android:layout_centerVertical="true"
android:text="#string/newGame" />
<Button
android:id="#+id/enter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/newGame"
android:layout_alignBottom="#+id/newGame"
android:layout_toLeftOf="#+id/newGame"
android:text="#string/enter" />
<EditText
android:id="#+id/userInput"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignBaseline="#+id/enter"
android:layout_alignBottom="#+id/enter"
android:layout_toLeftOf="#+id/enter"
android:ems="10"
android:inputType="text"
android:textSize="20dp" >
<requestFocus />
</EditText>
<ImageView
android:id="#+id/imageView9"
android:layout_width="250dp"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:contentDescription="#+id/header"
android:src="#drawable/header" />
</RelativeLayout>

Categories