SimpleCursorAdapter in android - java

This is my first time creating android app. and what i want to create now is to make a list and when a user click a name in the list the detail of the click name will show. I am trying to create simple cursor adapter. But an error occur
The constructor SimpleCursorAdapter(QuestionsNew, int, Cursor, String[], int[]) is undefined.
What do you think is the possible reason for this. Below is some part of my code
package tk.wew.wew;
import info.androidhive.sqlite.model.LocalStorage;
import info.androidhive.sqlite.model.Message;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import static tk.askd.askd.CommonUtilities.*;
public class QuestionsNew extends Fragment {
Cursor cursor;
ListView nameList;
protected ListAdapter adapter;
// TextView tvCompany = (TextView)
// findViewById(R.id.tvContactListCompany);
private static final String TAG = "Question";
private ListView list;
private static List questions;
ArrayList<String> senders = new ArrayList<String>();
ArrayList<String> shortMsg = new ArrayList<String>();
ArrayList<Integer> imageId = new ArrayList<Integer>();
SimpleCursorAdapter myCursorAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view;
//CommonUtilities.sendAQuestion(getActivity(), "msg123Kjjj11", "richmund_10023", "lofrancs1231", "Apil ka?");
questions = CommonUtilities.getAllQuestions(getActivity(), "N", null);
if(questions.size() > 0){
view = inflater.inflate(R.layout.questions_main_layout, container, false);
AskdDatabaseHelper msg_db = new AskdDatabaseHelper(getActivity());
List<Message> messages = msg_db.getAllQuestions("N", "lofrancs1231");
Cursor cursor = msg_db.getAllQuestions3();
// Setup mapping from cursor to view fields:
String[] fromFieldNames = new String[] { "KEY_MSG_MESSAGE_ID","KEY_MSG_MESSAGE" };
int[] toViewIDs = new int[] { R.id.KEY_MSG_MESSAGE_ID, R.id.KEY_MSG_MESSAGE_ID };
/* SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this, // Context
R.layout.message_list_item, // Row layout template
cursor, // cursor (set of DB records to map)
fromFieldNames, // DB Column names
toViewIDs // View IDs to put information in
);*/
myCursorAdapter = new SimpleCursorAdapter(QuestionsNew.this,
R.layout.message_list_item,
cursor,
fromFieldNames,
toViewIDs);
ListView contactList = (ListView) getView().findViewById(R.id.lvContacts);
contactList.setAdapter(myCursorAdapter);
for(int m=0; m<questions.size(); m++){
senders.add(messages.get(m).getFromUser());
shortMsg.add(messages.get(m).getMessage());
imageId.add(R.drawable.ic_launcher);
}
} else {
view = inflater.inflate(R.layout.fragments_question_new, container, false);
((TextView)view.findViewById(R.id.textView)).setText("No New Questions");
}
return view;
}
#Override
public void onStart(){
super.onStart();
Log.v(TAG, ": New onStart");
if(questions.size() > 0){
list = (ListView) getView().findViewById(R.id.list);
CustomLst adapter = new CustomLst(getActivity(), senders, imageId, shortMsg);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
// Cursor listCursor = (Cursor) parent.getItemAtPosition(position);
// Cursor listCursor = (Cursor) parent.getAdapter().getItem(position);
// Log.d("TAG", (String) parent.getItemAtPosition(id));
Toast.makeText(getActivity(),
"Position:"+ parent.getItemIdAtPosition((int) id), Toast.LENGTH_LONG)
.show();
// int message = listCursor.getInt(listCursor.getColumnIndex(AskdDatabaseHelper.KEY_MSG_MESSAGE_ID));
/*
Intent intent = new Intent(getActivity(), QuestionDetail.class);
intent.putExtra("Message_ID", listCursor.getString(listCursor.getColumnIndex(AskdDatabaseHelper.KEY_MSG_MESSAGE_ID)));
startActivity(intent);
// ListView clicked item index
int Position = position;
// ListView clicked item value
String itemValue = (String) list.getItemAtPosition(Position);
// show alert
// Toast.makeText(getActivity(),
// "Position:" + Position + " Listitem:" + itemValue, Toast.LENGTH_LONG)
// .show();
*/
}
});
} else {
Log.e(TAG, "No new question");
}
}
}

Change your constructor as below
myCursorAdapter = new SimpleCursorAdapter(getActivity(),
R.layout.message_list_item,
cursor,
fromFieldNames,
toViewIDs);
The first param is a Context. This QuestionsNew.this is not a valid context. Fragment does not extend Context.
Activity
java.lang.Object
↳ android.content.Context // check this
↳ android.content.ContextWrapper
↳ android.view.ContextThemeWrapper
↳ android.app.Activity // check this
Fragment
java.lang.Object
↳ android.app.Fragment // check this
So get context in fragment use getActivity()
public final Activity getActivity ()
Added in API level 11 Return the Activity this fragment is currently
associated with.
Also
SimpleCursorAdapter(Context context, int layout, Cursor c, String[]
from, int[] to) This constructor was deprecated in API level 11. This
option is discouraged, as it results in Cursor queries being performed
on the application's UI thread and thus can cause poor responsiveness
or even Application Not Responding errors. As an alternative, use
LoaderManager with a CursorLoader.
It is same when you use ArrayAdapter in Fragment class. The first param to the constructor of ArrayAdapter is a valid context. So even in that case you need to use getActivity() instead of FragmentName.this.

Related

Setting ListView

I am having trouble with listview and spinners. I am using a list view to display items and using a spinner to filter between categories and a button to refresh the view. My problem is that after selecting a different category it does not change the listView and reverts the spinner to the original category. I have tried using .clear() and an onClickListener() but my problem persists. Is there a way to make the spinner change the items in the listView after clicking the button?
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import androidx.fragment.app.Fragment;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static android.content.ContentValues.TAG;
public class MenuFragment extends Fragment {
private ListView menuList;
private Spinner menuSpinner;
private Button buttonRefresh;
//private ArrayList<Menu> menuArrayList ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_menu, container, false);
Log.i(TAG, "onCreateView of MenuFragment has loaded");
//menuApps=(TextView)rootView.findViewById(R.id.menuApps);
//menuTitle=(TextView)rootView.findViewById(R.id.menuTitle);
menuList=(ListView)rootView.findViewById(R.id.menuList);
menuSpinner=(Spinner)rootView.findViewById(R.id.menuSpinner);
buttonRefresh=(Button)rootView.findViewById(R.id.buttonRefresh);
//menuSpinner.setOnItemClickListener(new View.OnItemClickListener());
//menuViewingMethod();
buttonRefresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
menuViewingMethod();
Log.i(TAG,"Refresh has been clicked");
}
});
return rootView;
}
public ListView menuViewingMethod(){
List<String> list=new ArrayList<>();
list.add("Appetizers");
list.add("Salads");
list.add("Soups");
list.add("Side Items");
list.add("Entrees");
list.add("Desserts");
//sets up the spinner
ArrayAdapter<String>dataAdapter= new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item,list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
menuSpinner.setAdapter(dataAdapter);
String input= menuSpinner.getSelectedItem().toString();
Log.d(TAG,input);
if (input=="Appetizers"){
//menuList.clear();
/*menuList.setAdapter(arrayAdapter);
menuArrayList.add("Gerst Sampler – $12.99");
menuArrayList.add("Fried Oyster Basket – $11.99");
menuArrayList.add("Gerst Ham Rolls - $11.99");
menuArrayList.add("Bavarian Kraut Balls – $8.99");
Log.i(TAG,"Spinner item Appetizers has been selected");*/
String[] apps = new String[]{"Gerst Sampler – $12.99",
"Fried Oyster Basket – $11.99",
"Gerst Ham Rolls - $11.99",
"Bavarian Kraut Balls – $8.99"};
ArrayList<String> menuArrayList= new ArrayList<String>(Arrays.asList(apps));
ArrayAdapter<String>arrayAdapter= new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,menuArrayList);
menuList.setAdapter(arrayAdapter);
}
//https://android--code.blogspot.com/2015/08/android-listview-add-items.html
else if (input=="Salads"){
/*menuArrayList.clear();
menuList.setAdapter(arrayAdapter);
menuArrayList.add("Salad1");*/
String[] salads = new String[]{"Salad1", "Salad 2", "Salad 3"};
List<String> menuArrayList= new ArrayList<String>(Arrays.asList(salads));
ArrayAdapter<String>arrayAdapter= new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_2,menuArrayList);
menuList.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
else if(input=="Soups"){
/*menuList.setAdapter(arrayAdapter);
menuArrayList.clear();*/
String[] soups = new String[] {"Soup 1", "Soup 2", "Soup 3"};
List<String> menuArrayList= new ArrayList<String>(Arrays.asList(soups));
ArrayAdapter<String>arrayAdapter= new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,menuArrayList);
menuArrayList.clear();
menuList.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
String[] apps = new String[]{"Gerst Sampler – $12.99",
"Fried Oyster Basket – $11.99",
"Gerst Ham Rolls - $11.99",
"Bavarian Kraut Balls – $8.99"};
List<String> menuArrayList= new ArrayList<String>(Arrays.asList(apps));
ArrayAdapter<String>arrayAdapter= new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,menuArrayList);
menuList.setAdapter(arrayAdapter);
// menuSpinner.setOnTouchListener((View.OnTouchListener) this);
arrayAdapter.notifyDataSetChanged();
return menuList;
}
}
Would suggest two things:
Relocate your spinner setup from 'menuViewingMethod()' to 'onCreateView()'. This is probably the cause of your spinner resetting to 0 every time the 'menuViewingMethod()' is triggered.
In 'menuViewingMethod()', make 'menuArrayList' and 'arrayAdapter' class variable and reload the list with new contents instead.
String[] salads = new String[]{"Salad1", "Salad 2", "Salad 3"};
menuArrayList.clear();
menuArrayList.addAll(Arrays.asList(salads));
arrayAdapter.notifyDataSetChanged();

how to display listview items, when a user enter some number in textbox?

how to display listview items in android, when a user enter some number in edittext and click on a button to display the specified number of list items on the next activity ?
I have one EditText and a Button on MainActivity1 and a ListView and TextView on MainActivity2. TextView is just for letting me know tht value is passing on next screen.
MainActivity.java
package com.populatelist;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText edt = (EditText)findViewById(R.id.editText1);
Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myin = new Intent(MainActivity.this,MainActivity2.class);
myin.putExtra("textbox", edt.getText().toString());
startActivity(myin);
}
});
}
}
MainActivity2.java
package com.populatelist;
import android.support.v7.app.ActionBarActivity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity2 extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
TextView tv = (TextView)findViewById(R.id.textView1);
Intent myin2 = getIntent();
String str = myin2.getStringExtra("textbox");
tv.setText(str);
final ListView lv = (ListView) findViewById(R.id.listView1);
String[] arrStr = new String[] {
"Hello World",
"Hello India",
"Hello Rajasthan",
"Hello Jodhpur",
"Hello Mujeeb"
};
final List<String> hello_list = new ArrayList<String>(Arrays.asList(arrStr));
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, hello_list);
int n = Integer.parseInt(str);
lv.setAdapter(arrayAdapter);
}
}
You can simply add the coming value at last of your string array like
String[] arrStr = new String[] {
"Hello World",
"Hello India",
"Hello Rajasthan",
"Hello Jodhpur",
"Hello Mujeeb",
str
};
It will show your input value to last position of your listview.
And if you want to add new items and show old as well then you have to pass whole string array to previous activity and add new value to last position, pass it when start next activity. By using this you can see all data on listview.
Whenever you get value in second activity create a new array "b" with required no of values.
String str = myin2.getStringExtra("textbox");
int noOfNames = Integer.parseInt(str);
String[] b = new String[StringnoOfNames];
Then copy the items from the original array
b = Arrays.copyOf(arrStr, noOfNames);
final List<String> hello_list = new ArrayList<String>(Arrays.asList(b));
First, validate if your EditText isn't null, here your app may crash
if (edt.getText().length() > 0) {
Intent myin = new Intent(MainActivity.this,MainActivity2.class);
myin.putExtra("textbox", Integer.parseInt(edt.getText().toString()));
startActivity(myin);
}
Then handle your intent
ListView lv = (ListView) findViewById(R.id.listview1);
ArrayAdapter<String> arrayAdapter = null;
int number = intent.getIntExtra("textbox", 0);
switch (number) {
case 0:
arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, arrStr);
lv.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
break;
case 1:
arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, AnotherSourceArray);
lv.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
break;
case 2:
arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, AnotherSourceArray);
lv.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
break;
...
default:
break;
}
Note - this is just sample. You can resolve this on many another ways. Each switch case may contain another data to display. Using default layouts for listviews may be frustrating, better way is to create custom class which extends ArrayAdapter<String>

Unable to pass intent in custom array adapter

I am unable to pass an intent in this case. Nothing is displayed on the screen or Logs from the movie_detail.java. I cannot figure out hat is wrong, please help!
MainActivityFragment.java
package com.example.coderahul.a9to12;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import java.util.Arrays;
public class MainActivityFragment extends Fragment {
private movieListAdapter movieListA;
MovieList[] movieLists = {
new MovieList("Cupcake - 1.5", "/is6QqgiPQlI3Wmk0bovqUFKM56B.jpg", "368596"),
new MovieList("Donut - 1.6", "/cGOPbv9wA5gEejkUN892JrveARt.jpg", "209112"),
new MovieList("Eclair - 2.0-2.1", "/9KQX22BeFzuNM66pBA6JbiaJ7Mi.jpg", "47933"),
new MovieList("Froyo - 2.2-2.2.3", "/z09QAf8WbZncbitewNk6lKYMZsh.jpg", "127380"),
new MovieList("GingerBread - 2.3-2.3.7", "/5N20rQURev5CNDcMjHVUZhpoCNC.jpg", "271110"),
new MovieList("Honeycomb - 3.0-3.2.6", "/jjBgi2r5cRt36xF6iNUEhzscEcb.jpg", "135397"),
new MovieList("Ice Cream Sandwich - 4.0-4.0.4", "/6FxOPJ9Ysilpq0IgkrMJ7PubFhq.jpg", "258489"),
new MovieList("Jelly Bean - 4.1-4.3.1", "/tSFBh9Ayn5uiwbUK9HvD2lrRgaQ.jpg", "262504"),
new MovieList("Honeycomb - 3.0-3.2.6", "/inVq3FRqcYIRl2la8iZikYYxFNR.jpg", "87101"),
new MovieList("Ice Cream Sandwich - 4.0-4.0.4", "/zSouWWrySXshPCT4t3UKCQGayyo.jpg", "293660"),
new MovieList("Jelly Bean - 4.1-4.3.1", "/MZFPacfKzgisnPoJIPEFZUXBBT.jpg", "76341"),
new MovieList("Jelly Bean - 4.1-4.3.1", "/sM33SANp9z6rXW8Itn7NnG1GOEs.jpg", "246655")
};
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
movieListA = new movieListAdapter(getActivity(), Arrays.asList(movieLists));
// Get a reference to the ListView, and attach this adapter to it.
GridView gridView = (GridView) rootView.findViewById(R.id.movies_grid);
gridView.setAdapter(movieListA);
final Context context = getActivity();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
MovieList detail = (MovieList) movieListA.getItem(position);
Intent intent = new Intent(context, movie_detail.class)
.putExtra(Intent.EXTRA_TEXT, detail.title);
context.startActivity(intent);
Log.v("Check", detail.title);
}
});
return rootView;
}
}
movie_detail.java
package com.example.coderahul.a9to12;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class movie_detail extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_detail);
}
public static class DetailFragment extends Fragment {
public DetailFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.movie_detail, container, false);
Log.v("Check", "Inside Intent");
// The detail Activity called via intent. Inspect the intent for forecast data.
Intent intent = getActivity().getIntent();
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
String detail = intent.getStringExtra(Intent.EXTRA_TEXT);
Log.v("Check", detail);
((TextView) rootView.findViewById(R.id.movie_detail))
.setText(detail);
}
return rootView;
}
}
}
movieListAdapter.java
package com.example.coderahul.a9to12;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
public class movieListAdapter extends ArrayAdapter<MovieList> {
private static final String LOG_TAG = movieListAdapter.class.getSimpleName();
/**
* This is our own custom constructor (it doesn't mirror a superclass constructor).
* The context is used to inflate the layout file, and the List is the data we want
* to populate into the lists
*
* #param context The current context. Used to inflate the layout file.
A List of AndroidFlavor objects to display in a list
*/
public movieListAdapter(Activity context, List<MovieList> movieList) {
// Here, we initialize the ArrayAdapter's internal storage for the context and the list.
// the second argument is used when the ArrayAdapter is populating a single TextView.
// Because this is a custom adapter for two TextViews and an ImageView, the adapter is not
// going to use this second argument, so it can be any value. Here, we used 0.
super(context, 0, movieList);
}
/**
* Provides a view for an AdapterView (ListView, GridView, etc.)
*
* #param position The AdapterView position that is requesting a view
* #param convertView The recycled view to populate.
* (search online for "android view recycling" to learn more)
* #param parent The parent ViewGroup that is used for inflation.
* #return The View for the position in the AdapterView.
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Gets the AndroidFlavor object from the ArrayAdapter at the appropriate position
MovieList movieList = getItem(position);
// Adapters recycle views to AdapterViews.
// If this is a new View object we're getting, then inflate the layout.
// If not, this view already has the layout inflated from a previous call to getView,
// and we modify the View widgets as usual.
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.movie_item, parent, false);
}
ImageView iconView = (ImageView) convertView.findViewById(R.id.movie_image);
Picasso.with(getContext())
.load("http://image.tmdb.org/t/p/w185//" + movieList.link)
.resize(200, 200)
.centerCrop()
.into(iconView);
TextView versionNameView = (TextView) convertView.findViewById(R.id.movie_title);
versionNameView.setText(movieList.title);
return convertView;
}
}
You will be able to get your Intent in Activity's onCreate() method not in your fragment onCreateView() method because intent will be recevied by activity and not by fragment.
To get your intent in your movie_detail activity do it like this
static String detail="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_detail);
Intent intent =getIntent();
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
detail = intent.getStringExtra(Intent.EXTRA_TEXT);
}
}
After doing this you can use detail String to set Text in your textview
In your fragment class
((TextView) rootView.findViewById(R.id.movie_detail))
.setText(movie_detail.detail);
You must attach the fragment to your activity's layout in order to make you fragment visible in your activity
in your movie_detail activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_detail);
Intent intent = getActivity().getIntent();
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
String detail = intent.getStringExtra(Intent.EXTRA_TEXT);
Log.v("Check", detail);
}
Bundle extra = new Bundle();
extra.putExtra(Intent.EXTRA_TEXT,detail);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
DetailFragment fragment = new DetailFragment();
fragment.setArguments(extra);
fragmentTransaction.replace(android.R.id.content, fragment);
}
And in your fragment get the arguments and set the details wherever necessary

App Crashed on BackPressed 3rd of 4th time

I am facing a strange issue in my android app and I am not able to figure it out. Is there anyone who can help me regarding this issue.
Let me describe about my app and issue.
I am getting all the images from gallery and displaying them on a gridview using adapter. Once displayed, I am sending an image from this gridview of Activity A to next activity on click of gridview item and assigning this image on an image view in Activity B... When I come back from Activity B to Activity A on pressing Bsck button, it works fine. But when I repeat this process three to four times, app is crashing. I don't know what is the issue. I am sure that the issue is in Activity A..
Here is the code of Activity A....
package info.androidhive.tabsswipe;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
public class ImageLoader extends Fragment implements LoaderCallbacks<Cursor> {
GridView gridView;
SimpleCursorAdapter mAdapter;
Cursor cursor;
Uri uri;
String ID;
Intent intent;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.videos, container, false);
gridView = (GridView) getActivity().findViewById(R.id.gridView1);
gridView.setAdapter(null);
mAdapter = null;
cursor = null;
uri = null;
ID = null;
intent = null;
mAdapter = new SimpleCursorAdapter(
getActivity(),
R.layout.gridview_item1,
null,
new String[] { "_data","_id"} ,
new int[] { R.id.video_thumbnail_imageview},
0
);
/** Setting adapter for the gridview */
gridView.setAdapter(mAdapter);
/** Loader to get images from the SD Card */
getActivity().getSupportLoaderManager().initLoader(0, null, this);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
cursor = (Cursor)parent.getItemAtPosition(position);
ID = cursor.getString(cursor.getColumnIndex("image_id"));
intent = new Intent(getActivity(),Testing_Activity.class);
intent.putExtra("Image_Path",ID);
startActivity(intent);
}
});
return rootView;
}
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
/** Getting uri to the Thumbnail images stored in the external storage */
uri = MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI;
/** Invoking the uri */
return new CursorLoader(getActivity(), uri, null, null, null, null);
}
/** A callback method, invoked after the requested content provider returned all the data */
#Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
mAdapter.swapCursor(arg1);
}
#Override
public void onLoaderReset(Loader<Cursor> arg0) {
// TODO Auto-generated method stub
}
}
Any help regarding this issue will be highly appreciated. Thanks in Advance.

How to Call Activity using ListView [duplicate]

This question already has answers here:
How to Call Activity using ListView Array
(2 answers)
Closed 9 years ago.
Iam using Sherlock fragment to make a Action Bar. and I have ListView in action bar, but I will my listview can call activity .. Please help me Thanks.. :)
in this code have a listview using array list . and i want to mylist can call same activity.
So it can Like menu in action bar. and when we clik listview ..he can call activity
thank.. please help me !
Please correct my code ..how to call activity with each option in listview.. thanks..
AppleFragment.java
package iqbal.apps.visitkuningan;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;
import com.actionbarsherlock.app.SherlockListFragment;
public class AppleFragment extends SherlockListFragment{
/** An array of items to display*/
String apple_versions[] = new String[]{
"Mountain Lion",
"Lion",
"Snow Leopard",
"Leopard",
"Tiger",
"Panther"
};
/** An array of images to display*/
int apple_images[] = new int[]{
R.drawable.mountainlion,
R.drawable.lion,
R.drawable.snowleopard,
R.drawable.leopard,
R.drawable.tiger,
R.drawable.panther
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
// Each row in the list stores country name, currency and flag
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<5;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("txt", apple_versions[i]);
hm.put("img", Integer.toString(apple_images[i] ) );
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "img","txt" };
// Ids of views in listview_layout
int[] to = { R.id.img,R.id.txt};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(), aList, R.layout.listview_layout, from, to);
// Getting a reference to listview of main.xml layout file
ListView listview = AppleFragment.this.getListView();
listview.setAdapter(adapter);
// Setting the adapter to the listView
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position,long id) {
// ?? please add code in here to call activity from each option in listview.. T_T or correct my code
}
});
return super.onCreateView(inflater, container, savedInstanceState);
}
}
Edit the setOnItemClickListener and insert a condition which checks for position of the item and starts and activity depending on the item clicked.
Should look something like this
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0,View arg1, int position, long arg3) {
Intent n = null;
switch (position){
case 0:
n = new Intent(getActivity(), Class0.class);
break;
case 1:
n = new Intent(getActivity(), Class1.class);
break;
}
if(null!=n)
startActivity(n);
}
});

Categories