i m programming an android program of a simple hello world in netbeans but it returns me this error...what should i do in order to rid of this error ...i m new and exited to jump into this .
here is my code...
enter code here
package com.google.haha;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
/**
*
* #author abc
*/
public class NewActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// ToDo add your GUI initialization code here
TextView text=new TextView(this);
text.setText("hello");
setContentView(this);
}
}
When you do
setContentView(this);
this refers to the current class instance, not the TextView you just created.
Try:
setContentView(text);
Like "metter" said, the setContentView(VIEW) method expects an object of the View class (TextView, ListView, etc). So you have to pass a View element in there...
Related
I was building this simple Notepad application. All the notes are hosted within a RecyclerView and there's a button that can be used for deleting all the notes. Now, when the user presses the button to delete all the notes, an AlertDialog pops up. The thing is, this AlertDialog pops up even when there are no notes present within the application. I wanted to stop that. The AlertDialog should pop up only when there are notes present.
I was wondering if there was some way through which I could get the RecyclerView size within the Activity from the Adapter class. I thought this would be the best way to go about achieving this objective. If there are any better ways, by all means, do let me know.
Here are the respective classes:
NotesActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.arpansircar.java.notepadapplicationusingmvvm.R;
import com.arpansircar.java.notepadapplicationusingmvvm.databinding.ActivityNotesBinding;
import com.arpansircar.java.notepadapplicationusingmvvm.model.Constants;
import com.arpansircar.java.notepadapplicationusingmvvm.model.INotesActivity;
import com.arpansircar.java.notepadapplicationusingmvvm.room.NotesDatabase;
import com.arpansircar.java.notepadapplicationusingmvvm.room.NotesEntity;
import com.arpansircar.java.notepadapplicationusingmvvm.viewmodel.NotesActivityViewModel;
import java.util.List;
import java.util.Objects;
/**
* The NotesActivity is the primary activity in the entire applications.
* This activity starts up and shows the user all the notes that have been created or the facility to add a new note using the floating action button.
* All the notes that have been created using this application and short details associated with them show up in the RecyclerView.
* The user can click on any of these notes to view the complete details of the note.
*/
public class NotesActivity extends AppCompatActivity implements View.OnClickListener, INotesActivity {
private ActivityNotesBinding activityNotesBinding;
private NotesActivityViewModel notesActivityViewModel;
/*The onCreate method is the first method that is executed when the application starts up.
* Usually, in this method, such functions are executed that are to be performed only once.
* In this method, I've defined two other methods to be executed as soon as the application starts up and that are to be executed only once.
* The initializeDatabase() method is used to create an instance of the RoomDatabase.
* An application context is used because we want to use the same instance throughout the context of the application.
* The initializeViewModel() is used to create an instance of the ViewModel class associated with this activity.
* This ViewModel will be used to handle any configuration changes. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityNotesBinding = DataBindingUtil.setContentView(this, R.layout.activity_notes);
initializeDatabase();
initializeViewModel();
}
/*The onStart() is the next method executed after the onCreate() callback method.
* In this method, two methods are executed, namely the setOnClickListenerMethod() and the setObserverMethod().
* The setOnClickListenerMethod() method is tasked with setting the onClickListener for any and all buttons that might exist in the activity.
* Currently, the activity has a single floating action button so this button's onClickListener is set in this activity.
* The setObservableMethod() method is used to activate the Observer to observe changes in the LiveData object present in the ViewModel. */
#Override
protected void onStart() {
super.onStart();
setOnClickListenerMethod();
setObserverMethod();
}
/*The initializeDatabase() method is used to create an instance of the NotesDatabase class.
* This single instance will be used for performing all the database transactions including the CRUD operations.
* For creating an instance of this class, the application context is used.
* I've assumed that using an application context will allow me to use the instance throughout the entirety of the application.*/
private void initializeDatabase() {
NotesDatabase.initializeDatabase(getApplicationContext());
}
/*The initializeViewModel() method is used for initializing the NotesActivityViewModel instance with the ViewModel class.*/
private void initializeViewModel() {
notesActivityViewModel = new ViewModelProvider(this).get(NotesActivityViewModel.class);
}
/*The setObserverMethod() method is used simply for activating the observer.
* This task is done at the Started state of the activity to allow it to start observing the changes in the LiveData as soon as the activity starts.
* If there are any changes in the database, i.e., if it returns a List of NotesEntity objects, the list is sent to the setRecyclerViewMethod().*/
private void setObserverMethod() {
final Observer<List<NotesEntity>> observer = this::setRecyclerViewMethod;
notesActivityViewModel.selectAllNotesMethod().observe(this, observer);
}
/*The setRecyclerViewMethod(...) is called when the observer observes a change in the LiveData.
* Upon calling this method, the List of NotesEntity objects are passed into this method which promptly passes it to the RecyclerViewAdapter class.
* Accordingly, the RecyclerView is populated with the required views and a new RecyclerView is displayed with the newly added notes.*/
private void setRecyclerViewMethod(List<NotesEntity> notesEntityList) {
RecyclerView recyclerView = activityNotesBinding.notesListRecyclerView;
NotesAdapter notesAdapter = new NotesAdapter(notesEntityList, this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(false);
recyclerView.setAdapter(notesAdapter);
}
/*The setOnClickListenerMethod() is used to set the onClickListener to all the floating action buttons used in the activity.*/
private void setOnClickListenerMethod() {
activityNotesBinding.newNoteFloatingActionButton.setOnClickListener(this);
activityNotesBinding.deleteAllNotesFloatingActionButton.setOnClickListener(this);
}
/*The onClick(...) method allows us to intercept all the clicks placed within this method.
* Since, only a single view can be clicked in this activity, therefore, this method contains only a single if clause.
* The if clause checks if the floating action button has been clicked or not.
* If it has, an Intent object starts the AddEditActivity for the user to add a new note to the activity. */
#Override
public void onClick(View view) {
if (view == activityNotesBinding.newNoteFloatingActionButton) {
Intent newNoteIntent = new Intent(NotesActivity.this, AddEditNoteActivity.class);
newNoteIntent.putExtra("function", "insert");
startActivity(newNoteIntent);
}
if (view == activityNotesBinding.deleteAllNotesFloatingActionButton) {
AlertDialog alertDialog = showAlertDialogMethod(
"delete_all",
getString(R.string.delete_all_notes_alert_title),
getString(R.string.delete_all_notes_alert_message));
alertDialog.show();
}
}
/*The onNoteClicked(...) method here is an overridden method from the INotesActivity interface.
* When a note is clicked in the RecyclerView, the clicked noteID is transferred to this method.
* When this method is triggered, an Intent object is created to start the DisplayNoteActivity.java activity.
* Within this object, the noteID of the clicked note is sent as an Integer extra to next activity.
* Finally, the activity is started.*/
#Override
public void onNoteClicked(NotesEntity notesEntity) {
Intent intent = new Intent(NotesActivity.this, DisplayNoteActivity.class);
intent.putExtra(Constants.COLUMN_ID, notesEntity.getId());
startActivity(intent);
}
private AlertDialog showAlertDialogMethod(String function, String title, String message) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder
.setTitle(title)
.setMessage(message)
.setPositiveButton(R.string.yes_string, (dialogInterface, i) -> {
if (Objects.equals(function, "exit"))
super.onBackPressed();
if (Objects.equals(function, "delete_all"))
notesActivityViewModel.deleteAllNotesMethod();
})
.setNegativeButton(R.string.no_string, (dialogInterface, i) -> dialogInterface.cancel());
return alertDialogBuilder.create();
}
#Override
public void onBackPressed() {
AlertDialog alertDialog = showAlertDialogMethod(
"exit",
getString(R.string.exit_title),
getString(R.string.exit_message));
alertDialog.show();
}
}
NotesAdapter.java
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;
import com.arpansircar.java.notepadapplicationusingmvvm.R;
import com.arpansircar.java.notepadapplicationusingmvvm.databinding.IndividualItemsLayoutBinding;
import com.arpansircar.java.notepadapplicationusingmvvm.model.INotesActivity;
import com.arpansircar.java.notepadapplicationusingmvvm.room.NotesEntity;
import java.util.List;
/**
* The NotesAdapter class is used for setting up the RecyclerView.
* The class accepts a List of NotesEntity objects as the argument for it's constructor.
* This list is used to populate the RecyclerView with newer objects.
*/
public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.NotesViewHolder> {
private final List<NotesEntity> notesEntityList;
private final INotesActivity iNotesActivity;
public NotesAdapter(List<NotesEntity> notesEntityList, INotesActivity iNotesActivity) {
this.notesEntityList = notesEntityList;
this.iNotesActivity = iNotesActivity;
}
/*The onCreateViewHolder() method configures and returns the views for all the different objects present in the List.*/
#NonNull
#Override
public NotesViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
IndividualItemsLayoutBinding individualItemsLayoutBinding = DataBindingUtil.inflate(
LayoutInflater.from(parent.getContext()),
R.layout.individual_items_layout,
parent,
false
);
return new NotesViewHolder(individualItemsLayoutBinding, iNotesActivity);
}
/*The onBindViewHolder(...) method receives the views individually from the NotesViewHolder class.
* This method then binds all these individual views to the list.*/
#Override
public void onBindViewHolder(#NonNull NotesViewHolder holder, int position) {
NotesEntity currentNote = notesEntityList.get(position);
holder.individualItemsLayoutBinding.setNoteDetails(currentNote);
}
/*The getItemCount() method simply returns the value denoting the size that our RecyclerView is supposed to be. */
#Override
public int getItemCount() {
if (notesEntityList != null) {
return notesEntityList.size();
} else {
return 0;
}
}
/*The NotesViewHolder class is used to hold each of the views for each of the objects present in the notesEntitiesList list.*/
public class NotesViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private final IndividualItemsLayoutBinding individualItemsLayoutBinding;
private final INotesActivity iNotesActivity;
public NotesViewHolder(#NonNull IndividualItemsLayoutBinding individualItemsLayoutBinding, INotesActivity iNotesActivity) {
super(individualItemsLayoutBinding.getRoot());
this.individualItemsLayoutBinding = individualItemsLayoutBinding;
individualItemsLayoutBinding.getRoot().setOnClickListener(this);
this.iNotesActivity = iNotesActivity;
}
/*The onClick(...) method is used when we click a particular view present in the RecyclerView.
* When the user clicks on a particular note, this method stores the object for that particular note from the list.
* Next, the noteID is acquired from the object and is sent to the NotesActivity via the INotesActivity interface.*/
#Override
public void onClick(View view) {
iNotesActivity.onNoteClicked(notesEntityList.get(getAdapterPosition()));
}
}
}
Thanks for any help.
This may help :
if(layoutManager.findViewByPosition(0)==null){
that means recycler view is empty
}
please test it before to be sure,try it on a nonempty recycler view and make sure it does not give null when 0th position row is out of scene.if it gives nonnull value, we are good to go.let me know as well, if it works.
I'm new to android and i have been learning android form udacity.
in one of their lesson they asked students to copy code from git hub , i did so but when I pasted the code an error popped saying cannot symbol number format.please help me to resolve this and please give answer in detail it's a request. thank you.
..........................................................................................................................................................
link of github :- https://gist.github.com/anonymous/fa134c55a4a43e8d6004
...............................................................................java code which i've written:-
package com.example.android.justjava;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.;
/**
* This app displays an order form to order coffee.
*/
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* This method is called when the order button is clicked.
*/
public void submitOrder(View view) {
display(18 * 3 + 4 / (2+2) -1);
displayPrice(2*5);
}
/**
* This method displays the given quantity value on the screen.
*/
private void display(int number) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + number);
}
/**
* This method displays the given price on the screen.
*/
private void displayPrice(int number) {
TextView priceTextView = (TextView) findViewById(R.id.price_text_view);
priceTextView.setText(NumberFormat.getCurrencyInstance().format(number));
}
}
.............................................................................
Try add import java.text.NumberFormat;
In such way build system imports class you required.
Documentation describes it in details
I have a Java activity like so.
package com.xxx.yyy.overrideoncreate;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("DEBUG","Original oncreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
I wish to split some of the onCreate instructions to a separate class, so I created this too.
package com.xxx.yyy.overrideoncreate;
import android.os.Bundle;
import android.util.Log;
/**
* Created by oox on 26/6/17.
*/
public class SubClass extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("DEBUG","Overridden");
super.onCreate(savedInstanceState);
}
}
I intend for subClass.onCreate to override MainActivity.onCreate -- both Overridden and original oncreate messages should be displayed. However, that did not seem to happen, the overridden message did not appear in the Logcat.
Any idea what I did wrong?
Thanks in advance.
In order for SubClass's onCreate to be called, an instance of SubClass should be created instead of an instance of MainActivity when the application is launched.
For that to happen, SubClass should become the actual main activity of your application (i.e. the activity class registered in the AndroidManifest.xml which gets launched when the application is launched).
Hoping to get into android app development so I'm doing some basic tutorials just now.
Just trying to get comfortable with the basics at the moment, one of which is using the Typeface class.
package org.me.myandroidstuff;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Typeface;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class HelloWorldActivity extends Activity implements OnClickListener
{
private View mainView;
private TextView tbox1;
private Button exitButton;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mainView=(View)findViewById(R.id.mainView);
mainView.setBackgroundColor(getResources().getColor(R.color.silver));
tbox1 = (TextView)findViewById(R.id.textBox1);
tbox1.setTypeface(Typeface.MONOSPACE);
}
}
The line
tbox1 = (TextView)findViewById(R.id.textBox1);
Has a red cross beside it (I'm using eclipse) with the error
tbox1 cannot be resolved
Its been a while since i have used java, but as i aware the following code
create a new TextView object called tbox1
Assigns the tbox1 object the id specified in the xml for the TextView tag in an external main.xml
Then tbox1 executes the setTypeFace() method on itself?
Obviously I'm going wrong somewhere, any ideas? Something really simple no doubt...
You can't inform us about one error and neglect the others. Look at your code.
Besides what user370305 said, you have other problems. Namely, your Activity, according to the contract, implements OnClickListener but does not override the necessary onClick(View v) method. You must add it for the contract to be met.
So your code should look like:
package org.me.myandroidstuff;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class HelloWorldActivity extends Activity implements OnClickListener {
private View mainView;
private TextView tbox1;
private Button exitButton;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainView=(View)findViewById(R.id.mainView);
mainView.setBackgroundColor(getResources().getColor(R.color.silver));
tbox1 = (TextView)findViewById(R.id.textBox1);
tbox1.setTypeface(Typeface.MONOSPACE);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Remember, you can't talk about errors until you fix every other that might cause other errors to be falsely reported.
First try to set setContentView(R.layout.yourlayoutfilename); in onCreate().
1.) Delete line super.onCreate(savedInstanceState);
2.) Retype super.onCreate(savedInstanceState);
3.) Clean the Project
4.) Build the Project
I have huge problem. Have searching answer from many places but I do not find answer to question.
I have 2 classes in java. One is "main" and other is "menu"
On main, there is editText where person can type name and button ok.
When you press ok, I want to specific thing happen. That is where I need help. I am newcomer in Android.
I want that in other class, where will be main application and stuff, the entered name would be displayed. For example "Welcome " + name
I have tried many ways but I do not get it to work. So I want it to get one of 2 possible ways.
Set string in class 1 and then when it goes class 2, then it imports the string from class 1 to class 2 so I can use it.
I set string in class 2 and then in Class 1 I change the string in class 2, so the main 'data' string is actually in class 2, where I will continue using it if needed!
I have searched it from many places, used google and this database, but haven't found answer.
My codes are really nothing much, so no point pasting them here :).
Thanks for the help!
edit:// Ok, here are some codes then :)
package viimane.voimalus.incule;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class ViimaneVoimalusActivity extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button oknupp = (Button) findViewById(R.id.nimiOK);
oknupp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("viimane.voimalus.in" +cule.REALMENU"));
}
});
}
}
package viimane.voimalus.incule;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
public class RealMenu extends Activity {
EditText nimesisestus;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.peamenu);
}
}
You didn't show any code at all, so the answer won't be too detailed.
You can pass a String in the intent used to start the second activity, using putExtra method. In the second activity you may get the string by calling getStringExtra(). If you don't know much about starting activity and intents, there are many resources on the web, for example - this one.
To receive text input use EditText and to put text on the screen (that the user can't cange) use TextView.
Those are starting points. Next time I hope the question will be more focused.
Pass the string as parameter to the constructor of the menu class like this:
menu m = new menu(mystring);
then in the constructor save the atribute to your class
private String mystring;
menu(String mystring)
{
this.mystring = mystring;
}