I have an activity where I am adding objects into an ArrayList which implements the Parcelable interface. I then pass this list to another activity via a bundle however I get the following error when I try to print the size of the list in the new activity:
java.lang.RuntimeException: Unable to resume activity {com.example.test/com.example.test.SectionsActivity}: java.lang.NullPointerException
Here is the first activity where I add to list:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getApplicationContext(), l.getItemAtPosition(position).toString() + " added to order", Toast.LENGTH_SHORT).show();
// add clicked item to orderData....
MenuItem m = (MenuItem) l.getItemAtPosition(position);
// create new item
orderData.add(m);
subTotal += m.getPrice();
calc();
}
This is first activity where I send the data via intent:
confirmBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
b.putParcelable("order", orderData);
Intent i = new Intent(v.getContext(), SectionsActivity.class);
i.putExtra("data",b);
startActivity(i);
}
});
and this is second activity where I try to retrieve the bundle and display size:
#Override
protected void onResume() {
super.onResume();
getIntentData();
}
public void getIntentData(){
Intent i = getIntent();
if(i != null & i.hasExtra("data")){
Toast.makeText(this.getApplicationContext(), "recieved", Toast.LENGTH_LONG).show();
b = i.getExtras();
orderData = b.getParcelable("order");
int size = orderData.size();
Toast.makeText(this.getApplicationContext(), String.valueOf(size), Toast.LENGTH_LONG).show();
}
}
Any ideas why I am getting the null pointer?? It's driving me mad!
orderData is a MenuItemList object:
public class MenuItemList extends ArrayList <MenuItem> implements Parcelable{
/**
*
*/
private static final long serialVersionUID = 2998684930374219271L;
public MenuItemList(){
}
public static final Parcelable.Creator<MenuItemList> CREATOR = new Parcelable.Creator<MenuItemList>() {
#Override
public MenuItemList createFromParcel(Parcel source) {
return new MenuItemList(source);
}
#Override
public MenuItemList[] newArray(int size) {
return new MenuItemList[size];
}
};
public MenuItemList(Parcel source) {
readFromParcel(source);
}
private void readFromParcel(Parcel source) {
this.clear();
//read the size of the list
int size = source.readInt();
//Remember order of items written into the Parcel. Important here.
for(int i = 0; i < size; i ++){
MenuItem item = new MenuItem();
item.setName(source.readString());
item.setPrice(source.readDouble());
this.add(item);
}
}
#Override
public void writeToParcel(Parcel dest, int flags) {
int size = this.size();
dest.writeInt(size);
for(int i = 0; i < size; i ++){
MenuItem item = this.get(i);
dest.writeString(item.getName());
dest.writeDouble(item.getPrice());
}
}
#Override
public int describeContents() {
return 0;
}
}
CHANGES TO CODE THAT SOLVED PROBLEM:
CHANGED onClick(View v):
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), SectionsActivity.class);
i.putExtra("data", (ArrayList<MenuItem>)orderData);
startActivity(i);
}
CHANGED getIntent():
public void getIntentData(){
Intent i = getIntent();
if(i != null && i.hasExtra("data")){
Toast.makeText(this.getApplicationContext(), "recieved", Toast.LENGTH_LONG).show();
orderData = i.getParcelableExtra("data");
int size = orderData.size();
Toast.makeText(this.getApplicationContext(), String.valueOf(size), Toast.LENGTH_LONG).show();
}
}
Rewrite
The problem is that you have an extra Bundle. Currently in getIntentData() you have to call:
getIntent() // Fetch the Intent,
.getExtras() // Fetch the Bundle of extras,
.getBundle("data") // Fetch the Bundle "data",
.getParcelable("order"); // Then get your parcelable...
Let's cut out the unnecessary Bundle.
public void onClick(View v) {
Intent i = new Intent(v.getContext(), SectionsActivity.class);
i.putExtra("data", orderData);
startActivity(i);
}
Now update getIntentData():
Intent i = getIntent();
if(i != null && i.hasExtra("data")){
orderData = i.getParcelableExtra("data");
...
}
Unless I missed something, you are using the bitwise & instead of the logical && in your getIntentData() function
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
In my application I want get some list from server, and show this list into ChipCloud. ChipCloud has Tag library. Library Link : https://github.com/adroitandroid/ChipCloud
.I write below code but when run application when click on items show me below error :
java.lang.IndexOutOfBoundsException: Invalid index 11, size is 6
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.example.com.Activities.FullSearchMini$2$5.chipSelected(FullSearchMini.java:286)
at com.adroitandroid.chipcloud.ChipCloud.chipSelected(ChipCloud.java:253)
at com.adroitandroid.chipcloud.Chip.onClick(Chip.java:138)
at android.view.View.performClick(View.java:4764)
at android.view.View$PerformClick.run(View.java:19844)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5349)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
My Codes :
public class FullSearchMini extends AppCompatActivity {
#BindView(R.id.miniFullSearch_toolbarText)
EditText fullSearchMini_headerText;
#BindView(R.id.fullSearchMini_celebritiesRecyclerView)
RecyclerView fullSearchMini_celebritiesRecyclerView;
#BindView(R.id.miniFullSearch_movieRecyclerView)
RecyclerView miniFullSearch_movieRecyclerView;
#BindView(R.id.miniFullSearch_SeriesRecyclerView)
RecyclerView miniFullSearch_SeriesRecyclerView;
#BindView(R.id.miniFullSearch_UserRecyclerView)
RecyclerView miniFullSearch_UserRecyclerView;
#BindViews({R.id.fullSearchMini_celebritiesHeaderLay, R.id.miniFullSearch_movieHeaderLay, R.id.miniFullSearch_SeriesHeaderLay,
R.id.miniFullSearch_UserHeaderLay})
List<RelativeLayout> miniSearchLayouts;
#BindViews({R.id.celebritiesLine, R.id.moviesLine, R.id.SeriesLine})
List<RelativeLayout> miniSearchLines;
#BindView(R.id.fullSearchMini_didYouMeanLay)
RelativeLayout fullSearchMini_didYouMeanLay;
#BindView(R.id.miniFullSearch_LoadLay)
RelativeLayout miniFullSearch_LoadLay;
#BindView(R.id.fullSearchMini_chipCloud)
ChipCloud fullSearchMini_chipCloud;
#BindView(R.id.fullSearchMini_EmptyLay)
RelativeLayout fullSearchMini_EmptyLay;
#BindView(R.id.empty_text)
TextView empty_text;
#BindView(R.id.miniFullSearch_LoadProgress)
ProgressBar miniFullSearch_LoadProgress;
private Context context;
private MiniSearchCelebritiesAdapter celebritiesAdapter;
private MiniSearchMoviesAdapter moviesAdapter;
private MiniSearchSeriesAdapter seriesAdapter;
private MiniSearchUsersAdapter userAdapter;
private List<Celebrity> celebritiesModel = new ArrayList<>();
private List<Movie> moviesModel = new ArrayList<>();
private List<Series> seriesModel = new ArrayList<>();
private List<User> userModel = new ArrayList<>();
private String searchKey, chipKey;
private List<String> cloudChipList = new ArrayList<>();
private String[] mostlyMatchedKeywordsStrings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mini_full_search);
// Initialize
ButterKnife.bind(this);
context = this;
//Set Color to progressBar
miniFullSearch_LoadProgress.getIndeterminateDrawable().setColorFilter(Color.parseColor("#ff8d00"),
android.graphics.PorterDuff.Mode.SRC_ATOP);
celebritiesAdapter = new MiniSearchCelebritiesAdapter(context, celebritiesModel);
moviesAdapter = new MiniSearchMoviesAdapter(context, moviesModel);
seriesAdapter = new MiniSearchSeriesAdapter(context, seriesModel);
userAdapter = new MiniSearchUsersAdapter(context, userModel);
initRecyclerView(fullSearchMini_celebritiesRecyclerView);
initRecyclerView(miniFullSearch_movieRecyclerView);
initRecyclerView(miniFullSearch_SeriesRecyclerView);
initRecyclerView(miniFullSearch_SeriesRecyclerView);
initRecyclerView(miniFullSearch_UserRecyclerView);
// TextWatcher
fullSearchMini_headerText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
searchKey = editable.toString();
if (searchKey.length() > 1) {
getData(searchKey);
}
}
});
}
private void getData(String key) {
FullSearchSendData sendData = new FullSearchSendData();
sendData.setKey(key);
sendData.setLoadImages(true);
sendData.setSearchInCelebrities(true);
sendData.setSearchInMovies(true);
sendData.setSearchInSeries(true);
sendData.setSearchInEpisodes(false);
sendData.setSearchInUsers(true);
sendData.setPageIndex(1);
sendData.setPageSize(4);
sendData.setMaxDistance(1);
miniFullSearch_LoadLay.setVisibility(View.VISIBLE);
InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
Call<FullSearchResponse> call = api.getFullSearch(sendData);
call.enqueue(new Callback<FullSearchResponse>() {
#Override
public void onResponse(Call<FullSearchResponse> call, Response<FullSearchResponse> response) {
FullSearchResponse searchResponse = response.body();
if (searchResponse.getData().getCelebrities() != null) {
if (searchResponse.getData().getCelebritiesCount() > 0) {
celebritiesModel.clear();
celebritiesModel.addAll(searchResponse.getData().getCelebrities());
celebritiesAdapter.notifyDataSetChanged();
fullSearchMini_celebritiesRecyclerView.setAdapter(celebritiesAdapter);
miniSearchLayouts.get(0).setVisibility(View.VISIBLE);
miniSearchLines.get(0).setVisibility(View.VISIBLE);
fullSearchMini_celebritiesRecyclerView.setVisibility(View.VISIBLE);
miniSearchLayouts.get(0).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, FullSearch.class);
intent.putExtra(ExtraContains.FULL_SEARCH_TEXT.name(), searchKey);
startActivity(intent);
}
});
} else {
miniSearchLayouts.get(0).setVisibility(View.GONE);
miniSearchLines.get(0).setVisibility(View.GONE);
fullSearchMini_celebritiesRecyclerView.setVisibility(View.GONE);
}
}
if (searchResponse.getData().getMovies() != null) {
if (searchResponse.getData().getMoviesCount() > 0) {
moviesModel.clear();
moviesModel.addAll(searchResponse.getData().getMovies());
moviesAdapter.notifyDataSetChanged();
miniFullSearch_movieRecyclerView.setAdapter(moviesAdapter);
miniSearchLayouts.get(1).setVisibility(View.VISIBLE);
miniSearchLines.get(1).setVisibility(View.VISIBLE);
miniFullSearch_movieRecyclerView.setVisibility(View.VISIBLE);
miniSearchLayouts.get(1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, FullSearch.class);
intent.putExtra(ExtraContains.FULL_SEARCH_TEXT.name(), searchKey);
startActivity(intent);
}
});
} else {
miniSearchLayouts.get(1).setVisibility(View.GONE);
miniSearchLines.get(1).setVisibility(View.GONE);
miniFullSearch_movieRecyclerView.setVisibility(View.GONE);
}
}
if (searchResponse.getData().getSeries() != null) {
if (searchResponse.getData().getSeriesCount() > 0) {
seriesModel.clear();
seriesModel.addAll(searchResponse.getData().getSeries());
seriesAdapter.notifyDataSetChanged();
miniFullSearch_SeriesRecyclerView.setAdapter(seriesAdapter);
miniSearchLayouts.get(2).setVisibility(View.VISIBLE);
miniSearchLines.get(2).setVisibility(View.VISIBLE);
miniFullSearch_SeriesRecyclerView.setVisibility(View.VISIBLE);
miniSearchLayouts.get(2).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, FullSearch.class);
intent.putExtra(ExtraContains.FULL_SEARCH_TEXT.name(), searchKey);
startActivity(intent);
}
});
} else {
miniSearchLayouts.get(2).setVisibility(View.GONE);
miniSearchLines.get(2).setVisibility(View.GONE);
miniFullSearch_SeriesRecyclerView.setVisibility(View.GONE);
}
}
if (searchResponse.getData().getUsers() != null) {
if (searchResponse.getData().getUsersCount() > 0) {
userModel.clear();
userModel.addAll(searchResponse.getData().getUsers());
userAdapter.notifyDataSetChanged();
miniFullSearch_UserRecyclerView.setAdapter(userAdapter);
miniSearchLayouts.get(3).setVisibility(View.VISIBLE);
miniFullSearch_UserRecyclerView.setVisibility(View.VISIBLE);
miniSearchLayouts.get(3).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, FullSearch.class);
intent.putExtra(ExtraContains.FULL_SEARCH_TEXT.name(), searchKey);
startActivity(intent);
}
});
} else {
miniSearchLayouts.get(3).setVisibility(View.GONE);
miniFullSearch_UserRecyclerView.setVisibility(View.GONE);
}
}
// Did you mean
String[] mostlyMatchedKeywordsStrings = searchResponse.getData().getMostlyMatchedKeywordsText();
cloudChipList.clear();
for (int i = 0; i < mostlyMatchedKeywordsStrings.length; i++) {
cloudChipList.add(mostlyMatchedKeywordsStrings[i]);
if (i >= mostlyMatchedKeywordsStrings.length - 2) {
fullSearchMini_didYouMeanLay.setVisibility(View.VISIBLE);
fullSearchMini_chipCloud.addChip(mostlyMatchedKeywordsStrings[i]);
Log.e("searchKeys", mostlyMatchedKeywordsStrings[i]);
}
}
fullSearchMini_chipCloud.setChipListener(new ChipListener() {
#Override
public void chipSelected(int i) {
chipKey = cloudChipList.get(i);
Intent intent = new Intent(context, FullSearch.class);
intent.putExtra(ExtraContains.FULL_SEARCH_TEXT.name(), chipKey);
startActivity(intent);
}
#Override
public void chipDeselected(int i) {
}
});
if (searchResponse.getData().getCelebrities().size() == 0 && searchResponse.getData().getSeries().size() == 0
&& searchResponse.getData().getMovies().size() == 0 && searchResponse.getData().getUsers().size() == 0) {
fullSearchMini_EmptyLay.setVisibility(View.VISIBLE);
empty_text.setText(context.getResources().getString(R.string.noResultFound) + " for : " + searchKey);
} else {
fullSearchMini_EmptyLay.setVisibility(View.GONE);
}
miniFullSearch_LoadLay.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<FullSearchResponse> call, Throwable t) {
miniFullSearch_LoadLay.setVisibility(View.GONE);
}
});
}
Show me above error for this line :
chipKey = cloudChipList.get(i);
How can I fix this error? Please help me my friend. I really need your help. please
In the error it says,
Invalid index 11, size is 6
That means the actual number of elements in your cloudChipList is only 6. That is, your searchResponse.getData().getMostlyMatchedKeywordsText(); function returns only 6 values and then its stored in the array list. But when you call the public void chipSelected(int i) function, if the value of i is more than 5 then it will show this java.lang.IndexOutOfBoundsException. If you have 6 values in your array list then you can only provide index value from 0 till 5. In your case the value of i in public void chipSelected(int i) is 11 and so the error.
The index for schipSelected method is being calculated in the ChipCloud class.
fullSearchMini_chipCloud.setChipListener(new ChipListener() {
#Override
public void chipSelected(int i) { //This is callback from ChipCloud class
chipKey = cloudChipList.get(i);
}
#Override
public void chipDeselected(int i) {
}
});
The fullSearchMini_chipCloud layout is being added duplicate chips. You need to clear the existing childs before adding new chips.
After clearing the list with
cloudChipList.clear();
Remove existing childs with
fullSearchMini_chipCloud.removeAllViews()
This question already has answers here:
How to pass an object from one activity to another on Android
(35 answers)
Closed 9 years ago.
I am badly stuck to pass object from one activity to another activity using Parcelable but I am getting null pointer exception at line Log.i("Name",""+rcp.getName());, you can check this line in below code. Plz do check code CookingDataModel class at the end.
Here is the code of object Receiving Activity
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);// No title to display
setContentView(R.layout.recipe_ingredient_detail);
CookingDataModel cook = new CookingDataModel();
RecipeDataModel rcp;
ArrayList<IngredientDataModel> ing;
Bundle bundle = this.getIntent().getExtras();
if(bundle!=null)
cook = bundle.getParcelable("Cooking");
rcp = cook.getRecipe();
ing = cook.getIngredientList();
Log.i("Name",""+rcp.getName());
Log.i("Decrp",""+rcp.getDescription());
Log.i("Duration",""+rcp.getPrepTime());
Log.i("Instructions",""+rcp.getInstructions());
for(int k = 0; k < ing.size(); k++)
{
Log.i("Item Name",""+ing.get(k).getItemName());
Log.i("Item Amount",""+ing.get(k).getItemAmount());
}
}
Here is the code where I am sending object of CookingDataModel .
ListView recepeListView = getListView();
recepeListView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3)
{
CookingDataModel cook = recpeList.get(position);
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putParcelable("Cooking",cook);
intent.putExtras(bundle);
intent.setClass(RecipeList.this,RecipeIngredientDetail.class);
startActivity(intent);
}
});
Here is code of the CookingDataModel class.
public class CookingDataModel implements Parcelable{
private RecipeDataModel recipe = null;
private ArrayList<IngredientDataModel> ingredientList = null;
public RecipeDataModel getRecipe() {
return recipe;
}
public void setRecipe(RecipeDataModel recipe) {
this.recipe = recipe;
}
public ArrayList<IngredientDataModel> getIngredientList() {
return ingredientList;
}
public void setIngredientList(ArrayList<IngredientDataModel> ingredientList) {
this.ingredientList = ingredientList;
}
public static final Parcelable.Creator<CookingDataModel> CREATOR = new Parcelable.Creator<CookingDataModel>()
{
public CookingDataModel createFromParcel(Parcel in)
{
return new CookingDataModel(in);
}
public CookingDataModel[] newArray(int size)
{
return new CookingDataModel[size];
}
};
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel arg0, int arg1) {
// TODO Auto-generated method stub
}
public CookingDataModel(Parcel in) {
// TODO Auto-generated constructor stub
}
public CookingDataModel()
{
}
}
Please help me in this respect that I could proceed my project. Thanks in adavance.
On the main activity:
intent.putExtra("Cooking",cook);
Then on second activity:
getIntent().getExtras().getParcelable("Cooking");
Try this. Do not use bundle if you've just to send a single object.
You may need to cast the getIntent().... part, I'm not sure.
Few things that need change.
No need of creating a new object, it will be overwritten.
CookingDataModel cook = new CookingDataModel();
Typecast when you get the Parcelable object from intent extras,
cook = bundle.getParcelable("Cooking");
Make Sure when you sending the object, it has valid receipe member. If you notice, you are able to get the CookingDataModel from the intent, and also the Receipe from this object but not able to get data from ReceipeModel.
From the code in the sending activity, I cant really say if the CookingDataModel.Receipe is a valid object.
I'm trying to pass an array of custom objects to an activity. I've implemented parcelable as such:
public class WidgetState {
static class Light implements Parcelable
{
int id;
String text;
int offColor,onColor;
boolean on=false;
boolean isRows;
int size;
public static final Parcelable.Creator<Light> CREATOR = new Parcelable.Creator<Light>() {
public Light createFromParcel(Parcel in) {
return new Light(in);
}
public Light[] newArray(int size) {
return new Light[size];
}
};
#Override
public int describeContents() {
return 0;
}
public Light(Parcel src)
{
id = src.readInt();
text = src.readString();
offColor = src.readInt();
onColor = src.readInt();
on = src.readInt()==1;
isRows = src.readInt()==1;
size = src.readInt();
}
public Light() { }
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(text);
dest.writeInt(offColor);
dest.writeInt(onColor);
dest.writeInt(on?1:0);
dest.writeInt(isRows?1:0);
dest.writeInt(size);
}
}
}
I can put a single object in the bundle in the launching activity and retrieve it via
bundle.putParcelable(new WidgetState.Light(),"light");
and retrieve it in the resulting activity via
WidgetState.Light light = (WidgetState.Light)getIntent().getExtras().getParcelable("light")
but when packing and array like this
bundle.putParcelableArray(new WidgetState.Light[4],"lights");
I can do this just fine on the first activity
WidgetState.Light[] lights = (WidgetState.Light[])bundle.getParcelableArray("lights");
intent.putExtras(bundle);
startActivityForResult(intent,1);
but in the second activity i get a RuntimeException when I call
WidgetState.Light [] lights = (WidgetState.Light []) state.getParcelableArray("lights");
Here's all the code in the first activity
Intent intent = new Intent(MainActivity.this,GuiActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable("light", new WidgetState.Light());
bundle.putParcelableArray("lights", new WidgetState.Light[4]);
WidgetState.Light[]lights = (WidgetState.Light[])bundle.getParcelableArray("lights");
intent.putExtras(bundle);
startActivityForResult(intent,1);
And the second
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gui);
Bundle state = (savedInstanceState!=null)?savedInstanceState:getIntent().getExtras();
try {
WidgetState.Light light = (WidgetState.Light) state.getParcelable("light");
// Throws RuntimeException on next line
WidgetState.Light [] lights = (WidgetState.Light []) state.getParcelableArray("lights");
Toast.makeText(this, "Good bundle", Toast.LENGTH_SHORT).show();
}
catch ( RuntimeException e)
{
Toast.makeText(this, "Failed to read bundle", Toast.LENGTH_SHORT).show();
}
}
What am I missing?
In my application I have 2 fragment, Fragment A and Fragment B.On both these fragments Iam doing some XML parsing and populating listviews.I want to implement a splash screen for my app.So that it display during parsing and population of listviews and finishes when its done. For this, I have created an activity SplashActivity.I have Implemented asyntask on FragmentA and called the SplashActivity on preexecute section.Now, when the app launches SplashActivity get started.But I cant finish this acitivity on postexecute of FragmentA. getActivity().finishActivity() is not working.Please some one help me to solve this issue or suggest me another method to implement Splash screen on Fragment Activity. Thanks in advance....
here is my FragmentA=>
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating layout
View v = inflater
.inflate(R.layout.headlines_fragment, container, false);
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.i("Tag", "onCreateView");
// We set clear listener
loading = (ProgressBar) getActivity().findViewById(R.id.progressBar1);
if (Headlines.headflag == "malayalam") {
urls = "http://www.abc.com/rssfeeds/19_18_17_25/1/rss.xml";
}
if (Headlines.headflag == "english") {
urls = "http://www.abc.com/en/rssfeeds/1_2_3_5/latest/rss.xml";
}
new ProgressAsyncTask().execute();
MainActivity.refresh.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new ProgressAsyncTask().execute();
}
});
}
public void populate_listview() {
newsList = new ArrayList<HashMap<String, String>>();
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
newsList.add(map);
MarqueeStr = MarqueeStr + " *** " + Title[i];
}
}
public void StartProgress() {
new ProgressAsyncTask().execute();
}
public class ProgressAsyncTask extends AsyncTask<Void, Integer, Void> {
int myProgress;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
myProgress = 0;
Intent intent = new Intent(getActivity(), Splash.class);
startActivityForResult(intent, 5); //Here I called Splash Activity
loading.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
getActivity().finishActivity(5);// Here I tried to finish flash activity
if (Title == null) {
final AlertDialog.Builder alertbox = new AlertDialog.Builder(
getActivity());
alertbox.setMessage("Error in connection.Do you want to retry");
alertbox.setPositiveButton("retry",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// getActivity().finish();
// Intent intent = new Intent(getActivity(),
// MainActivity.class);
// startActivityForResult(intent,1);
}
});
alertbox.setNegativeButton("exit",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// getActivity().finish();
}
});
alertbox.show();
}
list = (GridView) getActivity().findViewById(R.id.grid);
// Getting adapter by passing xml data ArrayList
adapter = new HeadlinesAdapter(getActivity(), newsList);
list.setAdapter(adapter);
loading.setVisibility(View.INVISIBLE);
Typeface tf = Typeface.createFromAsset(getActivity().getAssets(),
"fonts/karthika.TTF");
MainActivity.flashnews.setText(MarqueeStr);
if (Headlines.headflag == "malayalam") {
MainActivity.flashnews.setTypeface(tf);
}
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent myintent = new Intent(
"com.abc.malayalam2headlinespodcast.PODCAST");
Bundle mybundle = new Bundle();
mybundle.putInt("number", position);
myintent.putExtras(mybundle);
startActivity(myintent);
}
});
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parse();
if (Title != null) {
populate_listview();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
}
}
public static void parse() {
//parsing done here
}
}
You should not implement your Splash as an Activity but rather as a DialogFragment. Simply style that dialog fragment so that it appears fullscreen.
Concerning showing:
SplashDialogFragment splashDlg = new SplashDialogFragment();
splashDlg.show(getSupportFragmentManager(), "SplashScreen");
Then closing:
SplashDialogFragment splashDlg = (SplashDialogFragment) getSupportFragmentManager().findByTag("SplashScreen");
splashDlg.dismiss();
just to answer the question which is your title actually "To finish an activity from Fragment", it's always a good way to use interface to interact from Fragment to Activity as per the docs: Communicating with Activity from Fragment. So one must always declare an interface in Fragment which is to be implemented in your activity something like below:
public class SplashActivity extends Activity implements FragmentA.FragmentListenerCallback {
public void onFragmentInteraction() {
//finish your activity or do whatever you like
finish();
}
}
public class FragmentA extends Fragment {
private FragmentListenerCallback fragmentListenerCallback;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
fragmentListenerCallback = (FragmentListenerCallback) activity;
}
public interface FragmentListenerCallback {
void onFragmentInteraction();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(fragmentListenerCallback != null){
fragmentListenerCallback.onFragmentInteraction();
}
}
}
I got a method in which server-client communication is done "onClick" therefor i create a anonymous OnClickListener, and I want to publish a toast if the communication was successfull or not.
To do this I need the Acitivity in which context to publish the toast, and as I externalized the method, it must be given as a "this" argument to the Activity. But as I am inside an anonymous inner class I cannot access the this pointer of the Acitivity, and even though I stored it in a local final variable
private final Activity activity = this;
#Override
public void onCreate(Bundle savedInstanceState) {
lastResult = null;
super.onCreate(savedInstanceState);
setLayout(R.layout.main);
qrscan = (Button) findViewById(R.id.qrcodescan);
qrscan.setOnClickListener( new View.OnClickListener() {
public void onClick(View view) {
initiateScan(activity);
}
}
);
}
private AlertDialog initiateSend(Activity activity) {
if(lastResult != null) {
String[] arr = lastResult.content.split("/");
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(activity);
String[] args = Util.filterString(arr,this);
downloadDialog.setTitle(args[0]);
downloadDialog.setMessage("Auftragsnummer:" + args[1]);
downloadDialog.setPositiveButton(getString(R.string.ja), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
try {
String send = lastResult.content;
send += "/uid/" + R.id.username + "/cid/" + R.id.password;
String result = Util.send(send);
//toaster(send);
Util.toaster(result,activity);
if(!(result.equals("OK") || result.equals("ok") || result.equals("Ok")))
throw new Exception("Bad Server Answer");
Util.toaster("Communication erfolgreich",activity);
} catch(Exception ex) {
ex.printStackTrace();
Util.toaster("Communication nicht erfolgreich",activity);
}
}
});
downloadDialog.setNegativeButton(getString(R.string.nein), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {}
});
return downloadDialog.show();
}
return null;
}
Any clue what i messed up?
declare variable before onCreate() like this
public class HelloAndroid extends Activity {
Activity activity = this; // declare here
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
EDITED
Activity mainActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setLayout(R.layout.main);
mainActivity = this;
lastResult = null;
qrscan = (Button) findViewById(R.id.qrcodescan);
qrscan.setOnClickListener( new View.OnClickListener() {
public void onClick(View view) {
initiateScan(mainActivity);
}
}
);
}
private AlertDialog initiateSend(final Activity activity) {
if(lastResult != null) {
String[] arr = lastResult.content.split("/");
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(activity);
String[] args = Util.filterString(arr,this);
downloadDialog.setTitle(args[0]);
downloadDialog.setMessage("Auftragsnummer:" + args[1]);
downloadDialog.setPositiveButton(getString(R.string.ja), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
try {
String send = lastResult.content;
send += "/uid/" + R.id.username + "/cid/" + R.id.password;
String result = Util.send(send);
//toaster(send);
Util.toaster(result,activity);
if(!(result.equals("OK") || result.equals("ok") || result.equals("Ok")))
throw new Exception("Bad Server Answer");
Util.toaster("Communication erfolgreich",activity);
} catch(Exception ex) {
ex.printStackTrace();
Util.toaster("Communication nicht erfolgreich",activity);
}
}
});
downloadDialog.setNegativeButton(getString(R.string.nein), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {}
});
return downloadDialog.show();
}
return null;
}