Unable to store value into string android - android

I would like to put the value to the String array, but it is unsuccessful.
I don't know what is the exact problem.
public String[] history = null;
public String record;
public int counter = 0;`
public void createString (String record){
history[counter] = record;
counter++;
}
Here is the defining variable.
What is the mistake i have done, and how to fix it ?
03-19 17:15:35.870: W/dalvikvm(4937): threadid=1: thread exiting with uncaught exception (group=0x40c20450)
03-19 17:15:35.890: E/AndroidRuntime(4937): FATAL EXCEPTION: main
03-19 17:15:35.890: E/AndroidRuntime(4937): java.lang.NullPointerException
03-19 17:15:35.890: E/AndroidRuntime(4937): at com.airportapplication.app.Buses.createString(Buses.java:147)
03-19 17:15:35.890: E/AndroidRuntime(4937): at com.airportapplication.app.Buses$1.onClick(Buses.java:101)

You need to initialize your array
like this:
String[] history = new String[lengthOfArray];
if you don't know the array length use this:
List<String> history = new ArrayList<String>();
history.add(record);

Related

Android App force closes, found java.lang.nullpointerexception

I built an android app that casts a spinner to a switch, to enable the user to select an operator for a calculation and see the result.
It is from the Android Boot Camp lessons. I was unhappy to find my app had no compile errors but crashed on start-up. I was watching the logcat as I ran the application and found the nullpointer exception to be on line 40. Where I pull the spinner's selection to a string variable.
//spinner
op3 = operation.getSelectedItem().toString();
I dumped the contents of my logcat to a text file. Here is what I think is relevant.
09-30 22:26:58.401: E/AndroidRuntime(1565): FATAL EXCEPTION: main
09-30 22:26:58.401: E/AndroidRuntime(1565): Process: com.schmop.flashmath, PID: 1565
09-30 22:26:58.401: E/AndroidRuntime(1565): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.schmop.flashmath/com.schmop.flashmath.MainActivity}: java.lang.NullPointerException
and
**09-30 22:26:58.401: E/AndroidRuntime(1565): Caused by: java.lang.NullPointerException
09-30 22:26:58.401: E/AndroidRuntime(1565): at** com.schmop.flashmath.MainActivity.onCreate(MainActivity.java:40)
09-30 22:26:58.401: E/AndroidRuntime(1565): at android.app.Activity.performCreate(Activity.java:5231)
09-30 22:26:58.401: E/AndroidRuntime(1565): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
09-30 22:26:58.401: E/AndroidRuntime(1565): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
09-30 22:26:58.401: E/AndroidRuntime(1565): ... 11 more
Here is the contents of my mainActivity in
MainActivity.java
public class MainActivity extends ActionBarActivity {
int number1;
int number2;
int result;
int op1;
int op2;
String op3 = null;
int calculator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText first = (EditText)findViewById(R.id.num);
final EditText second = (EditText)findViewById(R.id.num2);
final Spinner operation = (Spinner)findViewById(R.id.operator);
final Button equals = (Button)findViewById(R.id.button1);
final TextView t = (TextView)findViewById(R.id.result);
operation.setSelection(0);
//spinner
op3 = operation.getSelectedItem().toString();
//start logic
//onclick listener
equals.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//gettext
number1 = Integer.parseInt(first.getText().toString());
number2 = Integer.parseInt(second.getText().toString());
if(number1 < 21 && number1 > 0 && number2 < 21 && number2 > 0) {
//switch
switch(calculator) {
case 1: op3 = "+";
calculator = number1 + number2;
break;
case 2: op3 = "-";
calculator = number1 - number2;
break;
case 3: op3 = "x";
calculator = number1 * number2;
break;
}
} else {
t.setText("Error: One of your Numbers is out of Range");
}
t.setText(number1 + op3 + number2 + "=" + calculator);
}
});
//end logic
}
Since it was calling a null variable, I tried adding junk data into the declaration of op3 as an attempt to fix my problem. This proved unsuccessful. I've seen some examples being solved by adding a check for null in an if statement, however I dont think it would apply here.
Documentation for getSelectedItem():
Returns The data corresponding to the currently selected item, or null if there is nothing selected.
When the app is starting up, nothing is yet selected. Move the
op3 = operation.getSelectedItem()
inside the onClick() and check for != null before trying to call toString() on the result.
You haven't set any contents for the spinner, so operation.getSelectedItem() is returning null. The NPE is from trying to then call toString(). Populate your spinner first before trying to access items, or at least put a null check when you try to retrieve an item.

Android: Is it possible to have two intents int the same activity?

The following code causes my application to stop working:
// Passing values to the results activity
Intent intent = new Intent(this, TestResults.class);
intent.putExtra("results", results);
intent.putExtra("Questions", question);
intent.putExtra("CorrectAnswer", correctAnswer);
//this.startActivity(intent);
//passing the score value to the splash activity
Intent SplashIntent = new Intent(this, SplashTest.class);
SplashIntent.putExtra("score", score);
this.startActivity(SplashIntent);
Is this becuase I have two intents in the one activity?
Log Cat Crash report:
04-15 16:33:13.894: E/AndroidRuntime(2322): FATAL EXCEPTION: main
04-15 16:33:13.894: E/AndroidRuntime(2322): Process: com.example.multapply, PID: 2322
04-15 16:33:13.894: E/AndroidRuntime(2322): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.multapply/com.example.multapply.SplashTest}: android.content.res.Resources$NotFoundException: String resource ID #0x0
04-15 16:33:13.894: E/AndroidRuntime(2322): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-15 16:33:13.894: E/AndroidRuntime(2322): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-15 16:33:13.894: E/AndroidRuntime(2322): at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-15 16:33:13.894: E/AndroidRuntime(2322): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-15 16:33:13.894: E/AndroidRuntime(2322): at android.os.Handler.dispatchMessage(Handler.java:102)
04-15 16:33:13.894: E/AndroidRuntime(2322): at android.os.Looper.loop(Looper.java:136)
04-15 16:33:13.894: E/AndroidRuntime(2322): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-15 16:33:13.894: E/AndroidRuntime(2322): at java.lang.reflect.Method.invokeNative(Native Method)
04-15 16:33:13.894: E/AndroidRuntime(2322): at java.lang.reflect.Method.invoke(Method.java:515)
04-15 16:33:13.894: E/AndroidRuntime(2322): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-15 16:33:13.894: E/AndroidRuntime(2322): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-15 16:33:13.894: E/AndroidRuntime(2322): at dalvik.system.NativeStart.main(Native Method)
04-15 16:33:13.894: E/AndroidRuntime(2322): Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x0
04-15 16:33:13.894: E/AndroidRuntime(2322): at android.content.res.Resources.getText(Resources.java:244)
04-15 16:33:13.894: E/AndroidRuntime(2322): at android.widget.TextView.setText(TextView.java:3888)
04-15 16:33:13.894: E/AndroidRuntime(2322): at com.example.multapply.SplashTest.onCreate(SplashTest.java:32)
04-15 16:33:13.894: E/AndroidRuntime(2322): at android.app.Activity.performCreate(Activity.java:5231)
04-15 16:33:13.894: E/AndroidRuntime(2322): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-15 16:33:13.894: E/AndroidRuntime(2322): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-15 16:33:13.894: E/AndroidRuntime(2322): ... 11 more
The crash report is from the section where the app has crashed
Edit: Class that has the two intents:
public class Test extends Activity implements View.OnClickListener{
//declare vars
TextView text;
EditText answer;
Button submit;
int random1;
int random2;
String[] question= new String[10];//change to array?
int correctAnswer[]=new int[10];//change to array?
int[] results=new int[10];
int score=0;
int questionNumber=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
// initialising variables
initialiseVars();
//set up random
setUpRandom();
//Set text view equal to question
text.setText(question[questionNumber-1]);
//set on click listener for submit button
submit.setOnClickListener(this);
//updateQuestion?
updateQuestion();
}
public void initialiseVars() {
text = (TextView) findViewById(R.id.tvTopRandomTest);
answer = (EditText) findViewById(R.id.etEnterAnswerRandomTest);
submit = (Button) findViewById(R.id.btnSubmitRandomTest);
}
public void setUpRandom(){
//setting up randoms
Random random= new Random();
// Generating random number between 1 and 12
random1 = random.nextInt(12) + 1;
// Generating another random number between 1 and 12
random2 = random.nextInt(12) + 1;
question[questionNumber-1]= random1 + " x " + random2 + " = ";
correctAnswer[questionNumber-1]= random1*random2; //note: possibly may not be used
}
public void updateQuestion(){
//updating question after each click
setUpRandom();
text.setText(question[questionNumber-1]);
answer.setText("");
}
public void onClick(View v){
// sets text view equal to whats typed in in editText
final String entry = answer.getText().toString();
// convert from string value to int
int a = Integer.parseInt(entry); // note: maybe change name
//setting the user answer equal to the question
results[questionNumber-1]=a;
if(a==correctAnswer[questionNumber-1]){
score++;
}
if (questionNumber < 10) {
questionNumber++;//updates question
// called after an answer is given
updateQuestion();
} else {
// Passing values to the results activity
Intent intent = new Intent(this, TestResults.class);
intent.putExtra("results", results);
intent.putExtra("Questions", question);
intent.putExtra("CorrectAnswer", correctAnswer);
//this.startActivity(intent);
//passing the score value to the splash activity
Intent SplashIntent = new Intent(this, SplashTest.class);
SplashIntent.putExtra("score", score);
this.startActivity(SplashIntent);
}
}
}
The problem is that after you call startActivity() with the first intent, the code afterward is not executed. This means that whatever data you try to access in SplashTest is not actually present. A workaround to this issue would be to save the data to internal/external storage or SharedPreferences and access it from there.
Since your arrays aren't large, we can definitely use SharePreferences to store the data.
We save each piece of data in SharedPreferences as a String-String key-value pair.
To store the int arrays, we can combine all the elements into a single String and use a comma as a delimiter.
Storing the "question" String array as a String is an interesting problem, since a String can potentially contain any character. This makes it difficult to efficiently choose a delimiter. I wrote a class called EncodeDecode to convert a String array to a String(and back) here: https://gist.github.com/liangricha/10759438. Feel free to read through the code/give feedback. It should be fully functional.
My code snippets below use the functions in my EncodeDecode.
Saving Data
To store the data in SharedPreferences, you can write:
//Grab SharedPreferences of application.
SharedPreferences.Editor editor = getSharedPreferences("Data", MODE_PRIVATE).edit();
//Use StringBuilder to build data string.
StringBuilder strBuild = new StringBuilder();
//Store "results"(int array)
for(int i = 0; i < results.length; i++)
strBuild.append(str.append(correctAnswer[i]).append(","));
editor.putString("results", strBuild.toString());
strBuild.setLength(0);
//Store "question"(String array) ***REFERENCES CLASS IN GIST ABOVE***
String arrStr = EncodeDecode.encode(question)
editor.putString("questions", arrString);
//Store "correctAnswer"(int array)
for(int i = 0; i < correctAnswer.length; i++)
strBuild.append(str.append(correctAnswer[i]).append(","));
editor.putString("correctAnswer", strBuild.toString());
//Store "score"(int)
editor.putString("score", Integer.toString(score));
//Write changes to disk.
editor.commit();
Retrieving Data
First, grab a reference to the SharedPreferences:
SharedPreferences prefs = getSharedPreferences("Data", MODE_PRIVATE);
To get the "results" int array:
String[] resultsStrs = prefs.getString("results", "").split(",");
int arrLength = resultsStrs.length;
int[] results = new int[arrLength];
for(int i = 0; i < resultsStrs.length; i++)
results[i] = Integer.parseInt(resultsStrs[i]);
To get the "question" String array:
String qStr = prefs.getString("question", "");
String[] question = EncodeDecode.decode(qStr);
To get the "correctAnswer" int array:
String[] correctAnsStrs = prefs.getString("correctAnswer", "").split(",");
int arrLength = correctAnsStrs.length;
int[] correctAnswer = new int[arrLength];
for(int i = 0; i < correctAnsStrs.length; i++)
correctAnswer[i] = Integer.parseInt(correctAnsStrs[i]);
To get the "score" int:
String scoreStr = prefs.getString("score", "");
int score = Integer.parseInt(scoreStr);
Problem is not having or not more intents in the same activity: an Intent from a java viewpoint is an object so you can allocate as many intents you'd like.
But when you do startActivity() you are stopping the current activity in order to start a new one so, after that call, any subsequent code is not garantee to be executed as it is contained in an activity which is stopping.
You have to consider the startActivity() as a no return call, like a return statement, and so not put any code after that.
The error in your crash report shows you're trying to call setText(int) (when I'm assuming you're actually trying to set it to a String passed through the Intent, which is actually being parsed as an int).
In your second Activity, you should try to call
setText(String.valueOf(your_int_variable_here));
to make sure it doesn't parse it as a Resource ID (int) instead of an actual String.

Error parsing Colors from String

EDIT:A Pastebin consisting of the relevant parts of my project:
Here is the updated code
Also ColouredItem is a wrapper for:
public class ColouredItem
{//Only a wrapper class,no behaviour has been defined here
String name,colour;
}
I get a NumberFormatException when trying to parse a colour from a String using the following code:
row.setBackgroundColor(Color.parseColor(item.colour));
I use the following to create a list of items from a resource:
for(int i=0;i<list.length;i++)
{
item=new ColouredMenuItem();
String[] cmenu =list[i].split("#");
item.name=cmenu[0];
item.colour="#"+cmenu[1];
Log.d(TAG, item.colour);
menuList.add(item);
}
This is the exception that I get...I have found that view.setBackgroundColor only takes an integer value:
#ffffff
#ffffBB
#fff45f
#ffff00
Shutting down VM
threadid=1: thread exiting with uncaught exception (group=0x4001d800)
FATAL EXCEPTION: main
java.lang.NumberFormatException: ffffff
at java.lang.Long.parse(Long.java:364)
at java.lang.Long.parseLong(Long.java:354)
at android.graphics.Color.parseColor(Color.java:207)
at com.example.samplelistproject.MadAdapter.getView(MadAdapter.java:60)
at android.widget.AbsListView.obtainView(AbsListView.java:1315)
at android.widget.ListView.makeAndAddView(ListView.java:1727)
at android.widget.ListView.fillDown(ListView.java:652)
at android.widget.ListView.fillFromTop(ListView.java:709)
at android.widget.ListView.layoutChildren(ListView.java:1580)
at android.widget.AbsListView.onLayout(AbsListView.java:1147)
at android.view.View.layout(View.java:7035)
at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
at android.view.View.layout(View.java:7035)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1042)
at android.view.View.layout(View.java:7035)
at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
at android.view.View.layout(View.java:7035)
at android.view.ViewRoot.performTraversals(ViewRoot.java:1045)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
Adding the # as some of the answers suggest did not solve the issue:
java.lang.NumberFormatException: Invalid long: "#ffffff"
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
No difference with this implementation either:
String cmenu=list[i];
item.name=cmenu.substring(0, cmenu.indexOf("#"));
item.colour=cmenu.substring(cmenu.indexOf("#"));
Use this code
row.setBackgroundColor(Color.parseColor("#424242"));
it helped me too,dont remove "#".
i used this code
private List<String> item;
item = new ArrayList<String>();
item.add("#424242");
row.setBackgroundColor(Color.parseColor(item.get(0)));
and its working gud for me,may be your split thing is not working good
or for your code
Button btn;
ColouredMenuItem item;
ArrayList<ColouredMenuItem> menuList = new ArrayList<ColouredMenuItem>();
String[] list = new String[] { "Page1 #ffffff", "Page2 #ffffBB" };
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sample);
try {
btn = (Button) findViewById(R.id.button1);
for (int i = 0; i < list.length; i++) {
item = new ColouredMenuItem();
String[] cmenu = list[i].split("#");
item.name = cmenu[0];
item.color = "#" + cmenu[1];
Log.d("colored", item.color);
menuList.add(item);
}
btn.setBackgroundColor(Color.parseColor(menuList.get(1).color));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this is working good at my side
this is new code
Make your colored item as a bean class with getter and setter like this
public class ColouredMenuItem {// Only a wrapper class,no behaviour has been defined
// here
String name, colour;
List<ColouredMenuItem> list=new ArrayList<ColouredMenuItem>();
public List<ColouredMenuItem> getList() {
return list;
}
public void setList(List<ColouredMenuItem> menuList) {
this.list = menuList;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
}
Then in your adapter use this code
try {
Log.d(TAG, menuList.get(position).colour);
textView.setText(menuList.get(position).getName());
{
row.setBackgroundColor(Color.parseColor(menuList.get(position).getColour()));
}
} catch (Exception ex) {
Log.e(TAG, "Still does not work");
}
Just give it a try,it works here at my side
Also your array is like this only na
<string-array name="menu_array">
<item>Page1 #ff7788</item>
<item>Page1 #ff6688</item>
<item>Page1 #424242</item>
</string-array>
Try Color.parseColor("#ffffff"); instead of Color.parseColor("ffffff");
look at the Stack trace it will tell you:
java.lang.NumberFormatException: ffffff
at java.lang.Long.parse(Long.java:364)
at java.lang.Long.parseLong(Long.java:354)
at android.graphics.Color.parseColor(Color.java:207)
at com.example.samplelistproject.MadAdapter.getView(MadAdapter.java:60)
Line by Line:
you are trying to format Hexadecimal (base 16) value "0xffffff" to a decimal (base 10) value
you're trying to parse hexadecimal string "ffffff" to type Long
same as above.
error is thrown when calling `Color.parseColor()`
error is thrown from your MadAdapter.java Class on line 60.
so, you need to find a way to parse it from Hexadecimal instead of decimal value. Hexadecimal values are usually preceeded by 0x[value] OR #[value]
Assuming: while parsing the color from string object "item" is not taken from array of list, rather its taking instance variable of ColoureMenuItem.
ColouredMenuItem item;
ArrayList<ColouredMenuItem> menuList = new ArrayList<ColouredMenuItem>();
String[] list = new String[]{"#ffffff","#00ffff"};
// parsing your string here, no change in this
for(int i=0;i<list.length;i++)
{
item=new ColouredMenuItem();
String[] cmenu =list[i].split("#");
item.name=cmenu[0];
item.color="#"+cmenu[1];
Log.d("colored", item.color);
menuList.add(item);
}
// confirming whether value are parsing or not.
for(int i=0;i<menuList.size();i++)
{
int color = Color.parseColor(menuList.get(i).color);
Log.d("color",""+menuList.get(i).color);
}
and your ColouredMenuItem class.
public class ColouredMenuItem {
public String color;
public String name;
}

ActiveAndroid model bundle extras exception

folks! I wrote a Book class which has Chapter objects (a one to many relationship). It implements the method public List chapters(), as stated in the docs. This is the Book.java
#Table(name = "Books")
public class Book extends Model implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name = "Name", unique = true, onUniqueConflict = Column.ConflictAction.IGNORE)
public String name;
#Column(name = "Sort")
public int sort;
public Book() {
super();
}
public Book(String name, int sort) {
super();
this.name = name;
this.sort = sort;
}
public List<Chapter> chapters() {
return getMany(Chapter.class, "Book");
}
#Override
public String toString() {
return name;
}
}
On the main activity I can get the Chapter objects successfully. However, I have to pass a book object to another activity, which has a fragment, and though I get the object's stated attributes (String name and int sort) it throws an exception when I call to chapters():
Bundle bundle = getIntent().getExtras();
Book book = (Book) bundle.getSerializable("BOOK");
// This line is executed successfully
Log.d("TAGGED", "Recovered book: " + book.name + " has " + book.sort + " as its sort");
// This is the line that throws an exception
ArrayList<Chapter> chapters = book.chapters();
the thrown exception is the following:
05-06 15:21:59.701: E/AndroidRuntime(9647): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hanovit.libraria/com.hanovit.libraria.chapter.ChapterActivity}: java.lang.NullPointerException
05-06 15:21:59.701: E/AndroidRuntime(9647): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
05-06 15:21:59.701: E/AndroidRuntime(9647): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
05-06 15:21:59.701: E/AndroidRuntime(9647): Caused by: java.lang.NullPointerException
05-06 15:21:59.701: E/AndroidRuntime(9647): at com.activeandroid.query.From.getArguments(From.java:207)
05-06 15:21:59.701: E/AndroidRuntime(9647): at com.activeandroid.query.From.execute(From.java:183)
05-06 15:21:59.701: E/AndroidRuntime(9647): at com.activeandroid.Model.getMany(Model.java:266)
Any ideas what is wrong? Thanks!!!
Submitted an issue in Github and now is fixed (https://github.com/melvin7/ActiveAndroid)
On the other hand, putting into the extras bundle only the ID of the column also works. Then I can get the full object with Model.load(Book.class, id)

Android Text function forcecloses rand issue

after the previous fix i now have a new issue. Got advised to ask a new question, so here it is!
It still force closes, but now on a new line.
public void AI(String text) {
// initiate new lists to be on the safe side
List<String> indexer = new ArrayList<String>();
List<String> sentence = new ArrayList<String>();
List<String> explode = new ArrayList<String>();
List<String> ary = new ArrayList<String>();
explode = Arrays.asList(text.split(" "));
// initiate randint and trigger variable
Random rand = new Random();
int randint = rand.nextInt(explode.size());
// initiate the trigger variable
String trigger = explode.get(randint);
//check if word exists in database and add if it not.
int i = 0;
for(String word : explode) {
if(common.get(word) == null) {
words.add(word);
common.put(word, 1);
context.put(word, explode);
pos.put(word, i);
length.put(word, explode.size());
if(word.equals(trigger)) {
ary = new ArrayList<String>(explode);
}
}else{
common.put(word, common.get(word)+1 );
}
i++;
}
// fill the arraylist sentence with words to be used, some in context, some random from the database.
for(int i2 = 0; i2 < length.get(trigger); i2++ ) {
randint = rand.nextInt(length.get(trigger));
if(randint < length.get(trigger)/2) {
//
if(ary.get(i2)!=null) {
sentence.add(ary.get(i2));
}
}else{
sentence.add(words.get(rand.nextInt(words.size())));
}
}
// use to the pos-hashmap to check at which index the word was detected at, if not place it at the deliberate index.
for(int i3 = 0; i3 < sentence.size(); i3++) {
if(sentence.get(i3)!=null) {
indexer.add(pos.get(sentence.get(i3)), sentence.get(i3));
}
}
// compose the final string that is to be passed to the speak function
for(int i4 = 0; i4 < indexer.size(); i4++) {
say = say + indexer.get(i4)+" ";
}
// pass the string to the speak function
mTts.speak(say, TextToSpeech.QUEUE_FLUSH, null);
// removing final string to be ready for next iteration
say = "";
// end of AI stuff
}
Variables:
// arraylists
public List<String> explode = new ArrayList<String>();
public List<String> words = new ArrayList<String>();
public List<String> sentence = new ArrayList<String>();
public List<String> indexer = new ArrayList<String>();
// hashmaps
public Map<String, Integer> common = new HashMap<String, Integer>();
public Map<String, List<String>> context = new HashMap<String, List<String>>();
public Map<String, Integer> pos = new HashMap<String, Integer>();
public Map<String, Integer> length = new HashMap<String, Integer>();
//strings
public String say;
And logcat:
05-26 19:24:42.926: W/dalvikvm(543): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
05-26 19:24:42.926: E/AndroidRuntime(543): Uncaught handler: thread main exiting due to uncaught exception
05-26 19:24:42.956: E/AndroidRuntime(543): java.lang.IndexOutOfBoundsException: Invalid location 0, size is 0
05-26 19:24:42.956: E/AndroidRuntime(543): at java.util.ArrayList.get(ArrayList.java:341)
05-26 19:24:42.956: E/AndroidRuntime(543): at sarah.namespace.SarahActivity.AI(SarahActivity.java:186)
Second logcat:
05-26 21:38:44.555: W/dalvikvm(571): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
05-26 21:38:44.555: E/AndroidRuntime(571): Uncaught handler: thread main exiting due to uncaught exception
05-26 21:38:44.575: E/AndroidRuntime(571): java.lang.IndexOutOfBoundsException
05-26 21:38:44.575: E/AndroidRuntime(571): at java.util.ArrayList.add(ArrayList.java:145)
05-26 21:38:44.575: E/AndroidRuntime(571): at sarah.namespace.SarahActivity.AI(SarahActivity.java:188)
What the logcats are screaming at:
First:
sentence.add(words.get(rand.nextInt(words.size())));
Second:
for(int i3 = 0; i3 < sentence.size(); i3++) {
if(sentence.get(i3)!=null) {
indexer.add(pos.get(sentence.get(i3)), sentence.get(i3));
}
}
I would be very happy if someone could help me beat this riddle again!
Hmm, I am uncertain about which lines are 186 and 188 (the two that throw the OutOfBounds exceptions). But looking at this loop, I have some suggestions:
for(int i2 = 0; i2 < length.get(trigger); i2++ ) {
From above we notice that length.get(trigger) is always set to explode.size() and we can see that explode.size() never changes. We could check against explode.size() instead or use a for-each loop again. Carrying on:
randint = rand.nextInt(length.get(trigger));
if(randint < length.get(trigger)/2) {
This looks like you want a 50/50 chance of: adding the original word to sentence or
if(ary.get(i2)!=null) {
sentence.add(ary.get(i2));
}
}else{
sentence.add(words.get(rand.nextInt(words.size())));
}
}
... a random word to sentence.
Also I beleive this could throw an exception:
if(ary.get(i2)!=null) {
sentence.add(ary.get(i2));
because you are checking the validity of i2 against length.get(trigger) not ary.size(). Now remember that ary is simply a copy of explode.
So let's condense this loop to:
for(String word : explode) {
if(rand.nextInt(1)) // 50/50 chance of being false or true (0 or 1)
sentence.add(word);
else
sentence.add(words.get(rand.nextInt(words.size())));
}
Take a look at the remaining two loops, if you apply a similar for-each loop you will be able to condense and expedite these as well. I don't know the rest of the app's code, but you might be able to remove a few Lists and Maps entirely. Cheers!

Categories

Resources