Click Button to pass argument from fragment to another fragment - android

I am trying to make this but errors.
When I click a button and it executes function "showData()" ;
The reason I want to do this function because I want to change a fragment when
I click this button and also "pass the arguments" to the new fragment.
So it will keep executing function "passData()";
But it will get NullPointerException after 「editTextNAME.setText(restaurant.name); 」this line.
showData()
public void showData(View view){
RestaurantRepo repo = new RestaurantRepo(this);
ArrayList<HashMap<String, String>> restaurantList = repo.getRestaurantList();
if ( restaurantList.size()!=0 ) {
ListView lv = (ListView) findViewById(R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
restaurantID = (TextView) view.findViewById(R.id.restaurantID);
String idRestaurant = restaurantID.getText().toString();
Bundle data = new Bundle();
data.putString("restaurantID", idRestaurant); // argument
Fragment fraUorD = null;
fraUorD = new EditFragment_Fix_UorD();
if ( null != fraUorD ) {
android.app.FragmentManager fragementManager = getFragmentManager();
android.app.FragmentTransaction transaction = fragementManager.beginTransaction();
transaction.replace(R.id.content_frame, fraUorD);
transaction.addToBackStack(null);
transaction.commit();
passData(data); // when transaction done , execute passData() -> i want to pass argument when the new fragment come out
}
}
});
ListAdapter adapter = new SimpleAdapter( MainActivity.this,restaurantList, R.layout.edit_fragment_fix_view,
new String[] { "id","name","type","price","phone","addr"},
new int[] {R.id.restaurantID, R.id.restaurantNAME,R.id.restaurantTYPE,
R.id.restaurantPRICE,R.id.restaurantPHONE,R.id.restaurantADDR});
lv.setAdapter(adapter);
}
else
Toast.makeText(this,"No restaurant!",Toast.LENGTH_SHORT).show(); // no data
passData()
public void passData(Bundle data){
int a = Integer.parseInt( data.getString("restaurantID", "")) ; // get it
Toast.makeText(this, ""+a,Toast.LENGTH_SHORT).show();
editTextNAME = (EditText) findViewById(R.id.editTextUpdateName);
editTextTYPE = (EditText) findViewById(R.id.editTextUpdateType);
editTextPRICE = (EditText) findViewById(R.id.editTextUpdatePrice);
editTextPHONE = (EditText) findViewById(R.id.editTextUpdatePhone);
editTextADDR = (EditText) findViewById(R.id.editTextUpdateAddr);
RestaurantRepo repo = new RestaurantRepo(this);
Restaurant restaurant = new Restaurant();
restaurant = repo.getRestaurantById(a);
// Everything is ok, but when executing codes below here will get errors
// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
editTextNAME.setText(restaurant.name);
editTextTYPE.setText(String.valueOf(restaurant.type));
editTextPRICE.setText(String.valueOf(restaurant.price));
editTextPHONE.setText(restaurant.phone);
editTextADDR.setText(restaurant.addr);
}
Logcat here :
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
at com.example.user.foody.MainActivity$override.passData(MainActivity.java:284)
at com.example.user.foody.MainActivity$override.access$dispatch(MainActivity.java)
at com.example.user.foody.MainActivity.passData(MainActivity.java:0)
at com.example.user.foody.MainActivity$2$override.onItemClick(MainActivity.java:244)
at com.example.user.foody.MainActivity$2$override.access$dispatch(MainActivity.java)
at com.example.user.foody.MainActivity$2.onItemClick(MainActivity.java:0)

The problem is that you cannot findviewbyId on fragment before onViewCreated.
I recommend reading this post about passing data through fragments.
http://gunhansancar.com/best-practice-to-instantiate-fragments-with-arguments-in-android/
important piece:
public static MyFragment newInstance(...)

Related

How to write SQLite database in Fragment Android

while I am creating a database on android SQLite database with fragment if I write inside the onViewCreated method couldn't write the database name and Listview findViewById get the error I don't know. what I tried so I wrote below.
cannot resolve the method openOrCreateDatabase
SQLiteDatabase db = openOrCreateDatabase("course", Context.MODE_PRIVATE, null);
lst1 = findViewById(R.id.lst1);
cannot resolve the method findViewById
cannot resolve the constructor ArrayAdapter
**arrayAdapter = new ArrayAdapter(this, `R.layout.support_simple_spinner_dropdown_item, titles);**`
lst1 = findViewById(R.id.lst1);
ListView lst1;
ArrayList<String> titles = new ArrayList<String>();
ArrayAdapter arrayAdapter;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SQLiteDatabase db = openOrCreateDatabase("course", Context.MODE_PRIVATE, null);
lst1 = findViewById(R.id.lst1);
final Cursor c = db.rawQuery("select * from category", null);
int id = c.getColumnIndex("id");
int title = c.getColumnIndex("title");
int description = c.getColumnIndex("description");
titles.clear();
arrayAdapter = new ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, titles);
lst1.setAdapter(arrayAdapter);
final ArrayList<cate> cat = new ArrayList<cate>();
if (c.moveToFirst()) {
do {
cate stu = new cate();
stu.id = c.getString(id);
stu.course = c.getString(title);
stu.description = c.getString(description);
cat.add(stu);
titles.add(c.getString(id) + " \t " + c.getString(title) );
} while (c.moveToNext());
arrayAdapter.notifyDataSetChanged();
lst1.invalidateViews();
}
lst1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String aa = titles.get(position).toString();
cate stu = cat.get(position);
Intent i = new Intent(getApplicationContext(), editcategory.class);
i.putExtra("id", stu.id);
i.putExtra("category", stu.course);
i.putExtra("description", stu.description);
startActivity(i);
}
});
}
You can't directly call openOrCreateDatabase() in a fragment because it is a method from Context. A fragment is not a context. To get the context / Activity, just call getActivity()
It will result in the following :
SQLiteDatabase db = getActivity().openOrCreateDatabase("course", Context.MODE_PRIVATE, null);
For findViewById() you have to call that on the parent view
view.findViewById(R.id.lst1);
For the adapter constructor, R.layout.support_simple_spinner_dropdown_item is not a string but an id from R class, so no need for '
arrayAdapter = new ArrayAdapter(getActivity(), R.layout.support_simple_spinner_dropdown_item, titles);

Generating a ListView Using ArrayAdapter [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to populate a ListView using an ArrayAdapter that I am filling with input from an EditText. My program seems to compile fine but during app start up it immediately crashes. I suspect that it has something to do with me trying to set-up my list view. I am not sure what I am initializing wrong such that my app instantly crashes. Any and all tips would be greatly appreciated. Thanks in advance!
This is my global declarations for my ArrayList and Adapter.
ArrayList<scoreScreen> savedScores = new ArrayList<>();
ScoreAdapter adapter = new ScoreAdapter(this, savedScores);
ListView listView = (ListView) findViewById(R.id.dispScores);
listView.setAdapter(adapter);
My Adapter Class:
private class ScoreAdapter extends ArrayAdapter<scoreScreen> {
private ScoreAdapter(Context context, ArrayList<scoreScreen> scores) {
super(context, 0, scores);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
scoreScreen score1 = getItem(position);
if (convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_scores, parent, false);
}
TextView holeNum = (TextView) convertView.findViewById(R.id.holeNum);
holeNum.setText(score1.hole);
return convertView;
}
}
My ListView inside of my onCreate method.
ListView listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(adapter);
I am assuming my problem is not inside my EditText inputs since they are inside of an OnClickListener method, but just incase I have attached it below.
public View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText input1 = (EditText) findViewById(R.id.scorePrompt);
TextView output1 = (TextView) findViewById(R.id.textTotal);
String blankCheck = input1.getText().toString(); //CHANGE INPUT IN scorePrompt TO STRING
switch (view.getId()) {
case R.id.buttTotal:
if (blankCheck.equals("")) {
Toast blankError = Toast.makeText(getApplicationContext(), "YOU CANT SKIP HOLES JERK", Toast.LENGTH_LONG);
blankError.show();
break;
} else {
int num1 = Integer.parseInt(input1.getText().toString()); //Get input from text box
int sum = num1 + score2;
score2 = sum;
output1.setText("Your score is : " + Integer.toString(sum));
//savedScores.add(input1.getText().toString());
scoreScreen addScore = new scoreScreen("Score is" + num1);
adapter.add(addScore);
j++;
input1.setText(""); //Clear input text box
break;
}
case R.id.allScores: //CHANGE THIS TO AN EDIT BUTTON, ADD A HOLE NUMBER COUNTER AT TOP OF SCREEN!!!!!
output1.setText("you messed up");
break;
case R.id.editScore: //Need to set up Save Array before we can edit
//CURRENTLY ONLY DISPLAYS THE LAST NUNMBER IN THE TEXTEDIT, NEED TO SET UP LISTVIEW!!!!!!
for (int i=0; i < j; i++){
// output1.setText(savedScores.get(i));
} break;
}
}
};
onCreate method added as requested:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*Button scoresAct = (Button) findViewById(R.id.allScores); //THIS IS TO GO TO ALL SCORES ACTIVITY
scoresAct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent scoreScreen = new Intent(MainActivity.this, AllScoresAct.class);
startActivity(scoreScreen);
}
});*/
Button sumScores = (Button) findViewById(R.id.buttTotal);
Button saveScores = (Button) findViewById(R.id.allScores);
Button changeScores = (Button) findViewById(R.id.editScore);
sumScores.setOnClickListener(onClickListener);
saveScores.setOnClickListener(onClickListener);
changeScores.setOnClickListener(onClickListener);
ListView listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(adapter);
}
After moving my adapter and ArrayList into my onCreate, I get a new error. I did some research on null pointers, but I have already initialized both of these. Below is my logcat, any ideas? Thanks
Make sure super.onCreate(savedInstanceState) is the first thing you are calling in your onCreate() and also not trying to access any view from the layout xml before setContentView().
EDIT:
Initialize the adapter in onCreate() method instead of doing it globally.
onCreate() {
.......
this.adapter = new ScoreAdapter(this, savedScores);
}
This is my global declarations for my ArrayList and Adapter.
ArrayList<scoreScreen> savedScores = new ArrayList<>();
ScoreAdapter adapter = new ScoreAdapter(this, savedScores);
You can declare those globally, but for the Adapter, the this parameter must be used within/after onCreate, as the error says
System services not available to Activities before onCreate()
For example
private ArrayList<ScoreScreen> savedScores = new ArrayList<>();
private ScoreAdapter adapter;
#Override
protected void onCreate(Bundle b) {
...
adapter = new ScoreAdapter(this, savedScores);
}

I keep getting null pointer exception on my getArguments();

From a list, the user can click and item and a fragment will inflate showing the data for the clicked item, where the user also can edit that data and click save to save the edited data.
But from the screen that contains the list is also an add button if the user wants to create a new object.
When the user clicks on an item from the list, a newInstance(..); is called
and in the Fragments onCreateView(); I initilize all variables for that clicked item in the different views. But that is not working well because I keep getting:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String, int)' on a null object reference
newInstance is called from the RecyclerView Adapter onClick():
public static CreateTrainingFragment newInstance(ItemModel itemModel) {
bundle = new Bundle();
bundle.putInt(SB_DURATION, itemModel.getDuration());
bundle.putInt(SB_DISTANCE, itemModel.getDistance());
CreateTrainingFragment createTrainingFragment = new CreateTrainingFragment();
createTrainingFragment.setArguments(bundle);
return createTrainingFragment;
}
Here I use getArguments(); and feed the arguments into Views:
Would the default 0 variable not automatically be inserted into my sbduration.setProgress(); if the argument dont exist?
private void initArgumentsData() {
sbduration.setProgress(getArguments().getInt(SB_DURATION, 0));
sbDistance.setProgress(getArguments().getInt(SB_DISTANCE, 0));
txtduration.setText(getArguments().getInt(SB_DURATION, 0) + " min");
txtDistance.setText(getArguments().getInt(SB_DISTANCE, 0) + " km");
}
Here is how my Views is created and where I use InitArgumentData();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.createtraining_layout, container, false);
sbduration = (SeekBar) v.findViewById(R.id.seekbar_time);
sbDistance = (SeekBar) v.findViewById(R.id.seekbar_distance);
txtduration = (TextView) v.findViewById(R.id.time_value);
txtDistance = (TextView) v.findViewById(R.id.distance_value);
sbduration.setMax(100);
sbDistance.setMax(50);
initArgumentsData();
}
From RecyclerView I start a new fragment instance like this:
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ItemModel itemModel = realm.getDefaultInstance().where(ItemModel.class).equalTo("timestamp",list.get(getAdapterPosition()).getTimestamp()).findFirst();
CreateTrainingFragment createTrainingFragment = CreateTrainingFragment.newInstance(itemModel, true);
fragmentManager.beginTransaction().replace(R.id.navdrawer_maincontainer,createTrainingFragment).addToBackStack(null).commit();
}
});
From the add button the Fragment is started like this:
addbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().beginTransaction().replace(R.id.navdrawer_maincontainer,new CreateTrainingFragment()).addToBackStack(null).commit();
}
});
getFragmentManager().beginTransaction().replace(R.id.navdrawer_maincontainer,new CreateTrainingFragment()).addToBackStack(null).commit();
Here, you're using new CreateTrainingFragment(). Hence, you're not getting the bundle since there is no bundle attach to it. You should call the newInstance method first to get the an object of CreateTrainingFragment and then put it on replace.
ItemModel itemModel = realm.getDefaultInstance().where(ItemModel.class).equalTo("timestamp",list.get(getAdapterPosition()).getTimestamp()).findFirst();
CreateTrainingFragment createTrainingFragment = CreateTrainingFragment.newInstance(itemModel, true);
getFragmentManager().beginTransaction().replace(R.id.navdrawer_maincontainer, createTrainingFragment).addToBackStack(null).commit();
How about you just check if the arguments exist?
private void initArgumentsData() {
Bundle args = getArguments();
int duration = 0;
int distance = 0;
if (args != null) {
duration = args.getInt(SB_DURATION, 0);
distance = args.getInt(SB_DISTANCE, 0);
}
sbduration.setProgress(duration);
sbDistance.setProgress(distance);
txtduration.setText(duration + " min");
txtDistance.setText(distance + " km");
}
Even if you did call newInstance on the Fragment, you still would need to provide a new ItemModel to that method.

getSelectedItemPosition() of ListView returns -1

With this code, when System.out.println is executed after setSelection instruction, returns -1 and I don't know why.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.composition);
lv = (ListView) findViewById(android.R.id.list);
cabecera = (TextView) findViewById(R.id.cabecera);
information = (TextView) findViewById(R.id.paciente);
proceso = new ArrayList<>();
proceso.add("- Item1");
proceso.add("- Item2");
adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.customizedlistitem,proceso);
lv.setAdapter(adapter);
lv.post(new Runnable() {
#Override
public void run() {
lv.setSelected(true);
lv.setSelection(0);
adapter.notifyDataSetChanged();
System.out.println("Selected Item onCreate: "+lv.getSelectedItemPosition());
System.out.println("Get Count en onCreate: "+lv.getCount());
}
});
nextBundle = new Bundle();
nextBundle.putString("name",proceso.get(position));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
in = new Intent(getApplicationContext(),Check.class);
in.putExtras(nextBundle);
startActivity(in);
}
});
}
getCount() function applied to the ListView returns a correct value: 2
I have searched to find a solution but all that I have read and tested don't solve the problem.
UPDATE:
This code:
listPacientes = new ArrayList<>();
listPacientes.add("Elemento 1");
listPacientes.add("Elemento 2");
listPacientes.add("Elemento 3");
adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.customizedlistitem,list);
lv.setAdapter(adapter);
lv.setSelection(1);
System.out.println(lv.getSelectedItemPosition());
works on Main Activity. That "System.out" returns 1, but the same code in next Activities, returns -1, why? I can't understand it.
you are first selecting the cell and afterwards refreshing the ListView by calling adapter.notifyDataSetChanged(); - this way your selection is removed.
Use lv.getSelectedItemPosition() method inside onItemClick() method. you will get the proper value here

Fragment Error - ListFragment cannot be cast to android.app.Activity

I have a fragment view that needs replacement with another fragment.
When the ListFragment item is selected, the DetailsFragment is to be replaced with another ListFragment by passing along Extras to the new ( or 2nd) ListFragment in the activity. My problem is that I am getting a "No Activity found to handle Intent {(has extras)}". The ListFragment works fine when the activity first starts, but when i up date (replace) the Details activity with another ListFragment, I get the error.
This is my first Fragment activity and I guess I don't know how to pass Extras properly between the fragment. I am most surely not using the fragment-manager/transaction classes properly(?). If anyone could correct my implementation, I would greatly appreciate it.
UPDATE: I added "i.setClass(getActivity(), ListFragment.class);" to the intent in the ListFragment class and now the Log error has changed to the following:
UPDTATE 2: I corrected my intents to Arguments as Devunwired sugested and it works just beautifully now. Thnx Devunwired. the onlyn issue I have now is that the backstack doesnt work when the back key is pressed. The corrected class is below:
LogCat (UPDATED):
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.andaero.test/com.andaero.test.fragments.ListFragment}: java.lang.ClassCastException: com.andaero.test.fragments.ListFragment cannot be cast to android.app.Activity
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1739)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1831)
at android.app.ActivityThread.access$500(ActivityThread.java:122)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1024)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:132)
at android.app.ActivityThread.main(ActivityThread.java:4123)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:491)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: com.andaero.test.fragments.ListFragment cannot be cast to android.app.Activity
The ListFragment Class:
public class ListFragment extends android.app.ListFragment {
boolean mDualPane;
int mCurCheckPosition = 0;
protected TextView activityTitle;
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
File dbfile = new File(extStorageDirectory + "/Andaero/dB/Andaero.db");
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
private static final String QUERY_KEY = "QUERY_KEY";
private static final String QUERY_ORDER = "QUERY_ORDER";
private View layout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
layout = inflater.inflate(R.layout.listview, null);
return layout;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle extras = getActivity().getIntent().getExtras();
Bundle arg = this.getArguments();//**ADDED TO GET THE ARGS
/**
* Get the query string from last activity and pass it to this
* activity-----------------------------------------------------
*/
String q = null;
if (extras != null) {
q = extras.getString(QUERY_KEY);
}
if (arg != null) {
q = (String) (getArguments() != null ? getArguments().getString(
"QUERY_KEY") : 1);
}
loadQuery(q);
}
public void loadQuery(String q) {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
String qO = getActivity().getIntent().getStringExtra("QUERY_ORDER");
Cursor c = db.rawQuery(q + " ORDER BY `_id` " + qO, null);
setListAdapter(new QueryAdapter(getActivity(), c));
db.close();
} else {
Alerts.sdCardMissing(getActivity());
}
}
public class QueryAdapter extends CursorAdapter {
public QueryAdapter(Context context, Cursor c) {
super(context, c);
LayoutInflater.from(context);
}
#Override
public void bindView(View v, Context context, final Cursor c) {
int tvLabel = c.getColumnIndexOrThrow("label");
String label = c.getString(tvLabel);
final TextView labelTxt = (TextView) v.findViewById(R.id.label);
if (labelTxt != null) {
labelTxt.setText("(" + label + ")");
}
int tvTitle = c.getColumnIndexOrThrow("title");
final String title = c.getString(tvTitle);
TextView titleTxt = (TextView) v.findViewById(R.id.listTitle);
if (titleTxt != null) {
titleTxt.setText(title);
}
int tvDescription = c.getColumnIndexOrThrow("description");
String description = c.getString(tvDescription);
TextView descriptionTxt = (TextView) v.findViewById(R.id.caption);
if (descriptionTxt != null) {
descriptionTxt.setText(description);
}
int tvDate = c.getColumnIndexOrThrow("date");
String date = c.getString(tvDate);
TextView dateTxt = (TextView) v.findViewById(R.id.dateAdded);
if (dateTxt != null) {
dateTxt.setText(date);
}
int tvGoto = c.getColumnIndexOrThrow("gotoURL");
final String gotoURL = c.getString(tvGoto);
TextView gotoTxt = (TextView) v.findViewById(R.id.dummy);
if (gotoTxt != null) {
gotoTxt.setText(gotoURL);
}
gotoTxt.setVisibility(View.GONE);
v.setTag(gotoURL);
final ListView lv = getListView();
lv.setEnabled(true);
lv.setClickable(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int arg2,
long arg3) {
// Create new fragment and transaction
Fragment newFragment = new ListFragment();
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
// Replace whatever is in the fragment_container view with
// this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.detailFragment, newFragment);
transaction.addToBackStack(null);
String url = "";
url = (String) v.getTag();
int nI = c.getColumnIndexOrThrow("intent");
String intent = c.getString(nI);
Class<?> myIntent = null;
try {
myIntent = Class.forName("com.andaero.test.fragments"
+ intent);
} catch (ClassNotFoundException e) {
Log.e("ERROR", "Class Not Found for new intent!");
e.printStackTrace();
}
int tvTitle = c.getColumnIndexOrThrow("title");
String title = c.getString(tvTitle);
int tvLabel = c.getColumnIndexOrThrow("label");
String label = c.getString(tvLabel);
String queryKey = "SELECT * FROM " + label;
c.close();
db.close();
Bundle args = new Bundle();//**REPLACED THE INTENTS
args.putString("QUERY_KEY", queryKey);
args.putString("KEY_URL", url);
args.putString("KEY_SUBTITLE", title);
args.putString("KEY_LABEL", label);
args.putString("KEY_INTENT", intent);
args.putString("QUERY_ORDER", "ASC");
newFragment.setArguments(args);
// Commit the transaction
transaction.commit();
}
});
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final View v = LayoutInflater.from(context).inflate(
R.layout.list_item, parent, false);
return v;
}
}
}
You're on the right track with using the FragmentTransaction to replace one Fragment with another, but Fragment doesn't use an Intent to pass data from one instance to another like Activity does. In fact, calling startActivity() with an Intent pointed at a Fragment will cause all kinds of fireworks that you don't want (like you've seen).
It is perfectly okay to pass data to a new Fragment in its constructor, so you can create a constructor for your ListFragment that takes any parameters of data you want to forward. Another option is to set all of your "extras" as arguments on the new Fragment by putting them in a Bundle and using Fragment.setArguments(). Any time you want to access the arguments you attached to the Fragment, you can just call getArguments() to get back that same Bundle. So basically, replace all the code having to do with an Intent in your onItemClick() method, and instead:
Bundle args = new Bundle();
args.putString("QUERY_KEY", queryKey);
//...add all the extras to the bundle
newFragment.setArguments(args);
transaction.commit();
Also, off-topic, but you might want to rename your Fragment to something else so that you don't have to rely on the fully qualified package name to tell the difference between your ListFragment and the platform's version in your code.
HTH
why dont you just create a constructor that you pass the values into when you create the fragment? It seems that is what you are looking to do

Categories

Resources