Android global array string - android

i write simple android application with two method:
i define a simple string array in this line:
public class breakactivity extends Activity {
String[] id;
protected void onCreate(Bundle savedInstanceState) {
and into this method:
public void fill(){
id=new String[30];
id[0]="x1";
id[1]="x2";
}
and i want fetch the id array data into android onCreate method for example:
protected void onCreate(Bundle savedInstanceState) {
string temp=id[0];
}
How can solve that?thanks for all.

You created a method called fill() now you have to call it in onCreate()
public class breakactivity extends Activity {
String[] id;
protected void onCreate(Bundle savedInstanceState) {
fill();
String temp = id[0];
}
public void fill(){
id = new String[30];
id[0] = "x1";
id[1] = "x2";
}
}

Related

How can i pass variable from OnCreate to function(View view)

i have an activity that get a variable from another activity, and i want to display this variable when user click on button.
the problem is SaveFile(View view) method cannot find "SurveyTilte" variable.
How can i pass this variable?
public class CreateSurvey extends AppCompatActivity {
TextView Textfile;
String SurveyTilte;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_survey);
Bundle extras = getIntent().getExtras();
SurveyTilte = extras.getString("SurveyTilte");
}
}
i can't, but the code in OnClickListener because there is an #Override method
public void SaveFile(View view) {
Textfile = (TextView) findViewById(R.id.surveyDetails);
Textfile.setText(SurveyTilte);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(CreateSurvey.this, "Permission granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(CreateSurvey.this, "Permission not granted", Toast.LENGTH_SHORT).show();
finish();
}
}
This is actually more a matter of java than android.
By doing:
protected void onCreate(Bundle savedInstanceState) {
...
String SurveyTilte = extras.getString("SurveyTilte");
}
What you actually do is creating a local variable separated from your class field variable with the same name, and is 'alive' and available for that specific method scope. Meaning you'll loose its reference (and thus its value) when exiting onCreate method.
What you need to do:
All you need to do is not to declare a new variable inside onCreate but to use the same variable you declared in advanced in your class attributes.
#Override
protected void onCreate(Bundle savedInstanceState) {
...
SurveyTilte = extras.getString("SurveyTilte");
}
That's how you can use the same reference for your value in the entire class scope.
Remove String keyword from String SurveyTilte = extras.getString("SurveyTilte"); to assign value to the class field and not local variable:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_survey);
Bundle extras = getIntent().getExtras();
SurveyTilte = extras.getString("SurveyTilte");
}
and then
public void SaveFile(View view) {
Textfile = (TextView) findViewById(R.id.surveyDetails);
Textfile.setText(SurveyTilte); // <-- reference field that contains value from intent data
}
I think this can help you.
public class CreateSurvey extends AppCompatActivity {
TextView Textfile;
String SurveyTilte;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_survey);
}
}
public void SaveFile(View view) {
Bundle extras = getIntent().getExtras();
if(extras != null) {
SurveyTilte = extras.getString("SurveyTilte");
Textfile = (TextView) findViewById(R.id.surveyDetails);
Textfile.setText(SurveyTilte);
}
}

Application static property is null

I instantiate a static property at the beginning of Activity's onCreate(), but some of my users get NullpointerException when I try to get it in MainActivity.
In my opinion, you code should be
public class TestActivity extends AppCompatActivity {
public static String mValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
mValue = "my_value";
}
}
The value TestActivity.mValue should be null util the onCreate executes.You can init the mValue like this
public class TestActivity extends AppCompatActivity {
public static String mValue;
static {
mValue = "my_value";
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
}

My method does not execute first

My method from another class named Model.
public void coba(){
Log.i("sdsds","sdsds")
}
My activity
public class ViewInformasiSiswa extends AppCompatActivity {
Model mod;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mod = new Model();
mod.coba();
String a = "5";
Log.i("coba",a);
}
My question is why does Log.i("coba",a); this run before my mod.coba();
Messages I get:
coba 5
sdsds sdsds
I tried this code and this work perfect. method execute first and then the log appear.
public class Model {
public void coba()
{
Log.i("coba","sdsds");
}
}
public class MainActivity extends AppCompatActivity {
Model mod;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mod = new Model();
mod.coba();
String a = "5";
Log.i("coba",a);
}
}
I think you give the wrong name when you are setting Logcat .Let me know it is helpful for you.

Restarting activity inside onClick method

I have an app which reads .txt file and displays contents in table layout.
here is my MainActivity.java file:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new TableLayout(this,0));
}
}
Inside TableLayout class when adding first row (headers), i also add on click listeners.
Here is the code that gets executed when click happens:
public class MyOnClickListener extends MainActivity implements OnClickListener {
int rowNumber;
public MyOnClickListener(int rowNumber) {
this.rowNumber = rowNumber;
}
#Override
public void onClick(View v) {
setContentView(new TableLayout(context,rowNumber));
}
};
context is saved from when activity is first started, but i get nullpointexception error with this as an argument.
What i would like to do when header is clicked is to recreate table with header number argument.
So my question is what should i do to restart table creation within onClick method?
Edit: this is how context is saved
Context context;
public TableLayout(Context context, int rowNr) {
super(context);
this.context = context;
I would probably do something like this
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new TableLayout(this, getRowNumber()));
}
protected int getRowNumber(){
return 0;
}
}
and then you do something like
public class MyOnClickListener extends MainActivity implements OnClickListener {
// here you initialize rowNumber
static int rowNumber = 0;
#Override
protected void getRowNumber(){
return rowNumber;
}
#Override
public void onClick(View v) {
// here you set your rowNumber
rowNumber = some_value;
recreate();
}
};
P.S: I haven't compiled this but you can get the idea

AsyncTask : passing value to an Activity (onCreate method )

Update1
activity:
public Integer _number = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
if (_number >0)
{
Log.d("onSuccessfulExecute", ""+_number);
}
else
{
Log.d("onSuccessfulExecute", "nope empty songs lists");
}
}
public int onSuccessfulExecute(int numberOfSongList) {
_number = numberOfSongList;
if (numberOfSongList >0)
{
Log.d("onSuccessfulExecute", ""+numberOfSongList);
}
else
{
Log.d("onSuccessfulExecute", "nope empty songs lists");
}
return numberOfSongList;
}
end Update1
UPDATE: AsynchTask has its own external class.
How to pass an value from AsyncTask onPostExecute()... to activity
my code does returning value from onPostExecute() and updating on UI but i am looking for a way to set the activity variable (NumberOfSongList) coming from AsynchTask.
AsyncTask class:
#Override
public void onPostExecute(asynctask.Payload payload)
{
AsyncTemplateActivity app = (AsyncTemplateActivity) payload.data[0];
//the below code DOES UPDATE the UI textView control
int answer = ((Integer) payload.result).intValue();
app.taskStatus.setText("Success: answer = "+answer);
//PROBLEM:
//i am trying to populate the value to an variable but does not seems like the way i am doing:
app.NumberOfSongList = payload.answer;
..............
..............
}
Activity:
public Integer NumberOfSongList;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Several UI Code
new ConnectingTask().execute();
Log.d("onCreate", ""+NumberOfSongList);
}
What about using a setter method? e.g.
private int _number;
public int setNumber(int number) {
_number = number;
}
UPDATE:
Please look at this code. This will do what you're trying to accomplish.
Activity class
public class TestActivity extends Activity {
public int Number;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
Button btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast toast = Toast.makeText(v.getContext(), "Generated number: " + String.valueOf(Number), Toast.LENGTH_LONG);
toast.show();
}
});
new TestTask(this).execute();
}
}
AsyncTask class
public class TestTask extends AsyncTask<Void, Void, Integer> {
private final Context _context;
private final String TAG = "TestTask";
private final Random _rnd;
public TestTask(Context context){
_context = context;
_rnd = new Random();
}
#Override
protected void onPreExecute() {
//TODO: Do task init.
super.onPreExecute();
}
#Override
protected Integer doInBackground(Void... params) {
//Simulate a long-running procedure.
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Log.e(TAG, e.getMessage());
}
return _rnd.nextInt();
}
#Override
protected void onPostExecute(Integer result) {
TestActivity test = (TestActivity) _context;
test.Number = result;
super.onPostExecute(result);
}
}
Just a word of caution: Be very careful when attempting to hold a reference to an Activity instance in an AsyncTask - I found this out the hard way :). If the user happens to rotate the device while your background task is still running, your activity will be destroyed and recreated thus invalidating the reference being to the Activity.
Create a listener.
Make a new class file. Called it something like MyAsyncListener and make it look like this:
public interface MyAsyncListener() {
onSuccessfulExecute(int numberOfSongList);
}
Make your activity implement MyAsyncListener, ie,
public class myActivity extends Activity implements MyAsyncListener {
Add the listener to the constructor for your AsyncTask and set it to a global var in the Async class. Then call the listener's method in onPostExecute and pass the data.
public class MyCustomAsync extends AsyncTask<Void,Void,Void> {
MyAsyncListener mal;
public MyCustomAsync(MyAsyncListener listener) {
this.mal = listener;
}
#Override
public void onPostExecute(asynctask.Payload payload) {
\\update UI
mal.onSuccessfulExecute(int numberOfSongList);
}
}
Now, whenever your AsyncTask is done, it will call the method onSuccessfulExecute in your Activity class which should look like:
#Override
public void onSuccessfulExecute(int numberOfSongList) {
\\do whatever
}
Good luck.

Categories

Resources