how to open a new activity on spinner dropdown click - java

If someone could help thx.
I have created the spinner part but now whenever I click on the dropdown I need a new activity to open. I was confused where I need to put the if else/ switch case in the Spinner.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = findViewById(R.id.spinner);
flags = findViewById(R.id.flag);
spinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item,
CountryData.countryNames));
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
flags.setImageResource(CountryData.countryflag[spinner.getSelectedItemPosition()]);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});

I think You can do it like this:
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity
{
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> activityList = new ArrayList<>(); // list of string which will be added to Spinner
activityList.add("Select Activity");
activityList.add("Activity 1");
activityList.add("Activity 2");
spinner = findViewById(R.id.spinner);
spinner.setAdapter(new ArrayAdapter<>(this,
android.R.layout.simple_spinner_dropdown_item,
activityList
));
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l)
{
Log.i("MyTag", "Item selected at position " + i);
if (i==0) // check position of selected item and open activity
{
// do nothing
}
else if (i==1)
{
openActivity(NewActivity.class);
}
else
{
openActivity(NewActivitySecond.class);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView)
{
}
});
}
private void openActivity(Class x) //funtion which opens activity
{
Intent intent = new Intent(this, x);
startActivity(intent);
}
}

Related

How can i pass the spinner value from one activity to another?

I have an android studio assignment that requires us to create 3 activities, one of these activities has a spinner and text and we must pass the text and selected spinner value from the activity to another activity to show the input I figured out how to pass the text but I can't quite figure how to do the same to the spinner. this is the spinner code.
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class Homepage<adapter> extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Button btn;
EditText et;
String st;
String selectedItem="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
btn = findViewById(R.id.Btnstart);
et = findViewById(R.id.Std_Name);
Spinner spinner = findViewById(R.id.major_spinner);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Homepage.this, Input.class);
st = et.getText().toString();
i.putExtra("Value", st);
startActivity(i);
finish();
}
});
/**
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Homepage.this, Input.class);
selectedItem = spinner.getSelectedItem().toString();
intent.putExtra("selectedItem", selectedItem);
startActivity(intent);
}
});
**/
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.majors, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String text = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
Move your text variable to the scope of the activity and pass in the Intent, like you did with your st variable.

how is onActivityResult is different from registerForActivityResult?

actually previously i wanted to pick image fromthe gallery so i came
to know that onActivityResult was deprecated and we should use
registerForActivityResult(). so i used it by defining the mime type
as "image/*" but now i want to import pdf from gallery but there is
no such mime type for that i want to understand how these mime
things works and how can i achieve my task by
registerForActivityResult() method
i also want to understand the how we define the datatype of the someActivityResultLauncher as a string ?? i want to understand how this whole things work...can we define custom mime type by our own ?? please help me in this
'''
package com.parth.iitktimes;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.card.MaterialCardView;
import java.io.IOException;
public class addBooks extends AppCompatActivity {
private MaterialCardView selectImage;
private TextView docName;
private Spinner semSpinner, branchSpinner;
private Button btnUpload;
private ActivityResultLauncher<String> someActivityResultLauncher; // why string
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_books);
selectImage = findViewById(R.id.select_image);
docName = findViewById(R.id.tvDocName);
semSpinner = findViewById(R.id.spinner_sem);
branchSpinner = findViewById(R.id.spinner_branch);
btnUpload = findViewById(R.id.btnUploadNotes);
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "uploaded notes successfully", Toast.LENGTH_SHORT).show();
}
});
selectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
someActivityResultLauncher.launch("");//what used i fill here??
}
});
String[] semesterItems = {"First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth"};
//attaching array adapter to the spinner
//since we not using custom spinner therefore we are using the default array adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, semesterItems);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
semSpinner.setAdapter(adapter);
//on item selected listener to the spinner
semSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
imageCategory = eventSpinner.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
//setting the default category as others
imageCategory = spinnerItems[0];
}
});
String[] branchItems = {"Mchanical", "Electrical", "CSE", "MTH"};
//attaching array adapter to the spinner
//since we not using custom spinner therefore we are using the default array adapter
ArrayAdapter<String> branchAdapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, branchItems);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
branchSpinner.setAdapter(adapter);
//on item selected listener to the spinner
branchSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
imageCategory = eventSpinner.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
//setting the default category as others
imageCategory = spinnerItems[0];
}
});
//activity result launcher
someActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.GetContent(), new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri result) {
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), result);
} catch (IOException e) {
e.printStackTrace();
}
preview_events_image.setImageBitmap(bitmap);
}
});
}
}

Clicked list item into a String and transported to another activity

I have made this app where in one particular activity i have a all the items listed in a list view. when you click the list item it goes to another activity where similar thing is happening. after that i was the clicked list items to be converted into a strings and transported into a 3rd activity where i can display those.
when i try to display them this shows in the text view where the clicked text item should have appeared:
this is code for the first activity:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.internal.Objects;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class TicketCategory extends AppCompatActivity {
public static String Category;
public String getCategory() {
return Category;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ticket_category);
populateTicketCategoryList();
final ListView listView = (ListView) findViewById(R.id.lvTicketCategory);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (i == 0) {
Category = listView.getItemAtPosition(i).toString();
Intent intent = new Intent(TicketCategory.this, Subcategory.class);
startActivity(intent);
}
}
});
}
private void populateTicketCategoryList()
{
ArrayList<CompTicketCategory> arrayOfTicket = CompTicketCategory.getTicket();
CompTicketCategoryAdapter adapter = new CompTicketCategoryAdapter(this, arrayOfTicket);
ListView listView = (ListView) findViewById(R.id.lvTicketCategory);
listView.setAdapter(adapter);
}
}
the code for the second activity is:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class Subcategory extends AppCompatActivity {
public String Category;
public static String Subcat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subcategory);
populateSubcategoryList();
final ListView listView = (ListView) findViewById(R.id.lvSubcategory);
ArrayAdapter arrayAdapter = new ArrayAdapter<String>(Subcategory.this, android.R.layout.simple_list_item_1,arrayList);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Subcat = listView.getItemAtPosition(i).toString();
Intent intent = new Intent(Subcategory.this, SubmitTicket.class);
startActivity(intent);
}
});
and this is the code for the activity where both of the clicked items should be displayed:
public class SubmitTicket extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_submit_ticket);
Spinner spinner = (Spinner) findViewById(R.id.spinner_priority);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.priority_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final Button butt = findViewById(R.id.submit);
butt.setOnClickListener(new View.OnClickListener()
{
public void onClick (View view){
Toast.makeText(getApplicationContext(), "The ticket has been submitted", Toast.LENGTH_SHORT).show();
}
});
TextView textView = (TextView)findViewById(R.id.Category_submit_report);
textView.setText(TicketCategory.Category);
TextView tv = (TextView)findViewById(R.id.Subcategory_submit_report);
tv.setText(Subcategory.Subcat);
}
Please help me. i would appreciate any output. thanks!
UPDATE:
after trying
CompTicketCategory model = listView.getItemAtPosition(i);
Category=model.Category; // your Category variable
Category=model.getCategory();
this error is shown;
screenshot
You can use Intent Extra Feature.
In the First Activity,
Intent intent = new Intent(Subcategory.this, SubmitTicket.class);
switch1.putExtra("deviceID", listView.getItemAtPosition(i).toString(););
startActivity(intent);
Then Next activity recall them,
Intent intent = getIntent();
String data = intent.getStringExtra("data");
Try this in your TicketCategory actvity
Use this:
CompSubcategory model = listView.getItemAtPosition(i);
Category=model.Category; // your Category variable
Category=model.getCategory(); // or use getter setter method
Instead of this:
Category = listView.getItemAtPosition(i).toString();

Update List View When Clicked on RecycleView Item

I created a listView which is updated on click on item in Reycleview within same page.
Date fetch is working,json data is getting and updated in adpater,but new items is extended with previous data in listview
Layout
First row is RecycleView and Below is Listview, Listview should be update when click on item above in recycleview
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.sharanjit.fitness.R;
import com.google.gson.JsonArray;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
public class AllExercise extends AppCompatActivity {
ListView list;
ProgressDialog dialog;
Context context;
GetJSONData getJSONData;
String[] name = {"Abdominals","Arms","Back","Chest","Shoulders","Legs","Cardio"};
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
AllExerciseAdapter adapter;
ArrayList<Exercise> arrayList;
boolean first=true;
int pos=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.allexercises);
dialog=new ProgressDialog(this);
context=getApplicationContext();
getJSONData=new GetJSONData();
arrayList=new ArrayList<>();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mRecyclerView = (RecyclerView) findViewById(R.id.recycle);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyAdapter();
mRecyclerView.setAdapter(mAdapter);
new FetchData().execute();
list = (ListView) findViewById(R.id.exercise_list);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent=new Intent(AllExercise.this,ExerciseView.class);
startActivity(intent);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if(id==16908332)
{
finish();
}
return super.onOptionsItemSelected(item);
}
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public ViewHolder(View v) {
super(v);
imageView = (ImageView)v.findViewById(R.id.imageView11);
}
}
public MyAdapter() {
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.exercise_item, parent, false);
final ViewHolder vh = new ViewHolder(v);
vh.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pos=vh.getAdapterPosition();
first=false;
new FetchData().execute();
}
});
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final ViewHolder viewHolder=holder;
viewHolder.imageView.setImageResource(Constants.exercise_images[position]);
}
#Override
public int getItemCount() {
return 7;
}
}
public class AllExerciseAdapter extends ArrayAdapter {
final private Context cx;
final private int pos;
AllExerciseAdapter(Context cx,int pos) {
super(cx, R.layout.allexercise_list_item, arrayList);
this.cx = cx;
this.pos=pos;
}
#Override
public View getView(int position, View vw, ViewGroup group) {
vw = View.inflate(cx, R.layout.allexercise_list_item, null);
ImageView imageView=(ImageView)vw.findViewById(R.id.imageView11);
TextView title=(TextView)vw.findViewById(R.id.textView14);
TextView cat=(TextView)vw.findViewById(R.id.textView13);
title.setText(arrayList.get(position).names);
cat.setText(arrayList.get(position).category);
if(position==0)
Log.e("MS",title.getText().toString());
return vw;
}
}
private class FetchData extends AsyncTask<String,String,String>
{
String url="";
String data="";
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("In Progress...");
dialog.setCancelable(false);
dialog.show();
url="http://www.searchdata.in/fitness/get-exercises.php";
try {
data = URLEncoder.encode("category", "UTF-8") + "=" + URLEncoder.encode(name[pos], "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(String... params) {
String s= getJSONData.getData(url,data);
return s;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("sss",s);
try {
JSONArray array=new JSONArray(s);
for(int i=0;i<array.length();i++)
{
JSONObject object=array.getJSONObject(i);
Exercise exercise=new Exercise();
exercise.names=object.getString("name");
exercise.category=object.getString("category");
exercise.decription=object.getString("description");
arrayList.add(exercise);
}
dialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("ss",""+first);
adapter = new AllExerciseAdapter(context,pos);
if(!first) {
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
else {
list.setAdapter(adapter);
}
}
}
private class Exercise
{
public String names;
public String decription;
public String category;
public String imagePath;
}
}
Just Change your onPostExecute method by below code.
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("sss",s);
try {
arrayList=new ArrayList<>();
JSONArray array=new JSONArray(s);
for(int i=0;i<array.length();i++)
{
JSONObject object=array.getJSONObject(i);
Exercise exercise=new Exercise();
exercise.names=object.getString("name");
exercise.category=object.getString("category");
exercise.decription=object.getString("description");
arrayList.add(exercise);
}
dialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("ss",""+first);
adapter = new AllExerciseAdapter(context,pos);
list.setAdapter(adapter);
/*if(!first)
{
adapter.notifyDataSetChanged();
}
else {
list.setAdapter(adapter);
}*/
}
You need to make a small change in your code -
if(!first) {
list.setAdapter(adapter);
adapter.notifyDataSetChanged(); // No needed to do for first time
}
else {
list.setAdapter(adapter); // Need to call only once.
adapter.notifyDataSetChanged();// Here you need to call it to reflect changes
}
One more change you need to do in onPostExecute -
try {
JSONArray array=new JSONArray(s);
arraList.clear(); //Add this line
for(int i=0;i<array.length();i++)
Hope it will help :)
This Line Is working for the code:-
adapter = new AllExerciseAdapter(context,arrayList);
adapter.setNotifyOnChange(true); // <-----
list.setAdapter(adapter);

Multiple markers at this line - Syntax error on tokens, Annotation Name expected

Multiple markers at this line
- position cannot be resolved to a variable
- Cannot refer to a non-final variable items inside an inner class defined in a different method
int multiple=0;
ImageView imageView;
TextView tot_calories;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.items_details);
Spinner mspin=(Spinner) findViewById(R.id.spinner1);
Integer[] items = new Integer[]{1,2,3,4};
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this,android.R.layout.simple_spinner_item, items);
mspin.setAdapter(adapter);
TextView name_select=(TextView)findViewById(R.id.SelectedName);
name_select.setText(constant.food_items[constant.SelectedIndex]);
imageView =(ImageView) findViewById(R.id.imagedetail);
UpdateImage(constant.food_items[constant.SelectedIndex]);
TextView calories=(TextView)findViewById(R.id.calories111);
calories.setText(constant.food_calories[constant.index]+"");
tot_calories=(TextView)findViewById(R.id.caloriestotal);
mspin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
// Your code here
multiple=items[position]*constant.food_calories[constant.index];
}
public void onNothingSelected(AdapterView<?> adapterView) {
return;
}
});
tot_calories.setText(""+multiple);
}
Update this line of code with this:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
public class itemsdetail extends Activity {
int multiple=0;
ImageView imageView;
TextView tot_calories;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.items_details);
Spinner mspin=(Spinner) findViewById(R.id.spinner1);
Integer[] items = new Integer[]{1,2,3,4};
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this,android.R.layout.simple_spinner_item, items);
mspin.setAdapter(adapter);
TextView name_select=(TextView)findViewById(R.id.SelectedName);
name_select.setText(constant.food_items[constant.SelectedIndex]);
imageView =(ImageView) findViewById(R.id.imagedetail);
UpdateImage(constant.food_items[constant.SelectedIndex]);
TextView calories=(TextView)findViewById(R.id.calories111);
calories.setText(constant.food_calories[constant.index]+"");
tot_calories=(TextView)findViewById(R.id.caloriestotal);
mspin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
// Your code here
multiple=items[position]*constant.food_calories[constant.index];
}
public void onNothingSelected(AdapterView<?> adapterView) {
return;
}
});
tot_calories.setText(""+multiple);
}
}
Goodluck!

Categories