String declaration VariableDeclaratorId expected after this token - android

i have problem in this simple code, I declare a String , and want change it inside onCreate but AFTER onCreate i have "VariableDeclaratorId expected after this token" Error !!
And if i put item=222 inside onCreate i get "111null333" when Toast display
here is my code
public class MainActivity extends Activity {
static String item;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(getApplicationContext(), mStrings[0], Toast.LENGTH_SHORT).show();
}
item="222";
private String[] mStrings={
"111"+item+"333",
"test"
};
}

Can you please spend some time and format your question correctly ? i do not see clearly if the item = "222"; is inside a method or not.
But if your formatting is "correct" then your problem is that the assignation of a value to the item variable can not be done outside of a method or the static{} block of code. And so if you use the item variable in another object or class variable before assigning it a value it will be the default value (null for objects and 0 or false for the primitive values).
Hope this helps.
UPDATE:
public class MainActivity extends Activity {
static String item;
private String[] mStrings;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
item = "222";
mStrings = new String[2];
mStrings[0] = "111" + item + "333";
mStrings[1] = "test";
Toast.makeText(getApplicationContext(), mStrings[0], Toast.LENGTH_SHORT).show();
}
}

Related

How do I use setText from within a callback?

In my code below I am able to edit a text from my first setText() call but not from within the callback.
The error I receive is a NullPointerException for title in the callback.
How do I set this up so I can edit the text from within the callback?
public class ListingActivity extends AppCompatActivity {
final String TAG = "ListingActivity";
TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
title = (TextView)findViewById(R.id.tvTitle);
Intent intent = getIntent();
final String listingId = intent.getStringExtra("ObjectId");
setContentView(R.layout.listing_activity);
Log.e(TAG, "listingId: " + listingId);
title.setText("listingId");//fine
ListingManager.getListing(listingId, new ListingCB() {
#Override
public void done(String error, Listing listing) {
title.setText("listingId");//null pointer error
}
});
}
}
Your setContentView() method must be called before giving references using findViewById() method, so your code will be -
public class ListingActivity extends AppCompatActivity {
final String TAG = "ListingActivity";
TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listing_activity);
title = (TextView)findViewById(R.id.tvTitle);
Intent intent = getIntent();
final String listingId = intent.getStringExtra("ObjectId");
Log.e(TAG, "listingId: " + listingId);
title.setText("listingId");//fine
ListingManager.getListing(listingId, new ListingCB() {
#Override
public void done(String error, Listing listing) {
title.setText("listingId");//null pointer error
}
});
}
}
title.setText("listingId");//fine
That shouldn't be fine...
You must put setContentView before any findViewById. That is number one reason why your TextView is null.
Your callback is fine.

Android - How to get a view initialized in onCreate?

I try to get back a view I initialized before in my activity in onCreate(), but I don't know how to do this.
It's look like something like this :
public class activityA extends AppCompatActivity {
public ImageView ivImg1;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.layoutA);
ivImg1 = (ImageView)findViewById(R.id.img1);
}
The image view is empty of any ressource. I create a Handler in an other class :
public class firstClass{
final private imgHandler mHandler = new imgHandler();
final int KEY = 1;
Message msg = mHandler.obtainMessage(KEY,R.drawable.face1,0,ivImg1);
mHandler.sendMessage(msg);
}
And now I would like to set the first argument R.drawable.face1 to the ImageView in my Handler :
public class imgHandler extends Handler {
#Override
public void handleMessage(Message msg){
super.handleMessage(msg);
ImageView viewToSet = (ImageView)msg.obj;
viewToSet.setImageResource(msg.arg1); //Here is the logcat error
}
}
I result on a java.lang.NullPointerException. I think it's because the object I send in the message is empty. In onCreate the view is inside, but when I call it in the message, the findViewByIdisn't in ivImg1.
Class FirstClass is in a new Thread, and class imgHandler is in the UI Thread.
I hope someone can help me.
Sorry for my english.

Why getResources().getString() return null?

I always get NullPointerException whenever I call:
getApplicationContext().getResources().getStringArray(R.array.days);
I called it from DialogFragment in my Activity. I also tried using getActivity(), but that didn't work for me too. Does anybody have any idea about this problem?
Try this:
If you write this in a fragment:
String[] days = getActivity().getResources().getStringArray(R.array.days);
If you write this in an activity:
String[] days = this.getResources().getStringArray(R.array.days);
It´s just an assumption, but mostly if somebody gets this error, they make a mistake where the code is placed or when they call it. For example, if you call it before onCreate():
public class YourActivity extends Activity {
private String foo = "foo";
private String[] yourArray = getResources().getStringArray(R.array.yourArray);
public void onCreate(Bundle savedInstanceState){
...
}
}
This will result in a NullPointerException. Instead you have to call it like this:
public class YourActivity extends Activity {
private String foo = "foo";
private String[] yourArray;
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.yourLayout);
yourArray = getResources().getStringArray(R.array.yourArray);
}
}
Try this.
public class YourActivity extends Activity{
Context mContext;
public void onCreate(Bundle savedInstanceState){
setContentView(R.layout.yourLayout);
mContext = this;
}
class DialogFragment{
String[] days = mContext.getResources().getStringArray(R.array.days);
...............
}
}
I hope it helps!

Data saving when orientation changes

I have put a condition in onCreate() method to check if there exist some previous data or not. But it is not working.
please guide me.
And I don't want to use onRestoreSavedState() method for this.d
public class ActivityOne extends Activity {
Use these as keys when you're saving state between reconfigurations
private static final String RESTART_KEY = "restart";
private static final String RESUME_KEY = "resume";
private static final String START_KEY = "start";
private static final String CREATE_KEY = "create";
String for LogCat documentation
private final static String TAG = "Lab-ActivityOne";
private int mCreate=0, mRestart=0, mStart=0, mResume=0;
You will need to increment these variables' values when their
corresponding lifecycle methods get called.
TODO: Create variables for each of the TextViews
private TextView mTvCreate, mTvRestart, mTvStart, mTvResume;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
TODO: Assign the appropriate TextViews to the TextView variables
mTvCreate=(TextView)findViewById(R.id.create);
mTvRestart=(TextView)findViewById(R.id.restart);
mTvResume=(TextView)findViewById(R.id.resume);
mTvStart=(TextView)findViewById(R.id.start);
Button launchActivityTwoButton = (Button) findViewById(R.id.bLaunchActivityTwo);
launchActivityTwoButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=null;
intent = new Intent(v.getContext(),ActivityTwo.class);
startActivity(intent);
}
});
if(savedInstanceState!=null){
mCreate=savedInstanceState.getInt(String.valueOf(mCreate));
mRestart=savedInstanceState.getInt(String.valueOf(mRestart));
mResume=savedInstanceState.getInt(String.valueOf(mResume));
mStart=savedInstanceState.getInt(String.valueOf(mStart));
}
// Emit LogCat message
Log.i(TAG, "Entered the onCreate() method");
mCreate++;
displayCounts();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
Save state information with a collection of key-value pairs
4 lines of code, one for every count variable
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(String.valueOf(mCreate),mCreate);
savedInstanceState.putInt(String.valueOf(mRestart),mRestart);
savedInstanceState.putInt(String.valueOf(mResume),mResume);
savedInstanceState.putInt(String.valueOf(mStart),mStart);
}
Updates the displayed counters
This method expects that the counters and TextView variables use the names specified above
public void displayCounts() {
mTvCreate.setText("onCreate() calls: " + mCreate);
mTvStart.setText("onStart() calls: " + mStart);
mTvResume.setText("onResume() calls: " + mResume);
mTvRestart.setText("onRestart() calls: " + mRestart);
}
}
It looks like the problem is that you attempting to use values that have not been set yet when you try to capture the saved value.
All you need to do to fix it is to use the String constants that you have defined.
So, in onCreate(), you would have:
if(savedInstanceState!=null){
mCreate=savedInstanceState.getInt(CREATE_KEY);
mRestart=savedInstanceState.getInt(RESTART_KEY);
mResume=savedInstanceState.getInt(RESUME_KEY);
mStart=savedInstanceState.getInt(START_KEY);
}
Then, in onSaveInstanceState(), you would have:
savedInstanceState.putInt(CREATE_KEY,mCreate);
savedInstanceState.putInt(RESTART_KEY,mRestart);
savedInstanceState.putInt(RESUME_KEY,mResume);
savedInstanceState.putInt(START_KEY,mStart);

Assigning Values to a TextView from a different class

TestaActivity.java
public class TestaActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvText=(TextView)findViewById(R.id.textView1);
tvText.setText("Sample");
}
}
Print.java
public class Print {
public Print(Context tempContext) {
//I want to assign the value to the tvText from here
}
}
In the above example, as you can see I have set the text in tvText to "Sample". In the same way, I need to assign the textView1 ID with some value inside Print class, once it is created.
Please help me to figure out the way to do it.
If your class Print is instantiated when TestaActivity is on the screen, then you can get tvText reference, passing to Print in some way a TestaActivity reference.
Maybe you could pass it via constructor:
From TestaActivity you do:
Print print = new Print(this);
where this represents the instance of TestaActivity.
And then in your Print code you can do:
TextView tvText = (TextView)((TestaActivity)context.findViewById(R.id.textView1));
tvText.setText("Sample");
Another solution is provide an interface from TestaActivity, transparent for the outside, which manage your changes on the textview (or whatever).
Something like that:
private TextView tvText;
public void setTvText(String str){
tvText.setText( str );
}
And then in your Print class:
((TestaActivity)context).setTvText( "Sample" );
try as:
public class Print {
protected TestaActivity context;
public Print(Context tempContext) {
context = tempContext;
}
public void changetextViewtext(final String msg){
context.runOnUiThread(new Runnable() {
#Override
public void run() {
//assign the value to the tvText from here
context.tvText.setText("Hello Test");
}
});
}
}
and call changetextViewtext from Activity for Changeing TextView Text from Print Class
public class TestaActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvText=(TextView)findViewById(R.id.textView1);
tvText.setText("Sample");
Print myPrint = new Print(this);
myPrint.changetextViewtext("Hello World !!!");
}
}
as your need!!!!:)
#imran - the solution is correct except that you would want to pass the TextView as an argument in the constructor or the method.
Harcoding TextView in a method is bad because you cannot be reuse it.

Categories

Resources