GridView Pops out NullPointerException - android

The rows are coming in reverse order. It should be Monday then Tuesday then WednesdayI have a gridview which dynamically fetches data of current week(i.e monday to today). I am facing two issues.
1) My gridView elements are not arranged properly.
2) GridView shows data of that day also whose data does not exists. It simply copies all previous row values. I know rearrangement problem is because of resetPosition variable not getting updated. but if i update it, i get NullPointerException. How can i get rid of these problems?
public class ViewTimeTable extends AppCompatActivity {
private ArrayList<String> mondayStrength,tuesdayStrength,wednesdayStrength,thursdayStrength,fridayStrength;
String [] currentWeek;
int resetPosition;
private Date date;
private Map map;
private int position,pos;
private TextView classTextView,sectionTextView,dateTextView;
private String Class,section,today,day;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.one_day_layout);
classTextView = (TextView)findViewById(R.id.class_textView);
sectionTextView = (TextView)findViewById(R.id.section_textView);
dateTextView = (TextView)findViewById(R.id.date_textView);
Intent intent = getIntent();
ParseAnalytics.trackAppOpenedInBackground(intent);
mondayStrength = new ArrayList<String>();
tuesdayStrength = new ArrayList<>();
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if (menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception ignored) {
}
map = new HashMap();
String[] lectureTimings = {"Lec/Day","I","II","III","IV","V","VI"};
for(int i =0;i<lectureTimings.length;i++){
mondayStrength.add(lectureTimings[i]);
pos = i;
}
System.out.println(position);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Lectures");
GridView mondayRow = (GridView)findViewById(R.id.mon_grid_view);
final GridAdapterChirag mondayAdapter = new GridAdapterChirag(ViewTimeTable.this,R.layout.grid_element, mondayStrength);
mondayRow.setAdapter(mondayAdapter);
System.out.println(position);
currentWeek = getThisWeek();
Class = intent.getStringExtra("Class");
section = intent.getStringExtra("Section");
position = pos+1;
System.out.println(position);
classTextView.append(Class);
sectionTextView.append(section);
resetPosition=position;
String [] day = {"Mon","Tue","Wed","Thu","Fri"};
for(int i=0;i<currentWeek.length;i++) {
mondayStrength.add(position, day[i]);
System.out.print("ResetPosition before loop"+resetPosition);
query.whereEqualTo("Date", currentWeek[i]);
try {
List<ParseObject> objects = query.find();
for (ParseObject object : objects) {
String lid = object.getString("LectureID");
if (lid.substring(7, 9).equals(Class)) {
String m = String.valueOf(lid.charAt(10));
if (m.equals(section)) {
String periodNumber = lid.substring(4, 6);
if (periodNumber.equals("01"))
position += 1;
else if (periodNumber.equals("02"))
position += 2;
else if (periodNumber.equals("03"))
position += 3;
else if (periodNumber.equals("04"))
position += 4;
else if (periodNumber.equals("05"))
position += 5;
else if (periodNumber.equals("06"))
position += 6;
else
position = 100;
map.put(position, object.getString("Strength"));
}
}
System.out.println("ResetPosition"+resetPosition);
System.out.println("Position"+position);
position = resetPosition;
}
System.out.println(map);
for (int k = 1; k <= map.size(); k++) {
mondayStrength.add(resetPosition + k, map.get(resetPosition+k).toString());
}resetPosition+=7;
System.out.println(mondayStrength.size());
//position++;
//mondayAdapter.notifyDataSetChanged();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
//This method simply returns array of dates of current week
private String[] getThisWeek() {
int factor;
ArrayList<String> week = new ArrayList<>();
long oneDay = 86400000;
Calendar calendar = Calendar.getInstance();
long todayInMillis = calendar.getTimeInMillis();
String date;
String todaysDay = new SimpleDateFormat("EEE").format(new Date());
if(todaysDay.equals("Mon"))
factor = 0;
else if(todaysDay.equals("Tue"))
factor = 1;
else if(todaysDay.equals("Wed"))
factor = 2;
else if(todaysDay.equals("Thu"))
factor = 3;
else if(todaysDay.equals("Fri"))
factor = 4;
else if(todaysDay.equals("Sat"))
factor = 5;
else
factor = 6;
for(;factor>=0;factor--){
calendar.setTimeInMillis(todayInMillis-factor*oneDay);
Date d = new Date(calendar.getTimeInMillis());
date = new SimpleDateFormat("dd-MM-yyyy").format(d);
week.add(date);
}
String [] runningWeek = new String[week.size()];
runningWeek = week.toArray(runningWeek);
return runningWeek;
}
LogCat:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tonystark.adminlogin/com.example.tonystark.adminlogin.ViewTimeTable}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2306)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.access$600(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5297)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.tonystark.adminlogin.ViewTimeTable.onCreate(ViewTimeTable.java:126)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358) 
at android.app.ActivityThread.access$600(ActivityThread.java:156) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:153) 
at android.app.ActivityThread.main(ActivityThread.java:5297) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) 
at dalvik.system.NativeStart.main(Native Method) 

Related

Populated ArrayList throws OutOfBounds Exception

My App
I wanted to make a simple game to get started. For that, I generate houses and then later want to display them to the player.
My Problem
When I try to access my ArrayList that should store the classes of my houses I get an Exception (see below). In my debugger, I can see, that the classes get generated properly before I try to access them.
My Code
Houses.java (This is where I generate my Houses on App start and later try to access them)
public class Houses{
ArrayList<Integer> classes = new ArrayList<>();
int[][] NewHouseProps = new int[20][10];
int[][] HouseProps;
public Houses(){
}
public ArrayList<Integer> getClasses()
{
for(int id=0;id<=8;id++){
Log.d("getClasses()","ID: "+id+" CLASSES: "+classes.get(id)); //Exception
}
return classes;
}
public void GenerateHouses(){
Log.d("Generate Houses","!!");
for(int id=0; id<=8; id++){
Random r = new Random();
int h_class, garage = 0, rooms = 0, furn = 0, balkon = 0, pool = 0;
h_class = r.nextInt(4); //Klasse
if(h_class == 0){
rooms = r.nextInt(4)+1;
balkon = r.nextInt(1);
}else if(h_class == 1){
rooms = r.nextInt(3)+3;
garage = r.nextInt(1)+1;
pool = r.nextInt(1);
balkon = r.nextInt(2);
}else if(h_class == 2){
rooms = r.nextInt(3)+2;
garage = r.nextInt(2)+2;
pool = r.nextInt(1);
}else if(h_class == 3){
rooms = r.nextInt(8)+6;
garage = r.nextInt(6)+4;
pool = r.nextInt(1);
balkon = r.nextInt(3);
}
furn = r.nextInt(1);
int price = GenerateHousePrice(id, h_class, garage, rooms, furn, balkon, pool);
NewHouseProps[id][0] = h_class;
NewHouseProps[id][1] = price;
NewHouseProps[id][2] = rooms;
NewHouseProps[id][3] = furn;
NewHouseProps[id][4] = balkon;
NewHouseProps[id][5] = pool;
NewHouseProps[id][6] = garage;
classes.add(h_class);
Log.d("GenerateHouses","ID: "+id+" CLASS: "+h_class);
Log.d("GenerateHouses","CLASSES: "+classes.get(id));
Log.d("GenerateHouses","PROPS: "+NewHouseProps[id][0]);
}
}
public int GenerateHousePrice(int id, int h_class, int garage, int rooms, int furn, int balkon, int pool){
int price = 0, pricep = 0;
Random r = new Random();
if(h_class == 0){
price = r.nextInt(150000)+50000; // 50 - 200 tausend
price += rooms * 7500;
}
else if(h_class == 1){
price = r.nextInt(165000)+85000; //85 - 250 tausend
price += rooms * 12500;
}
else if(h_class == 2){
price = r.nextInt(300000)+100000; //100 - 400 tausnd
price += rooms * 20000;
}
else if(h_class == 3){
price = r.nextInt(800000)+500000; // 500 - 1.3 Mill.
price += rooms * 15000;
}
if(garage > 0){
pricep += price*0.20;
pricep += garage * 500;
}
if(furn == 1){
pricep += price*0.25;
}
if(balkon > 0){
pricep += price*0.1;
pricep += balkon*500;
}
if(pool == 1){
pricep += 20000;
}
price += pricep;
return price;
}
}
BuyHousesActivity (This is where i want to display it, and when i try to get the Classes it crashes)
public class BuyHousesActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buy_houses);
Houses h = new Houses();
ArrayList<Integer> classes = h.getClasses();
for(int id=0;id<=8;id++){
Log.d("OnCreate Classes: ","Classes: "+classes.get(id)); //Exception
}
ViewPager viewPager = findViewById(R.id.vpPager);
viewPager.setAdapter(new MyViewPagerAdapter(getSupportFragmentManager(), classes));
}
protected class MyViewPagerAdapter extends FragmentStatePagerAdapter {
int clicker = 0;
private List<Integer> pclasses;
private ArrayList<Integer> threeclasses;
MyViewPagerAdapter(FragmentManager fm, ArrayList<Integer> classes) {
super(fm);
pclasses = classes;
if(clicker == 0){
for(int id=0;id<=2;id++) {
threeclasses.add(classes.get(id));
}
}else if(clicker == 1){
for(int id=3;id<=5;id++) {
threeclasses.add(classes.get(id));
}
}else if(clicker == 2){
for(int id=6;id<=8;id++){
threeclasses.add(classes.get(id));
}
clicker = 0;
return;
}
clicker++;
return;
}
#Override
public int getCount() {
return pclasses.size()/3;
}
#Override
public Fragment getItem(int position) {
return FragmentBuyHouse.newInstance(threeclasses);
}
}
The Exception ( Lines marked above):
E/AndroidRuntime: FATAL EXCEPTION: main
Process: at.simonic.realtoroffice, PID: 4913
java.lang.RuntimeException: Unable to start activity ComponentInfo{at.simonic.realtoroffice/at.simonic.realtoroffice.BuyHousesActivity}: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at at.simonic.realtoroffice.BuyHousesActivity.onCreate(BuyHousesActivity.java:31)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6669) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
I hope u can help me see where my data gets lost along the way and help me understand the problem behind it.
You are not calling GenerateHouses on your Houses class constructor. Check your BuyHousesActivity onCreate. What you are doing is:
Houses h = new Houses(); // This will create an new object
And in the constructor of this object you do nothing:
public Houses(){}
So this object classes parameter will be empty when you access it:
ArrayList<Integer> classes = h.getClasses();
And that is the reason why you are getting the exception.
So the solution is one of these:
Call GenerateHouses in the Houses object constructor
Call GenerateHouses before accessing classes variable

java.lang.ClassCastException in Handler Message

Here are the error log:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.ClassCastException: java.lang.String cannot be cast to com.example.demoapp.device.Dev
at com.example.demoapp.MainActivity$MyHandler.handleMessage(MainActivity.java:177)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5140)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
This is My Handler Code error occurred here in new DevSetNameThread
class MyHandler extends Handler {
public MyHandler() {
}
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
new DevSetNameThread(((Dev) msg.obj), deviceNickName).start();
}
}
And Here is the code from that send message to handler with put object
static final int CMD_TIMEOUT = 8;
static final int DISPLAY_DEVID = 9;
static final int FIND_DEVID = 3;
static final int FIND_ERROR = 4;
public static final int SCAN_CODE = 1;
static final int START_SUBMIT = 5;
static final int SUBMIT_ERROR = 2;
static final int SUBMIT_START = 0;
static final int SUBMIT_SUCCEED = 1;
public static final String TAG = "MainActivity";
static final int TIME_OUT = 6;
Handler handler;
List<Dev> listDev;
Msg msg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
info = "";
type = "";
msg = new Msg();
listDev = new ArrayList();
}
class SubmitThread extends Thread {
SubmitThread() {
}
public void run() {
if (listDev.size() > 0) {
Dev d = (Dev) listDev.get(SUBMIT_START);
listDev.remove(d);
if (d != null) {
MainActivity mainActivity;
int index;
Message message = new Message();
message.what = SUBMIT_ERROR;
Log.v("SubmitThread", "\u5f00\u59cb\u63d0\u4ea4\u6570\u636e start..");
int delay = 50;
int reSendTime = SUBMIT_SUCCEED;
Cfg.isSubmitDev = false;
String strId = d.getId();
if (StrTools.stringToInt(strId.substring(SUBMIT_START, SUBMIT_SUCCEED)) == 0) {
mainActivity = MainActivity.this;
devId = strId.substring(SUBMIT_SUCCEED);
} else {
devId = strId;
}
message.obj = devId;
mainActivity = MainActivity.this;
passwd = d.getPass();
byte[] data = new byte[16];
long val = StrTools.stringToInt(devId);
int i = SUBMIT_START;
int index2 = SUBMIT_START;
while (i < CMD_TIMEOUT) {
index = index2 + SUBMIT_SUCCEED;
data[index2] = (byte) ((int) (val % 256));
val /= 256;
i += SUBMIT_SUCCEED;
index2 = index;
}
byte[] b = new byte[CMD_TIMEOUT];
val = StrTools.stringToInt(passwd);
for (i = SUBMIT_START; i < CMD_TIMEOUT; i += SUBMIT_SUCCEED) {
b[i] = (byte) ((int) (val % 256));
val /= 256;
}
byte[] buff = StrTools.byteToSwapByte(b);
i = SUBMIT_START;
while (i < CMD_TIMEOUT) {
index = index2 + SUBMIT_SUCCEED;
data[index2] = buff[i];
i += SUBMIT_SUCCEED;
index2 = index;
}
msg.setId(Cfg.userId);
msg.setCmdType(MSGCMDTYPE.valueOf(-17));
msg.setCmd(MSGCMD.valueOf((int) TIME_OUT));
msg.setTorken(Cfg.tcpTorken);
msg.setData(data);
msg.setDataLen(data.length);
protocol.MessageEnCode(msg);
Log.i(TAG, " data:" + StrTools.bytesToHexString(data));
Log.i(TAG, "sendData:" + StrTools.bytesToHexString(msg.getSendData()));
Message handlermsg = new Message();
handlermsg.obj = devId;
handlermsg.what = SUBMIT_START;
handler.sendMessage(handlermsg);
do {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
reSendTime--;
if (reSendTime <= 0) {
reSendTime = 10;
socketService.socketSendMessage(msg);
}
if (Cfg.isSubmitDev) {
message.what = SUBMIT_SUCCEED;
message.obj = d;
succedDev = d;
handler.sendMessage(message);
return;
}
delay--;
} while (delay > 0);
message.what = SUBMIT_ERROR;
handler.sendMessage(message);
}
}
}
}
Sorry for inconvenience i can't put whole code.
I tried to casting retrieved object with standard code but it's giving me this error so, how can i retrieve Dev object through handler and use it ?

Creating a Gridview for a word search

I am trying to create a word search using a gridview but I'm unsure how to add rows from a JSONArray, but my app keeps crashing at this point and also at gridView.addView(tableRow);
This is my new puzzle class
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.DragEvent;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Arrays;
public class NewPuzzleActivity extends Activity implements OnRetrieveHTTPData {
//word search data
String[] rows;
String[] words;
char[] letters;
//variables for the grid creation
int letterID = 0;
int rowID = 0;
//found words by the user
String[] wordsFound;
int[] rowFound;
int[] columnFound;
int[]directionFound;
// objects within the game *miscellaneous properties*
boolean firstLetterSelected = false;
int numOFLettersSelected = 0;
int[] lettersSelected;
int[] rowsSelected;
int[] columnsSelected;
String selectedString = "";
int directionSelected = 0;
int lastLetterSelected = -1;
String date;
GridView gridView;
TextView textView;
Toast toast;
public NewPuzzleActivity(){
}
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_puzzle);
gridView = (GridView) findViewById(R.id.gridView1);
Intent intent = getIntent();
if(intent.hasExtra("rows")){
// initialize the data
rows = intent.getExtras().getStringArray("rows");
addRows();
stringArrayToCharArray();
fillGrid();
lettersSelected = new int[rows.length];
rowsSelected = new int[rows.length];
columnsSelected = new int[rows.length];
}
if(intent.hasExtra("words")){
words = intent.getExtras().getStringArray("words");
wordsFound = new String[words.length];
rowFound = new int[words.length];
columnFound = new int[words.length];
directionFound = new int[words.length];
fillWords();
}
if(intent.hasExtra("date")){
date = intent.getExtras().getString("date");
//textView = (TextView)findViewById(R.id.Title);
//textView.append(date);
}
}
public void letterButonClick(View view){
if(toast != null){
toast.cancel(); // cancel toast message to prevent multiple toast messages
}
TextView textView1 = (TextView) findViewById(view.getId());
textView1.setTextColor(Color.RED);
//works out the column number of the selected letter(s)
columnsSelected[numOFLettersSelected] = (Integer.parseInt(view.getTag().toString())% rows.length);
if(columnsSelected[numOFLettersSelected] == 0) columnsSelected[numOFLettersSelected] = rows.length;
//works out the row number of the selected letter(s)
rowsSelected[numOFLettersSelected] = (Integer.parseInt(view.getTag().toString())/ rows.length)+1;
if(rowsSelected[numOFLettersSelected] == 0) rowsSelected[numOFLettersSelected] = rows.length;
//fixes the last column
if(columnsSelected[numOFLettersSelected] == rows.length) rowsSelected[numOFLettersSelected]-=1;
lettersSelected[numOFLettersSelected] = Integer.parseInt(view.getTag().toString()) + 4999;
Log.i("Selected Column", Integer.toString(columnsSelected[numOFLettersSelected]));
Log.i("Selected Row", Integer.toString(rowsSelected[numOFLettersSelected]));
if(!firstLetterSelected){
firstLetterSelected = true;
//resets the selected string
selectedString = textView1.getText().toString();
numOFLettersSelected = 1;
}else{
//adds letters to selected string
selectedString += textView1.getText().toString();
//compares to the last letter to work out the direction
if(columnsSelected[numOFLettersSelected] +1 == columnsSelected[numOFLettersSelected - 1] &&
rowsSelected[numOFLettersSelected] +1 == rowsSelected[numOFLettersSelected - 1]){
//direction left / down
directionSelected = 0;
Log.i("Direction", "0");
checkWordFound();
}
else if(rowsSelected[numOFLettersSelected]+1 == rowsSelected[numOFLettersSelected-1]&&
columnsSelected[numOFLettersSelected] == columnsSelected[numOFLettersSelected-1]){
//direction is down
directionSelected = 1;
Log.i("Direction", "1");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected] - 1 == columnsSelected[numOFLettersSelected-1] &&
rowsSelected[numOFLettersSelected]+1 == rowsSelected[numOFLettersSelected-1]){
//direction is right-down
directionSelected = 2;
Log.i("Direction", "2");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected]+1 == columnsSelected[numOFLettersSelected-1]&&
rowsSelected[numOFLettersSelected] == rowsSelected[numOFLettersSelected-1]){
//direction is left
directionSelected = 3;
Log.i("Direction", "3");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected]-1 == columnsSelected[numOFLettersSelected-1]&&
rowsSelected[numOFLettersSelected] == rowsSelected[numOFLettersSelected-1]){
//direction is right
directionSelected = 4;
Log.i("Direction", "4");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected]+1 == columnsSelected[numOFLettersSelected-1] &&
rowsSelected[numOFLettersSelected]-1 == rowsSelected[numOFLettersSelected-1]){
//direction is left-up
directionSelected = 5;
Log.i("Direction", "5");
checkWordFound();
}
else if(rowsSelected[numOFLettersSelected]-1 == rowsSelected[numOFLettersSelected-1]&&
columnsSelected[numOFLettersSelected] == columnsSelected[numOFLettersSelected-1]){
//direction is up
directionSelected = 6;
Log.i("Direction", "6");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected]-1 == columnsSelected[numOFLettersSelected-1] &&
rowsSelected[numOFLettersSelected]-1 == rowsSelected[numOFLettersSelected-1]) {
//direction is right-up
directionSelected = 7;
Log.i("Direction", "7");
checkWordFound();
}else{
// not a letter within/ around the the first letter selected, reset any selected letters
//deselect words and select a new letter to starr again
//selected string reset
selectedString = textView1.getText().toString();
for(int i : lettersSelected){
try{
TextView letters = (TextView)findViewById(i);
letters.setTextColor(Color.BLACK);
i++;
}catch (Exception e){
//break
Toast.makeText(getApplication(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
//variables reset
directionSelected = -1;
numOFLettersSelected = 0;
lettersSelected = new int[rows.length];
rowsSelected = new int[rows.length];
columnsSelected = new int[rows.length];
// new letter to be selected
columnsSelected[0] = (Integer.parseInt(view.getTag().toString())% rows.length);
if(columnsSelected[0] == 0) columnsSelected[0] = rows.length;
rowsSelected[0] = (Integer.parseInt(view.getTag().toString()) / rows.length)+1;
if(rowsSelected[0] == 0) rowsSelected[0] = rows.length;
if(columnsSelected[0] == rows.length) rowsSelected[0] -= 1;
lettersSelected[0] = Integer.parseInt(view.getTag().toString()) + 4999;
textView1.setTextColor(Color.RED);
}
numOFLettersSelected++;
Log.i("Selected TEXT", selectedString);
}
lastLetterSelected = Integer.parseInt(view.getTag().toString());
}
private void fillGrid(){
int LetterChars = 0;
for(int i = 0; i < rows.length * rows.length; i++){
if(LetterChars >= rows.length){
rowID--;
LetterChars = 0;
}
addLetter((TableRow)findViewById(rowID+4000+ rows.length-1));
TextView textView1 = (TextView)findViewById(i+5000);
textView1.setText(Character.toString(letters[i]));
LetterChars++;
}
}
private void fillWords(){
for(int i = 1; i < rows.length -1; i++){
String name = "Word"+i;
int id = getResources().getIdentifier(name, "id", getPackageName());
if(id != 0){
TextView textView1 = (TextView)findViewById(id);
try{
textView1.setText(words[i-1]);
}catch(Exception e){
textView1.setText("");
}
}
}
}
private void stringArrayToCharArray(){
char[] chars = new char[rows.length * rows.length];
int i = 0;
//selection of strings
for(int j = 0; j< rows.length; j++){
// selection of letters
for(int k = 0; k < rows.length; k++){
try{
chars[i] = rows[j].charAt(k);
}catch (Exception e){
Log.e("Error", "Error when adding chars");
}
i++;
}
}
letters = chars;
}
private void addLetter(TableRow row){
TextView textView1 = new TextView(this);
textView1.setId(letterID+5000);
textView1.setPadding(3,3,3,3);
textView1.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
TableRow.LayoutParams textLayout = new TableRow.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.FILL_PARENT);
textLayout.setMargins(10,0,0,10);
textView1.setTextAlignment(textView1.TEXT_ALIGNMENT_CENTER);
textView1.setGravity(Gravity.CENTER);
textView1.setTag(""+(letterID+1));
textView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
letterButonClick(v);
}
});
textView1.setOnDragListener(new View.OnDragListener() {
//draggin selection *To be implemented*
#Override
public boolean onDrag(View v, DragEvent event) {
return false;
}
});
textView1.setLayoutParams(textLayout);
row.addView(textView1);
letterID++;
}
private void addRows(){
for(int i= 0; i < rows.length;i++){
TableRow tableRow = new TableRow(this);
tableRow.setId(i+4000);
gridView.addView(tableRow);
}
}
private void checkWordFound(){
int foundID = 0;
for(String w: words){
if(selectedString.contains(w)){
//word that have been found
Log.i("Word Found", "Found: " + w);
//highlight words that have been found in the word list
for(int i = 1; i < rows.length-1; i++){
String name = "Word"+i;
int id = getResources().getIdentifier(name, "id", getPackageName());
if(id != 0){
TextView textView1 = (TextView)findViewById(id);
try{
if(textView1.getText().equals(w)){
//textview that contains the found words
textView1.setTextColor(Color.GREEN);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
//add to found
wordsFound[foundID] =w;
columnFound[foundID] = columnsSelected[0];
rowFound[foundID] = rowsSelected[0];
directionFound[foundID] = directionSelected;
//variables reset
directionSelected = -1;
numOFLettersSelected = 0;
lettersSelected = new int[rows.length];
rowsSelected = new int[rows.length];
columnsSelected = new int[rows.length];
}
foundID++;
}
checkCompletion();
//no words are found
}
private void checkCompletion(){
if(Arrays.equals(words, wordsFound)){
new AlertDialog.Builder(this)
.setTitle("Word Search Complete")
.setMessage("Submit Score?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//submit score
submitResults();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
}
}
public void homeClicked(View v){
finish();
}
public void submitResults(){
}
#Override
public void onRetrieveTaskCompleted(String httpData) {
Log.i("Solution Response", responseData);
//debug toasts
Toast.makeText(getApplication(),("Solution Submitted"), Toast.LENGTH_LONG).show();
finish();
}
}
error log
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
05-04 00:49:18.929 6068-6068/sl.lloyd.steve.angrywordsearchthefinalone D/AndroidRuntime﹕ Shutting down VM
05-04 00:49:18.937 6068-6068/sl.lloyd.steve.angrywordsearchthefinalone E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: sl.lloyd.steve.angrywordsearchthefinalone, PID: 6068
java.lang.RuntimeException: Unable to start activity ComponentInfo{sl.lloyd.steve.angrywordsearchthefinalone/sl.lloyd.steve.angrywordsearchthefinalone.NewPuzzleActivity}: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
at android.widget.AdapterView.addView(AdapterView.java:461)
at sl.lloyd.steve.angrywordsearchthefinalone.NewPuzzleActivity.addRows(NewPuzzleActivity.java:320)
at sl.lloyd.steve.angrywordsearchthefinalone.NewPuzzleActivity.onCreate(NewPuzzleActivity.java:75)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
The problem is you cannot addView(view) directly to GridView, because it is an AdapterView which does not allow that. So you have to do this operation in your Adapter. You just have to add more data to the adapter and after call notifyDataSetChanged() on the adapter, so your GridView will be added the View by itself.

Android array error

This is my code:
public ArrayList generare_diferente(){
int rezultat;
ArrayList<String> termeni= new ArrayList<String>();
int termA=parseInt(String.valueOf(randomBetween(1, 20)));
int termB=parseInt(String.valueOf(randomBetween(1, 20)));
if(termA<termB){
int aux; aux=termA; termA=termB; termB=aux;
rezultat=termA-termB;
String diff = termA + "-" + termB;
termeni.add(String.valueOf(rezultat));
termeni.add(diff);
Log.v("termeeeeni", String.valueOf(termeni));
}
return termeni;
}
public void generare_3_diferente() {
ArrayList<String> scaderea1 = new ArrayList<String>();
ArrayList<String> scaderea2 = new ArrayList<String>();
ArrayList<String> scaderea3 = new ArrayList<String>();
int raspuns_corect;
int[] raspunsuri = new int[]{0, 0, 0, 0};
int i = 0;
do {
scaderea1 = generare_diferente();
scaderea2 = generare_diferente();
scaderea3 = generare_diferente();
Button scadere1 = (Button) findViewById(R.id.scadere1);
Button scadere2 = (Button) findViewById(R.id.scadere2);
Button scadere3 = (Button) findViewById(R.id.scadere3);
scadere1.setText((CharSequence) scaderea1.get(1));
scadere2.setText((CharSequence) scaderea2.get(1));
scadere3.setText((CharSequence) scaderea3.get(1));
}
while (scaderea1.get(0) == scaderea2.get(0) || scaderea2.get(0) == scaderea3.get(0) || scaderea3.get(0) == scaderea1.get(0));
raspunsuri[1]= Integer.parseInt(scaderea1.get(0));
raspunsuri[2]= Integer.parseInt(scaderea2.get(0));
raspunsuri[3]= Integer.parseInt(scaderea3.get(0));
pozitia_corecta = parseInt(String.valueOf(randomBetween(1, 3)));
raspuns_corect = raspunsuri[pozitia_corecta];
TextView rezultat = (TextView) findViewById(R.id.Rezultat);
rezultat.setText(raspuns_corect);
}
I'm getting this error:
java.lang.RuntimeException: Unable to start activity : java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.get(ArrayList.java:308)
at com.example.pinguin.MyActivity.generare_3_diferente(MyActivity.java:93)
at .onCreate(MyActivity.java:24)
I don't understand why, the array should not have the size 0.
thank you!
your code seems wrong. because in generare_diferente() if termA<termB or equal you return empty array and then in generare_3_diferente() you try to read data from empty list.
first you should handle this issue.then I think your random number are not generate so termA and termB both is zero or anything and if statement are not true.
change code like this
public ArrayList generare_diferente(){
int rezultat;
ArrayList<String> termeni= new ArrayList<String>();
int termA=random.nextInt(max - min + 1) + min ;
int termB=random.nextInt(max - min + 1) + min ;
if(termA<termB){
int aux; aux=termA; termA=termB; termB=aux;
rezultat=termA-termB;
String diff = termA + "-" + termB;
termeni.add(String.valueOf(rezultat));
termeni.add(diff);
Log.v("termeeeeni", String.valueOf(termeni));
}
return termeni.clone();
}
public void generare_3_diferente() {
ArrayList<String> scaderea1 = new ArrayList<String>();
ArrayList<String> scaderea2 = new ArrayList<String>();
ArrayList<String> scaderea3 = new ArrayList<String>();
int raspuns_corect;
int[] raspunsuri = new int[]{0, 0, 0, 0};
int i = 0;
do {
scaderea1 = generare_diferente();
scaderea2 = generare_diferente();
scaderea3 = generare_diferente();
Button scadere1 = (Button) findViewById(R.id.scadere1);
Button scadere2 = (Button) findViewById(R.id.scadere2);
Button scadere3 = (Button) findViewById(R.id.scadere3);
if(scaderea1.size()>0 && scaderea2.size()>0 && scaderea3.size()>0){
scadere1.setText((CharSequence) scaderea1.get(1));
scadere2.setText((CharSequence) scaderea2.get(1));
scadere3.setText((CharSequence) scaderea3.get(1));
}else{
scadere1.setText("something");
scadere2.setText("something");
scadere3.setText("something");
break;
}
}
while (scaderea1.get(0) == scaderea2.get(0) || scaderea2.get(0) == scaderea3.get(0) || scaderea3.get(0) == scaderea1.get(0));
if(scaderea1.size()>0 && scaderea2.size()>0 && scaderea3.size()>0){
raspunsuri[1]= Integer.parseInt(scaderea1.get(0));
raspunsuri[2]= Integer.parseInt(scaderea2.get(0));
raspunsuri[3]= Integer.parseInt(scaderea3.get(0));
}else{
raspunsuri[1]= Integer.parseInt("0");
raspunsuri[2]= Integer.parseInt("0");
raspunsuri[3]= Integer.parseInt("0");
}
pozitia_corecta = parseInt(String.valueOf(randomBetween(1, 3)));
raspuns_corect = raspunsuri[pozitia_corecta];
TextView rezultat = (TextView) findViewById(R.id.Rezultat);
rezultat.setText(raspuns_corect);
}

How to reset data of NumberPicker

I am using two NumberPickers to display province(mProvincePicker) and city(mCityPicker) data in my app. When user changes province data, city data should be changed accordingly. I reset the mCityPicker data in NumberPicker.onValueChange(NumberPicker picker, int oldVal, int newVal). But it does not work well and an java.lang.ArrayIndexOutOfBoundsException crash the app.
Here is my code:
public class AreaPickerDialog extends Dialog implements OnValueChangeListener, OnClickListener {
static final String TAG = "AreaPickerDialog";
private NumberPicker mProvincePicker;
private NumberPicker mCityPicker;
private Button mCancelBtn;
private Button mOKBtn;
private AreaUtil mAreaUtil;
private List<Area> mProvinces;
private int mAreaId;
private int mProvinceId;
private Handler mHandler;
public AreaPickerDialog(Context context, Handler handler, int areaId) {
super(context);
mAreaUtil = AreaUtil.getInstance();
mProvinces = mAreaUtil.getProvinceList();
mAreaId = areaId;
mProvinceId = mAreaUtil.getProvinceIdByAreaId(areaId);
mHandler = handler;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_area_picker);
mProvincePicker = (NumberPicker) findViewById(R.id.np_province);
mCityPicker = (NumberPicker) findViewById(R.id.np_city);
mCancelBtn = (Button) findViewById(R.id.btn_cancel);
mOKBtn = (Button) findViewById(R.id.btn_ok);
initProvinceData();
mProvincePicker.setOnValueChangedListener(this);
mCityPicker.setOnValueChangedListener(this);
mCancelBtn.setOnClickListener(this);
mOKBtn.setOnClickListener(this);
}
private void initProvinceData() {
if (mProvinces != null && mProvinces.size() > 0) {
String[] provinceNames = new String[mProvinces.size()];
for (int i = 0; i < provinceNames.length; i++) {
provinceNames[i] = mProvinces.get(i).getProvincename();
}
mProvincePicker.setDisplayedValues(provinceNames );
mProvincePicker.setMinValue(1);
mProvincePicker.setMaxValue(mProvinces.size());
}
mProvincePicker.setValue(mProvinceId);
initCityData(mProvincePicker.getValue());
}
private void initCityData(int provinceId) {
List<Arealist> cities = mAreaUtil.getCityListOfProvince(provinceId);
if (cities != null && cities.size() > 0) {
try {
int min = Integer.parseInt(cities.get(0).getAreaid());
int max = Integer.parseInt(cities.get(cities.size() -1).getAreaid());
String[] cityNames = new String[cities.size()];
for (int i = 0; i < cityNames.length; i++) {
cityNames[i] = cities.get(i).getName();
}
mCityPicker.setValue(0);
mCityPicker.setDisplayedValues(cityNames);
mCityPicker.setMinValue(min);
mCityPicker.setMaxValue(max);
} catch (NumberFormatException e) {
ILog.e(TAG, e.getMessage(), e);
}
}
}
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
if (mProvincePicker.equals(picker)) {
initCityData(mProvincePicker.getValue());
} else if (mCityPicker.equals(picker)) {
mAreaId = mCityPicker.getValue();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_cancel:
dismiss();
break;
case R.id.btn_ok:
Message msg = mHandler.obtainMessage(MineActivity.MSG_UPDATE_AREA);
msg.arg1 = mAreaId;
msg.sendToTarget();
dismiss();
break;
default:
break;
}
}
}
And logcat error trace:
12-30 23:09:26.560: E/InputEventReceiver(5620): Exception dispatching input event.
12-30 23:09:26.560: W/dalvikvm(5620): threadid=1: thread exiting with uncaught exception (group=0x41ddf438)
12-30 23:09:26.580: E/AndroidRuntime(5620): FATAL EXCEPTION: main
12-30 23:09:26.580: E/AndroidRuntime(5620): java.lang.ArrayIndexOutOfBoundsException: length=14; index=15
12-30 23:09:26.580: E/AndroidRuntime(5620): at net.simonvt.numberpicker.NumberPicker.updateInputTextView(NumberPicker.java:1840)
12-30 23:09:26.580: E/AndroidRuntime(5620): at net.simonvt.numberpicker.NumberPicker.setDisplayedValues(NumberPicker.java:1423)
12-30 23:09:26.580: E/AndroidRuntime(5620): at com.meishai.app.dialog.AreaPickerDialog.initCityData(AreaPickerDialog.java:88)
12-30 23:09:26.580: E/AndroidRuntime(5620): at com.meishai.app.dialog.AreaPickerDialog.onValueChange(AreaPickerDialog.java:100)
12-30 23:09:26.580: E/AndroidRuntime(5620): at net.simonvt.numberpicker.NumberPicker.notifyChange(NumberPicker.java:1855)
12-30 23:09:26.580: E/AndroidRuntime(5620): at net.simonvt.numberpicker.NumberPicker.setValueInternal(NumberPicker.java:1641)
12-30 23:09:26.580: E/AndroidRuntime(5620): at net.simonvt.numberpicker.NumberPicker.scrollBy(NumberPicker.java:1106)
12-30 23:09:26.580: E/AndroidRuntime(5620): at net.simonvt.numberpicker.NumberPicker.onTouchEvent(NumberPicker.java:886)
12-30 23:09:26.580: E/AndroidRuntime(5620): at android.view.View.dispatchTouchEvent(View.java:7127)
12-30 23:09:26.580: E/AndroidRuntime(5620): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2170)
12-30 23:09:26.580: E/AndroidRuntime(5620): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1905)
12-30 23:09:26.580: E/AndroidRuntime(5620): at net.simonvt.numberpicker.NumberPicker.dispatchTouchEvent(NumberPicker.java:944)
....
I am reseting the minValue,maxValue and DisplayedValues to reset the NumberPicker data and not working, so what is the right way?
check for Call setDisplayedValues(null) before setMaxValue in onClick.
Reference: https://stackoverflow.com/a/24322319/2624806
I have the same problem and I fixed it without modifing NumberPicker.java. Here is the code for your reference.
private void initCityData(int provinceId) {
List<Arealist> cities = mAreaUtil.getCityListOfProvince(provinceId);
if (cities != null && cities.size() > 0) {
try {
int min = Integer.parseInt(cities.get(0).getAreaid());
int max = Integer.parseInt(cities.get(cities.size() -1).getAreaid());
String[] cityNames = new String[cities.size()];
for (int i = 0; i < cityNames.length; i++) {
cityNames[i] = cities.get(i).getName();
}
int maxV = mCityPicker.getMaxValue();
if (max> maxV){
mCityPicker.setMinValue(min);
mCityPicker.setValue(0);
mCityPicker.setDisplayedValues(cityNames);
mCityPicker.setMaxValue(max);
}else{
mCityPicker.setMinValue(min);
mCityPicker.setValue(0);
mCityPicker.setMaxValue(max);
mCityPicker.setDisplayedValues(cityNames);
}
} catch (NumberFormatException e) {
ILog.e(TAG, e.getMessage(), e);
}
}
}
Just set displayedValues to null before resetting number picker like below:
pickerWard.displayedValues = null
pickerWard.maxValue = values.size - 1
pickerWard.displayedValues = values
Well, I look into the source code of NumberPicker.java, find that it will recompute the data and refresh UI in setMinValue(int minValue) and setMaxValue(int minValue). When set the new minValue, it will compute using new minValue and old maxValue, then error occured.
So, I modify a little of the NumberPicker: set value only in setMinValue(int minValue) and setMaxValue(int maxValue), and update UI in setDisplayedValues(String[] displayedValues). When data of NumberPicker changed, just reset the minValue、maxVaule and displayedValues. Note that setDisplayedValues(String[] displayedValues) MUST be called at last.
Here is what I modified:
NumberPicker.java:
public void setMinValue(int minValue) {
if (mMinValue == minValue) {
return;
}
if (minValue < 0) {
throw new IllegalArgumentException("minValue must be >= 0");
}
mMinValue = minValue;
if (mMinValue > mValue) {
mValue = mMinValue;
}
//boolean wrapSelectorWheel = mMaxValue - mMinValue > mSelectorIndices.length;
//setWrapSelectorWheel(wrapSelectorWheel);
//initializeSelectorWheelIndices();
//updateInputTextView();
//tryComputeMaxWidth();
invalidate();
}
public void setMaxValue(int maxValue) {
if (mMaxValue == maxValue) {
return;
}
if (maxValue < 0) {
throw new IllegalArgumentException("maxValue must be >= 0");
}
mMaxValue = maxValue;
if (mMaxValue < mValue) {
mValue = mMaxValue;
}
//boolean wrapSelectorWheel = mMaxValue - mMinValue > mSelectorIndices.length;
//setWrapSelectorWheel(wrapSelectorWheel);
//initializeSelectorWheelIndices();
//updateInputTextView();
//tryComputeMaxWidth();
invalidate();
}
public void setDisplayedValues(String[] displayedValues) {
if (mDisplayedValues == displayedValues) {
return;
}
mDisplayedValues = displayedValues;
if (mDisplayedValues != null) {
// Allow text entry rather than strictly numeric entry.
mInputText.setRawInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
} else {
mInputText.setRawInputType(InputType.TYPE_CLASS_NUMBER);
}
boolean wrapSelectorWheel = mMaxValue - mMinValue > mSelectorIndices.length;
setWrapSelectorWheel(wrapSelectorWheel);
updateInputTextView();
initializeSelectorWheelIndices();
tryComputeMaxWidth();
}
AreaPickerDialog.java:
private void initCityData(int provinceId) {
List<Arealist> cities = mAreaUtil.getCityListOfProvince(provinceId);
if (cities != null && cities.size() > 0) {
try {
int min = Integer.parseInt(cities.get(0).getAreaid());
int max = Integer.parseInt(cities.get(cities.size() -1).getAreaid());
String[] cityNames = new String[cities.size()];
for (int i = 0; i < cityNames.length; i++) {
cityNames[i] = cities.get(i).getName();
}
mCityPicker.setMinValue(min);
mCityPicker.setMaxValue(max);
mCityPicker.setDisplayedValues(cityNames);
} catch (NumberFormatException e) {
ILog.e(TAG, e.getMessage(), e);
}
}
}
This is an ugly but working solution.
looking the code of NumberPicker you're using:
private boolean updateInputTextView() {
/*
* If we don't have displayed values then use the current number else
* find the correct value in the displayed values for the current
* number.
*/
String text = (mDisplayedValues == null) ? formatNumber(mValue)
: mDisplayedValues[mValue - mMinValue];
you can see that's using mMinValue before you call setMinValue.
Try setting minValue and maxValue, before set the displayed values.

Categories

Resources