I need to setText in SecondActivity, when item is clicked, but text must be different according to item. I've got an error when item is clicked and it doesn't work. Can you tell me how to setText from First Activity to Second?
First Activity:
final String[] setP = { "P1", "P2", "P3", "P4", "P5", "P6", "P7", "P8", "P9" };
final ListAdapter theAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, setP);
final ListView theListView = (ListView) findViewById(R.id.theListView2);
theListView.setAdapter(theAdapter);
theListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String itemPicked = "Selected: " + String.valueOf(adapterView.getItemAtPosition(position));
Toast.makeText(MainActivity.this, itemPicked, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("newsId", "1");
MainActivity.this.startActivity(intent);
String chosen = String.valueOf(adapterView.getItemAtPosition(position));
if (chosen == "P1") { // doesn't work
SecondActivity.displayR.setText("EXAMPLE FOR P1");
} else if (chosen.equals("P2")) { // doesn't work
SecondActivity.displayR.setText("EXAMPLE FOR P2");
}
}
});
and SecondActivity:
public static TextView displayR;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe);
displayR = (TextView) findViewById(R.id.textR);
}
you need to put your choosen item's name in to Intent and get it's name in second activity from Intent like this:
first activity
theListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String itemPicked = "Selected: " + String.valueOf(adapterView.getItemAtPosition(position));
Toast.makeText(MainActivity.this, itemPicked, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("newsId", "1");
String chosen = String.valueOf(adapterView.getItemAtPosition(position));
if (chosen == "P1") { // doesn't work
intent.putExtra("name", "p1");
} else if (chosen.equals("P2")) { // doesn't work
intent.putExtra("name", "p2");
}
MainActivity.this.startActivity(intent);
}
});
second activity
public static TextView displayR;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe);
displayR = (TextView) findViewById(R.id.textR);
String name = getIntent().getStringExtra("name");
displayR.setText(name);
}
Related
Been trying to add a favorites system to this notes app where I can tap and hold an item in the list view to add it to another activity with a list view. Here is the activity with the first list.
Items are added via the MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.savebutton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editTextHeading = (EditText) findViewById(R.id.editTextTextPersonName);
EditText editTextContent = (EditText) findViewById(R.id.contentfield);
String heading = editTextHeading.getText().toString().trim();
String content = editTextContent.getText().toString().trim();
if (!heading.isEmpty()) {
if(!content.isEmpty()) {
try {
FileOutputStream fileOutputStream = openFileOutput(heading + ".txt", Context.MODE_PRIVATE); //heading will be the filename
fileOutputStream.write(content.getBytes());
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else {
editTextContent.setError("Content can't be empty!");
}
}else{
editTextHeading.setError("Heading can't be empty!");
}
editTextContent.setText("");
editTextHeading.setText("");
}
});
Button button2 = (Button) findViewById(R.id.btn_gotosaved);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, saved.class));
}
});
Button button3 = (Button) findViewById(R.id.btn_faves);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, favorites.class));
}
});
}
}
Items added will be viewed here
public class saved extends MainActivity {
public static final String EXTRA_MESSAGE = "com.example.notes.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved);
File files = getFilesDir();
String[] array = files.list();
ArrayList<String> arrayList = new ArrayList<>();
final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
for (String filename : array) {
filename = filename.replace(".txt", "");
System.out.println(filename);
adapter.add(filename);
}
final ListView listView = (ListView) findViewById(R.id.lv_saved);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
Intent intent = new Intent(getApplicationContext(), Note.class);
intent.putExtra(EXTRA_MESSAGE, item);
startActivity(intent);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
}
});
}
}
And tapping and holding an item from there should "favorite" it and copy it to this new activity with another listview
public class favorites extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorites);
ListView listView = (ListView) findViewById(R.id.lv_favorites);
}
}
How should I approach this?
With your implementation of creating an individual .txt file in the default directory for each note, this is how you could implement:
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
Boolean isItemFavorite = item.contains("_favorite");
if (!isItemFavorite){
File itemFile = new File(item + ".txt");
File favoriteItemFile = new File(item + "_favorite.txt");
itemFile.renameTo(favoriteItemFile);
}
}
});
Then in your "favorites" activity you could access all of your note .txt file the same as you do in your "saved" activity - just filtering out any items that don't contain "_favorite" in your "String[] array = files.list();"
Also, some tips: follow naming convention with your activities. "saved" should at least start with an uppercase letter and really should be named something like "SavedNotesListActivity". Also, you should use a room database to keep track of your notes. You should have a favorites table in your room database to keep track of all of your favorites.
I can't open a new Intent by a button but only in listview I followed a guide but it solved it listview and I need a normal click where is the problem in my code
The code only works with the listview...
buttonadd.setOnClickListener(new AdapterView.OnClickListener(){
#Override
public void onClick(AdapterView<?> parent, View view, int postition, long id){
String curentgruopname = parent.getItemAtPosition(postition).toString();
Intent groupchatintent = new Intent(MainActivity.this , buttonaddactivity.class);
groupchatintent.putExtra("groupname", curentgruopname);
startActivity(groupchatintent);
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int postition, long id) {
String curentgruopname = parent.getItemAtPosition(postition).toString();
Intent groupchatintent = new Intent(MainActivity.this , buttonaddactivity.class);
groupchatintent.putExtra("groupname", curentgruopname);
startActivity(groupchatintent);
}
});
Maybe it works when you initialize the OnClicklistener in the OnCreate Method.
Here is an Example:
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
button = findViewById(R.id.button);
button.setOnClickListener(buttonClick);
}
View.OnClickListener buttonClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(testActivity.this, nextActivity.class);
startActivity(intent);
}
};
There is something I want to ask, I have recycle view where is pass from adapter to activity, my question is :
I need to get value/data checkbox from adapter viewHolder Recycleview to activity who is use the adapter for show recycleview
CartAdapter.java
private Context mContext;
private ArrayList<CartModel> mCartList;
public boolean isSelectedAll = true;
public CartAdapter(Context context, ArrayList<CartModel> CartList){
mContext = context;
mCartList = CartList;
}
#NonNull
#Override
public CartViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(mContext).inflate(R.layout.masteritem_cardview_cart, viewGroup, false);
return new CartViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull CartViewHolder cartViewHolder, int i) {
CartModel currentItem = mCartList.get(i);
cartViewHolder.mCartCheckbox.setChecked(true); //i want pass this value
ShoppingCartActivity.java
private RecyclerView mRecyclerView;
private CartAdapter mCartAdapter;
private ArrayList<CartModel> mCartModelList;
private RequestQueue mRequestQueue;
boolean cartfirst;
private Button mButtonCheckout;
public CheckBox mCartCheckAll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_cart);
cartfirst = false;
mNavigationView = findViewById(R.id.navigation_view);
mNavigationView.setNavigationItemSelectedListener(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.cart_drawer);
mToogle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToogle);
mToogle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mRecyclerView = findViewById(R.id.recycler_view_cart);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mCartModelList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJsonCartItem();
mButtonCheckout = findViewById(R.id.checkOut_btn);
mCartCheckAll = findViewById(R.id.cartChecKall_checkBox);
//firsttime checkall
mCartCheckAll.setChecked(true);
mButtonCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(ShoppingCartActivity.this);
builder.setTitle("Confirm Checkout");
builder.setMessage("Do you really want to Checkout?");
builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
for (int i = 0; i < mCartModelList.size(); i++){
//to here, for checking value if true they will checkout, else do nothing
//checkOutChartJSON();
}
}
startActivity(new Intent(getApplicationContext(),ShoppingCartActivity.class));
finish(); //finish current activity
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}});
builder.setNegativeButton(android.R.string.no, null);
builder.create().show();
}
});
To check validation if checkbox is true they will do function checkOutChartJSON, else do nothing
If you wanna pass the data or value from an adapter to new activity then you can do it by using Intent and if you wanna pass the value to existing activity then interface is the best way to do it.
For new activity.
// Passing data to TargetActivity.class
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
intent.putExtra("message", str);
startActivity(intent);
// Get the data in TargetActivity.class
Intent intent=getIntent();
String msg = intent.getStringExtra("message");
For existing activity.
First, make an interface. OnPassingData
public interface OnPassingData {
void onPassing(int value1, String value2,...,int valueN);
}
In the adapter.
OnPassingData onPassingData;
if (onPassingData != null) {
onPassingData .onPassing(value1, value2,..,valueN);
}
public void setOnPassingData(OnPassingData onPassingData) {
this.onPassingData= onPassingData;
}
At the adapter calling in activity.
adapter.setOnPassingData((value1, value2,...,valueN) -> {
Log.i(TAG, "value1 : " + value1);
Log.i(TAG, "value2 : " + value2);
});
So i made a bunch of 4 buttons , put an intent to each of them . They all navigate to the same Fragment class . But their extras are different, so if button1 was clicked , Fragment would open and do a certain action , if button2 was clicked , Fragment would do another action and so on. I tried the code on normal activities and it worked , but in fragments its not working . It just returns me "Id is null"
Class sending the intent
public class Intennt extends ActionBarActivity {
Button bt1,bt2,bt3,bt4;
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intennt);
bt1 = (Button) findViewById(R.id.button);
bt2 = (Button) findViewById(R.id.button2);
bt3 = (Button) findViewById(R.id.button3);
bt4 = (Button) findViewById(R.id.button4);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, ItemListActivity.class);
i.putExtra(ItemDetailFragment.ID_ACTION,ItemDetailFragment.ACTION_1);
startActivity(i);
}
});
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, ItemListActivity.class);
i.putExtra(ItemDetailFragment.ID_ACTION,
ItemDetailFragment.ACTION_2);
startActivity(i);
}
});
}
Fragment receiving the intent and extras
public class ItemDetailFragment extends Fragment {
public static final int ACTION_1 = 1;
public static final int ACTION_2 = 2;
public static final int ACTION_3 = 3;
public static final int ACTION_4 = 4;
public static final int ACTION_NULL = -1;
public static final String ID_ACTION = "action_id";
public static final String ARG_ITEM_ID = "item_id";
private DummyContent.DummyItem mItem;
public ItemDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments().containsKey(ARG_ITEM_ID)) {
// Load the dummy content specified by the fragment
// arguments. In a real-world scenario, use a Loader
// to load content from a content provider.
mItem =
DummyContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));
}
int id = getActivity().getIntent().getIntExtra(ID_ACTION, -1);
if (id == ACTION_NULL) {
Log.d("TAG", "id is null");
Toast.makeText(getActivity(), "id is null!",
Toast.LENGTH_SHORT).show();
} else if (id == ACTION_1) {
Log.i("TAG", "ALLOHA! from button 1");
Toast.makeText(getActivity(), "Aloha from button 1!",
Toast.LENGTH_LONG).show();
} else if (id == ACTION_2) {
Log.i("TAG", "Hello from button 2");
Toast.makeText(getActivity(),"Hello from button 2!",
Toast.LENGTH_LONG).show();
}
else if (id == ACTION_3) {
Log.i("TAG", "Hello from button 3");
Toast.makeText(getActivity(),"Hello from button 2!",
Toast.LENGTH_LONG).show();
}
else if (id == ACTION_4) {
Log.i("TAG", "Hello from button 4");
Toast.makeText(getActivity(),"Hello from button 2!",
Toast.LENGTH_LONG).show();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_item_detail,
container, false);
return rootView;
}
}
To navigate to a fragment, you need to instantiate the fragment class then use the FragmentManager to proceed to a transaction :
FragmentClass fragment = new FragmentClass();
getFragmentManager()
.beginTransaction()
.replace(R.id.your_fragment_view, fragment)
.commit();
You can proceed to every action right in the current activity (as it stays the main activity).
public class Questions extends DialogFragment {
private static Button Submit;
public int count = 0;
public interface DialogListener {
void onQuestionsFinish(ArrayList<xmlQuestion> l);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_questions, container, false);
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
//getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Submit = (Button) rootView.findViewById(R.id.SubmitButton);
Submit.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0){
for(int i = 0; i<questionList.size(); i++)
{
questionList.get(i).setAnswer();
}
DialogListener activity = (DialogListener) getActivity();
activity.onQuestionsFinish(questionList);
Questions.this.dismiss();
}
});
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
yInch = metrics.ydpi;
pixHeight = metrics.heightPixels;
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point(); display.getSize(size);
screenWidth=size.x; screenHeight=size.y;
LinearLayout.LayoutParams bodyParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,screenHeight*900/1024);
BodyLayout.setLayoutParams(bodyParams);
WindowManager.LayoutParams wmlp = getDialog().getWindow().getAttributes();
wmlp.height=screenHeight; wmlp.width=screenWidth;
getDialog().getWindow().setAttributes(wmlp);
WindowManager.LayoutParams lp = getDialog().getWindow().getAttributes();
lp.dimAmount=0.4f;
getDialog().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
getDialog().setCanceledOnTouchOutside(true);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_FRAME, android.support.v7.appcompat.R.style.Theme_AppCompat_Light);
}
public Questions()
{
}
}
You don't have to use intents to start fragments. My main benefit for using fragments is being able to reference the data in each one much easier. You can simply create a new instance of your fragment class, and assign it's public variables. Then start it like so...
Questions q = new Questions();
q.count = 0;
q.show(getSupportFragmentManager(), "Dialog Fragment");
FirstActivity.java
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etName = (EditText) findViewById(R.id.etName);
btnOk = (Button) findViewById(R.id.btnOk);
btnOk.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Name = etName.getText().toString();
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
// Create a bundle object
intent.putExtra("NAME", Name);
startActivity(intent);
}
});
My Second Activity.java is as follows:
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
String UName;
String iName;
ListView lvName;
Button btnBack;
Bundle savedInstanceState;
#Override
protected void onCreate(Bundle b) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
b = getIntent().getExtras();
lvName = (ListView) findViewById(R.id.lvNames);
btnBack = (Button) findViewById(R.id.btnBack);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
UName=b.getString("NAME");
list.add(UName);
adapter.notifyDataSetChanged();
lvName.setAdapter(adapter);
lvName.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String item = ((TextView)view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),
ThirdActivity.class);
// Create a bundle object
intent.putExtra("ITEMNAME", item);
startActivity(intent);
}
});
btnBack.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(intent);
}
});
}
My problem is whenever I click on back button, activity is restarted. So that first item in list is overwritten by second item. I want to get the output as list(items one by one) in second activity, whatever the data I enter in first activity. How can I do this?
For example when I enter ABC in edittext its displaying the same data ABC in list.Its good.
But when I click on back button and again enter any data in edittext its not displaying the data as second item in list but it is over writing the first item.This is the thing I wanna get to be solved...
You can put all items into intent in the first activity:
intent.putStringArrayListExtra(ITEMS, list);
And then you can extract them from intent in the second activity:
List<String> items = getIntent().getStringArrayListExtra(ITEMS);
use the extends Application class
public class MyGlobal extends Application {
public ArrayList<String> selectedAppsPackageNames = new ArrayList<String>();
}
for getting this in your activity
private MyGlobal mMyGlobal = (MyGlobal) getApplicationContext();
declare in manifest inside the Application Tag(give the path)
<application
android:name="com.afbb.lockaddicted.core.MyControlList"
..............
.........
</application>
You Just have to create the global list somewhere in your app like you can create Singletone or Application Class where you have to store your username List.
In below code you have to update your arrayList in first activity and you have to get your nameList in SecondActivity
public class MySingleton
{
private static MySingleton _instance;
private ArrayList<String> nameList;
private MySingleton()
{
}
public static MySingleton getInstance()
{
if (_instance == null)
{
_instance = new MySingleton();
}
return _instance;
}
public ArrayList<String> getNameList(){
return nameList;
}
public void setNameList(ArrayList<String> nameList(){
nameList = nameList;
}
}
You can save the names in the FirstActivity to shared preferences, with an id. Then retrieve those values in the SecondActivity. Also do not forget to clear the shared preferences when you destroy your FirstActivity.
FirstActivity
public class FirstActivity extends Activity {
private EditText etName;
private Button btnOk;
private String name;
private int id = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
etName = (EditText) findViewById(R.id.etName);
btnOk = (Button) findViewById(R.id.btnOK);
btnOk.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
id++;
SharedPreferences.Editor editor = getSharedPreferences("shared_pref", MODE_PRIVATE).edit();
editor.putString(Integer.toString(id), etName.getText().toString());
editor.commit();
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
startActivity(intent);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
getSharedPreferences("shared_pref", MODE_PRIVATE).edit().clear().commit();
}
}
SecondActivity
public class SecondActivity extends Activity {
private ArrayList<String> list = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private String UName;
private String iName;
private ListView lvName;
private Button btnBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
lvName = (ListView) findViewById(R.id.lvNames);
btnBack = (Button) findViewById(R.id.btnBack);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
lvName.setAdapter(adapter);
SharedPreferences sharedPreferences = getSharedPreferences("shared_pref", MODE_PRIVATE);
Map<String,String> names = (Map<String, String>) sharedPreferences.getAll();
if(names != null){
for(String value: names.values()){
list.add(value);
}
adapter.notifyDataSetChanged();
}
btnBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
}