0

If my code extends AppCompatActivity:

View uploadProgressView = getLayoutInflater().inflate(R.layout.view_upload_progress, null);
UploadProgressViewHolder viewHolder = new UploadProgressViewHolder(uploadProgressView, filename);

I can use getLayoutInflater() but when I change to extends Services it is not working.

I was research on Stackoverflow from this post and receive answer and change to:

LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View uploadProgressView = inflater.inflate(R.layout.view_upload_progress, null);
UploadProgressViewHolder viewHolder = new UploadProgressViewHolder(uploadProgressView, filename);

But it is not working, how to use getLayoutInflater()?

This throw exception: java.lang.NullPointerException

CallRecordService.addUploadToList(CallRecordService.java:167) Error at first line LayoutInflater inflater = ......

Context context;
private void addUploadToList(String uploadID, String filename) {
    LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
    View uploadProgressView = inflater.inflate(R.layout.view_upload_progress, null);
    UploadProgressViewHolder viewHolder = new UploadProgressViewHolder(uploadProgressView, filename);
    viewHolder.uploadId = uploadID;
    container.addView(viewHolder.itemView, 0);
    uploadProgressHolders.put(uploadID, viewHolder);
}
Community
  • 1
  • 1
leo.Ren
  • 13
  • 3

3 Answers3

1

Change the following line,

LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );

to

LayoutInflater inflater = (LayoutInflater) getSystemService( Context.LAYOUT_INFLATER_SERVICE );

This is because, Service is a Context. Service extends ContextWrapper which extends Context. You can also use 'this' keyword in the service.

K Neeraj Lal
  • 6,768
  • 3
  • 24
  • 33
  • Thanks. It pass line inflater but throw exception in this rows: `container.addView(viewHolder.itemView, 0);` error like this: `CallRecordService.addUploadToList(CallRecordService.java:173)` – leo.Ren Mar 15 '16 at 09:55
0

You need to add Layout to WindowManager after inflating view using LayoutManager.

windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
windowManager.addView(view, getLayoutParams());
K Neeraj Lal
  • 6,768
  • 3
  • 24
  • 33
maveroid
  • 1,840
  • 1
  • 20
  • 20
0

If your in a class that extends Service you can use

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

or

LayoutInflater inflater = LayoutInflater.from(this);

Both are valid because a Service is a Context

0xDEADC0DE
  • 2,453
  • 1
  • 17
  • 22