getStringExtra() works but getIntExtra() returns null - java

When I tried to pass a String extra over to the next activity, It works fine. When I try to pass a int like the following codes, it crashs and throws Resources$NotFoundException. I've been playing around it for few hours so I thought I can get some guidance with this.
This is the code from the activity that is passing the values with putExtra()
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Intent cP = new Intent("com.example.loldb.championscreen");
int x = arg2 + 1;
System.out.println(x);
cP.putExtra("champNo", x);
startActivity(cP);
}
and here's the code of the receiving activity trying to getIntExtra() the data
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_champion_screen);
Intent intent = getIntent();
TextView cName = (TextView) findViewById(R.id.cname);
int temp = intent.getIntExtra("champNo", 0);
//int champNo = Integer.parseInt(temp);
cName.setText(temp);
}
If possible I would like to get an explanation on this matter, so I can understand it a little more.
Thanks in advance.

Change to
cName.setText(String.valueOf(temp));
setText will take charactersequence. There is one that takes int value which is a resource. If not found you end up getting ResourceNotFoundException.
public final void setText (int resid)
Takes resid which is a int.
What you need
public final void setText (CharSequence text)
Added in API level 1
Sets the string value of the TextView. TextView does not accept HTML-like formatting, which you can do with text strings in XML resource files. To style your strings, attach android.text.style.* objects to a SpannableString, or see the Available Resource Types documentation for an example of setting formatted text in the XML resource file.

Related

Spinner in Custom Function for Android with java

I am confused about calling the spinner widget through a custom function. I am create an app in which I use spinner 20-35 times a spinner widget in single layout or activity. So for this i want to avoid the spinner code repetition again and again. i am creating a method for this i add the items to the spinner but i want to pass item value on select to other activity which bind to that class
Here is my code
Spin_tester.class
public class Spin_tester {
public String result;
public Context ctx;
public Spin_tester(Spinner spinner, final ArrayList<String> arraylist, final Context ctx , final String value) {
this.ctx= ctx;
ArrayAdapter<String> adpts =
new ArrayAdapter<String>(ctx, android.R.layout.simple_dropdown_item_1line,arraylist);
spinner.setAdapter(adpts);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
result = arraylist.get(position);
value = result ; // This is not working
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
Test_Activity.class
public class Test_Activity extends AppCompatActivity {
ArrayList<String> data_list = new ArrayList<>();
Spinner spins;
String value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
spins = (Spinner)findViewById(R.id.spinner);
data_list.add("1");
data_list.add("2");
data_list.add("3");
data_list.add("4");
Spin_tester asd = new Spin_tester(spins,data_list,this,value);
TextView txt = (TextView)findViewById(R.id.textView17);
}
}
Please help
Thanks in advance
Java is a pass-by-value language, not pass-by-reference. What this means is that setting value in setOnItemSelectedListener will only change value within that method — the result won't be passed back anywhere.
I see that you've place the result in result. That is where the calling program will find the answer.
Remove all instances of value from Spin_tester and Test_Activity and then have your main activity get the result from asd.result
I'm going to get a little meta at this point: I've only answered the question you actually asked, but this code is wrong on so many levels that you're never going to get it to work. I strongly suggest you work your way through the examples and tutorials in the documentation before you try to proceed any further.

Convert string array to int array android

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.

Save The value of Variable in Java/Android [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Making data persistent in android
Edited:
I am building an android app which works on the principle of a simple counter.
public class TasbeehActivity extends Activity {
/** Called when the activity is first created. */
int count;
ImageButton imButton;
TextView display;
static String ref = "Myfile";
static String key = "key";
SharedPreferences myPrefs;
boolean check = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imButton = (ImageButton) findViewById(R.id.bCount);
display = (TextView) findViewById(R.id.tvDisplay);
myPrefs = getSharedPreferences(ref, 0);
if(check){
String dataReturned = myPrefs.getString(key, "0");
count = Integer.parseInt(dataReturned);
display.setText(""+count);
}
imButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Random rand = new Random();
display.setTextColor(Color.rgb(rand.nextInt(255),
rand.nextInt(255), rand.nextInt(255)));
count++;
display.setText("" + count);
}
});
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
String data = display.getText().toString(); SharedPreferences.Editor
editor = myPrefs.edit(); editor.putString(key, data);
editor.commit();
check = true;
}}
I want to save the value of count so that when my app restarts after closing it should have the value of count before closing app.
Also when I change orientation of the emulator i.e. from portrait to landscape or vice versa count gets set to 0.
Is there any solution for both of these problems?
You should use SharedPreferences to save your variable, and Override OnConfigurationChange because it's probably calling your oncreate method (don't forget to add android:configChanges="orientation|keyboardHidden|screenSize" in your manifest)
I Hope this will help you.
1. use sharedpreferences for saving or retrieving value of count when app is restarts after closing
2. see handle orientation change in android count gets set to 0 when I change orientation of the emulator i.e. from portrait to landscape or vice versa
Try these....
android:configChanges="orientation" , This will prevent your Activity to again restart when orientation changes.
Use Bundle, but thats only for small amount of data. Serialization and Deserialization will be needed.
You can also use onRetainNonConfigurationInstance(), and getLastNonConfigurationInstance(), for storing and retrieving data.
See this link for further details:
http://developer.android.com/guide/topics/resources/runtime-changes.html

Local variable may not been initialized

How do i initialized autoComplete? I cant use it with AutoCompleteTextView because it'll tell me that local variable is duplicated. Tried declaring it static as well but its not permitted.
Please advice!
public class Search extends Activity {
public void onCreate(Bundle savedInstanceSate) {
final int autoComplete;
super.onCreate(savedInstanceSate);
setContentView(R.layout.searchshop);
//The duplicate im talking about
AutoCompleteTextView autoCompletee = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, shops);
autoCompletee.setAdapter(adapter);
autoCompletee.setThreshold(1);
autoCompletee.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Intent intent;
int index=999;
for(int i=0;i<shops.length;i++) {
//The local variable autoComplete may not been initialized
if(shops[i].equals(Integer.toString(autoComplete))) {
index=i;
break;
}
}
switch(index) {
case 0:
intent=new Intent(Search.this, Adidas.class);
startActivity(intent);
break;
case 1:
intent=new Intent(Search.this, Affin.class);
startActivity(intent);
break;
}
}
});
}
static final String[] shops = new String[] {
"Adidas", "Affin Bank", "Alam Art", "Al Amin"
};
}
Modifying the int autoComplete to be static, final, etc won't matter one bit because the compiler is complaining about the fact that you already have a variable called "autoComplete". In your actual code example, you named your AutoCompleteTextView "autoCompletee" with two e's which is different from autoComplete so that will work. But I'd recommend using more meaningful variable names like int autoCompleteValue or something along those lines. Either way, the problem is that you have variables colliding. Once you have a variable in scope with a certain name, you cannot use that name again...
You have autoComplete field as local variable, which need to set to some default value.
just set final int autoComplete=0;
Move this as third statement in code, first two statements should be super.... and setContent(...)

Android putExtra issue

I have scoured SE and google and found what I thought were decent examples of how to implement putExtra() in tandem with getStringExtra().
The trouble I seem to be unable to resolve is that my putExtra data never appears to be getting retrieved from my getStringExtra call in the target activity.
I've tried numerous SE examples where others have asked this question countless times and yet it never seems to get me closer to a working base to expand on.
My primary activity's put is as follows;
(First, I tried this with no luck)
// Click handler for group list items
lvGroups.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
int gid = groupIds.get(arg2);
Intent intent = new Intent(RadSMS_Activity.this, RadSMS_CreateGroup.class);
intent.putExtra("SELECTED_GROUP_ID", gid);
startActivity(intent);
finish();
}
});
(Then, I tried this. Also with no luck.)
// Click handler for group list items
lvGroups.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
int gid = groupIds.get(arg2);
Intent target = new Intent();
target.putExtra("SELECTED_GROUP_ID", gid);
Intent intent = new Intent(RadSMS_Activity.this, RadSMS_CreateGroup.class);
startActivity(intent);
finish();
}
});
My target activity that I want to extract the value from is the following;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.creategroup);
String strGID = getIntent().getStringExtra("SELECTED_GROUP_ID");
selectedGID = new Long(strGID);
// ... additional code would be here
}
Function truncated for brevity's sake.
So, according to everything I've seen so far, it appears I'm doing it right, but when I put a breakpoint at the line where selectedGID gets assigned its value, strGID is always null. This is really beginning to make me crazy.
Can anyone please tell me if I have done something incorrect?
gid is an int.
You are putting an int.
You appear to be trying to retrieve a string.
Consider:
int gid= getIntent().getIntExtra("SELECTED_GROUP_ID",-1);
You are putting an integer value while getting it as a string. It will always return null. Use intent.getExtras().getInt() instead of intent.getStringExtra().

Categories

Resources