Below i have pasted the code of MainActivity
package com.example.tunifi;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import java.io.File;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
ListView listView;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
Dexter.withContext(this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
//Toast.makeText(MainActivity.this, "Runtime permission given !", Toast.LENGTH_SHORT).show();
ArrayList<File> mySongs = fetchSongs(Environment.getExternalStorageDirectory());
String [] items = new String[mySongs.size()];
for (int i=0;i<mySongs.size();i++){
items[i] = mySongs.get(i).getName().replace(".mp3","");
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_expandable_list_item_1,items);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, PlaySong.class);
String currentSong = listView.getItemAtPosition(position).toString();
intent.putExtra("SongList",mySongs);
intent.putExtra("CurrentSong",currentSong);
intent.putExtra("Position",position);
startActivity(intent);
}
});
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
})
.check();
}
public ArrayList<File> fetchSongs(File file){
ArrayList arrayList = new ArrayList();
File [] songs = file.listFiles();
if (songs != null){
for (File myFile : songs){
if (!myFile.isHidden() && myFile.isDirectory()){
arrayList.addAll(fetchSongs(myFile));
}
else{
if (myFile.getName().endsWith(".mp3") && !myFile.getName().startsWith(".")){
arrayList.add(myFile);
}
}
}
}
return arrayList;
}
}
Below i have pasted the code of PlaySong
package com.example.tunifi;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.File;
import java.util.ArrayList;
public class PlaySong extends AppCompatActivity {
TextView textView;
ImageView previous, play, next;
ArrayList<File> songs;
MediaPlayer mediaPlayer;
String textContent;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_song);
textView = findViewById(R.id.textView);
previous = findViewById(R.id.previous);
play = findViewById(R.id.play);
next = findViewById(R.id.next);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
songs = (ArrayList) bundle.getParcelableArrayList("songs");
textContent = intent.getStringExtra("CurrentSong");
textView.setText(textContent);
position = intent.getIntExtra("Position",0);
Uri uri = Uri.parse(songs.get(position).toString());
mediaPlayer = MediaPlayer.create(this,uri);
mediaPlayer.start();
}
}
This is what my Logcat shows:
2021-08-13 13:05:25.898 23725-23725/? I/zygote: Not late-enabling -Xcheck:jni (already on)
2021-08-13 13:04:58.820 1538-23594/? I/AudioFlinger: AudioFlinger's thread 0xb1903c80 tid=23594 ready to run
2021-08-13 13:05:25.917 23725-23725/? W/zygote: Unexpected CPU variant for X86 using defaults: x86
2021-08-13 13:03:30.914 1697-2352/system_process W/ActivityManager: Slow operation: 566ms so far, now at getContentProviderImpl: done!
2021-08-13 13:05:25.898 23725-23725/? I/zygote: Not late-enabling -Xcheck:jni (already on)
2021-08-13 13:05:25.917 23725-23725/? W/zygote: Unexpected CPU variant for X86 using defaults: x86
2021-08-13 13:05:25.898 23725-23725/? I/zygote: Not late-enabling -Xcheck:jni (already on)
2021-08-13 13:05:25.917 23725-23725/? W/zygote: Unexpected CPU variant for X86 using defaults: x86
2021-08-13 13:05:26.244 23725-23749/com.example.tunifi D/OpenGLRenderer: HWUI GL Pipeline
2021-08-13 13:05:26.331 23725-23749/com.example.tunifi I/OpenGLRenderer: Initialized EGL, version 1.4
2021-08-13 13:05:26.332 23725-23749/com.example.tunifi D/OpenGLRenderer: Swap behavior 1
2021-08-13 13:05:26.334 23725-23749/com.example.tunifi W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
2021-08-13 13:05:26.334 23725-23749/com.example.tunifi D/OpenGLRenderer: Swap behavior 0
2021-08-13 13:05:26.382 23725-23749/com.example.tunifi D/EGL_emulation: eglCreateContext: 0xa0385120: maj 2 min 0 rcv 2
2021-08-13 13:05:26.405 23725-23749/com.example.tunifi D/EGL_emulation: eglMakeCurrent: 0xa0385120: ver 2 0 (tinfo 0xa0383280)
2021-08-13 13:05:26.544 23725-23749/com.example.tunifi D/EGL_emulation: eglMakeCurrent: 0xa0385120: ver 2 0 (tinfo 0xa0383280)
2021-08-13 13:05:28.347 23725-23725/com.example.tunifi D/AndroidRuntime: Shutting down VM
2021-08-13 13:05:28.351 23725-23725/com.example.tunifi E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.tunifi, PID: 23725
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tunifi/com.example.tunifi.PlaySong}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.ArrayList.get(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.ArrayList.get(int)' on a null object reference
at com.example.tunifi.PlaySong.onCreate(PlaySong.java:38)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Can someone please help me out in finding what is wrong and how to correct it, sice i am new to this android development world and i am really upset for this thing since i am trying from many days to correct it,but nothing is working. Thank You So Much in advance !
The trick is to read the stacktrace, it says :
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.ArrayList.get(int)' on a null object reference
So looks like songs is null when you try to get a value of that list, can you make sure that songs is initialized before calling the
Uri uri = Uri.parse(songs.get(position).toString());
Edit
Perhaps this is not the root cause of your bug but you are doing this
intent.putExtra("SongList",mySongs);
looks like you are sending your song list with this bundle name "SongList" but then you are trying to retrieve it with :
songs = (ArrayList) bundle.getParcelableArrayList("songs");
I guess it should be "SongList" instead of "songs"
change
songs = (ArrayList) bundle.getParcelableArrayList("songs");
to
songs = (ArrayList) bundle.getParcelableArrayList("SongList");
Uri uri = Uri.parse(songs.get(position).toString());
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.ArrayList.get(int)' on a null object reference
from this error,we can know the this arraylist is null,you should check it first
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
Whats wrong in this code? It is not sending the intent to next page.I have done it many times.When i click on the button on the Mainactivity.java i get this log.It doesn't go to the next page.Intent is not working in this activity why?Hope to get answer soon.Thanks in advance.
package com.example.testing1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<String> hisnumber=new ArrayList<>();
ArrayList<Bitmap> hisimages=new ArrayList<>();
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=findViewById(R.id.button);
Intent intent = getIntent();
hisnumber = intent.getStringArrayListExtra("hisnumber");
hisimages = intent.getParcelableArrayListExtra("hisimages");
Log.d("num1", String.valueOf(hisnumber));
Log.d("img1", String.valueOf(hisimages));
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(MainActivity.this, Testing2.class);
myIntent.putExtra("hisnumber", hisnumber);
myIntent.putParcelableArrayListExtra("hisimages", hisimages);
Log.d("num", String.valueOf(hisnumber));
Log.d("img", String.valueOf(hisimages));
startActivity(myIntent);
}
});
}
}
Mainactivity.java
package com.example.testing1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
public class Testing2 extends AppCompatActivity {
ArrayList<String> hisnumber=new ArrayList<>();
ArrayList<Bitmap> hisimages=new ArrayList<>();
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testing2);
button=findViewById(R.id.button);
Intent intent = getIntent();
hisnumber = intent.getStringArrayListExtra("hisnumber");
hisimages = intent.getParcelableArrayListExtra("hisimages");
Log.d("num3", String.valueOf(hisnumber));
Log.d("img3", String.valueOf(hisimages));
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(hisnumber==null){
hisnumber=new ArrayList<>();
hisimages=new ArrayList<>();
}
hisnumber.add("ass");
Bitmap bp= BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_background);
hisimages.add(bp);
Intent myIntent = new Intent(Testing2.this, MainActivity.class);
myIntent.putExtra("hisnumber", hisnumber);
myIntent.putParcelableArrayListExtra("hisimages", hisimages);
Log.d("num2", String.valueOf(hisnumber));
Log.d("img2", String.valueOf(hisimages));
startActivity(myIntent);
}
});
}
}
Testing.java
07/28 11:07:11: Launching 'app' on Realme RMX1901.
$ adb shell am start -n "com.example.testing1/com.example.testing1.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 18360 on device 'realme-rmx1901-618cb732'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/Perf: Connecting to perf service.
E/Perf: Fail to get file list com.example.testing1
getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
Fail to get file list com.example.testing1
getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
W/xample.testing: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/xample.testing: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
D/num1: null
D/img1: null
D/WindowManager: Add to mViews: DecorView#5a6d981[MainActivity], this = android.view.WindowManagerGlobal#9161a26,pkg= com.example.testing1
I/AdrenoGLES: QUALCOMM build : e4029f9, I6b4cbc7431
Build Date : 10/01/19
OpenGL ES Shader Compiler Version: EV031.27.05.01
Local Branch :
Remote Branch :
Remote Branch :
Reconstruct Branch :
I/AdrenoGLES: Build Config : S P 8.0.11 AArch64
I/AdrenoGLES: PFP: 0x016ee187, ME: 0x00000000
W/AdrenoUtils: <ReadGpuID_from_sysfs:194>: Failed to open /sys/class/kgsl/kgsl-3d0/gpu_model
<ReadGpuID:218>: Failed to read chip ID from gpu_model. Fallback to use the GSL path
W/Gralloc3: mapper 3.x is not supported
I/Choreographer: Skipped 9 frames! The application may be doing too much work on its main thread.
I/Choreographer: Skipped 1 frames! The application may be doing too much work on its main thread.
D/ColorViewRootUtil: nav gesture mode swipeFromBottom ignore false downY 349 mScreenHeight 2340 mScreenWidth 1080 mStatusBarHeight 54 globalScale 1.125 nav mode 3 event MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=334.0, y[0]=349.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, classification=NONE, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=660935273, downTime=660935273, deviceId=7, source=0x1002, displayId=0 } rotation 0
D/num: null
D/img: null
I/Choreographer: Skipped 1 frames! The application may be doing too much work on its main thread.
I/Choreographer: Skipped 1 frames! The application may be doing too much work on its main thread.
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy#fa02c62
D/num3: null
D/img3: null
D/WindowManager: Add to mViews: DecorView#76b323c[Testing2], this = android.view.WindowManagerGlobal#9161a26,pkg= com.example.testing1
I/Choreographer: Skipped 6 frames! The application may be doing too much work on its main thread.
I/Choreographer: Skipped 3 frames! The application may be doing too much work on its main thread.
I/xample.testing: ProcessProfilingInfo new_methods=681 is saved saved_to_disk=1 resolve_classes_delay=5000
D/ColorViewRootUtil: nav gesture mode swipeFromBottom ignore false downY 327 mScreenHeight 2340 mScreenWidth 1080 mStatusBarHeight 54 globalScale 1.125 nav mode 3 event MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=81.0, y[0]=327.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, classification=NONE, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=660939314, downTime=660939314, deviceId=7, source=0x1002, displayId=0 } rotation 0
I/Choreographer: Skipped 1 frames! The application may be doing too much work on its main thread.
E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 3240640)
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.testing1, PID: 8832
java.lang.RuntimeException: Failure from system
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1720)
at android.app.Activity.startActivityForResult(Activity.java:5319)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
at android.app.Activity.startActivityForResult(Activity.java:5263)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663)
at android.app.Activity.startActivity(Activity.java:5648)
at android.app.Activity.startActivity(Activity.java:5616)
at com.example.testing1.Testing2$1.onClick(Testing2.java:50)
at android.view.View.performClick(View.java:7256)
at android.view.View.performClickInternal(View.java:7218)
at android.view.View.access$3800(View.java:824)
at android.view.View$PerformClick.run(View.java:27719)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:228)
at android.app.ActivityThread.main(ActivityThread.java:7782)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:981)
Caused by: android.os.TransactionTooLargeException: data parcel size 3240640 bytes
at android.os.BinderProxy.transactNative(Native Method)
at android.os.BinderProxy.transact(BinderProxy.java:523)
at android.app.IActivityTaskManager$Stub$Proxy.startActivity(IActivityTaskManager.java:3868)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1714)
at android.app.Activity.startActivityForResult(Activity.java:5319)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
at android.app.Activity.startActivityForResult(Activity.java:5263)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663)
at android.app.Activity.startActivity(Activity.java:5648)
at android.app.Activity.startActivity(Activity.java:5616)
at com.example.testing1.Testing2$1.onClick(Testing2.java:50)
at android.view.View.performClick(View.java:7256)
at android.view.View.performClickInternal(View.java:7218)
at android.view.View.access$3800(View.java:824)
at android.view.View$PerformClick.run(View.java:27719)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:228)
at android.app.ActivityThread.main(ActivityThread.java:7782)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:981)
I/Process: Sending signal. PID: 8832 SIG: 9
Log
Main reason behind NPE is this
hisnumber = intent.getStringArrayListExtra("hisnumber");
hisimages = intent.getParcelableArrayListExtra("hisimages");
You need to check why is this not working
Workaround for NPE
Arraylist seems to be null , so check if its null or not in onClick()
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(Testing2.this, MainActivity.class);
if(hisnumber!=null){
myIntent.putExtra("hisnumber", hisnumber);
}
if(hisimages!=null){
hisnumber.add("ass");
Bitmap bp= BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_background);
hisimages.add(bp);
myIntent.putParcelableArrayListExtra("hisimages", hisimages);
Log.d("num2", String.valueOf(hisnumber));
Log.d("img2", String.valueOf(hisimages));
}
startActivity(myIntent);
}
});
Your hisnumberand hisimages lists are NULL
Check their Nullability before adding somthing..
Testing.java
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (hisnumber != null) {
hisnumber.add("ass");
}
Bitmap bp= BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_background);
if (hisimages != null) {
hisimages.add(bp);
}
Intent myIntent = new Intent(Testing2.this, MainActivity.class);
myIntent.putExtra("hisnumber", hisnumber);
myIntent.putParcelableArrayListExtra("hisimages", hisimages);
Log.d("num2", String.valueOf(hisnumber));
Log.d("img2", String.valueOf(hisimages));
startActivity(myIntent);
}
});
I’m making a project in which i get data through api and stored it in arraylist but when i return it, it is empty.
Can Anyone Help Me Out?
Here is the Main Activity
package com.example.trivia;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import com.example.trivia.Data.Async;
import com.example.trivia.Data.setQ;
import com.example.trivia.controller.AppController;
import com.example.trivia.model.question;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private CardView c;
private Button t_btn,f_btn;
private ImageButton next,prev;
private List<question>q;
private TextView set;
private int count=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
c=findViewById(R.id.cardView);
t_btn=findViewById(R.id.true_btn);
f_btn=findViewById(R.id.false_btn);
next=findViewById(R.id.next);
prev=findViewById(R.id.prev);
set=findViewById(R.id.setq);
//ArrayList<question> dummy = new ArrayList<question>();
//AppController.OnCreate();
q=new setQ().getData(new Async() {
#Override
public void finish(ArrayList<question> c) {
set.setText(c.get(count).getQ());
// Log.d("test", "onCreate: "+c);
}
});
Log.i("in main", "Main: "+q.size());
}
}
the code of setQ class
package com.example.trivia.Data;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.trivia.controller.AppController;
import com.example.trivia.model.question;
import org.json.JSONArray;
import org.json.JSONException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
public class setQ {
ArrayList<question> q =new ArrayList<question>();
JSONArray r;
private String url="https://raw.githubusercontent.com/curiousily/simple-quiz/master/script/statements-data.json";
public List<question> getData(final Async call) {
final JsonArrayRequest jarr = new JsonArrayRequest(Request.Method.GET, url, (JSONArray)null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
r=response;
for (int i = 0; i < response.length(); i++) {
try {
JSONArray a = response.getJSONArray(i);
question k = new question(a.getString(0), a.getBoolean(1));
//Log.i("list", "onResponse: "+k.getAns());
q.add(k);
// Log.i("response", "onResponse: " +a.get(0));
} catch (JSONException e) {
e.printStackTrace();
}
}
if(call!=null) {
call.finish( q);
}
//return q;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Log.i("error ",""+AppController.getInstance());
AppController.getInstance().addToRequestQueue(jarr);
return q;
// return q;
}
}
output
07/11 23:55:18: Launching 'app' on Pixel 3 API 21.
$ adb shell am start -n "com.example.trivia/com.example.trivia.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 15594 on device 'emulator-5554'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
I/error: com.example.trivia.controller.AppController#24777a64
***I/in main: Main: 0***
D/OpenGLRenderer: Render dirty regions requested: true
D/: HostConnection::get() New Host Connection established 0x7f28894105c0, tid 15594
D/Atlas: Validating map...
I/art: Background sticky concurrent mark sweep GC freed 5802(428KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 2MB/2MB, paused 8.789ms total 42.738ms
D/: HostConnection::get() New Host Connection established 0x7f28950b0e40, tid 15624
I/OpenGLRenderer: Initialized EGL, version 1.4
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0x7f2894773200: maj 3 min 1 rcv 4
D/EGL_emulation: eglMakeCurrent: 0x7f2894773200: ver 3 1 (tinfo 0x7f289470fe40)
E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf
glUtilsParamSize: unknow param 0x00008824
D/OpenGLRenderer: Enabling debug mode 0
D/EGL_emulation: eglMakeCurrent: 0x7f2894773200: ver 3 1 (tinfo 0x7f289470fe40)
I/Choreographer: Skipped 62 frames! The application may be doing too much work on its main thread.
Implement the callback pattern.
Create a new Interface file:
Interface MyVolleyResponse {
void onResponse(JSONArray response);
void onError(VolleyError error);
}
Your activity should implement this, as follows:
public class MainActivity extends AppCompatActivity implements MyVolleyResponse {...}
Add the new methods to your activity:
void onResponse(JSONArray response) {
// process your response here, building your question array...
}
void onError(VolleyError error) {
// handle errors here...
}
Change your Volley responses within SetQ:
public void onResponse(JSONArray response) {
callback.onResponse(response);
}
public void onErrorResponse(VolleyError error) {
callback.onError(error);
}
Create a constructor within SetQ to set the callback:
private MyVolleyResponse callback;
SetQ(MyVolleyResponse callback) {
this.callback = callback;
}
Call this constructor in your activity with:
SetQ volley = new SetQ(this);
Change the signnature of getData to just:
void getData() {...}
And run the Volley call with volley.getData().
Remove all AsyncTask objects in your code, because Volley is already asynchronous.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I just got done one part of my code and went to launch the app and everything went fine. The build was successful and no issues were found. I then go to the emulator and the app doesn't launch and the log shows a lot of error.
Anyone know where I messed up and how I can fix it.Below is the errors from the log that I receive and I also pasted in the code that I was working on.
2019-05-07 13:06:14.358 22792-22792/com.example.drunktankfix E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.drunktankfix, PID: 22792
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.drunktankfix/com.example.drunktankfix.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(int)' on a null object reference
at com.example.drunktankfix.MainActivity.onCreate(MainActivity.java:55)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2019-05-07 13:06:16.368 22792-22792/com.example.drunktankfix I/Process: Sending signal. PID: 22792 SIG: 9
Also here is the code:
package com.example.drunktankfix;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.example.drunktankfix.AppFragment;
import com.example.drunktankfix.BlacklistFragment;
import com.example.drunktankfix.HelpFragment;
import com.example.drunktankfix.HomeFragment;
//implement the interface OnNavigationItemSelectedListener in your activity class
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
Button Save;
EditText edt1, edt2, edt3;
int in;
Float fl;
String st;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//loading the default fragment
loadFragment(new HomeFragment());
//getting bottom navigation view and attaching the listener
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(this);
Save = (Button) findViewById(R.id.BtnSave);
edt1 = (EditText) findViewById(R.id.editText1);
edt2 = (EditText) findViewById(R.id.editText2);
edt3 = (EditText) findViewById(R.id.editText3);
// to Retrieve the Data from the SharedPref
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int in1= prefs.getInt("in",0);
edt1.setText(in1);
float fl1 = prefs.getFloat("fl", 0);
edt2.setText(""+fl1);
String st1 = prefs.getString("st","");
edt3.setText(st1);
Save.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View v) {
in = Integer.parseInt(edt1.getText().toString());
fl = Float.parseFloat(edt2.getText().toString());
st = edt3.getText().toString();
// To save the data that is entered
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("in", in);
editor.putFloat("fl", fl);
editor.putString("st", st);
editor.apply();
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
fragment = new HomeFragment();
break;
case R.id.navigation_Apps:
fragment = new AppFragment();
break;
case R.id.navigation_Blacklist:
fragment = new BlacklistFragment();
break;
case R.id.navigation_Help:
fragment = new HelpFragment();
break;
}
return loadFragment(fragment);
}
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
}
You can not enter int value inside the edit text . Try to make it string.
edt1.setText(in1+"");
To set the integer propertly do the following:
edt1.setText("" + integer);
or better solution:
edt1.setText(String.valueOf(integer));
I am not sure how are you getting Nullpointer Exception But from the I code, I see any issue with your here.
editText.setText(Integer Value)
You are setting integer value to Edit text, So that in turn tries to get String resource based on the integer which you set to EditText.That should throw Resource not found Exception not NPE.
I'm building android apps using retrofit as my httprequest to connect to my hapi server. my server is working fine, I've test it on postman and my WebApps. But my retrofit can not connect to it. below is my code. For the sake of simplicity to read I delete lines that not necessary:
LoginActivity.java
package com.sianghee.reviu;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import com.sianghee.reviu.interfaces.APIService;
import com.sianghee.reviu.lib.Session;
import com.sianghee.reviu.models.UserLogin;
import static com.sianghee.reviu.lib.Helper.returnError;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
public class LoginActivity extends Activity {
private static final String TAG = "LoginActivity";
private static final int REQUEST_SIGNUP = 0;
Session session;
public static final String BASE_URL = "localhost:3000";
private EditText emailText;
private EditText passwordText;
#BindView(R.id.btn_login) Button _loginButton;
#BindView(R.id.link_signup) TextView _signupLink;
// TODO: Init sewaktu pertama kali form diload
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
emailText = (EditText)findViewById(R.id.input_email);
passwordText = (EditText)findViewById(R.id.input_password);
}
// TODO: bind login and do login
#OnClick(R.id.btn_login)
public void submitLogin() {
login();
}
// TODO: bind signup and do register
....
public void login() {
Log.d(TAG, "Login");
if (!validate()) {
onLoginFailed();
return;
}
_loginButton.setEnabled(false);
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Authenticating...");
progressDialog.show();
String email = emailText.getText().toString();
String password = passwordText.getText().toString();
// TODO: Implement your own authentication logic here.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService api = retrofit.create(APIService.class);
UserLogin userLogin = new UserLogin(email, password);
Call<UserLogin> call = api.login(userLogin);
call.enqueue(new Callback<UserLogin>() {
#Override
public void onResponse(Call<UserLogin> call, Response<UserLogin> response) {
String result;
progressDialog.dismiss();
try {
result = response.body().toString();
if (returnError(result).isEmpty()) {
JSONObject obj;
obj = new JSONObject(result);
session.setLoginSession(obj.getString("scope"), obj.getString("token"));
Intent i = new Intent(LoginActivity.this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
.......
}
APIService.java
package com.sianghee.reviu.interfaces;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;
import com.sianghee.reviu.models.UserLogin;
/**
* Created by andy on 11/26/17.
*/
public interface APIService {
#POST("auth")
Call<UserLogin> login(#Body UserLogin auth);
}
UserLogin.java
package com.sianghee.reviu.models;
public class UserLogin {
String email;
String password;
public UserLogin(String email, String password) {
this.email = email;
this.password = password;
}
}
Whenever I clicked the login button, It's failed to connect to server. below is the logcat:
12-02 23:24:42.771 3660-3660/com.sianghee.reviu I/InstantRun: starting instant run server: is main process
12-02 23:24:43.116 3660-3690/com.sianghee.reviu D/OpenGLRenderer: HWUI GL Pipeline
12-02 23:24:43.213 3660-3660/com.sianghee.reviu I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
12-02 23:24:43.219 3660-3660/com.sianghee.reviu I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
[ 12-02 23:24:43.283 3660: 3690 D/ ]
HostConnection::get() New Host Connection established 0x896438c0, tid 3690
12-02 23:24:43.471 3660-3690/com.sianghee.reviu I/zygote: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
12-02 23:24:43.471 3660-3690/com.sianghee.reviu I/OpenGLRenderer: Initialized EGL, version 1.4
12-02 23:24:43.471 3660-3690/com.sianghee.reviu D/OpenGLRenderer: Swap behavior 1
12-02 23:24:43.471 3660-3690/com.sianghee.reviu W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
12-02 23:24:43.471 3660-3690/com.sianghee.reviu D/OpenGLRenderer: Swap behavior 0
12-02 23:24:43.473 3660-3690/com.sianghee.reviu D/EGL_emulation: eglCreateContext: 0x9b543860: maj 2 min 0 rcv 2
12-02 23:24:43.475 3660-3690/com.sianghee.reviu D/EGL_emulation: eglMakeCurrent: 0x9b543860: ver 2 0 (tinfo 0xa4a8f700)
12-02 23:24:43.527 3660-3690/com.sianghee.reviu D/EGL_emulation: eglMakeCurrent: 0x9b543860: ver 2 0 (tinfo 0xa4a8f700)
12-02 23:24:43.856 3660-3660/com.sianghee.reviu I/AssistStructure: Flattened final assist data: 1684 bytes, containing 1 windows, 5 views
12-02 23:24:49.113 3660-3673/com.sianghee.reviu I/zygote: Do partial code cache collection, code=30KB, data=26KB
12-02 23:24:49.113 3660-3673/com.sianghee.reviu I/zygote: After code cache collection, code=30KB, data=26KB
12-02 23:24:49.113 3660-3673/com.sianghee.reviu I/zygote: Increasing code cache capacity to 128KB
12-02 23:24:51.355 3660-3673/com.sianghee.reviu I/zygote: Do partial code cache collection, code=61KB, data=59KB
12-02 23:24:51.356 3660-3673/com.sianghee.reviu I/zygote: After code cache collection, code=61KB, data=59KB
12-02 23:24:51.356 3660-3673/com.sianghee.reviu I/zygote: Increasing code cache capacity to 256KB
12-02 23:24:54.016 3660-3673/com.sianghee.reviu I/zygote: Do full code cache collection, code=123KB, data=99KB
12-02 23:24:54.016 3660-3673/com.sianghee.reviu I/zygote: After code cache collection, code=107KB, data=66KB
12-02 23:24:56.503 3660-3660/com.sianghee.reviu D/LoginActivity: Login
12-02 23:24:56.573 3660-3673/com.sianghee.reviu I/zygote: Do partial code cache collection, code=114KB, data=93KB
12-02 23:24:56.573 3660-3673/com.sianghee.reviu I/zygote: After code cache collection, code=114KB, data=93KB
12-02 23:24:56.573 3660-3673/com.sianghee.reviu I/zygote: Increasing code cache capacity to 512KB
12-02 23:24:56.574 3660-3673/com.sianghee.reviu I/zygote: JIT allocated 56KB for compiled code of void android.view.View.<init>(android.content.Context, android.util.AttributeSet, int, int)
12-02 23:24:56.603 3660-3660/com.sianghee.reviu D/NetworkSecurityConfig: No Network Security Config specified, using platform default
12-02 23:24:56.803 3660-3660/com.sianghee.reviu W/error: java.net.ConnectException: Failed to connect to /127.0.0.1:3000
12-02 23:24:57.094 3660-3690/com.sianghee.reviu D/EGL_emulation: eglMakeCurrent: 0x9b543860: ver 2 0 (tinfo 0xa4a8f700)
12-02 23:24:57.126 3660-3690/com.sianghee.reviu D/EGL_emulation: eglMakeCurrent: 0x9b543860: ver 2 0 (tinfo 0xa4a8f700)
My server API Url for login is : http://127.0.0.1:3000/auth
notice that error from my Log.w() method before that say:
java.net.ConnectException: Failed to connect to /127.0.0.1:3000
Maybe this is just my common mistake, please help.
127.0.0.1 is your localhost / loopback address a of your Machine (on which server is hosted). 127.0.0.1 is mapped to the IP address of the machine, hence http://127.0.0.1:3000/auth is accessible from your machine only.
Now, in order to access http://127.0.0.1:3000/auth from any other machine (i.e. your phone in this case), your machine (server) and device (phone) should be on the same network (e.g same Wi-Fi) You need to access it via http://IPAddressOfYourMachine:3000/auth.
On MacOs / Linux you can find out the IP address using ifconfig command on a terminal. On a Windows machine the command is ipconfig. The IP address should be of the form of 192.168.x.y.
So the final BASE_URL should be something like http://192.168.x.y:3000
make sure that your phone(emulator) and your computer are in a same network
and use ip adress http://192.168.8.106:3030 for example, instead of http://localhost:3030
Retrofit hasn't any problem. The issue is in the BASE_URL for reaching from your android device to your server.
Please check your computer's local ip address that the server is installed in (ex: 192.168.1.103), then replace the BASE_URL with that such as following example
public static final String BASE_URL = "http://192.168.1.103:3000";
I'm new to programming and have been assigned to code a simple music player, there were slides to help guide and I have slightly altered them (can't use the exact same variables).
So now it's error free but when I click on the play button it crashes, no idea why. Here's my code for the page where I select the library:
package sg.edu.tp.project1;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import sg.edu.tp.project1.util.AppUtil;
public class myMusic extends AppCompatActivity {
private String[] Musicsong = new String[6];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_music);
//store values in array of the first song
Musicsong[0] = "s1001";
Musicsong[1] = "The Way You Look Tonight";
Musicsong[2] = "ed sheeran";
Musicsong[3] = "a5b8972e764025020625bbf9c1c2bbb06e394a60?cid=null";
Musicsong[4] = "4.39";
Musicsong[5] = "music to play";
}
public void sendDataToActiviy(String[] song)
{
//1.create intent and specify destination
Intent intent = new Intent(this, PlayMusicActivity.class);
//2.store song info in intent to send to destination
intent.putExtra("id", song[0]);
intent.putExtra("title",song[1]);
intent.putExtra("artist",song[2]);
intent.putExtra("fileLink",song[3]);
intent.putExtra("coverArt",song[5]);
//3. launch desntination activiy
startActivity(intent);
}
public void handleSelection(View view)
{
// 1. get id of selected song
String resourceId = AppUtil.getResourceId(this, view);
//2. Search for the selected song based on the ID so that
// all infomation of the song can be retreived
String[] selectedSong =searchById(resourceId);
//3.popup to show tittle of song
AppUtil.popMessage(this, "Streaming song:" + selectedSong[1]);
//4. send song data to player screen
sendDataToActiviy(selectedSong);
}
private Object[] songs = {Musicsong};
public String[] searchById(String id) {
//temporary empty array
String[] song = null;
//for loop to get song
for (int index = 0; index < songs.length; index++) {
//3. store each song item to song array.
song = (String[]) songs[index];
//4. match song id to see if its the one i want
if (song[0].equals(id)) {
return song;
}
}
//if song not found in array empty array will be returned
return song;
}
}
This part where the player is:
package sg.edu.tp.project1;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
import sg.edu.tp.project1.util.AppUtil;
public class PlayMusicActivity extends AppCompatActivity
{
//streaming website
private static final String BASE_URL = "https://p.scdn.co/mp3-preview/";
private String songId ="";
private String title = "";
private String artist = "";
private String fileLink = "";
private String coverArt = "";
private String url = "";
//builtin media player
private MediaPlayer player = null;
//position of song in playback
private int musicPosition = 0;
//button variable to link to play btn
private Button btnPlayPause = null;
private String[] Musicsong = {
"s1001",
"The Way You Look Tonight",
"ed sheeran",
"a5b8972e764025020625bbf9c1c2bbb06e394a60?cid=null",
"4.39",
"music to play"};
private Object[] songs = {Musicsong};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_music);
btnPlayPause = (Button) findViewById(R.id.btnPlayPause);
retrieveData();
displaySong(title,artist,coverArt);
}
private void retrieveData() {
Bundle songData = this.getIntent().getExtras();
songId = songData.getString("id");
title = songData.getString("title");
artist = songData.getString("artist");
fileLink = songData.getString("fileLink");
coverArt = songData.getString("coverArt");
url = BASE_URL + fileLink;
}
private void displaySong(String title, String artist, String coverArt)
{
//retrieve song title
TextView txtTitle = (TextView) findViewById(R.id.txtSongTitle);
//set text of song title
txtTitle.setText(title);
//retrieve artist
TextView txtArtist = (TextView) findViewById(R.id.txtArtist);
//set text of artist
txtArtist.setText(artist);
//get id of coverart
int imageId = AppUtil.getImageIdFromDrawable(this,coverArt);
//retrieve coverart
ImageView ivCoverArt = (ImageView) findViewById(R.id.imgCoverArt);
ivCoverArt.setImageResource(imageId);
}
public void playOrPauseMusic(View view)
{// start player
player.start();
//2.
btnPlayPause.setText("PAUSE");
//3.set the heading title of played song
setTitle("Now Playing:" + title + "-" + artist);
}
private void preparePlayer() { //create a new player
player = new MediaPlayer();
try {
//set stream type to music
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
//set source of music
player.setDataSource(url);
//prepare player for playback
player.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}}
Logs:
08-10 16:04:02.478 2567-2567/sg.edu.tp.project1 I/art: Not late-enabling -Xcheck:jni (already on)
08-10 16:04:02.478 2567-2567/sg.edu.tp.project1 W/art: Unexpected CPU variant for X86 using defaults: x86
08-10 16:04:02.535 2567-2567/sg.edu.tp.project1 W/System: ClassLoader referenced unknown path: /data/app/sg.edu.tp.project1-2/lib/x86
08-10 16:04:02.539 2567-2567/sg.edu.tp.project1 I/InstantRun: Starting Instant Run Server for sg.edu.tp.project1
08-10 16:04:02.913 2567-2567/sg.edu.tp.project1 W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
08-10 16:04:03.399 2567-2632/sg.edu.tp.project1 I/OpenGLRenderer: Initialized EGL, version 1.4
08-10 16:04:03.400 2567-2632/sg.edu.tp.project1 D/OpenGLRenderer: Swap behavior 1
08-10 16:04:03.400 2567-2632/sg.edu.tp.project1 W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
08-10 16:04:03.400 2567-2632/sg.edu.tp.project1 D/OpenGLRenderer: Swap behavior 0
08-10 16:04:03.490 2567-2567/sg.edu.tp.project1 W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
08-10 16:04:14.759 2567-2632/sg.edu.tp.project1 D/OpenGLRenderer: endAllActiveAnimators on 0x8d2e9b00 (RippleDrawable) with handle 0x8d2ff830
08-10 16:04:27.207 2567-2570/sg.edu.tp.project1 I/art: Do partial code cache collection, code=29KB, data=27KB
08-10 16:04:27.207 2567-2570/sg.edu.tp.project1 I/art: After code cache collection, code=29KB, data=27KB
08-10 16:04:27.207 2567-2570/sg.edu.tp.project1 I/art: Increasing code cache capacity to 128KB
08-10 16:04:27.463 2567-2632/sg.edu.tp.project1 D/OpenGLRenderer: endAllActiveAnimators on 0x8c313a00 (RippleDrawable) with handle 0x8d2ff420
08-10 16:04:29.695 2567-2567/sg.edu.tp.project1 D/AndroidRuntime: Shutting down VM
Beginning of crash:
08-10 16:04:29.696 2567-2567/sg.edu.tp.project1 E/AndroidRuntime: FATAL EXCEPTION: main
Process: sg.edu.tp.project1, PID: 2567
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at sg.edu.tp.project1.PlayMusicActivity.playOrPauseMusic(PlayMusicActivity.java:106)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
The exception message is very clear:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at sg.edu.tp.project1.PlayMusicActivity.playOrPauseMusic(PlayMusicActivity.java:106)
So your player field is null because you've never called PlayMusicActivity's preparePlayer() before.