How to update(refresh) ListView Widget from Activity? - java

package com.example.ss.new_my_wid;
import android.app.Activity;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;
public class ItemChanging extends Activity implements View.OnClickListener, View.OnKeyListener
{
EditText EdT;
Button btn_OK;
Button btn_Cancel;
Button btn_Delete;
Intent intent;
String str, changed_text;
Toast tst;
final static String CURRENT_TEXT_IN_ITEM = "current_text_in_item";
final static String POSITION = "position";
public ItemChanging() {
super();
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.type_to_item);
EdT = (EditText) findViewById(R.id.editText);
intent = getIntent();
str = intent.getStringExtra(CURRENT_TEXT_IN_ITEM);
EdT.setText(str, TextView.BufferType.EDITABLE);
btn_OK = (Button)findViewById(R.id.but_OK);
btn_Cancel = (Button) findViewById(R.id.but_Cancel);
btn_Delete = (Button) findViewById(R.id.but_Del);
btn_OK.setOnClickListener(this);
btn_Cancel.setOnClickListener(this);
btn_Delete.setOnClickListener(this);
EdT.setOnKeyListener(this);
}
#Override
public void onClick(View v)
{
int pos = intent.getIntExtra(POSITION,0);
switch (v.getId())
{
case R.id.but_OK:
changed_text = EdT.getText().toString();
MyFactory.data.set(pos, changed_text);
/*HERE need update of ListView*/
tst = Toast.makeText(this, changed_text, Toast.LENGTH_SHORT);
tst.show();
finish();
break;
case R.id.but_Cancel:
finish();
break;
case R.id.but_Del:
MyFactory.data.remove(pos);
MyFactory.data.add("");
finish();
break;
}
}
#Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
return false;
}
}
I have widget with ListView and activity with button. In activity I change an item in the ListView. When I click on the button changes are saved in ListView, but I dont know how to update the listView and the widget from activit.How can I do this?
P.S. sorry for my english =)

Call notifyDataSetChanged() on your Adapter object once you've modified the data in that adapter.
How to refresh Android listview?

When ever you Made changes in your listview's data then you need to notify your adapter with new data
you can do it by calling notifyDataSetChanged(); method on your adaptor
for examlple
adapter.notifyDataSetChanged();

Related

(Android) When Back pressed, Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference

I've been working on a Android Project (A Basic College Information App), I have three main activities, the user goes in like, Goal/Course Select activity-> CollegeList activity-> College Details Activity. Now When I press back on College Details Activity it crashes with this Error:
Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
Below are the files/code which I think might be responsible for this.....
CollegeListActivity.java file
package com.anurag.college_information.activities;
import static com.anurag.college_information.activities.CareerGoalActivity.GOAL;
import static com.anurag.college_information.activities.CareerGoalActivity.SHARED_PREFS;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.anurag.college_information.R;
import com.anurag.college_information.adapters.RecyclerAdapter;
import com.anurag.college_information.models.ModelClass;
import java.util.ArrayList;
import java.util.List;
public class CollegeListActivity extends AppCompatActivity {
private RecyclerAdapter.RecyclerViewClickListener listener;
//ListView collegeList;
TextView collegeListTitle;
Button courseChange;
RecyclerView recyclerView;
LinearLayoutManager LayoutManager;
RecyclerAdapter recyclerAdapter;
List<ModelClass> cList;
String courseName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_college_list);
collegeListTitle = findViewById(R.id.college_list_title);
courseChange = findViewById(R.id.btn_change_course);
//collegeListTitle.setText(goal + "Colleges");
collegeListTitle.setText(getIntent().getStringExtra("Title") + " Colleges");
initData();
initRecyclerView();
//collegeList = findViewById(R.id.lv_college_list);
courseChange.setTransformationMethod(null);
courseChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
Intent i = new Intent(CollegeListActivity.this, CareerGoalActivity.class);
startActivity(i);
//finish();
}
});
}
private void initData() {
cList = new ArrayList<>();
courseName = getIntent().getStringExtra("Title");
switch (courseName) {
case "BE/BTech":
cList.add(new ModelClass("https://images.static-collegedunia.com/public/college_data/images/campusimage/1479294300b-5.jpg", "A.P. Shah College of Engineering", "Thane", "8.0"));
break;
case "Pharmacy":
cList.add(new ModelClass("https://images.static-collegedunia.com/public/college_data/images/campusimage/14382400753.jpg", "Bombay College Of Pharmacy", "Mumbai", "9.0"));
break;
}
}
private void initRecyclerView() {
setOnClickListener();
recyclerView = findViewById(R.id.recycler_view);
LayoutManager = new LinearLayoutManager(this);
LayoutManager.setOrientation(RecyclerView.VERTICAL);
recyclerView.setLayoutManager(LayoutManager);
recyclerAdapter = new RecyclerAdapter(cList, listener);
recyclerView.setAdapter(recyclerAdapter);
}
private void setOnClickListener() {
listener = new RecyclerAdapter.RecyclerViewClickListener() {
#Override
public void onClick(View v, int position) {
Intent i = new Intent(CollegeListActivity.this, CollegeDetailsActivity.class);
startActivity(i);
}
};
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
RecyclerAdapter.java
package com.anurag.college_information.adapters;
import android.content.Context;
import android.content.Intent;
import android.telecom.Call;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.anurag.college_information.activities.CollegeDetailsActivity;
import com.anurag.college_information.models.ModelClass;
import com.anurag.college_information.R;
import com.squareup.picasso.Picasso;
import java.util.List;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private List<ModelClass> collegeList ;
private RecyclerViewClickListener listener;
List<String> imageUrl, collegeName, collegeLocation, collegeRating;
public RecyclerAdapter(List<ModelClass> collegeList, RecyclerViewClickListener listener){
this.collegeList=collegeList;
this.listener = listener;
}
#NonNull
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.college_list_single_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerAdapter.ViewHolder holder, int position) {
String imageLink = collegeList.get(position).getImageLink();
//int img = collegeList.get(position).getCollegeImage();
String cName = collegeList.get(position).getCollegeName();
String cRating = collegeList.get(position).getCollegeRating();
String cLocation = collegeList.get(position).getLocation();
Picasso.get().load(imageLink).into(holder.imageView);
//holder.setData(img, cName, cRating);
holder.setData(imageLink, cName, cLocation ,cRating);
}
#Override
public int getItemCount() {
return collegeList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView imageView;
private TextView collegeName, collegeRating, collegeLocation;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.college_image);
collegeName = itemView.findViewById(R.id.college_name);
collegeRating = itemView.findViewById(R.id.college_rating);
collegeLocation = itemView.findViewById(R.id.college_location);
itemView.setOnClickListener(this);
}
public void setData(String imageLink, String cName, String cLocation, String cRating) {
//imageView.setImageResource(img);
Picasso.get().load(imageLink).error(R.drawable.error).into(imageView);
collegeName.setText(cName);
collegeRating.setText(cRating);
collegeLocation.setText(cLocation);
}
#Override
public void onClick(View v) {
listener.onClick(v, getAdapterPosition());
Intent i = new Intent(v.getContext(), CollegeDetailsActivity.class);
i.putExtra("collegeImage", collegeList.get(getAdapterPosition()).getImageLink());
i.putExtra("collegeName", collegeList.get(getAdapterPosition()).getCollegeName());
i.putExtra("collegeRating", collegeList.get(getAdapterPosition()).getCollegeRating());
i.putExtra("collegeLocation", collegeList.get(getAdapterPosition()).getLocation());
v.getContext().startActivity(i);
}
}
public interface RecyclerViewClickListener{
void onClick(View v, int position);
}
}
CollegeDetailsActivity.java
package com.anurag.college_information.activities;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.anurag.college_information.R;
import com.squareup.picasso.Picasso;
public class CollegeDetailsActivity extends AppCompatActivity {
Button btnApply;
ImageView dCollegeImage;
TextView dCollegeName, dCollegeRating, dCollegeLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_college_details);
dCollegeImage = findViewById(R.id.details_college_image);
dCollegeName = findViewById(R.id.details_college_name);
dCollegeRating = findViewById(R.id.details_college_rating);
dCollegeLocation = findViewById(R.id.details_college_location);
btnApply = findViewById(R.id.btn_apply);
Intent i = getIntent();
String cn = i.getStringExtra("collegeName");
String cr = i.getStringExtra("collegeRating");
String ci = i.getStringExtra("collegeImage");
String cl = i.getStringExtra("collegeLocation");
Picasso.get().load(ci).error(R.drawable.error).into(dCollegeImage);
dCollegeName.setText(cn);
dCollegeRating.setText(cr);
dCollegeLocation.setText(cl);
btnApply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "The institute will be notified, of your application", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "The college will contact you, Thank you", Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onBackPressed() {
Intent i = new Intent(CollegeDetailsActivity.this, CollegeListActivity.class);
startActivity(i);
}
}
This is the Error Screenshot:
I'm pretty new to android I've just worked on just 4 to 5 projects,
Any Assistance will be appreciated, Thank You
The commented Out code, is just a normal listview I implemented just In Case, I have to remove the recycler view.
This will probably go away if you don't override onBackPressed in CollegeDetailsActivity. Instead of going back to an activity that had a valid "Title" string extra, the code you posted will go to a new activity where "Title" isn't defined, then get a NullPointerException since courseName will be null in initData (which the error message tells you results in an error on line 81 in that method). Using a null string in a switch results in that type of error
Just remove your onBackPressed entirely in CollegeDetailsActivity.

Firebase Realtime Database Recycler View onclick. Passing image from first activity recycler view to another

I'm trying to pass images from a Realtime Database Recycler View to another activity.
First activity
package com.khumomashapa.notes.activities;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.khumomashapa.notes.R;
import com.khumomashapa.notes.adapter.RecyclerAdapter;
import com.khumomashapa.notes.Messages;
import com.khumomashapa.notes.interfaces.RecyclerTouchListener;
import java.util.ArrayList;
public class StoreActivity extends AppCompatActivity {
// Widget
RecyclerView recyclerView;
//Firebase
private DatabaseReference mref;
// Variable
private ArrayList<Messages> messagesList;
private RecyclerAdapter recyclerAdapter;
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_store);
recyclerView = findViewById(R.id.products_view);
GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext()
,recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
Intent intent = new Intent(getBaseContext(), PreviewActivity.class);
intent.putExtra("images", position);
startActivity(intent);
Messages messages = messagesList.get(position);
Toast.makeText(StoreActivity.this, "You have selected: "+ messages.getTitle(), Toast.LENGTH_SHORT).show();
}
#Override
public void onLongClick(View view, int position) {
}
#Override
public void onButtonClicks(View view, int position) {
}
})
);
// Firebase
mref = FirebaseDatabase.getInstance().getReference();
// Arraylist
messagesList = new ArrayList<Messages>();
// Clear arraylist
ClearAll();
// Get data Method
GetDataFromFirebase();
}
private void GetDataFromFirebase(){
Query query = mref.child("Wallpapers");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
ClearAll();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Messages messages = new Messages();
messages.setImage(snapshot.child("image").getValue().toString());
messages.setTitle(snapshot.child("title").getValue().toString());
messagesList.add(messages);
}
recyclerAdapter = new RecyclerAdapter(getApplicationContext(), messagesList);
recyclerView.setAdapter(recyclerAdapter);
recyclerAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void ClearAll(){
if(messagesList != null){
messagesList.clear();
if (recyclerAdapter !=null){
recyclerAdapter.notifyDataSetChanged();
}
}
messagesList = new ArrayList<Messages>();
}
}
This is the first activity layout
The activity I want the images to be displayed in.
package com.khumomashapa.notes.activities;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.khumomashapa.notes.R;
import com.squareup.picasso.Picasso;
public class PreviewActivity extends AppCompatActivity {
private ImageView preview;
Button purchaseBtn;
Button downloadBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preview);
preview = findViewById(R.id.ImagePreview);
purchaseBtn = findViewById(R.id.PurchaseBtn);
downloadBtn = findViewById(R.id.DownloadBtn);
String preview = getIntent().getStringExtra("images");
}
}
This is the second activities layout
As you can see there's no image showing up in the imageview.
This code does work. It does take the user to another activity, but it doesn't show the image that was clicked in the first activity and as you can see I have more than one image I want to show. The image that was clicked must be shown in the next activity.
So in short what I want to happen is:
Someone clicks an image e.g. Abduction, Blue Cinema etc.
Then the user is taken to another activity and is shown the image they clicked(Abduction or Blue Cinema etc).
Sorry if I sound redundant, but I've been stuck on this for awhile and the tutorials/posts I read before didn't help, because they don't use code that works with Firebase Realtime Database.

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();

onActivityResult() Errors

Can anyone clearly explain why onActivityResult is producing the following errorsAnnotations are not allowed here
“;” expected
Operator ‘==‘ cannot be applied to ‘int’, ‘null’
cannot resolve method ‘getExtras()’
cannot resolve symbol ‘ACTION_CALL’
cannot resolve symbol ‘ACTION_VIEW’
Also can you explain how to fix it. Thank you.
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import static android.R.attr.data;
public class ContactIntentActivity extends AppCompatActivity {
private final int PHONE = 0;
private final int WEBSITE = 1;
private ListView intentListView;
private ArrayAdapter<String> adapter;
private List<ContactObject> contactsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_intent);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// inflate my view
setContentView(R.layout.activity_contact_intent);
intentListView = (ListView) findViewById(R.id.listView1);
// initialize the list and add item
contactsList = new ArrayList<>();
contactsList.add(new ContactObject("Android One", "111-111-1111", "www.naruto.com"));
contactsList.add(new ContactObject("Android Two", "222-222-2222", "www.naruto.com"));
contactsList.add(new ContactObject("Android Three", "333-333-3333", "www.naruto.com"));
contactsList.add(new ContactObject("Android Four", "444-444-4444", "www.naruto.com"));
List<String> listName = new ArrayList<>();
for (int i = 0; i < contactsList.size(); i++) {
listName.add(contactsList.get(i).getName());
}
// initialize the ArrayAdapter object
adapter = new ArrayAdapter<>(ContactIntentActivity.this, android.R.layout.simple_list_item_1, listName);
// set the adapter of the ListView
intentListView.setAdapter(adapter);
// setonclicklistener in adapterview cannot be applied here. changed to setonItemClickListener
intentListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(ContactIntentActivity.this, ContactPageActivity.class);
i.putExtra("Object", contactsList.get(position));
startActivityForResult(i, 0);
}
});
#Override
protected void onActivityResult ( int requestCode, int resultCode, Intent data)
{
if (data == null) {
return;
}
Bundle resultData = data.getExtras();
String value = resultData.getString("value");
switch (resultCode) {
case PHONE:
//Implicit intent to make a call
startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + value)));
break;
case WEBSITE:
//Implicit intent to visit website
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://" + value)));
break;
}
}
}
Close your onCreate funtion: Add a } before your last #Override annotation.

How do I use setResult when returning from an activity?

I need help, I am making a simple application, and I don´t know how to return to the MainActivity the string from the spinner and the name of the person when i click in the "Aceptar" button.
MainActivity.java
package com.example.holaamigos;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
public final static String EXTRA_SALUDO = "com.example.holaamigos.SALUDO";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText txtNombre = (EditText)findViewById(R.id.TxtNombre);
final Button btnHola = (Button)findViewById(R.id.BtnHola);
final CheckBox checkbox1 =(CheckBox)findViewById(R.id.checkBox1);
checkbox1.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton arg0,
boolean checked) {
if (checked)
{
Toast.makeText(checkbox1.getContext(), "Activo", Toast.LENGTH_LONG).show();
btnHola.setVisibility(0);
btnHola.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ActivitySaludo.class);
String saludo = txtNombre.getText().toString();
intent.putExtra(EXTRA_SALUDO, saludo);
startActivity(intent);
}
});
}
else
{
Toast.makeText(checkbox1.getContext(), "Inactivo", Toast.LENGTH_SHORT).show();
btnHola.setVisibility(View.INVISIBLE);
}
}
});
}
public void HobbyReturn(int requestcode, int resultadocode, Intent data) {
if (resultadocode == ActivitySaludo.ACEPTAR_OK); {
String string = data.getStringExtra(ActivitySaludo.ACEPTAR_OK);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
ActivitySaludo
package com.example.holaamigos;
import com.example.holaamigos.R.string;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class ActivitySaludo extends Activity {
public static final String ACEPTAR_OK = "com.example.holaamigos.ACEPTAR_OK";
String myspinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saludo);
Intent intent = getIntent();
String saludo = intent.getStringExtra(MainActivity.EXTRA_SALUDO);
TextView txtCambiado = (TextView) findViewById(R.id.TxtSaludo);
txtCambiado.setText(getString(R.string.hola_saludo) + " " + saludo);
final Spinner spinner = (Spinner)findViewById(R.id.SpinnerSaludo);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.hobby, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener () {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
parent.getItemAtPosition(pos);
myspinner = spinner.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
//another call
}
});
final Button BtnAceptar=(Button) findViewById(R.id.buttonAceptar);
BtnAceptar.setOnClickListener(new OnClickListener (){
#Override
public void onClick(View v) {
Intent iboton = new Intent();
iboton.putExtra("HOBBY", myspinner);
setResult(ACEPTAR_OK, iboton);
finish();
}
});
}
}
You need to start your second activity with the flag that you are waiting for a result, so instead of startActivity you need to make use of startActivityForResult.
If you need a little bit more information take a look at this tutorial it should cover all you need to get things working.

Categories