Convert string array to int array android - java

I'm trying to convert an string array (listview_array) to int array, and then compare numbers. Unfortunately, the app is crashing everytime I execute it.
Here is the code:
public class FindStop3 extends Activity implements OnItemClickListener{
private String stop,line,listview_array[],buschain,dayweek,weekly;
private int selected,day;
private TextView tvLine,tvToday,tvNext;
private ListView lv;
String currentdate = java.text.DateFormat.getDateInstance().format(Calendar.getInstance().getTime());//Get current time
String currenttime = java.text.DateFormat.getTimeInstance().format(Calendar.getInstance().getTime());//Get current time
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_stop3);
FindStop3.this.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);//Lateral transition
Intent intent = getIntent();//Take data from last activity
Bundle bundle = intent.getExtras();
line=bundle.getString("Line");//Takes the previous selected line from the last activity
stop=bundle.getString("Stop");//Takes the previous selected stop from the last activity
setTitle("Selected stop: "+stop);//Modifies title
getDayOfWeek();//Gets day of week
getBusChain(line,stop,weekly);//Calls method to get the xml chain name
tvLine = (TextView) findViewById(R.id.tvLine);
tvLine.setText("Line from "+line);
tvNext = (TextView) findViewById(R.id.tvNext);
tvNext.setText("Next bus arrives at "+currenttime);
tvToday = (TextView) findViewById(R.id.tvToday);
tvToday.setText(dayweek+","+currentdate+" schedule:");
selected= getResources().getIdentifier(buschain, "array",
this.getPackageName());//Lets me use a variable as stringArray
listview_array = getResources().getStringArray(selected);
lv = (ListView) findViewById(R.id.lvSchedule);
lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listview_array));
getNextBus();
}
And here is the method to convert it:
public void getNextBus () {
//Converts listview_array into an integer array
int myar[]=new int[listview_array.length];
for(int i=0;i<listview_array.length;i++){
myar[i]=Integer.parseInt(listview_array[i]);
}
If the method is not executed, the application works perfectly. The values are taken from an xml file as follows:
<string-array name="Schedule">
<item>05:40</item>
<item>06:00</item>
<item>06:16</item>
<item>06:28</item>
<item>06:40</item>
<item>07:16</item>
<item>07:29</item>
<item>07:43</item>
<item>07:55</item>
<item>08:07</item>
<item>08:22</item>
</string-array>
Could anyone gives an idea about what can be the problem?
Thanks.

I think that your problem is when you try to convert the values, because a value like this "05:40" cannot be converted into a int.
Problably, you're getting a NumberFormatException.
If you want a better answer please send the log of your app.

Related

Android ListView only shows one item at a time

My program is that when a user enteres some information and clicks the "Submit" button, this data will be stored in a separate activity's list View.I have a Shared Preferences incorporated so that the data will be stored. The problem is that only one piece of information gets stored at a time. If I enter a new piece of data, the previous one is overwritten.
public class PreviousPractices extends Activity {
int minutes,hours;
String description;
String date;
ListView practiceList;
ArrayAdapter<String> adapter;
ArrayList<String> listItems = new ArrayList<String>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.previous_practices_layout);
practiceList=(ListView)findViewById(R.id.practiceList);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,listItems);
practiceList.setAdapter(adapter);
getIntents();
LoadPreferences();
}
public void getIntents(){
if (getIntent().getExtras() == null) {
}
else {
Bundle extras = getIntent().getExtras();
hours = extras.getInt("Hours");
minutes = extras.getInt("Minutes");
description = extras.getString("Description");
date = extras.getString("dateOfPractice");
adapter.notifyDataSetChanged();
SavePreferences("LISTS", date);
}
}
Right now I'm only working with the date to simplify things. I'm not sure what the issue is, and I'd appreciate some help.

Is it possible to change a String value into a R.string reference name?

The title is a little confusing so let me explain further. An application I am trying to make has multiple buttons opening a new activity that look the same, but the text is different depending on the button clicked (Like a dictionary). So instead of recreating the activity 50+ times, I made a new method for onClick() in the first activity with a new Intent, and added a getIntent() to the second activity.
//first activity method
public final static String TRANSFER_SYMBOL = "com.engineering.dictionary.MESSAGE";
public void openView(View view)
{
Intent open = new Intent(this,displayCharHB.class);
Button setBtn = (Button) findViewById(view.getId());
String grabText = setBtn.getText().toString();
String thisChar = "sym_hira_" + grabText;
open.putExtra(TRANSFER_SYMBOL,thisChar);
startActivity(open);
}
//second Activity method
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent grabChar = getIntent();
String thisChar = grabChar.getStringExtra(hira_basic.TRANSFER_SYMBOL);
//String strValue = "R.string." + thisChar;
TextView displaySym = (TextView) findViewById(R.id.charDisplay);
displaySym.setText(thisChar);
}
sym_hira_ + whatever is stored in grabText is the name of a String in strings.xml (For example, grabText = "ro", sym_hira_ro is a String name). Is it possible to get it to reference that string name with setText() and not actually set the text to "sym_hira_..."?
Is it possible to get it to reference that string name with setText()
Use getIdentifier to get value from strings.xml using name:
int resId = getResources().getIdentifier(thisChar, "string",getPackageName());
displaySym.setText(getResources().getString(resId));
you can using BeanShell execute the "R.string.xxxx" command to get the string resource id.
this is my code example;
String str = "";
Interpreter i = new Interpreter();
i.set("context", MainActivity.this);
Object res = i.eval("com.example.testucmbilebase.R.string.hello_world");
if(res != null) {
Integer resI = (Integer)res;
str = MainActivity.this.getResources().getString(resI);
}

How to add different values in same TextView in Android

A want to develop a project in android using SOAP service protocol. So that i get XML and parse it into String array. I want to show one String (Like String[0]) in one TextView then when a user click the next button next String (Like String[1]) will show on the same page and the same TextView. How how could i do that?
Probably you do not know much of android.
in your main activity class where you want to show data create the filed String array as
public class NNN extends Activity {
//... some other fields
private String[] data;
private int current;
Private TextView yourTextView;
//in on create
data = null;
current = 0;
yourTextView = (TextView) findViewById(R.id.myTextView);
then in the method where you parsed the XML of string array do
data = parsedArray;
current =0;
then on button click where you want to set the text to text view
if(data ! = null) {
//means you have parsed XML to string array
if(current != data.length) {
//means there is some data that user did not viewd
youTextView.setText(data[current]);
current++;
}
}
You must see some tutorials to get familiar to the android. See Creating hello world app
I don't know the SOAP architecture. But I will assume you store the strings parsed as following array. And also we must keep track of the current displaying string:
static String[] myparsedarray;
static int curIndex;
add an OnClickListener to your 'next' button:
class MyActivity extends Activity {
//your string array
static String[] myparsedarray;
static int curIndex;
.
.
. //lots of other code
// inside onCreate()
public void onCreate(...) {
Button nextBut = (Button) findViewById(R.id.nextbutton);
nextBut.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
TextView myloopingtext = (TextView) findViewById(R.id.mytextview);
curIndex = (curIndex + 1) % myparsedarray.length;
//the modulus to avoid arrayIndexOutOfBoundsException :)
myloopingtext.setText(myparsedarray[curIndex]);
}
});
.
.
. //rest of the code
}
}
P.S others: Correct me if I am wrong :)
edit: As indivisible said, look into android tutorials. I also suggest you search for similar questions. Cheers!

Google Glass Voice Recognition

What I tried to do:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<String> voiceResults = getIntent().getExtras()
.getStringArrayList(RecognizerIntent.EXTRA_RESULTS);
Card ShowDataCard = new Card(this);
ShowDataCard.setText(voiceResults);
View ShowDataCardView = ShowDataCard.toView();
setContentView(ShowDataCardView);
}
Failed work-around:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String voiceResults = getIntent().getExtras()
.getString(RecognizerIntent.EXTRA_RESULTS);
Card ShowDataCard = new Card(this);
ShowDataCard.setText(voiceResults);
View ShowDataCardView = ShowDataCard.toView();
setContentView(ShowDataCardView);
}
The String voiceResults is a failed workaround to the fact I cannot .setText to an arraylist string
Actual voice recognition code:
ArrayList<String> voiceResults = getIntent().getExtras()
.getStringArrayList(RecognizerIntent.EXTRA_RESULTS);
Basically I am trying to save this voice recognition (going to use SharedPreferences) but for some reason it is an arraylist string and not just a string. Anybody know how to save it as a String? (or publish an activity with an arraylist string)
Since the results are an ArrayList of strings, you should check that the size() of the list is at least 1 and then call voiceResults.get(0) to get the string.

Can't update TextView from another activity

I have an activity with a TextView that needs to be updated from a second activity.
I can pass the Text view data to the 2nd activity ok, but when I try to update that TextView
within the 2nd activity it crashes. My code:
1st Activity (where the TextView is defined in my xml):
Intent intent = new Intent(1stactivity.this, 2ndactivity.class);
intent.putExtra("homescore_value", ((TextView)findViewById(R.id.score_home)).getText());
startActivity(intent);
// code snippet
Then in my 2nd activity:
Bundle bundle = getIntent().getExtras();
hometext = bundle.getString("homescore_value"); // this works and displays the correct String from 1st activity,
but it crashes when I try to pull in as a TextView:
// other code snipped
int homescore = 0;
String Home_nickname = "HOME ";
TextView homestext = (TextView) bundle.get("homescore_value");
hometext.setText(Home_nickname +": "+homescore );
Please help.
You are trying to get a String as a TextView (you are setting a String in the intent from the first Activity).
You trying to cast String to TextView. The code that crashes is equivalent of:
String text = bundle.get("homescore_value"); //this is ok
TextView textView = (TextView)text; //this is bad
You should do instead:
String text = bundle.get("homescore_value");
TextView textView = (TextView)findViewById(R.id.yourTextViewId);
textView.setText(text);
This line here:
intent.putExtra("homescore_value", ((TextView)findViewById(R.id.score_home)).getText());
is attaching a String along with the intent, not a TextView.
You must inflate a new TextView within the 2nd activity, by either declaring it in the layout.xml, or programmatically placing it within the layout.
Something that solved part of this problem for me was setting the receiving String variables to null like this:
public String param1new = null;
public String param2new= null;
My issue with this is I'm trying to set background colors on several TextViews and only the first one is being set at this time.

Categories

Resources