[Q] Fragment null pointer after orientation change - Android Q&A, Help & Troubleshooting

Hi
I have a class Fragment_b extends Fragment with
Code:
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_b_layout, container, false);
return view;
}
frag_b_layout with root element of ScrollView containing a RelativeLayout with @+id/dummy for Android Studio ID sake.
in the container Activity
Code:
public class MainActivity extends ActionBarActivity{
Fragment_b fragment_b;
FragmentManager manager;
//...
FragmentTransaction transaction = manager.beginTransaction();
public void myFunc(){
if (fragment_b == null){
fragment_b = new Fragment_b();
transaction.add(R.id.container_activity_layout, fragment_b, "someTag");
transaction.commit();
//...
}
}
//...
}
All works fine, but when device orientation changes, fragment_b appears again but with fragment_b == null returns true, I was expecting false. what can I do so that it works as I expect?
for no avail, I tried
in the AndroidManifest
Code:
android:windowSoftInputMode="stateUnchanged|adjustResize"
in the onCreate of fragment_b
Code:
this.setRetainInstance(true);
Thank you

Related

[Q] How to get the position of an item when dropped in a Gridview

Hi there!
I'm trying to know how to get the position of an item when it is already been dropped. I have used a gridview to list images.
my xml code is:
Code:
<RelativeLayout xmlns:android="..."
xmlns:tools="..."
android:id="@+id/parent_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<GridView
android:id="@+id/grid_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:horizontalSpacing="10dip"
android:numColumns="4"
android:verticalSpacing="10dip" />
</RelativeLayout>
here is my mainactivity class:
Code:
public class MainActivity extends Activity implements OnDragListener,
OnItemLongClickListener {
ArrayList drawables;
GridView gridView;
private BaseAdapter adapter;
private int draggedIndex = -1;
private int droppedIndex = -1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawables = new ArrayList();
drawables.add(R.drawable.ic_launcher);
drawables.add(R.drawable.ic_launcher);
drawables.add(R.drawable.ic_launcher);
drawables.add(R.drawable.ic_launcher);
drawables.add(R.drawable.ic_launcher);
drawables.add(R.drawable.ic_launcher);
drawables.add(R.drawable.ic_launcher);
drawables.add(R.drawable.ic_launcher);
gridView = (GridView) findViewById(R.id.grid_view);
gridView.setOnItemLongClickListener(MainActivity.this);
gridView.setAdapter(adapter = new BaseAdapter() {
@Override
// Get a View that displays the data at the specified position in
// the data set.
public View getView(int position, View convertView,
ViewGroup gridView) {
// try to reuse the views.
ImageView view = (ImageView) convertView;
// if convert view is null then create a new instance else reuse
// it
if (view == null) {
view = new ImageView(MainActivity.this);
}
view.setImageResource((Integer) drawables.get(position));
view.setTag(String.valueOf(position));
return view;
}
@Override
// Get the row id associated with the specified position in the
// list.
public long getItemId(int position) {
return position;
}
@Override
// Get the data item associated with the specified position in the
// data set.
public Object getItem(int position) {
return drawables.get(position);
}
@Override
// How many items are in the data set represented by this Adapter.
public int getCount() {
return drawables.size();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onDrag(View view, DragEvent dragEvent) {
switch (dragEvent.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
// Ignore this event
return true;
case DragEvent.ACTION_DRAG_ENTERED:
// Ignore this event
return true;
case DragEvent.ACTION_DRAG_EXITED:
// Ignore this event
return true;
case DragEvent.ACTION_DRAG_LOCATION:
// Ignore this event
return true;
case DragEvent.ACTION_DROP:
// Dropped inside a new view
// get the position where the item is been dropped
adapter.notifyDataSetChanged();
case DragEvent.ACTION_DRAG_ENDED:
view.setOnDragListener(null);
return true;
}
return false;
}
@Override
public boolean onItemLongClick(AdapterView gridView, View view,
int position, long row) {
ClipData.Item item = new ClipData.Item((String) view.getTag());
ClipData clipData = new ClipData((CharSequence) view.getTag(),
new String[] { ClipDescription.MIMETYPE_TEXT_PLAIN }, item);
view.startDrag(clipData, new View.DragShadowBuilder(view), null, 0);
view.setVisibility(View.INVISIBLE);
draggedIndex = position;
return true;
}
}
I guessed that i can get the position when the action is "DragEvent.ACTION_DROP" but i cannot come up with the way to get the position!
Any ideas?
thanks in advance

[SOLVED][Q] Cannot find a symbol, while other symbols are found fine

I couldn't think of a better way to word the title, but the issue I'm having is this: I'm using HoloColorPicker by Lars Werkman. Now I have correctly imported the library, I can see the ColorPicker and other views from the library in my app, the only symbol that is failing to be found is OnColorChangedListener. I looked through the code of the library and it is an interface that is defined in ColorPicker.java, which I am importing, and the ColorPicker view itself, as I already stated, is appearing in my GUI fine.
Here is my associated code:
Code:
import com.larswerkman.holocolorpicker.SaturationBar;
import com.larswerkman.holocolorpicker.ColorPicker;
import com.larswerkman.holocolorpicker.ValueBar;
public class ColorChooserDialog extends DialogFragment {
private String title;
private CustomColor cur_color;
private boolean edit = false;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.choose_color_dialog_title);
// Inflate layout color chooser view and set to builder
LayoutInflater layout_inflater = getActivity().getLayoutInflater();
View view = layout_inflater.inflate(R.layout.color_chooser_view, null);
builder.setView(view);
// Get views by IDs
EditText hex_input = (EditText)view.findViewById(R.id.hexInput);
EditText red_input = (EditText)view.findViewById(R.id.redInput);
EditText green_input = (EditText)view.findViewById(R.id.greenInput);
EditText blue_input = (EditText)view.findViewById(R.id.blueInput);
ColorPicker color_picker = (ColorPicker)view.findViewById(R.id.colorPicker);
SaturationBar sat_bar = (SaturationBar)view.findViewById(R.id.saturationBar);
ValueBar val_bar = (ValueBar)view.findViewById(R.id.valueBar);
// Connect bars to color picker
color_picker.addSaturationBar(sat_bar);
color_picker.addValueBar(val_bar);
// When color is changed via picker, set text fields
color_picker.setOnColorChangedListener(new OnColorChangedListener() {
@Override
public void onColorChanged(int color) {
//TODO
}
});
// Add listener for when HEX value is changed
hex_input.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable editable) {}
@Override
public void beforeTextChanged(CharSequence chars, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence chars, int start, int before, int count) {
//TODO
}
});
builder.setPositiveButton(
R.string.ok_button,
new DialogInterface.OnClickListener() {
// User clicked OK, add color to palette
public void onClick(DialogInterface dialog, int id) {
//TODO
}
}
);
builder.setNegativeButton(
R.string.cancel_button,
new DialogInterface.OnClickListener() {
// User cancelled the dialog, don't create palette
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}
);
// Create the AlertDialog object and return it
return builder.create();
}
}
OK, so I figured it out, I didn't notice this at first because Java is not my first language, but the OnColorChangedListener is within the ColorPicker class, so I instead of using this:
Code:
color_picker.setOnColorChangedListener(new OnColorChangedListener() {
@Override
public void onColorChanged(int color) {
//TODO
}
});
I needed to use this:
Code:
color_picker.setOnColorChangedListener(new [B]ColorPicker.[/B]OnColorChangedListener() {
@Override
public void onColorChanged(int color) {
//TODO
}
});

[Q] Can't reference a non static method.

I hope this is the right place to ask this. The other sections seem to be more about discussion. I am running into one error that I have not encountered before and have tried quite a bit to find out what is going on.
AndroidStudio said:
Error: (109, 51) error: non-static method getAllContacts() cannot be referenced from a static context
Click to expand...
Click to collapse
Code:
// Class for dealing with the database
package com.testapplication.app;
import ...
public class DataBaseHandler extends SQLiteOpenHelper {
public List<Contact> getAllContacts() {
List<Contact> contListAdapt = new ArrayList<Contact>();
// Becomes non static in a static context if the method becomes static
SQLiteDatabase sql = getWritableDatabase();
Cursor cursor = sql.rawQuery("SELECT * FROM " + TABLE_CONTACTS, null);
if (cursor.moveToFirst()) {
do {
new Contact(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), Uri.parse(cursor.getString(5)));
} while (cursor.moveToNext());
}
cursor.close();
sql.close();
return contListAdapt;
}
}
Code:
// The main activity
package com.testapplication.app;
import ...
public class MainActivity extends ActionBarActivity {
List<Contact> contactListAdapter = new ArrayList<Contact>();
@Override
protected void onCreate (Bundle savedInstanceState) {
// There is a class called Contact
// FIXME : non static method in static context
Collection<Contact> coll = DataBaseHandler.getAllContacts();
if(!coll.isEmpty()) {
contactListAdapter.addAll(coll);
}
}
}
As far as I can tell this is all that is involved with this error. If I make getAllContacts() static then I will get the same old error but in a different spot: getWritableDatabase();

[Q] referencing a dynamica fragment

Hi
Frag1 which is a side navigation drawer, is instantiated in MainActivity.java onCreate by manager.findFragmentById since there is a fragment tag in a xml file.
Frag2 and Frag3 are dynamically committed at some point by a manager, non of their layouts contain a <fragment> tag, they are not committed in the MainActivity onCreate method and thus don't have ids or tags either.
When a button on frag2 is pressed, frag3 "a dialogFragment" needs to be displayed on the screen for user login inputs.
How can I get this to work? I am getting null pointer when referencing frag2 in MainActivity.
here is a illustrative stripped down version of the code. sorry for any unintended typos
Thank you for helping
Frag2.java
Code:
public class Frag2 extends Fragment {
Frag2Communicator = mFrag2communicator;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.frag2_layout, container, false);
class ClickHandler implements View.OnClickListener {
@Override
public void onClick(View v) {
mFrag2communicator.show_frag3();
}
}
}
public interface Frag2Communicator {
public void show_frag3();
}
public void setFrag2Communicator(Frag2Communicator frag2communicator) {
mFrag2communicator = frag2communicator;
}
}
MainActivity.java
Code:
public class MainActivity extends ActionBarActivity implements frag2.frag2Communicator {
protected void onCreate(Bundle savedInstanceState) {
Frag2 frag2 = getSupportFragmentManager().findFragmentById(R.id.frag_2);
//frag_2 is the id of a RelativeLayout inside a ScrollView inside frag2_layout.xml
//I tried to move this ide to the root tag "ScrollView" but still get a null pointer.
frag2.setFrag2Communicator(this);
public void show_frag3(){
FragmentManager manager = getSupportFragmentManager();
Frag3 frag_3 = new Frag3();
frag_3.show(manager, "loging");
}
}
}

transfer List from activity to fragment in Android

Hello,
I have an activity:
public List<Steps> steps;
Recipe recipe;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_activity);
///..........
steps = recipe.getRecipeSteps();
int len1 = steps.size();
Log.i(TAG, "Steps length=" + len1);
}
public List<Steps> getMyData() {
return steps;
}
and a fragment
public class FragmentStepTitle extends Fragment {
// Whether the app has two panel( tablet ) or one panel( phone ).
//private boolean hasTwoPanel = false;
@nullable
@override
public View onCreateView(LayoutInflater inflater, @nullable ViewGroup container, @nullable Bundle savedInstanceState) {
.....
//receive info from detail
DetailActivity activity = (DetailActivity) getActivity();
List<Steps> myDataFromActivity = activity.getMyData();
Log.i("Fragment",myDataFromActivity.get(0).getShortDescription());
return ret;
}
}
The error caused is:
Attempt to invoke interface method ‘java.lang.Object java.util.List.get(int)’ on a null object reference
at com.example.ionutb.baking.ui.FragmentStepTitle.onCreateView
Why I don-t see the List value??

Categories

Resources