Class cast exception when extending ListActivity - java

I am wondering why I am getting the following logcat when I run my app and try and click on the Daily Forecast option.
Caused by: java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.ListView
HERE IS MY DAILYFORECASTACTIVITY
package com.dredaydesigns.stormy.ui;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import com.dredaydesigns.stormy.R;
import com.dredaydesigns.stormy.adapters.DayAdapter;
import com.dredaydesigns.stormy.weather.Day;
import java.util.Arrays;
public class DailyForecastActivity extends ListActivity {
private Day[] mDays;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_forecast);
Intent intent = getIntent();
Parcelable[] parcelables = intent.getParcelableArrayExtra(MainActivity.DAILY_FORECAST);
mDays = Arrays.copyOf(parcelables, parcelables.length, Day[].class);
DayAdapter adapter = new DayAdapter(this, mDays);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String dayOfTheWeek = mDays[position].getDayOfTheWeek();
String conditions = mDays[position].getSummary();
String highTemp = mDays[position].getTemperatureMax() + "";
String message = String.format("On %s the high will be %s and it will be %s", dayOfTheWeek, highTemp, conditions);
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
EDIT: SORRY FORGOT TO POST THIS!HERE IS ACTIVITY DAILY FORECAST
'package com.dredaydesigns.stormy.ui;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import com.dredaydesigns.stormy.R;
import com.dredaydesigns.stormy.adapters.DayAdapter;
import com.dredaydesigns.stormy.weather.Day;
import java.util.Arrays;
import butterknife.ButterKnife;
public class DailyForecastActivity extends ListActivity {
private Day[] mDays;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_forecast);
ButterKnife.inject(this);
Intent intent = getIntent();
Parcelable[] parcelables = intent.getParcelableArrayExtra(MainActivity.DAILY_FORECAST);
mDays = Arrays.copyOf(parcelables, parcelables.length, Day[].class);
DayAdapter adapter = new DayAdapter(this, mDays);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String dayOfTheWeek = mDays[position].getDayOfTheWeek();
String conditions = mDays[position].getSummary();
String highTemp = mDays[position].getTemperatureMax() + "";
String message = String.format("On %s the high will be %s and it will be %s", dayOfTheWeek, highTemp, conditions);
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
'
Do I need to declare the ListActivity differently?

Set the id of your ListView id as #android:id/list and then your onCreate method will be
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_forecast);
Intent intent = getIntent();
Parcelable[] parcelables = intent.getParcelableArrayExtra(MainActivity.DAILY_FORECAST);
mDays = Arrays.copyOf(parcelables, parcelables.length, Day[].class);
DayAdapter adapter = new DayAdapter(this, mDays);
setListAdapter(adapter);
}

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.

android Recycler View not showing Items but they are there

I am making a practice app for my self creating friends profile my self in my app and having their avatar as imageview and name,nickname as text view it accepts object but it never shows anything on recyclerview
Please Help!
My main activity.java
package rex.MyFriends;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.OnItemTouchListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class MainActivity extends AppCompatActivity {
FloatingActionButton btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView view = findViewById(R.id.elementsview);
btn = (FloatingActionButton) findViewById(R.id.newfbtn);
view.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
view.setAdapter(new Friendsadapter(this));
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getBaseContext(),FriendsAdder.class));
}
});
}
}
my FriendAdder activity
package rex.MyFriends;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class FriendsAdder extends AppCompatActivity {
TextView name,nickname;
Button add ,selectimage;
ImageView image;
String imgpath;
private static final int SELECT_IMAGE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.friendsadder);
name = findViewById(R.id.name);
nickname = findViewById(R.id.nickname);
add = findViewById(R.id.add);
selectimage = findViewById(R.id.selimg);
image = findViewById(R.id.disimg);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(name.toString().isEmpty() || nickname.toString().isEmpty() || image.getDrawable()==null){
Toast.makeText(getBaseContext(),"please fill every thing!",Toast.LENGTH_SHORT).show();
}
else{
FriendList.addFriend(name.toString(),nickname.toString(),imgpath);
finish();
Toast.makeText(getBaseContext(),"Friend Added!",Toast.LENGTH_SHORT).show();
}
}
});
selectimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Your Friends Avatar!"), SELECT_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==SELECT_IMAGE && resultCode== Activity.RESULT_OK){
imgpath= data.getData().getPath();
Toast.makeText(getBaseContext(),imgpath,Toast.LENGTH_LONG).show();
image.setImageURI(data.getData());
}
}
}
my adapter class
package rex.MyFriends;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
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 java.io.File;
public class Friendsadapter extends RecyclerView.Adapter<Friendsadapter.FriendsHolder> {
Context context;
public Friendsadapter(Context context) {
this.context = context;
}
#NonNull
#Override
public FriendsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.friendrow,null,false);
return new FriendsHolder(view);
}
#Override
public void onBindViewHolder(#NonNull FriendsHolder holder, int position) {
FriendList.Friend friend = (FriendList.Friend) FriendList.friendlist.get(position);
holder.nickname.setText(friend.nickname);
holder.name.setText(friend.name);
File imgFile = new File(friend.imgpath);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
holder.image.setImageBitmap(myBitmap);
}
}
#Override
public int getItemCount() {
return FriendList.friendlist.size();
}
public class FriendsHolder extends RecyclerView.ViewHolder {
TextView name,nickname;
ImageView image;
public FriendsHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
nickname = itemView.findViewById(R.id.nickname);
image = itemView.findViewById(R.id.imageView2);
}
}
}
A helper Class I made with static Array list of Friend object acting as A runtime temporary database to add and remove Friend used in adapter class to display
package rex.MyFriends;
import java.util.ArrayList;
public class FriendList {
public static ArrayList<Friend> friendlist = new ArrayList<>();
public static class Friend {
String name;
String nickname;
String imgpath ;
public Friend(String name, String nickname, String imgpath) {
this.name = name;
this.nickname = nickname;
this.imgpath = imgpath;
}
}
public static void addFriend(String name, String nickname, String imgpath){
Friend friend = new Friend(name,nickname,imgpath);
friendlist.add(friend);
}
public int getSize(){
return friendlist.size();
}
public Friend getFriend(int position){
return friendlist.get(position);
}
}
Where the RecyclerView is handled adapterName.notifyDataSetChanged (); you need to run.
In your case, the data is collected statically. The place where the data is processed is a different Activity.
After switching to the new screen and adding data, you will need to update your adapter in onResume if you want the relevant data to appear when you come back. Recyclerview will appear blank since there is no data in its initial state.
#Override
public void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}

error when startActivity

happy new year to all of you.
I am having a problem with the method onItemClickListener, because when I tried to toast the position and id ,in my second activity, I get zeros.
here is the code, I rely on the position of the image in the array that is why I need to get the position/id accurately.
+
I am duplicating my array in both activities because I don't know how to access it from the second activity?
MainActivity.java
package swe.trial;
import android.content.Context;
import android.widget.ImageView;
import android.view.View;
import android.view.ViewGroup;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.AdapterView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView items = (GridView) findViewById(R.id.itemsList);
items.setAdapter(new item_adapter(this));
items.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//if an item is clicked or selceted,then go to the activity itemDetails:
Intent i= new Intent (MainActivity.this, itemDetails.class);
i.putExtra("position", position);
i.putExtra("id", id);
startActivity(i);
}
});
}
}
class item_adapter extends BaseAdapter {
Integer[] picsId = {
R.drawable.pic1,
R.drawable.pic2,
R.drawable.pic3,
R.drawable.pic4,
R.drawable.pic5,
R.drawable.pic6,
R.drawable.pic7};
private Context context;
public item_adapter(Context context) {
this.context = context;
}
public Object getItem(int position) {
return null;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imgview= new ImageView(context);
imgview.setLayoutParams(new GridView.LayoutParams(250,250));
imgview.setScaleType(ImageView.ScaleType.CENTER_CROP);
imgview.setPadding(20,20,20,20);
imgview.setImageResource(picsId[position]);
return imgview;
}
public long getItemId(int position) {
return position;
}
public int getCount (){
return picsId.length;
}
}
itemDetails.java
package swe.trial;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;
import android.net.Uri;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by good on 1/01/17.
*/
public class itemDetails extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item);
ArrayList<item> items = new ArrayList<item>();
// items item1=
// Bundle d = getIntent().getExtras();
int id=0;getIntent().getIntExtra("id",id);
int position=0;
getIntent().getIntExtra("position", position);
Toast.makeText( this, "id= " +id + " . and posistion= "+ position, Toast.LENGTH_LONG).show();
Integer[] picsId = {
R.drawable.pic1,
R.drawable.pic2,
R.drawable.pic3,
R.drawable.pic4,
R.drawable.pic5,
R.drawable.pic6,
R.drawable.pic7
};
ImageView imgview = (ImageView) findViewById(R.id.item_image);
imgview.setImageResource(picsId[id+ 1]);
TextView txt= (TextView) findViewById(R.id.pricetxtview);
txt.setText("This is the description provided." + id);
//(id);
// item item1 = {"Red rose", "#/drawable/", 1, 1.25};
// items.add(item1);
// now i will search for the array that holds the given id. and i will retrieve its info and display it again
// in the new layout.
}
}
You misunderstand the way you should use intents.
The right form is like this :
int id =getIntent().getIntExtra("id",0);
int position = getIntent().getIntExtra("position", 0);
when you use getIntExtra , the second parameter is the default value. In case there is not such value with that tag in your intent, it will return that default value.
See Google docs for more info
You have to fetch value according the following way,
int id=0;
int position=0;
i=getIntent().getIntExtra("id",id);
position= getIntent().getIntExtra("position", position);
Toast.makeText( this, "id= " +id + " . and posistion= "+ position, Toast.LENGTH_LONG).show();

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