'this' keyword not working - java

I created some ImageViews using a for loop and inserted them into a ScrollView.
Then I need to create one more ImageView when on touching the screen.
The this keyword cannot be used for creating an ImageView at the '###' marked position.
I am a beginner.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ScrollView scroll=new ScrollView(this);
final LinearLayout layout =new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lparams.setMargins(0, 10, 0, 10);
lparams.gravity=Gravity.CENTER;
int i;
for(i=0;i<15;i++) {
//here 'this' is working ******************
ImageView imView = new ImageView(this);
imView.setLayoutParams(lparams);
Drawable new_image = getResources().getDrawable(R.drawable.rakthasakshi);
imView.setBackgroundDrawable(new_image);
layout.addView(imView, lparams);
}
scroll.addView(layout);
setContentView(scroll);
scroll.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP){
//but here says 'this' cannot be applied ###############
ImageView imView = new ImageView(this);
imView.setLayoutParams(lparams);
Drawable new_image = getResources().getDrawable(R.drawable.rakthasakshi);
imView.setBackgroundDrawable(new_image);
layout.addView(imView, lparams);
scroll.addView(layout);
setContentView(scroll);
return true;
}
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Use ImageView imView = new ImageView(MainActivity.this);.
In the first case, this refers to MainActivity already.
However, in the second case, this actually refers to View.OnTouchListener.

Do you realise what this means in your context?
this references an anonymous class of type View.OnTouchListener.
To reference the object of your class MainActivity you have to reference MainActivity.this.

Add a final context which have this and use it.
Example:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ScrollView scroll=new ScrollView(this);
final Context ctx = this;
...
//but here says 'this' cannot be applied ###############
ImageView imView = new ImageView(ctx);

This keyword works well in the parent class, but as you create child classes, you have to use ActivityName.this instead of this.

Related

How to pass String from One Activity to another Activity and use it in intent for Dialpad and Email

I have two one Adapter and another Activity . Adapter send the String Extra as per position in Firebase Data Structure into Next activity where data is displayed which is passed from Adapter.
It works pretty well. I am ablet to show the data in Textview. But When I user intent to Dial a phone or send Email , Then I'm not able to use Extras I"m receivng with but when I setText in Textview ..they show the exact Data. Please help
Here is the method in Adapter
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
database = FirebaseDatabase.getInstance();
dbreference = database.getReference("gender");
g = bookslist.get(position);
holder.teacher_quali.setText(g.getBqualifications());
holder.profile_details.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), gender_details.class);
intent.putExtra(NEAR_LOCATION, g.getBlocation());
intent.putExtra(AVAILAIBILITY, g.getBavailaile());
intent.putExtra(MOBILE, g.getSellermobile());
intent.putExtra(EMAIL, g.getSelleremail());
v.getContext().startActivity(intent);
}
});
where I have defined MOBILE and EMAIL as
public static final String MOBILE = "other_mobile";
public static final String EMAIL= "other_email";
in same adapter view and my activity is
public class gender_details extends AppCompatActivity {
private TextView tutor_email,tutor_mobile;
private ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_details); // get the reference of Toolbar
toolbar.setTitle(getIntent().getStringExtra(KEY_NAME));
toolbar.setLogo(R.drawable.ic_person_black_24dp);
setSupportActionBar(toolbar);
String tutor_email_txt = "";
String tutor_mobile_txt = "";
tutor_email_txt = intent.getStringExtra(EMAIL);
tutor_mobile_txt = intent.getStringExtra(MOBILE);
// Setting values
TextView Email_Txt = (TextView) findViewById(R.id.tutor_email);
Email_Txt.setText(tutor_email_txt);
TextView Contact_Txt = (TextView) findViewById(R.id.tutor_contact);
Contact_Txt.setText(String tutor_mobile_txt);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.toolbar_menu, menu);
return true;
}
// Activity's overrided method used to perform click events on menu items
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
// Display menu item's title by using a Toast.
if (id == R.id.action_call) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:"+tutor_mobile_txt));
startActivity(intent);
return true;
} else if (id == R.id.action_email) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("plain/text");
intent.putExtra(Intent.EXTRA_EMAIL, tutor_email_txt);
intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
intent.putExtra(Intent.EXTRA_TEXT, "mail body");
startActivity(Intent.createChooser(intent, ""));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(gender_details.this, MainActivity.class);
startActivity(intent);
}
}
As you can see in Textview , information are shown correctl but when I use to Intent Action Dail or send email...I'm not been able to do so.
Please help
Try this:
Declare the variable Globally
public class gender_details extends AppCompatActivity {
private TextView tutor_email,tutor_mobile;
private ImageView img;
String tutor_email_txt;
String tutor_mobile_txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_details); // get the reference of Toolbar
toolbar.setTitle(getIntent().getStringExtra(KEY_NAME));
toolbar.setLogo(R.drawable.ic_person_black_24dp);
setSupportActionBar(toolbar);
tutor_email_txt = intent.getStringExtra(EMAIL);
tutor_mobilee_txt = intent.getStringExtra(MOBILE);
// Setting values
TextView Email_Txt = (TextView) findViewById(R.id.tutor_email);
Email_Txt.setText(tutor_email_txt);
TextView Contact_Txt = (TextView) findViewById(R.id.tutor_contact);
Contact_Txt.setText(String tutor_mobile_txt);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.toolbar_menu, menu);
return true;
}
// Activity's overrided method used to perform click events on menu items
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
// Display menu item's title by using a Toast.
if (id == R.id.action_call) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:"+tutor_mobile_txt));
startActivity(intent);
return true;
} else if (id == R.id.action_email) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("plain/text");
intent.putExtra(Intent.EXTRA_EMAIL, tutor_email_txt);
intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
intent.putExtra(Intent.EXTRA_TEXT, "mail body");
startActivity(Intent.createChooser(intent, ""));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(gender_details.this, MainActivity.class);
startActivity(intent);
}
}
Are You Declare Permission in Manifest If Not Then Declare it :
uses-permission android:name="android.permission.CALL_PHONE"
There are some serious naming problems in your code. First you need to make your tutor_mobile_txt variable global. Secondly inside onCreate your are initializing tutor_mobilee_txt instead of tutor_mobile_txt. Correct the spellings and then check.

Settings button are not available with listview

Where is setting button (3 small points in right corner) ? And how to return it?
When I started to use ListView with another layout , my action bar dissapear.
May be reason is using another layout?
MainActivity.java
public class MainActivity extends ListActivity {
String[] values = new String[100];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
ListView listView = (ListView)findViewById(R.id.listView);
for (int i=0;i<=99;i++){
values[i]=Integer.toString(i+1);
}
MyCustomAdapter adapter = new MyCustomAdapter(this, values);
setListAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(MainActivity.this,SettingActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String item = (String) getListAdapter().getItem(position);
Toast.makeText(this, item + " selected", Toast.LENGTH_SHORT).show();
}
}
To use the default ActionBar:
Ensure your app's theme (in styles.xml has a Theme.AppCompat.* parent which also contains an ActionBar. For example:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">#color/specify_action_bar_color_here</item>
<item name="colorPrimaryDark">#color/specify_status_bar_color_here</item>
<item name="colorAccent">#color/specify_widget_color_here</item>
</style>
Then, ensure your Activity class extends AppCompatActivity, rather than simply Activity. For example:
public class MainActivity extends AppCompatActivity {
//...
}

what to do if backpressed

i have a code to change the text of textview in a layout according to the value of the edittext (et) in the previous layout >> somethig like this
I cannot comment, so i will help you editing. Use SharedPreferences to store the string from the edittext in order to get persistance. Then get the string from the SharedPreferences and do the same thing that you are doing(pass it through the intent)
there is MorningDrsGeneral :
public class MorningDrsGeneral extends ActionBarActivity {
Button button ;
EditText et;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.morningdrs);
et = (EditText) findViewById(R.id.et);
addListenerOnButton1();
}
public void addListenerOnButton1() {
final Context context = this;
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, bookingKamal.class);
intent.putExtra("fn" , et.getText().toString());
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
and there is bookingKamal.java :
public class bookingKamal extends ActionBarActivity {
Button button;
TextView textView3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bookingkamal);
textView3 = (TextView) findViewById(R.id.textView3);
String A = textView3.getText().toString();
String N = " ";
if (A.equals(N)){
Intent intent = getIntent();
String texx = intent.getStringExtra("fn");
textView3.setText(texx);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
So i have to keep the text in the bookingKamal activity .. it means when i go back from this layout and back to it the text should be the same as previous. And in this code it back to null :/ or
You have two options here:
Save the value into the internal file system so it can still will be loaded after the app has been unloaded
Save the value in the Activity which holds the button to this activity and save the text over there in a variable and when the bookingkamal activity starts, it could be read from somewhere (hint: Intent#putExtra("KEY", "VALUE"))
I am not describing how you should do it because there is enough documentation about it out there and that is not the point of this answer. This should give you an idea how to it.
You can do that by using sharedpreferences.
The above link will help you undderstand how to use it.
To add data to SharedPreferences use
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("text", mSaved.getText().toString());
editor.putInt("selection-start", mSaved.getSelectionStart());
editor.putInt("selection-end", mSaved.getSelectionEnd());
editor.apply();
And to retrieve
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null)
{
//mSaved.setText(restoredText, TextView.BufferType.EDITABLE);
int selectionStart = prefs.getInt("selection-start", -1);
int selectionEnd = prefs.getInt("selection-end", -1);
/*if (selectionStart != -1 && selectionEnd != -1)
{
mSaved.setSelection(selectionStart, selectionEnd);
}*/
}
Note : that SharedPreferences will save the value such that, even of you close the application and restart it. The values will still remain. So, make sure you clear the data when you done with it. You can read more about it here at the SharedPreferences docs.

Null Pointer Exception when using LayoutInflator()?

I'm using the LayoutInflator to try and get the user's text to display in a TableLayout (Which is a child of a scrollView) But so far, it just keeps throwing the Null Pointer Exception. All the IDs are working fine, I tried cleaning the project to see if that would help but to no avail, can anyone help me out?
By the way, it tells me the error is in 2 places, reminderListTextView.setText(text); and in inflate("test");
Code:
public class MainActivity extends ActionBarActivity {
private TableLayout reminderTableScrollView;
// TextView and Button added
EditText reminderEditText;
Button addReminderButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
reminderTableScrollView = (TableLayout) findViewById(R.id.reminderTableScrollView);
reminderEditText = (EditText) findViewById(R.id.reminderEditText);
addReminderButton = (Button) findViewById(R.id.enterButton);
addReminderButton.setOnClickListener(reminderClickListener);
}
private OnClickListener reminderClickListener = new Button.OnClickListener() {
#Override
public void onClick(View v) {
if (reminderEditText.getText().toString() == null || reminderEditText.getText().toString() == "") {
Toast.makeText(getApplicationContext(), "Enter reminder", Toast.LENGTH_SHORT).show();
} else {
inflate("Test");
reminderEditText.setText("");
}
}
};
public void inflate(String text) {
LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View reminder = inflator.inflate(R.layout.reminder_layout, null);
TextView reminderListTextView = (TextView) findViewById(R.id.reminderListTextView);
reminderListTextView.setText(text);
reminderTableScrollView.addView(reminder);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.menuAdd) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
It's actually in just one place that you get the exception : reminderListTextView.setText(text);, the 2 lines are the trace to tell you that you get the error at reminderListTextView.setText(text); when inflate("test"); is called.
Try reminder.findViewById(...);, you need to use the view in which you inflated the layout to be able to retrieve elements from it.
Try changing your inflate method to this:
public void inflate(String text) {
LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View reminder = inflator.inflate(R.layout.reminder_layout, null);
TextView reminderListTextView = (TextView)reminder.findViewById(R.id.reminderListTextView);
reminderListTextView.setText(text);
reminderTableScrollView.addView(reminder);
}
Without seeing your reminder_layout, I'm not certain, but I'm guessing the view with id reminderListTextView is in your reminder_layout.xml and not your activity_main.xml

Fatal Exception: main and Null pointer exception arise while running a simple android program

I was trying to do some simple stuff on Android. I created a Login Page and worked on. When I try to create a pop up window, Fatal exception is thrown. Help out
NewProjectActivity.java
public class NewProjectActivity extends Activity {
PopupWindow popUp;
LinearLayout layout;
TextView tv;
LayoutParams params;
LinearLayout mainLayout;
boolean click = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_project);
TextView alertdetail = (TextView) findViewById(R.id.link_to_register);
alertdetail.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (click) {
popUp.showAtLocation(mainLayout, Gravity.BOTTOM, 10, 10);
popUp.update(50, 50, 300, 80);
click = false;
} else {
popUp.dismiss();
click = true;
}
}
});
params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layout.setOrientation(LinearLayout.VERTICAL);
tv.setText("Hi this is a sample text for popup window");
layout.addView(tv, params);
popUp.setContentView(layout);
popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
mainLayout.addView(alertdetail, params);
setContentView(mainLayout);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.new_project, menu);
return true;
}
}
TextView tv is not initialized and layout and popUp and mainLayout.
Also you have setContentView twice for the same activity which is not wrong but bad design
Your simple application is crashing because you have declared these variables :-
PopupWindow popUp;
LinearLayout layout;
TextView tv;
LayoutParams params;
LinearLayout mainLayout;
and initialised only :-
TextView alertdetail = (TextView) findViewById(R.id.link_to_register);
This is called as passing the reference. You need to do the same for the above

Categories