Passing param to java android class - java

Here is the class i am passing to
public class AxxessCCPAccountDetails extends Activity {
public AxxessCCPAccountDetails(String username) {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.accountdetails);
}
}
Here is the code that i am passing from
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(view.getContext(), AxxessCCPAccountList.class);
startActivityForResult(myIntent, 0);
}
});
I need to pass a username to a class. How can i pass the param to the class then activate the activity(class) which is linked to a view.
Thanks

Using Intent. You should not create your own constructor for the Activity class.
Here is a short example:
Intent myIntent = new Intent(view.getContext(), AxxessCCPAccountList.class);
myIntent.putExtra("username", userName);
myIntent.putExtra("pass", pass);
And then, in your AxxessCCPAccountList.onCreate method:
String userName = this.getIntent().getStringExtra("username");
String pass = this.getIntent.getStringExtra("pass");

Add the data to the intent (intent.putExtra() or something), and get it on the other side from the intent in onCreate (intent.getExtra() ) by using the same key.

This is the solution
getIntent().getExtras().getString("username");

Related

Sending data to Listview of another activity

After pressing the button I would like to go to the second activity, enter the data in the second activity and then return to the main activity, but having data in ListView. This is my code:
MainActivity:
public class MainActivity extends AppCompatActivity {
Button button;
ListView listView;
String name;
private static final int REQUEST_CODE = 1;
ArrayAdapter<String> adapter;
ArrayList<String> nameList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button2);
listView = findViewById(R.id.CarList);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, SecondActivity.class);
startActivityForResult(i, REQUEST_CODE);
}
});
nameList = new ArrayList<String>();
nameList.addAll(Arrays.asList(name));
adapter = new ArrayAdapter<String>(this, R.layout.element, nameList);
listView.setAdapter(adapter);
}
protected void onActivityResult(int requestCode, int resultCode, Intent i){
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
name = i.getStringExtra("name");
}
}
}
And this is my SecondActivity:
public class SecondActivity extends AppCompatActivity {
EditText editText;
Button button2;
String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
editText = findViewById(R.id.editText);
button2 = findViewById(R.id.button);
}
public void finish() {
Intent i = new Intent();
name = editText.getText().toString();
i.putExtra("name", name);
setResult(RESULT_OK, i);
super.finish();
}
}
What could I change to make the application work? Because now I only get the message that: app has stopped, but I don't receive information about any error.
After pressing the button I would like to go to the second activity, enter the data in the second activity and then return to the main activity, but having data in ListView.
What could I change to make the application work? Because now I only get the message that: app has stopped, but I don't receive information about any error.
This is simply because you've incorrectly thinking that Activity.finish() is always called whenever you close the activity. But it never be called by the Android. Take a look for this Lifecyle picture from Activity-lifecycle concepts:
you can see that only onStop() then onDestroy() is called when activity is closed.
You need to call the finish() method manually to send your intent. Or, the better way, create a method that only build and set the intent for the result. Something like this:
private void prepareResult(String name) {
Intent i = new Intent();
i.putExtra("name", name);
setResult(RESULT_OK, i);
}
then call it whenever you want to close your activity:
String name = editText.getText().toString();
prepareResult(name);
finish();
Or you can override the onBackPressed() to also handing the back pressed, like the following:
#Override
public void onBackPressed() {
Intent i = new Intent();
name = editText.getText().toString();
i.putExtra("name", name);
setResult(RESULT_OK, i);
// The default implementation simply finishes the current activity
// see the documentation.
super.onBackPressed();
}

RecyclerView - Get the selected position and pass the position to another activity where the same list will appear with that specific item selected

I have declared a ViewModel.class for the RecyclerView an Adapter and I have parsed to the MainActivity and to another Activity so I have the same adapter for both activities.
I can show the parsed data in both activities but the problem it is I cannot take the data of the selected item to MainActivity and then to set to that btnSearch for a click so then I can share between activities the data from the selected item.
Every time when the app is open the first item is selected. What I am trying to achieve is.
Get the item position to the MainActivity so when I click for a button search the data of the selectedItem will going to intent.putExtra and then get the data at another Activity.
If I click the second item and go to another Activity the same item will be selected.
Here is what I have tried so far.
The SearchEngineAdapter.class
public class SearchEngineAdapter extends RecyclerView.Adapter<SearchEngineAdapter.ViewHolder> {
private int selectedItem = 0;
private static RecyclerViewClickListener itemListener;
private Context context;
ArrayList<SearchEngine> arrayList = new ArrayList<>();
public SearchEngineAdapter(Context context, ArrayList<SearchEngine> arrayList, int selectedItem) {
this.context = context;
this.arrayList = arrayList;
this.selectedItem = selectedItem;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int i) {
holder.tvIcon.setImageResource(arrayList.get(i).getIcon());
holder.tvId.setText(arrayList.get(i).getId());
holder.tvSearchUrl.setText(arrayList.get(i).getUrl());
final String url = holder.tvSearchUrl.getText().toString();
SharedPreferences sp = context.getSharedPreferences("SavedSelected", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("selected", selectedItem);
editor.apply();
sp = context.getSharedPreferences("SavedSelected", Context.MODE_PRIVATE);
int myIntValue = sp.getInt("selected", -1);
Log.d("Selected", "SharedPreferences" + myIntValue);
if (selectedItem == i) {
holder.tvIcon.setBackgroundColor(Color.parseColor("#30000000"));
Intent intent = new Intent("search_engines");
intent.putExtra("url", url);
intent.putExtra("selected", selectedItem);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
} else {
holder.tvIcon.setBackgroundColor(Color.parseColor("#00000000"));
}
holder.tvIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("search_engines");
intent.putExtra("url", url);
int PreviousSelectedItem = selectedItem;
selectedItem = i;
intent.putExtra("selected", selectedItem);
holder.tvIcon.setBackgroundColor(Color.parseColor("#30000000"));
notifyItemChanged(PreviousSelectedItem);
notifyDataSetChanged();
}
});
}
// ... Other necessary functions.
}
Now the MainActivity.class
RecyclerView paramRecyclerView;
SearchEngineAdapter sEngineAdapter;
paramRecyclerView = findViewById(R.id.lvEngines);
paramRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
paramRecyclerView.setHasFixedSize(true);
Intent intent = getIntent();
int intValue = intent.getIntExtra("selected", 0);
sEngineAdapter = new SearchEngineAdapter(context, arrayList, intValue);
paramRecyclerView.setAdapter(sEngineAdapter);
// Calling network APIs to populate the arrayList.
The onResume function of the MainActivity looks like the following.
protected void onResume() {
super.onResume();
searchPlugin.setText("");
getChangeColor();
}
This is the click handler defined in MainActivity which send me to another Activity.
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = searchPlugin.getText().toString();
AddHistory(newEntry);
getFragmentRefreshListener().onRefresh();
Intent intent = new Intent(MainActivity.this, ActivitySearchEngine.class);
intent.putExtra("url", url );
intent.putExtra("name", newEntry);
intent.putExtra("selected", selectedItem2);
startActivity(intent);
}
});
And the other activity which is ActivitySearchEngine.class
public class ActivitySearchEngine extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
public String selectedName;
public int selectedID;
public String selectedSearchUrl;
RecyclerView mListView;
RecyclerView paramRecyclerView;
SearchEngineAdapter sEngineAdapter;
ArrayList<SearchEngine> arrayList = new ArrayList<>();
final Context context = this;
int selectedItem;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result);
// Variables initialization
// Setting up adapter
paramRecyclerView.setAdapter(sEngineAdapter);
sEngineAdapter.notifyDataSetChanged();
// Calling network APIs to populate the arrayList here
Intent receivedIntent = getIntent();
selectedName = receivedIntent.getStringExtra("name");
selectedID = receivedIntent.getIntExtra("id", 1); //NOTE: -1 is just the default value
selectedSearchUrl = receivedIntent.getStringExtra("url");
// Loading the url in a WebView for searching
}
}
I could share the selected item position between these two activities. However, I am not sure how to achieve the behavior of the item is being selected in the RecyclerView of the second activity as well. If I select another item in the RecyclerView of the second activity, the change should be reflected in the first (i.e. MainActivity) as well when I get back to it.
Any help would be appreciated.
There was a lot of changes in the question and hence the last update of this answer below is the final version.
As far as I could understand about the problem, I can see you are very close to the solution if I had understood correctly. The SearchEngineAdapter already has a selectedItem variable in it which can be used for highlighting the item selected in ActivitySearchEngine as well. You just have to modify the adapter a little bit like the following. I am rewriting the adapter here.
public class SearchEngineAdapter extends RecyclerView.Adapter<SearchEngineAdapter.ViewHolder> {
private int selectedItem = 0;
private static RecyclerViewClickListener itemListener;
private Context context;
ArrayList<SearchEngine> arrayList = new ArrayList<>();
// Added another argument to be passed in the constructor
public SearchEngineAdapter(Context context, ArrayList<SearchEngine> arrayList, int selectedItem) {
this.context = context;
this.arrayList = arrayList;
this.selectedItem = selectedItem;
}
#NonNull
#Override
public SearchEngineAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.s_engine_item, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int i) {
if (selectedItem == i) {
holder.tvIcon.setBackgroundColor(Color.parseColor("#30000000"));
} else {
holder.tvIcon.setBackgroundColor(Color.parseColor("#00000000"));
}
holder.tvIcon.setImageResource(arrayList.get(i).getIcon());
holder.tvId.setText(arrayList.get(i).getId());
holder.tvSearchUrl.setText(arrayList.get(i).getUrl());
holder.tvIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int PreviousSelectedItem = selectedItem;
selectedItem = i;
holder.tvIcon.setBackgroundColor(Color.parseColor("#30000000"));
notifyItemChanged(PreviousSelectedItem);
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView tvId, tvSearchUrl;
ImageView tvIcon;
public ViewHolder(#NonNull View itemView) {
super(itemView);
tvId = itemView.findViewById(R.id.ivEngineText);
tvIcon = itemView.findViewById(R.id.ivEngine);
tvSearchUrl = itemView.findViewById(R.id.ivSearchUrl);
}
}
}
Check that, I just have modified the constructor of your adapter, taking another extra variable which is selectedItem. Just pass the selected item position when you are initializing the adapter in both activities. In the default case, you can pass -1, I think you get the idea.
You have passed the selected item position to the ActivitySearchEngine as well. Which can be used for initializing for the desired behavior. Hope that helps!
Update 1:
I would like to suggest you put the following code to your onResume function in the ActivitySearchEngine class. You might consider removing the lines from the onCreate function of your code as well.
#Override
public void onResume() {
super.onResume();
Intent receivedIntent = getIntent();
selectedName = receivedIntent.getStringExtra("name");
selectedID = receivedIntent.getIntExtra("id", 1); // NOTE: -1 is just the default value
selectedSearchUrl = receivedIntent.getStringExtra("url");
sEngineAdapter = new SearchEngineAdapter(context, arrayList, selectedID);
paramRecyclerView.setAdapter(sEngineAdapter);
}
Update 2:
The RecyclerView in your MainActivity is getting reloaded as you are setting the adapter again to the RecyclerView in the onResume function. Moreover, you are trying to get data from intent which is not available here I think because you have not set any data to be sent to the MainActivity when you return back from the ActivitySearchEngine. Hence, the RecyclerView is reloading again with a fresh set of data.
You might remove the code associated with your RecyclerView from the onResume function of the MainActivity to remove this complication as I think this is not necessary. So the updated onResume function will look like the following.
protected void onResume() {
super.onResume();
searchPlugin.setText("");
getChangeColor();
}
Update 3:
Take a public static variable in your MainAcitivity and declare it as a global variable like the following.
// Setting 0 as you wanted to put the first item at the first time
// If you do not want that, then initialize with -1
public static int selectedItem = 0;
Now inside your onCreate function, remove the lines for getting the intent.
paramRecyclerView = findViewById(R.id.lvEngines);
paramRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
paramRecyclerView.setHasFixedSize(true);
// Remove the following
// Intent intent = getIntent();
// int intValue = intent.getIntExtra("selected", 0);
// Move the adapter setup to the onResume
// sEngineAdapter = new SearchEngineAdapter(context, arrayList, selectedItem);
// paramRecyclerView.setAdapter(sEngineAdapter);
// Calling network APIs to populate the arrayList.
Modify the onResume function in the MainActivity to set up the adapter there.
protected void onResume() {
super.onResume();
searchPlugin.setText("");
getChangeColor();
// Set the adapter here
sEngineAdapter = new SearchEngineAdapter(context, arrayList, selectedItem);
paramRecyclerView.setAdapter(sEngineAdapter);
}
Modify the onClickListener in your adapter like the following. Just add a new line there.
holder.tvIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("search_engines");
intent.putExtra("url", url);
int PreviousSelectedItem = selectedItem;
selectedItem = i;
// Set the static value in the MainActivity
// This can be accessed from all other classes
MainActivity.selectedItem = i;
intent.putExtra("selected", selectedItem);
holder.tvIcon.setBackgroundColor(Color.parseColor("#30000000"));
notifyItemChanged(PreviousSelectedItem);
notifyDataSetChanged();
}
});
Hope that helps!

Not an enclosing class error Android Studio

I am new in android development and do not have an in depth knowledge of Java. I am stuck on a problem for a long time. I am trying to open a new activity on button click. But I am getting an error that error: not an enclosing class: Katra_home.
Here is the code for MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn=(Button)findViewById(R.id.bhawan1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(Katra_home.this, Katra_home.class);
Katra_home.this.startActivity(myIntent);
}
});
And this is the code for Katra_home.java
public class Katra_home extends BaseActivity {
protected static final float MAX_TEXT_SCALE_DELTA = 0.3f;
private ViewPager mPager;
private NavigationAdapter mPagerAdapter;
private SlidingTabLayout mSlidingTabLayout;
private int mFlexibleSpaceHeight;
private int mTabHeight;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.katra_home);
ActionBar ab = getSupportActionBar();
if (ab != null) {
ab.setDisplayHomeAsUpEnabled(true);
ab.setHomeButtonEnabled(true);
}
Though I have seen many answers on stackoverflow but I could not understand them as I am new in android development. So I would like to ask what changes do I need to make in my code to make it work.
It should be
Intent myIntent = new Intent(this, Katra_home.class);
startActivity(myIntent);
You have to use existing activity context to start new activity, new activity is not created yet, and you cannot use its context or call methods upon it.
not an enclosing class error is thrown because of your usage of this keyword. this is a reference to the current object — the object whose method or constructor is being called. With this you can only refer to any member of the current object from within an instance method or a constructor.
Katra_home.this is invalid construct
Intent myIntent = new Intent(MainActivity.this, Katra_home.class);
startActivity(myIntent);
This Should the perfect one :)
you are calling the context of not existing activity...so just replace your code in onClick(View v) as
Intent intent=new Intent(MainActivity.this,Katra_home.class);
startActivity(intent);
it will definitely works....
String user_email = email.getText().toString().trim();
firebaseAuth
.createUserWithEmailAndPassword(user_email,user_password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
Toast.makeText(RegistraionActivity.this, "Registration sucessful", Toast.LENGTH_SHORT).show();
startActivities(new Intent(RegistraionActivity.this,MainActivity.class));
}else{
Toast.makeText(RegistraionActivity.this, "Registration failed", Toast.LENGTH_SHORT).show();
}
}
});
replace code in onClick() method with this:
Intent myIntent = new Intent(this, Katra_home.class);
startActivity(myIntent);
startActivity(new Intent(this, Katra_home.class));
try this one it will be work

taking variable from another class

I have to spinners, and when I start my app, the PHP only returns values of spinner's first choice.
First code is part of one class (IzboraGrada.java)
public void addListenerOnButton() {
spinner1=(Spinner) findViewById(R.id.spinner1);
spinner2=(Spinner) findViewById(R.id.spinner2);
button=(Button) findViewById(R.id.button);
str_grad=spinner1.getSelectedItem().toString();
str_predmet=spinner2.getSelectedItem().toString();
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent (v.getContext(), MainActivity.class);
url = "http://192.168.1.102/test/spinner.php";
url=url+"?grad="+str_grad+"&predmet="+str_predmet;
i.putExtra("URL",url);
startActivity(i);
}
});
And the second code is part of MainActivity.class that was in intent.
private void initView() {
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://192.168.1.102/test/spinner.php";
Bundle extras = getIntent().getExtras();
if (extras != null) {
url = extras.getString("URL");
}
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
I presume that's because str_grad and str_predmet are not defined in second class. But If I put str_grad and str_predmet in second class, they are can't be resolved as type.Any ideas what to do?
It looks like you are calling this method at the beginning, before an item is selected, so I think the problem is that you are setting the values for str_grad and str_predmet when they are first set so the selected item is the default item. Those are getter functions not listeners.
You need to move those lines inside the onClick() or use onItemSelected() on your Spinners to set those variable values
public void addListenerOnButton() {
spinner1=(Spinner) findViewById(R.id.spinner1);
spinner2=(Spinner) findViewById(R.id.spinner2);
button=(Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
str_grad=spinner1.getSelectedItem().toString(); // move these lines here
str_predmet=spinner2.getSelectedItem().toString();
Intent i=new Intent (v.getContext(), MainActivity.class);
url = "http://192.168.1.102/test/spinner.php";
url=url+"?grad="+str_grad+"&predmet="+str_predmet;
i.putExtra("URL",url);
startActivity(i);
}
});
If I understand your problem correctly, that should solve your problem.

Beginner Android: ListView to affect the next class

I am a beginner programmer so please bear with me. I am trying to create an app where the item in the list view affects what will be displayed in the next activity. So far, I have the list activity:
public class Primary extends ListActivity{
private static final String[] items = {"Item1", "Item2", "Item3", "item4", "Item5"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items));
TextView heading =(TextView)findViewById(R.id.listViewHeading);
heading.setText("Primary");
}
public void onListItemClick(ListView parent, View v, int position, long id){
}
and for the second activity, I have this:
public class ImageActivity extends Activity{
TextView heading;
ImageView image;
TextView text;
public static final String[] headings={"heading 1", "heading 2", "heading 3", "heading 4", "heading 5",};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_activity);
heading = (TextView)findViewById(R.id.adHeading);
image = (ImageView)findViewById(R.id.adImage);
text =(TextView)findViewById(R.id.adText);
addInfo();
}
private void addInfo() {
heading.setText(headings[x]);
image.setImageResource(images[x]);
text.setText(text[x]);
}
How can i make it so that the heading, image, and text change based on what item in the list view was selected?
In the listview Activity.
Intent i = new Intent(this, ImageActivity.class);
i.putExtra("data", data);
startActivity(i);
The next Acitivty onCreate() method.
final String data = getIntent().getStringExtra("data");
I think u want to set the heading, image and text in second activity, related to first activity's selected index in list.
just do 1 thing, put following code in 1st activity
public void onListItemClick(ListView parent, View v, int position, long id)
{
Intent intent = new Intent(this.getApplicationContext(), ImageActivity.class);
intent.putExtra("pos", position);
startActivity(intent);
}
so, now u r passing the position of item selected in list.
now, put following code in next activity
private void addInfo()
{
Bundle ext = getIntent().getExtras();
if(ext != null)
{
int pos= ext.getInteger("pos");
// ext.getInt("pos");
heading.setText(headings[pos]);
// hey, frend, you don't have any array for selecting image-name and text
// image.setImageResource(images[x]);
// text.setText(text[x]);
}
}
Use the "extras" feature that are part of an Intent.
When you call start ImageActivity from Primary, you can use a 'extras' to pass information between the two.
See this link for details.
I'll give you a basic example here. When the list item is clicked, put the data that you want ImageActivity to have into the intent using "putExtra".
Intent intent = new Intent(getBaseContext(), ImageActivity.class);
String data = "somedata";
intent.putExtra("DATA", data);
startActivity(intent)
Then, in ImageActivity onCreate, retrieve the data like this:
Bundle extras = getIntent().getExtras();
if(extras !=null) {
String data= extras.getString("DATA"); // matches the tag used in putExtra
}
Once you have retrieved the data, set the necessary views.
use below code
public void onListItemClick(ListView parent, View v, int position, long id)
{
Intent intent = new Intent(Primary.this, ImageActivity.class);
intent.putExtra("selected value", item[position]);
startActivity(intent);
}
in ImageActivity class:in oncreate (or you can put item variable as global)
String item = getIntent().getStringExtra("Selected value");

Categories