I have this code below. It works before in Activity. Now I want to convert it to Fragment. I have tried context.getContentResolver(); or getActivity().getContentResolver(); But it doesn't work. How to fix this ?
public class MyFragmentA extends Fragment {
//song list variables
private ArrayList<Song> songList;
private ListView songView;
public Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.fragment_a, container, false);
//retrieve list view
songView = (ListView) myFragmentView.findViewById(R.id.song_list);
//instantiate list
songList = new ArrayList<Song>();
//get songs from device
getSongList();
//sort alphabetically by title
Collections.sort(songList, new Comparator<Song>(){
public int compare(Song a, Song b){
return a.getTitle().compareTo(b.getTitle());
}
});
//create and set adapter
SongAdapter songAdt = new SongAdapter(this.getActivity(), songList);
songView.setAdapter(songAdt);
return myFragmentView;
}
public void getSongList() {
ContentResolver musicResolver = context.getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
----------------------
----------------------
----------------------
----------------------
}
}
}
This my logcat trace
11-25 20:29:34.001: E/AndroidRuntime(4092): FATAL EXCEPTION: main
11-25 20:29:34.001: E/AndroidRuntime(4092): Process: com.ddev.delta, PID: 4092
11-25 20:29:34.001: E/AndroidRuntime(4092): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ddev.delta/com.ddev.delta.AndroidNavigationTabsActivity}: java.lang.NullPointerException
11-25 20:29:34.001: E/AndroidRuntime(4092): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2212)
11-25 20:29:34.001: E/AndroidRuntime(4092): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271)
11-25 20:29:34.001: E/AndroidRuntime(4092): at android.app.ActivityThread.access$800(ActivityThread.java:144)
11-25 20:29:34.001: E/AndroidRuntime(4092): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
11-25 20:29:34.001: E/AndroidRuntime(4092): at android.os.Handler.dispatchMessage(Handler.java:102)
11-25 20:29:34.001: E/AndroidRuntime(4092): at android.os.Looper.loop(Looper.java:136)
11-25 20:29:34.001: E/AndroidRuntime(4092): at android.app.ActivityThread.main(ActivityThread.java:5146)
11-25 20:29:34.001: E/AndroidRuntime(4092): at java.lang.reflect.Method.invokeNative(Native Method)
11-25 20:29:34.001: E/AndroidRuntime(4092): at java.lang.reflect.Method.invoke(Method.java:515)
11-25 20:29:34.001: E/AndroidRuntime(4092): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
11-25 20:29:34.001: E/AndroidRuntime(4092): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
11-25 20:29:34.001: E/AndroidRuntime(4092): at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
11-25 20:29:34.001: E/AndroidRuntime(4092): at dalvik.system.NativeStart.main(Native Method)
11-25 20:29:34.001: E/AndroidRuntime(4092): Caused by: java.lang.NullPointerException
11-25 20:29:34.001: E/AndroidRuntime(4092): at com.ddev.delta.AndroidNavigationTabsActivity.onCreate(AndroidNavigationTabsActivity.java:17)
11-25 20:29:34.001: E/AndroidRuntime(4092): at android.app.Activity.performCreate(Activity.java:5231)
11-25 20:29:34.001: E/AndroidRuntime(4092): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-25 20:29:34.001: E/AndroidRuntime(4092): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
11-25 20:29:34.001: E/AndroidRuntime(4092): ... 12 more
ContentResolver musicResolver = context.getContentResolver();
Your context is not initialized.
Since you're in a fragment lifecycle callback onCreateView() or a method called from one, you can use getActivity() for a Context:
ContentResolver musicResolver = getActivity().getContentResolver();
Remove the Context context; declaration as unnecessary, too.
public Context context;
Your context is null, try use getActivity().getContentResolver();
Initialize context object in onCreateView() before call getSongList():
context = getActivity();
OR
getActivity().getContentResolver()
Create an object of Activity and then initialize it by
Activity a=getActivity();
And then use
ContentResolver musicResolver = a.getContentResolver();
Use Following for these Cases:
Application :- getApplicationContext()
activity :- context
Fragment :- getActivity()
Related
I have this problem that whenever i click on the listView OnItemClick method it always crashes when it is trying to reach another intent down below i leave some code.
public class SelectFichas extends AppCompatActivity {
TextView tv;
ListView lv;
RecyclerView.LayoutManager mLayoutManager;
ImageButton btn1;
ArrayList<Ficha> slFichas;
List<Ficha> ftchArray;
DBHelper db;
MyAdapter aAdapt = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_ficha);
btn1 = (ImageButton) (findViewById(R.id.rg));
lv = (ListView) (findViewById(R.id.lv1));
db = new DBHelper(this);
try {
//Verificamos que la base de datos no este vacia
if (!db.isEmpty()) {
ftchArray = db.getAllFichas();
slFichas = new ArrayList<Ficha>();
for (Ficha fi : ftchArray) {
slFichas.add(fi);
}
// mAdapter = new MyAdapter(ftchArray,getApplication());
aAdapt = new MyAdapter(SelectFichas.this,0,slFichas);
View header = getLayoutInflater().inflate(R.layout.list_header, null);
lv.addHeaderView(header);
lv.setAdapter(aAdapt);
lv.setItemsCanFocus(false);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick( AdapterView<?> parent, View view, int position, long id) {
Ficha fi = (Ficha) aAdapt.getItem(position-1);
String sel = fi.getPreg();
String[] opc = {"Actualizar", "Borrar", "Adivinar", "Atras"};
Toast.makeText(getApplicationContext(), "Usted selecciono " +sel, Toast.LENGTH_SHORT).show();
final Intent intent = new Intent(SelectFichas.this,UpdFicha.class);
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
if (intent.resolveActivity(getPackageManager()) != null){
startActivity(intent);
}
}
}, 2000);
I also used a custom ArrayAdapter for my ListView is that influencing, in case i will leave some code about the adapter below.
public class MyAdapter extends ArrayAdapter<Ficha> {
private Context context;
private ArrayList<Ficha> ficha;
public MyAdapter(Context context, int resource, ArrayList<Ficha> objects) {
super(context, resource, objects);
this.context = context;
this.ficha = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
Ficha fi = ficha.get(position);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.list_items, parent,false);
RelativeLayout rv = (RelativeLayout)(view.findViewById(R.id.relativeLayout));
TextView id = (TextView)view.findViewById(R.id.id_view);
TextView preg = (TextView)view.findViewById(R.id.preg_view);
TextView ans = (TextView) view.findViewById(R.id.answer_view);
id.setText(String.valueOf(fi.getId()));
preg.setText(fi.getPreg());
ans.setText(fi.getRes());
return view;
}
}
Here is my Logcat EDITED
2-05 11:52:06.886 5997-5997/com.giamp.fichas W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x9ccbcb20)
12-05 11:52:06.886 5997-5997/com.giamp.fichas E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.giamp.fichas, PID: 5997
java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:386)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:193)
at android.widget.Spinner.onMeasure(Spinner.java:482)
at android.support.v7.widget.AppCompatSpinner.onMeasure(AppCompatSpinner.java:416)
at android.view.View.measure(View.java:16497)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:719)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:389)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
at android.view.View.measure(View.java:16497)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:544)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.TextView
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:379)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:193)
at android.widget.Spinner.onMeasure(Spinner.java:482)
at android.support.v7.widget.AppCompatSpinner.onMeasure(AppCompatSpinner.java:416)
at android.view.View.measure(View.java:16497)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:719)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:389)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
at android.view.View.measure(View.java:16497)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:544)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
AdapterView<?> parent is not an Adapter, but it is a ViewGroup.
change
ArrayAdapter<Ficha> aAdapt = new MyAdapter(SelectFichas.this, 0, slFichas);
to
final MyAdapter aAdapt = new MyAdapter(SelectFichas.this, 0, slFichas);
and
Ficha fi = (Ficha) parent.getItemAtPosition(position);
to
Ficha fi = (Ficha) aAdapt.getItem(position);
I am trying to use the Volley library to query an xml api on the web with a search query provided by the user through a SearchWidget.
Whenever I enter a search string, the app crashes with a NullPointerException on adding the StringRequest to the RequestQueue.
Why is this happening?
I am already using Volley with a singleton pattern, as recommended in the Android Developer Guide.
Here is my search() function in the MainActivity.
public static final String TAG = "MYAPPTAG"
private RequestQueue mRequestQueue;
...
protected void onCreate(Bundle savedInstanceState) {
...
// Handle search intent
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
search(query);
}
volley = MySingleton.getInstance(getApplicationContext());
mRequestQueue = volley.getRequestQueue();
}
...
private void search(String query) {
String xml = null;
String url = "http://www.acme.com/example.php?query=" + query;
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
stringRequest.setTag(TAG);
mRequestQueue
.add(stringRequest); // the exception fires here
}
...
See below for the stack trace.
02-22 23:08:50.636 9856-9856/com.example.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.app, PID: 9856
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.app/com.example.app.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2212)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5146)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.app.MainActivity.search(MainActivity.java:121)
at com.example.app.MainActivity.onCreate(MainActivity.java:83)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5146)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
at dalvik.system.NativeStart.main(Native Method)
You are firing off a search before you've set the requestqueue from singleton.
So onCreate, you check for the Intent and then start a search before you've got a handle on the volley singleton and, in turn, the requestqueue. Try moving the volley code before the Intent check, like this:
volley = MySingleton.getInstance(getApplicationContext());
mRequestQueue = volley.getRequestQueue();
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
search(query);
}
My problem is the following:
I want to create a really simple App, that shall play a song when i press a button.
public class MainActivity extends ActionBarActivity {
int counter;
Button add1;
Button sub1;
Button sound;
TextView display;
MediaPlayer mySound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
if (mySound==null){
mySound = MediaPlayer.create(this, R.raw.tetris_theme);
}
else { mySound.release();
}
sound = (Button) findViewById(R.id.button1);
display = (TextView) findViewById(R.id.textView2);
sound.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO Auto-generated method stub
if (mySound==null){
display.setText("Error");
}
else {
mySound.start();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
When I run the app and press the button "sound" it displays "Error"(since I checked whether mySound is null or not)
So, I figured that meant that the mySound MediaPLayer I created is null.
I checked the logcat and it showed the following:
11-25 14:27:02.900: E/MediaPlayer(1026): error (1, -2147483648)
11-25 14:27:02.920: D/MediaPlayer(1026): create failed:
11-25 14:27:02.920: D/MediaPlayer(1026): java.io.IOException: Prepare failed.: status=0x1
11-25 14:27:02.920: D/MediaPlayer(1026): at android.media.MediaPlayer.prepare(Native Method)
11-25 14:27:02.920: D/MediaPlayer(1026): at android.media.MediaPlayer.create(MediaPlayer.java:850)
11-25 14:27:02.920: D/MediaPlayer(1026): at com.example.simpleapp.MainActivity.onCreate(MainActivity.java:49)
11-25 14:27:02.920: D/MediaPlayer(1026): at android.app.Activity.performCreate(Activity.java:5242)
11-25 14:27:02.920: D/MediaPlayer(1026): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-25 14:27:02.920: D/MediaPlayer(1026): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2161)
11-25 14:27:02.920: D/MediaPlayer(1026): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2258)
11-25 14:27:02.920: D/MediaPlayer(1026): at android.app.ActivityThread.access$800(ActivityThread.java:138)
11-25 14:27:02.920: D/MediaPlayer(1026): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1209)
11-25 14:27:02.920: D/MediaPlayer(1026): at android.os.Handler.dispatchMessage(Handler.java:102)
11-25 14:27:02.920: D/MediaPlayer(1026): at android.os.Looper.loop(Looper.java:136)
11-25 14:27:02.920: D/MediaPlayer(1026): at android.app.ActivityThread.main(ActivityThread.java:5026)
11-25 14:27:02.920: D/MediaPlayer(1026): at java.lang.reflect.Method.invokeNative(Native Method)
11-25 14:27:02.920: D/MediaPlayer(1026): at java.lang.reflect.Method.invoke(Method.java:515)
11-25 14:27:02.920: D/MediaPlayer(1026): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
11-25 14:27:02.920: D/MediaPlayer(1026): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
11-25 14:27:02.920: D/MediaPlayer(1026): at dalvik.system.NativeStart.main(Native Method)
I guess that means that create failed, because prepare failed, but why?
I already searched for that problem on this website and found a hundred different cases but none
of the solutions did work for me.
the file I want to play is in mp3 and is located in my R.raw folder.
I can play it on my PC without any problems, so I guess it can't be corrupt or something.
I already tried with different types like .ogg and .aac but nothing(!!) works.
This will occur Your MediaPlayer object is not having any resource associated with it and so returned null.
Your file is having special characters. remove special characters and it must be in lower case.
mySound= MediaPlayer.create(this, R.raw.tetristheme);
your media file shoouldf be in the name tetristheme
Now you can use mySound.start() to start playing your media
I am getting the following errors:
The method getApplicationContext() is undefined
The method findViewById(int) is undefined for the type Fragment1
These errors seem to be eliminated when my class is extended to an Activity as oppose to a fragment, but it is important that this activity remains as a fragment, so I am not too sure how to work this out.
Any help would be greatly appreciated.
Thanks in advance.
Below is the code
public class Fragment1 extends Fragment {
private String currentUserId;
private ArrayAdapter<String> namesArrayAdapter;
private ArrayList<String> names;
private ListView usersListView;
private Button logoutButton;
String userGender = ParseUser.getCurrentUser().getString("Gender");
String activityName = ParseUser.getCurrentUser().getString("ActivityName");
Number maxDistance = ParseUser.getCurrentUser().getNumber("Maximum_Distance");
String userLookingGender = ParseUser.getCurrentUser().getString("Looking_Gender");
Number minimumAge = ParseUser.getCurrentUser().getNumber("Minimum_Age");
Number maximumAge = ParseUser.getCurrentUser().getNumber("Maximum_Age");
Number userage = ParseUser.getCurrentUser().getNumber("Age");
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
if (container == null){
return null;
}
return (LinearLayout)inflater.inflate(R.layout.fragment1_layout,
container,false);
logoutButton = (Button) findViewById(R.id.logoutButton);
logoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ParseUser.logOut();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
}
});
setConversationsList();
}
private void setConversationsList() {
currentUserId = ParseUser.getCurrentUser().getObjectId();
names = new ArrayList<String>();
// String userActivitySelectionName = null;
ParseQuery<ParseUser> query = ParseUser.getQuery();
// query.whereEqualTo("ActivityName",userActivitySelectionName);
query.whereNotEqualTo("objectId", ParseUser.getCurrentUser().getObjectId());
// users with Gender = currentUser.Looking_Gender
query.whereEqualTo("Gender", userLookingGender);
// users with Looking_Gender = currentUser.Gender
query.whereEqualTo("Looking_Gender", userGender);
query.setLimit(1);
query.whereEqualTo("ActivityName", activityName);
query.whereGreaterThanOrEqualTo("Minimum_Age", minimumAge).whereGreaterThanOrEqualTo("Age", userage);
query.whereLessThanOrEqualTo("Maximum_Age", maximumAge).whereLessThanOrEqualTo("Age", userage);
// query.whereWithinKilometers("Maximum_Distance", point, maxDistance)
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> userList, ParseException e) {
if (e == null) {
for (int i=0; i<userList.size(); i++) {
names.add(userList.get(i).get("Name").toString());
names.add(userList.get(i).get("Headline").toString());
names.add(userList.get(i).get("Age").toString());
// names.add(userList.get(i).getParseObject("ProfilePicture").;
}
usersListView = (ListView)findViewById(R.id.usersListView);
namesArrayAdapter =
new ArrayAdapter<String>(getApplicationContext(),
R.layout.user_list_item, names);
usersListView.setAdapter(namesArrayAdapter);
usersListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
openConversation(names, i);
}
});
} else {
Toast.makeText(getApplicationContext(),
"Error loading user list",
Toast.LENGTH_LONG).show();
}
}
});
}
public void openConversation(ArrayList<String> names, int pos) {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("Name", names.get(pos));
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> user, ParseException e) {
if (e == null) {
Intent intent = new Intent(getApplicationContext(), MessagingActivity.class);
intent.putExtra("RECIPIENT_ID", user.get(0).getObjectId());
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(),
"Error finding that user",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
Update
Unreachable code error for setConversationList
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
if (container == null){
return null;
}
return (LinearLayout)inflater.inflate(R.layout.fragment1_layout,
container,false);
setConversationsList();
}
private void setConversationsList() {
currentUserId = ParseUser.getCurrentUser().getObjectId();
names = new ArrayList<String>();
// String userActivitySelectionName = null;
ParseQuery<ParseUser> query = ParseUser.getQuery();
Update
Upon launching the activity, I received the following message:
08-15 14:52:16.365: E/AndroidRuntime(3332): FATAL EXCEPTION: main
08-15 14:52:16.365: E/AndroidRuntime(3332): Process: com.dooba.beta, PID: 3332
08-15 14:52:16.365: E/AndroidRuntime(3332): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dooba.beta/com.dooba.beta.usermatch}: java.lang.NullPointerException
08-15 14:52:16.365: E/AndroidRuntime(3332): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
08-15 14:52:16.365: E/AndroidRuntime(3332): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
08-15 14:52:16.365: E/AndroidRuntime(3332): at android.app.ActivityThread.access$800(ActivityThread.java:135)
08-15 14:52:16.365: E/AndroidRuntime(3332): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
08-15 14:52:16.365: E/AndroidRuntime(3332): at android.os.Handler.dispatchMessage(Handler.java:102)
08-15 14:52:16.365: E/AndroidRuntime(3332): at android.os.Looper.loop(Looper.java:136)
08-15 14:52:16.365: E/AndroidRuntime(3332): at android.app.ActivityThread.main(ActivityThread.java:5017)
08-15 14:52:16.365: E/AndroidRuntime(3332): at java.lang.reflect.Method.invokeNative(Native Method)
08-15 14:52:16.365: E/AndroidRuntime(3332): at java.lang.reflect.Method.invoke(Method.java:515)
08-15 14:52:16.365: E/AndroidRuntime(3332): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-15 14:52:16.365: E/AndroidRuntime(3332): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-15 14:52:16.365: E/AndroidRuntime(3332): at dalvik.system.NativeStart.main(Native Method)
08-15 14:52:16.365: E/AndroidRuntime(3332): Caused by: java.lang.NullPointerException
08-15 14:52:16.365: E/AndroidRuntime(3332): at com.dooba.beta.usermatch.initialisePaging(usermatch.java:32)
08-15 14:52:16.365: E/AndroidRuntime(3332): at com.dooba.beta.usermatch.onCreate(usermatch.java:20)
08-15 14:52:16.365: E/AndroidRuntime(3332): at android.app.Activity.performCreate(Activity.java:5231)
08-15 14:52:16.365: E/AndroidRuntime(3332): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-15 14:52:16.365: E/AndroidRuntime(3332): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
08-15 14:52:16.365: E/AndroidRuntime(3332): ... 11 more
Below is the activity page that calls for the fragment
import java.util.List;
import java.util.Vector;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
public class usermatch extends FragmentActivity {
private PageAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpager_layout);
initialisePaging();
}
private void initialisePaging() {
// TODO Auto-generated method stub
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, Fragment1.class.getName()));
fragments.add(Fragment.instantiate(this, Fragment2.class.getName()));
fragments.add(Fragment.instantiate(this, Fragment3.class.getName()));
mPagerAdapter = new PageAdapter(this.getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(mPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mood, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Update 2
Below is the message I receive in logcat
08-15 17:42:28.863: E/AndroidRuntime(4974): FATAL EXCEPTION: main
08-15 17:42:28.863: E/AndroidRuntime(4974): Process: com.dooba.beta, PID: 4974
08-15 17:42:28.863: E/AndroidRuntime(4974): java.lang.NullPointerException
08-15 17:42:28.863: E/AndroidRuntime(4974): at com.dooba.beta.Fragment1$1.done(Fragment1.java:108)
08-15 17:42:28.863: E/AndroidRuntime(4974): at com.parse.FindCallback.internalDone(FindCallback.java:45)
08-15 17:42:28.863: E/AndroidRuntime(4974): at com.parse.FindCallback.internalDone(FindCallback.java:1)
08-15 17:42:28.863: E/AndroidRuntime(4974): at com.parse.Parse$6$1.run(Parse.java:888)
08-15 17:42:28.863: E/AndroidRuntime(4974): at android.os.Handler.handleCallback(Handler.java:733)
08-15 17:42:28.863: E/AndroidRuntime(4974): at android.os.Handler.dispatchMessage(Handler.java:95)
08-15 17:42:28.863: E/AndroidRuntime(4974): at android.os.Looper.loop(Looper.java:136)
08-15 17:42:28.863: E/AndroidRuntime(4974): at android.app.ActivityThread.main(ActivityThread.java:5017)
08-15 17:42:28.863: E/AndroidRuntime(4974): at java.lang.reflect.Method.invokeNative(Native Method)
08-15 17:42:28.863: E/AndroidRuntime(4974): at java.lang.reflect.Method.invoke(Method.java:515)
08-15 17:42:28.863: E/AndroidRuntime(4974): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-15 17:42:28.863: E/AndroidRuntime(4974): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-15 17:42:28.863: E/AndroidRuntime(4974): at dalvik.system.NativeStart.main(Native Method)
You can get the activity that contains the fragment with getActivity().
Therefore getActivity().getApplicationContext() would work.
getActivity().findViewById(int) would also work.
Make sure, though, you don't use getActivity() prior to onActivityCreated(), since it would return null prior to that.
Change
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
to
Intent intent = new Intent(getActivity(), LoginActivity.class);
you can access context from onAttach() like below example
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
}
In my Android application i am creating a pie chart using achartengine library. When click a button it takes data from sqlite database and draw a pie chart. This is my code segment.
btnpieChart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SelectDBAdapter selectDBAdapter = SelectDBAdapter
.getDBAdapterInstance(getActivity());
try {
selectDBAdapter.openDataBase();
chartDataMap = selectDBAdapter
.getPieChartData(strBusinessUnit,
currentPeriod, currentYear);
} catch (Exception e) {
selectDBAdapter.close();
e.printStackTrace();
} finally {
selectDBAdapter.close();
}
System.out.println("chartDataMap === "+ chartDataMap);
if (chartDataMap.size() > 0) {
for (Map.Entry<String, Double> entry : chartDataMap.entrySet()) {
lstBrandNames.add(entry.getKey());
lstAchievedVals.add(entry.getValue());
}
ArrayList<Double> distribution = calc_Percentage(lstAchievedVals);
System.out.println("distribution === " + distribution);
lstBrandNames = set_lables(lstBrandNames, distribution);
CategorySeries distributionSeries = new CategorySeries(
"Brands - Achievement Progress");
for (int i = 0; i < distribution.size(); i++) {
distributionSeries.add(lstBrandNames.get(i), distribution.get(i));
}
DefaultRenderer defaultRenderer = new DefaultRenderer();
defaultRenderer.setApplyBackgroundColor(true);
defaultRenderer.setBackgroundColor(Color.WHITE);
for (int i = 0; i < distribution.size(); i++) {
SimpleSeriesRenderer seriesRenderer = new SimpleSeriesRenderer();
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
seriesRenderer.setColor(color);
seriesRenderer.setGradientEnabled(false);
seriesRenderer.setDisplayChartValues(true);
seriesRenderer.setShowLegendItem(false);
defaultRenderer.setLabelsTextSize(25);
defaultRenderer.addSeriesRenderer(seriesRenderer);
}
defaultRenderer.setLabelsColor(Color.BLACK);
defaultRenderer.setChartTitle("Brands - Achievement Progress");
defaultRenderer.setChartTitleTextSize(30);
defaultRenderer.setZoomButtonsVisible(true);
defaultRenderer.setShowLabels(true);
FragmentTransaction ft = getFragmentManager().beginTransaction();
mChartView = ChartFactory.getPieChartView(getActivity(), distributionSeries, defaultRenderer);
ft.replace(mChartView.getId(), new DummySectionFragment(), "NewFragmentTag");
ft.addToBackStack(null);
ft.commit();
}
}
});
My mChartView is,
private GraphicalView mChartView = null;
Log cat says:
11-25 07:03:58.311: E/AndroidRuntime(2706): FATAL EXCEPTION: main
11-25 07:03:58.311: E/AndroidRuntime(2706): android.content.res.Resources$NotFoundException: Unable to find resource ID #0xffffffff
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.content.res.Resources.getResourceName(Resources.java:1659)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:919)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.os.Handler.handleCallback(Handler.java:725)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.os.Handler.dispatchMessage(Handler.java:92)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.os.Looper.loop(Looper.java:137)
11-25 07:03:58.311: E/AndroidRuntime(2706): at android.app.ActivityThread.main(ActivityThread.java:5039)
11-25 07:03:58.311: E/AndroidRuntime(2706): at java.lang.reflect.Method.invokeNative(Native Method)
11-25 07:03:58.311: E/AndroidRuntime(2706): at java.lang.reflect.Method.invoke(Method.java:511)
11-25 07:03:58.311: E/AndroidRuntime(2706): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-25 07:03:58.311: E/AndroidRuntime(2706): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-25 07:03:58.311: E/AndroidRuntime(2706): at dalvik.system.NativeStart.main(Native Method)
I would be much obliged if anyone could explain what's going on here and how can I solve this issue.
Thanks
Check these lines
mChartView = ChartFactory.getPieChartView(getActivity(), distributionSeries, defaultRenderer);
ft.replace(mChartView.getId(), new DummySectionFragment(), "NewFragmentTag");
especially mChartView.getId() log this value and check it with what you expected