My AsyncTask is executed in my MainActivity, but it doesn't call onPostExecute. The method doInBackground is finished until the return statement (checked with System.out)!
The Call:
#Override
protected void onStart() {
super.onStart();
if (playIntent == null) {
playIntent = new Intent(this, MusicService.class);
if (CheckPermissions()) {
Prepare();
}
}
}
private void Prepare() {
MusicStore musicStore = new MusicStore(getApplicationContext());
sSongs = musicStore.getSongs();
StoreParcel storeParcel = new StoreParcel(StoreParcel.StoreAction.READ_PLAYLISTS, this);
musicStore.execute(storeParcel);
if (sSongs.length < 1) {
fabPlayPause.hide();
snbInformation = Snackbar.make(recyclerView, getString(R.string.snb_Information) + "Music.", Snackbar.LENGTH_INDEFINITE);
snbInformation.show();
}
else {
fabPlayPause.show();
}
bindService(playIntent, musicServiceConn, BIND_AUTO_CREATE);
startService(playIntent);
}
The AsyncTask:
public class MusicStore extends AsyncTask<StoreParcel, Void, StoreParcel> {
private Context mContext;
public MusicStore(Context context) {
mContext = context;
}
//region AsyncTask
#Override
protected StoreParcel doInBackground(StoreParcel... params) {
StoreParcel parcel = params[0];
StoreParcel storeParcel = new StoreParcel(parcel.getAction(), parcel.getPlaylistInterface());
switch (parcel.getAction()) {
case WRITE_PLAYLISTS:
WritePlaylists(parcel.getPlaylists());
break;
case READ_PLAYLISTS:
storeParcel.setPlaylists(ReadPlaylists());
break;
}
return storeParcel;
}
#Override
protected void onPostExecute(StoreParcel storeParcel) {
if (storeParcel.getAction() == StoreParcel.StoreAction.READ_PLAYLISTS) {
storeParcel.getPlaylistInterface().SyncPlaylists(storeParcel.getPlaylists());
}
super.onPostExecute(storeParcel);
}
//region Methods
private void WritePlaylists(Playlist[] playlists) {
File dir = new File(mContext.getFilesDir() + Preferences.dirPlaylists);
if (!dir.exists()) {
dir.mkdirs();
}
for (File f : dir.listFiles()) {
f.delete();
}
if (playlists == null) return;
String sFilename;
File file;
for (int i = 0; i < playlists.length; i++) {
sFilename = playlists[i].getName();
try {
file = new File(dir, sFilename + ".json");
file.createNewFile();
Writer writer = new OutputStreamWriter(new FileOutputStream(file));
Gson gson = new GsonBuilder().create();
gson.toJson(playlists[i], writer);
writer.close();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
private Playlist[] ReadPlaylists() {
Playlist[] playlists;
File dir = new File(mContext.getFilesDir() + Preferences.dirPlaylists);
File[] files = dir.listFiles();
if (files == null) return null;
playlists = new Playlist[files.length];
Reader reader = null;
try {
for (int i = 0; i < files.length; i++) {
reader = new InputStreamReader(new FileInputStream(files[i]));
Gson gson = new GsonBuilder().create();
playlists[i] = gson.fromJson(reader, Playlist.class);
}
if (reader != null) reader.close();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
return playlists;
}
//endregion
//endregion
}
The StoreParcel is a class created by me! It only countains an Interface, and an Enum-Value!
I think you should run the task in onResume so you are the ui exists. You can do UI stuff in onStart and onPostExecute has to run on UI thread.
#Override
protected void onStart() {
super.onStart();
if (playIntent == null) {
playIntent = new Intent(this, MusicService.class);
}
}
#Override
protected void onStart() {
super.onStart();
if (CheckPermissions()) {
Prepare();
}
}
Related
This is the implementation of downloadRequestqueue class inside a library .This java file uses work manager inside its add request function.But the work manager getworkinfobyliveId function is not called.I think the problem is because of lifecycle owner of this java class which also I have implemented in this class
public class DownloadRequestQueue extends AppCompatActivity implements LifecycleOwner
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLifecycleRegistry=new LifecycleRegistry(this);
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
}
#Override
public void onStart() {
super.onStart();
mLifecycleRegistry=new LifecycleRegistry(this);
mLifecycleRegistry.markState(Lifecycle.State.STARTED);
}
#NonNull
#Override
public Lifecycle getLifecycle() {
mLifecycleRegistry=new LifecycleRegistry(this);
Log.d("uu",mLifecycleRegistry+"");
return mLifecycleRegistry;
}
public DownloadRequestQueue(Context context) {
this.context = context;
currentRequestMap = new ConcurrentHashMap<>();
sequenceGenerator = new AtomicInteger();
}
public static void initialize(Context context) {
getInstance(context);
}
public static DownloadRequestQueue getInstance(Context context) {
if (instance == null) {
synchronized (DownloadRequestQueue.class) {
if (instance == null) {
instance = new DownloadRequestQueue(context);
}
}
}
return instance;
}
private int getSequenceNumber() {
return sequenceGenerator.incrementAndGet();
}
public void pause(int downloadId) {
DownloadRequest request = currentRequestMap.get(downloadId);
if (request != null) {
request.setStatus(Status.PAUSED);
}
}
public void resume(int downloadId) {
final Response response = new Response();
final DownloadRequest request = currentRequestMap.get(downloadId);
if (request != null) {
request.setStatus(Status.QUEUED);
request.deliverStartEvent();
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
Log.d("fff",request.getOnProgressListener()+"");
String json = gson.toJson(request);
prefsEditor.putString("SerializableObject", json);
prefsEditor.commit();
Data data = new Data.Builder().putInt("ID", downloadId).build();
final OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MyWorker.class).setInputData(data).build();
WorkManager.getInstance().enqueue(workRequest);
WorkManager.getInstance().getWorkInfoByIdLiveData(workRequest.getId()).observe(this, new Observer<WorkInfo>() {
#Override
public void onChanged(#Nullable WorkInfo workInfo) {
if (workInfo != null) {
Log.d("this","dip");
if (workInfo.getState().isFinished()) {
Data data = workInfo.getOutputData();
String output = data.getString("Response");
if (output.equals(Status.CANCELLED + "")) {
response.setCancelled(true);
}
if (output.equals(Status.PAUSED + "")) {
response.setPaused(true);
}
if (output.equals("abc")) {
Error error = new Error();
error.setConnectionError(true);
error.setConnectionException(new Exception());
response.setError(error);
}
if (output.equals("def")) {
Error error = new Error();
error.setServerError(true);
response.setError(error);
}
}
if (response.isSuccessful()) {
request.deliverSuccess();
} else if (response.isPaused()) {
request.deliverPauseEvent();
} else if (response.getError() != null) {
request.deliverError(response.getError());
} else if (!response.isCancelled()) {
request.deliverError(new Error());
}
}
}
});
// request.setFuture(Core.getInstance()
// .getExecutorSupplier()
// .forDownloadTasks()
// .submit(new DownloadRunnable(request)));
}
}
private void cancelAndRemoveFromMap(DownloadRequest request) {
if (request != null) {
request.cancel();
currentRequestMap.remove(request.getDownloadId());
}
}
public void cancel(int downloadId) {
DownloadRequest request = currentRequestMap.get(downloadId);
cancelAndRemoveFromMap(request);
}
public void cancel(Object tag) {
for (Map.Entry<Integer, DownloadRequest> currentRequestMapEntry : currentRequestMap.entrySet()) {
DownloadRequest request = currentRequestMapEntry.getValue();
if (request.getTag() instanceof String && tag instanceof String) {
final String tempRequestTag = (String) request.getTag();
final String tempTag = (String) tag;
if (tempRequestTag.equals(tempTag)) {
cancelAndRemoveFromMap(request);
}
} else if (request.getTag().equals(tag)) {
cancelAndRemoveFromMap(request);
}
}
}
public void cancelAll() {
for (Map.Entry<Integer, DownloadRequest> currentRequestMapEntry : currentRequestMap.entrySet()) {
DownloadRequest request = currentRequestMapEntry.getValue();
cancelAndRemoveFromMap(request);
}
}
public Status getStatus(int downloadId) {
DownloadRequest request = currentRequestMap.get(downloadId);
if (request != null) {
return request.getStatus();
}
return Status.UNKNOWN;
}
public void addRequest(final DownloadRequest request) {
Log.d("did", request.getUrl() + "");
final Response response = new Response();
Log.d("yoii", request.getOnProgressListener()+"");
request.setStatus(Status.QUEUED);
abc=request.getOnProgressListener()+"";
onProgressListener1=request.getOnProgressListener();
currentRequestMap.put(request.getDownloadId(), request);
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
Log.d("fff",request.getOnProgressListener()+"");
request.setOnProgressListener(request.getOnProgressListener());
String json = gson.toJson(request);
ArrayList<Integer> arrayList=new ArrayList<Integer>();
arrayList.add(1);
prefsEditor.putString("SerializableObject", json);
prefsEditor.commit();
if (request != null) {
Log.d("999", currentRequestMap.get(request.getDownloadId()).getUrl() + "");
}
if (request == null) {
Log.d("none", "bro");
}
if (request != null) {
Log.d("all", request.getUrl() + "");
}
if (request == null) {
Log.d("none", "bro");
}
Data data = new Data.Builder().putInt("ID", request.getDownloadId()).putString("status", request.getStatus() + "").build();
OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MyWorker.class).setInputData(data).build();
WorkManager.getInstance().enqueue(workRequest);
Log.d("boss", "pls");
WorkManager.getInstance().getWorkInfoByIdLiveData(workRequest.getId()).observe(this, new Observer<WorkInfo>() {
#Override
public void onChanged(#Nullable WorkInfo workInfo) {
Log.d("abd","see");
if(workInfo==null){
Log.d("bug","buggy");
}
if (workInfo != null) {
Log.d("boss2", "pls2");
if (workInfo.getState().isFinished()) {
Log.d("boss3", "pls3");
Data data = workInfo.getOutputData();
String output = data.getString("Response");
Log.d("boss4", output);
if (output.equals(Status.CANCELLED + "")) {
response.setCancelled(true);
}
if (output.equals(Status.PAUSED + "")) {
response.setPaused(true);
}
if (output.equals("succ")) {
response.setSuccessful(true);
}
if (output.equals("abc")) {
Error error = new Error();
error.setConnectionError(true);
error.setConnectionException(new Exception());
response.setError(error);
}
if (output.equals("def")) {
Error error = new Error();
error.setServerError(true);
response.setError(error);
}
}
if (response.isSuccessful()) {
request.deliverSuccess();
} else if (response.isPaused()) {
request.deliverPauseEvent();
} else if (response.getError() != null) {
request.deliverError(response.getError());
} else if (!response.isCancelled()) {
request.deliverError(new Error());
}
}
}
});
}
public void finish(DownloadRequest request) {
currentRequestMap.remove(request.getDownloadId());
}
}
public MyWorker(#NonNull Context context, #NonNull WorkerParameters workerParams) {
super(context, workerParams);
currentRequestMap=new ConcurrentHashMap<>();
mPrefs=PreferenceManager.getDefaultSharedPreferences(context);
}
#NonNull
#Override
public Result doWork() {
int a = getInputData().getInt("ID",2);
String statu = getInputData().getString("status");
Gson gson = new Gson();
String json = mPrefs.getString("SerializableObject", "");
if(json.equals("")){
Log.d("noii","nn");
}
request = gson.fromJson( json, DownloadRequest.class);
Log.d("zoiiii",currentRequestMap.get(a)+"")
if(request!=null){
Log.d("soii",request.getStatus()+"");
}
else{
Log.d("loii","toy");
}
Response response = new Response();
if (request.getStatus() == Status.CANCELLED) {
response.setCancelled(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
} else if (request.getStatus() == Status.PAUSED) {
response.setPaused(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
}
try {
Log.d("koko","gogo");
if(request.getOnProgressListener()==null){
Log.d("dope",request.getUrl()+"");
//progressHandler = new ProgressHandler(request.getOnProgressListener());
}
if (request.getOnProgressListener() != null) {
Log.d("toll","lol");
progressHandler = new ProgressHandler(request.getOnProgressListener());
}
Log.d("suppp","ppp");
tempPath = Utils.getTempPath(request.getDirPath(), request.getFileName());
File file = new File(tempPath);
DownloadModel model = getDownloadModelIfAlreadyPresentInDatabase();
Log.d("dupp","nupp");
if (model != null) {
Log.d("love","no");
if (file.exists()) {
request.setTotalBytes(model.getTotalBytes());
request.setDownloadedBytes(model.getDownloadedBytes());
} else {
removeNoMoreNeededModelFromDatabase();
request.setDownloadedBytes(0);
request.setTotalBytes(0);
model = null;
}
}
Log.d("ab","devel");
httpClient = ComponentHolder.getInstance().getHttpClient();
Log.d("ggs","iipu");
httpClient.connect(request);
if (request.getStatus() == Status.CANCELLED) {
response.setCancelled(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
} else if (request.getStatus() == Status.PAUSED) {
response.setPaused(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
}
httpClient = Utils.getRedirectedConnectionIfAny(httpClient, request);
responseCode = httpClient.getResponseCode();
eTag = httpClient.getResponseHeader(Constants.ETAG);
Log.d("sipi","kipi");
if (checkIfFreshStartRequiredAndStart(model)) {
model = null;
Log.d("lova","nova");
}
if (!isSuccessful()) {
Log.d("lvv","nppp");
Error error = new Error();
error.setServerError(true);
error.setServerErrorMessage(convertStreamToString(httpClient.getErrorStream()));
error.setHeaderFields(httpClient.getHeaderFields());
error.setResponseCode(responseCode);
response.setError(error);
Data output = new Data.Builder()
.putString("Response","abc")
.build();
return Result.failure(output);
}
setResumeSupportedOrNot();
Log.d("coder","npppp");
totalBytes = request.getTotalBytes();
if (!isResumeSupported) {
deleteTempFile();
}
if (totalBytes == 0) {
totalBytes = httpClient.getContentLength();
request.setTotalBytes(totalBytes);
}
if (isResumeSupported && model == null) {
createAndInsertNewModel();
}
if (request.getStatus() == Status.CANCELLED) {
response.setCancelled(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
} else if (request.getStatus() == Status.PAUSED) {
response.setPaused(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
}
Log.d("dodo","soso");
request.deliverStartEvent();
Log.d("coco","momo");
inputStream = httpClient.getInputStream();
byte[] buff = new byte[BUFFER_SIZE];
if (!file.exists()) {
if (file.getParentFile() != null && !file.getParentFile().exists()) {
if (file.getParentFile().mkdirs()) {
//noinspection ResultOfMethodCallIgnored
file.createNewFile();
}
} else {
//noinspection ResultOfMethodCallIgnored
file.createNewFile();
}
}
this.outputStream = FileDownloadRandomAccessFile.create(file);
if (isResumeSupported && request.getDownloadedBytes() != 0) {
outputStream.seek(request.getDownloadedBytes());
}
Log.d("miggy","siggy");
if (request.getStatus() == Status.CANCELLED) {
response.setCancelled(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
} else if (request.getStatus() == Status.PAUSED) {
response.setPaused(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
}
do {
Log.d("left","some");
final int byteCount = inputStream.read(buff, 0, BUFFER_SIZE);
if (byteCount == -1) {
break;
}
outputStream.write(buff, 0, byteCount);
request.setDownloadedBytes(request.getDownloadedBytes() + byteCount);
Log.d("now1","one1");
sendProgress();
Log.d("now2","one2");
syncIfRequired(outputStream);
Log.d("common","yessin");
if (request.getStatus() == Status.CANCELLED) {
response.setCancelled(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
} else if (request.getStatus() == Status.PAUSED) {
sync(outputStream);
response.setPaused(true);
Data output = new Data.Builder()
.putString("Response",response+"")
.build();
return Result.failure(output);
}
} while (true);
final String path = Utils.getPath(request.getDirPath(), request.getFileName());
Utils.renameFileName(tempPath, path);
response.setSuccessful(true);
Log.d("yup","dove");
if (isResumeSupported) {
removeNoMoreNeededModelFromDatabase();
}
} catch (IOException | IllegalAccessException e) {
if (!isResumeSupported) {
deleteTempFile();
}
Error error = new Error();
error.setConnectionError(true);
error.setConnectionException(e);
response.setError(error);
Data output = new Data.Builder()
.putString("Response","def")
.build();
return Result.failure(output);
} finally {
closeAllSafely(outputStream);
}
Log.d("final","done");
Data output = new Data.Builder()
.putString("Response","succ")
.build();
return Result.success(output);
}
private void deleteTempFile() {
File file = new File(tempPath);
if (file.exists()) {
//noinspection ResultOfMethodCallIgnored
file.delete();
}
}
private boolean isSuccessful() {
return responseCode >= HttpURLConnection.HTTP_OK
&& responseCode < HttpURLConnection.HTTP_MULT_CHOICE;
}
private void setResumeSupportedOrNot() {
isResumeSupported = (responseCode == HttpURLConnection.HTTP_PARTIAL);
}
private boolean checkIfFreshStartRequiredAndStart(DownloadModel model) throws IOException,
IllegalAccessException {
if (responseCode == Constants.HTTP_RANGE_NOT_SATISFIABLE || isETagChanged(model)) {
if (model != null) {
removeNoMoreNeededModelFromDatabase();
}
deleteTempFile();
request.setDownloadedBytes(0);
request.setTotalBytes(0);
httpClient = ComponentHolder.getInstance().getHttpClient();
httpClient.connect(request);
httpClient = Utils.getRedirectedConnectionIfAny(httpClient, request);
responseCode = httpClient.getResponseCode();
return true;
}
return false;
}
private boolean isETagChanged(DownloadModel model) {
return !(eTag == null || model == null || model.getETag() == null)
&& !model.getETag().equals(eTag);
}
private DownloadModel getDownloadModelIfAlreadyPresentInDatabase() {
return ComponentHolder.getInstance().getDbHelper().find(request.getDownloadId());
}
private void createAndInsertNewModel() {
DownloadModel model = new DownloadModel();
model.setId(request.getDownloadId());
model.setUrl(request.getUrl());
model.setETag(eTag);
model.setDirPath(request.getDirPath());
model.setFileName(request.getFileName());
model.setDownloadedBytes(request.getDownloadedBytes());
model.setTotalBytes(totalBytes);
model.setLastModifiedAt(System.currentTimeMillis());
ComponentHolder.getInstance().getDbHelper().insert(model);
}
private void removeNoMoreNeededModelFromDatabase() {
ComponentHolder.getInstance().getDbHelper().remove(request.getDownloadId());
}
private void sendProgress() {
if (request.getStatus() != Status.CANCELLED) {
Log.d("ttyl","ggyl");
if (progressHandler != null) {
Log.d("mozz","illa");
progressHandler
.obtainMessage(Constants.UPDATE,
new Progress(request.getDownloadedBytes(),
totalBytes)).sendToTarget();
}
else{
Log.d("maybe","into");
}
}
}
private void syncIfRequired(FileDownloadOutputStream outputStream) {
final long currentBytes = request.getDownloadedBytes();
final long currentTime = System.currentTimeMillis();
final long bytesDelta = currentBytes - lastSyncBytes;
final long timeDelta = currentTime - lastSyncTime;
if (bytesDelta > MIN_BYTES_FOR_SYNC && timeDelta > TIME_GAP_FOR_SYNC) {
sync(outputStream);
lastSyncBytes = currentBytes;
lastSyncTime = currentTime;
}
}
private void sync(FileDownloadOutputStream outputStream) {
boolean success;
try {
outputStream.flushAndSync();
success = true;
} catch (IOException e) {
success = false;
e.printStackTrace();
}
if (success && isResumeSupported) {
ComponentHolder.getInstance().getDbHelper()
.updateProgress(request.getDownloadId(),
request.getDownloadedBytes(),
System.currentTimeMillis());
}
}
private void closeAllSafely(FileDownloadOutputStream outputStream) {
if (httpClient != null) {
try {
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
if (outputStream != null) {
try {
sync(outputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
} finally {
if (outputStream != null)
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String convertStreamToString(InputStream stream) {
StringBuilder stringBuilder = new StringBuilder();
if (stream != null) {
String line;
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new InputStreamReader(stream));
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
} catch (IOException ignored) {
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (NullPointerException | IOException ignored) {
}
}
}
return stringBuilder.toString();
}
I keep getting an an error when trying to call WowZa GoCoder SDK's PlayerActivity and I am unable to understand the cause. The error appears when mStreamPlayerView.play(mStreamPlayerConfig, statusCallback) is called. Would really appreciate help on where i am going wrong
vodFragment.java
public class vodFragment extends Fragment {
private int mColumnCount = 1;
ListView videoView;
ArrayList <Vidoes> videoList;
private static String value;
String videoName;
String url = "http://192.168.43.149/twende/channelVOD.php";
public vodFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (getActivity().getActionBar() != null) {
getActivity().getActionBar().setTitle(value);
}
View view = inflater.inflate(R.layout.fragment_vod_list, container, false);
videoView = (ListView) view.findViewById(R.id.listView);
videoList = new ArrayList<Vidoes>();
JSONObject channelInfo = new JSONObject();
try {
channelInfo.put("channelName", value);
channelInfo.put("channelOwner", "dan");
postJSONObject(url,channelInfo);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return view;
}
public static void setChannel(String channel){
value = channel;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
public void postJSONObject(final String myurl, final JSONObject parameters) {
class postJSONObject extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
loadIntoVodView(s);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
HttpURLConnection conn = null;
try {
StringBuffer response = null;
URL url = new URL(myurl);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(parameters.toString());
writer.close();
out.close();
int responseCode = conn.getResponseCode();
System.out.println("responseCode" + responseCode);
switch (responseCode) {
case 200:
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (conn != null) {
try {
conn.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return null;
}
}
postJSONObject postJSONObject = new postJSONObject();
postJSONObject.execute();
}
private void loadIntoVodView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
final String[] videos = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
videos[i] = removeExtension(obj.getString("title"));
Vidoes vidoe = new Vidoes();
vidoe.setTitle(videos[i]);
videoList.add(vidoe);
}
VideoListAdapter adapter = new VideoListAdapter(getActivity(), R.layout.vodparsedata, videoList);
videoView.setAdapter(adapter);
videoView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
videoName = Arrays.asList(videos).get(position);
Intent intent = new Intent(getActivity(), PlayerActivity.class);
String message = videoName+".mp4";
intent.putExtra("videoName", message);
startActivity(intent);
System.out.println("arr: " + Arrays.asList(videos).get(position));
}
});
}
public static String removeExtension(String fileName) {
if (fileName.indexOf(".") > 0) {
return fileName.substring(0, fileName.lastIndexOf("."));
} else {
return fileName;
}
}
}
PlayerActivity.java
public class PlayerActivity extends GoCoderSDKActivityBase {
final private static String TAG = PlayerActivity.class.getSimpleName();
String videoName;
private WOWZPlayerView mStreamPlayerView = null;
private WOWZPlayerConfig mStreamPlayerConfig = new WOWZPlayerConfig();
private MultiStateButton mBtnPlayStream = null;
private MultiStateButton mBtnSettings = null;
private MultiStateButton mBtnMic = null;
private MultiStateButton mBtnScale = null;
private SeekBar mSeekVolume = null;
private ProgressDialog mBufferingDialog = null;
private StatusView mStatusView = null;
private TextView mHelp = null;
private TimerView mTimerView = null;
private ImageButton mStreamMetadata = null;
private boolean mUseHLSPlayback = false;
private WOWZPlayerView.PacketThresholdChangeListener packetChangeListener = null;
private VolumeChangeObserver mVolumeSettingChangeObserver = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stream_player);
mRequiredPermissions = new String[]{};
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
videoName= null;
} else {
videoName= extras.getString("videoName");
}
} else {
videoName= (String) savedInstanceState.getSerializable("videoName");
}
System.out.print(videoName);
mStreamPlayerConfig.setIsPlayback(true);
mStreamPlayerConfig.setHostAddress("192.168.43.149");
mStreamPlayerConfig.setApplicationName("Dark Souls 2 Channel");
mStreamPlayerConfig.setStreamName(videoName);
mStreamPlayerConfig.setPortNumber(1935);
mStreamPlayerView = (WOWZPlayerView) findViewById(R.id.vwStreamPlayer);
mBtnPlayStream = (MultiStateButton) findViewById(R.id.ic_play_stream);
mBtnSettings = (MultiStateButton) findViewById(R.id.ic_settings);
mBtnMic = (MultiStateButton) findViewById(R.id.ic_mic);
mBtnScale = (MultiStateButton) findViewById(R.id.ic_scale);
mTimerView = (TimerView) findViewById(R.id.txtTimer);
mStatusView = (StatusView) findViewById(R.id.statusView);
mStreamMetadata = (ImageButton) findViewById(R.id.imgBtnStreamInfo);
mHelp = (TextView) findViewById(R.id.streamPlayerHelp);
mSeekVolume = (SeekBar) findViewById(R.id.sb_volume);
WOWZStatusCallback statusCallback = new StatusCallback();
mStreamPlayerView.play(mStreamPlayerConfig, statusCallback);
mTimerView.setVisibility(View.GONE);
mStreamPlayerView.play(mStreamPlayerConfig, statusCallback);
if (sGoCoderSDK != null) {
/*
Packet change listener setup
*/
final PlayerActivity activity = this;
packetChangeListener = new WOWZPlayerView.PacketThresholdChangeListener() {
#Override
public void packetsBelowMinimumThreshold(int packetCount) {
WOWZLog.debug("Packets have fallen below threshold "+packetCount+"... ");
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Packets have fallen below threshold ... ", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void packetsAboveMinimumThreshold(int packetCount) {
WOWZLog.debug("Packets have risen above threshold "+packetCount+" ... ");
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Packets have risen above threshold ... ", Toast.LENGTH_SHORT).show();
}
});
}
};
mStreamPlayerView.setShowAllNotificationsWhenBelowThreshold(false);
mStreamPlayerView.setMinimumPacketThreshold(20);
mStreamPlayerView.registerPacketThresholdListener(packetChangeListener);
///// End packet change notification listener
mTimerView.setTimerProvider(new TimerView.TimerProvider() {
#Override
public long getTimecode() {
return mStreamPlayerView.getCurrentTime();
}
#Override
public long getDuration() {
return mStreamPlayerView.getDuration();
}
});
mSeekVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mStreamPlayerView != null && mStreamPlayerView.isPlaying()) {
mStreamPlayerView.setVolume(progress);
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
// listen for volume changes from device buttons, etc.
mVolumeSettingChangeObserver = new VolumeChangeObserver(this, new Handler());
getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, mVolumeSettingChangeObserver);
mVolumeSettingChangeObserver.setVolumeChangeListener(new VolumeChangeObserver.VolumeChangeListener() {
#Override
public void onVolumeChanged(int previousLevel, int currentLevel) {
if (mSeekVolume != null)
mSeekVolume.setProgress(currentLevel);
if (mStreamPlayerView != null && mStreamPlayerView.isPlaying()) {
mStreamPlayerView.setVolume(currentLevel);
}
}
});
mBtnScale.setState(mStreamPlayerView.getScaleMode() == WOWZMediaConfig.FILL_VIEW);
// The streaming player configuration properties
mStreamPlayerConfig = new WOWZPlayerConfig();
mBufferingDialog = new ProgressDialog(this);
mBufferingDialog.setTitle(R.string.status_buffering);
mBufferingDialog.setMessage(getResources().getString(R.string.msg_please_wait));
mBufferingDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(R.string.button_cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
cancelBuffering(dialogInterface);
}
});
// testing player data event handler.
mStreamPlayerView.registerDataEventListener("onMetaData", new WOWZDataEvent.EventListener(){
#Override
public WOWZDataMap onWZDataEvent(String eventName, WOWZDataMap eventParams) {
String meta = "";
if(eventParams!=null)
meta = eventParams.toString();
WOWZLog.debug("onWZDataEvent -> eventName "+eventName+" = "+meta);
return null;
}
});
// testing player data event handler.
mStreamPlayerView.registerDataEventListener("onStatus", new WOWZDataEvent.EventListener(){
#Override
public WOWZDataMap onWZDataEvent(String eventName, WOWZDataMap eventParams) {
if(eventParams!=null)
WOWZLog.debug("onWZDataEvent -> eventName "+eventName+" = "+eventParams.toString());
return null;
}
});
// testing player data event handler.
mStreamPlayerView.registerDataEventListener("onTextData", new WOWZDataEvent.EventListener(){
#Override
public WOWZDataMap onWZDataEvent(String eventName, WOWZDataMap eventParams) {
if(eventParams!=null)
WOWZLog.debug("onWZDataEvent -> "+eventName+" = "+eventParams.get("text"));
return null;
}
});
} else {
mHelp.setVisibility(View.GONE);
mStatusView.setErrorMessage(WowzaGoCoder.getLastError().getErrorDescription());
}
}
#Override
protected void onDestroy() {
if (mVolumeSettingChangeObserver != null)
getApplicationContext().getContentResolver().unregisterContentObserver(mVolumeSettingChangeObserver);
super.onDestroy();
}
/**
* Android Activity class methods
*/
#Override
protected void onResume() {
super.onResume();
syncUIControlState();
}
#Override
protected void onPause() {
if (mStreamPlayerView != null && mStreamPlayerView.isPlaying()) {
mStreamPlayerView.stop();
// Wait for the streaming player to disconnect and shutdown...
mStreamPlayerView.getCurrentStatus().waitForState(WOWZState.IDLE);
}
super.onPause();
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public boolean isPlayerConfigReady()
{
return false;
}
/*
Click handler for network pausing
*/
public void onPauseNetwork(View v)
{
Button btn = (Button)findViewById(R.id.pause_network);
if(btn.getText().toString().trim().equalsIgnoreCase("pause network")) {
WOWZLog.info("Pausing network...");
btn.setText("Unpause Network");
mStreamPlayerView.pauseNetworkStack();
}
else{
WOWZLog.info("Unpausing network... btn.getText(): "+btn.getText());
btn.setText("Pause Network");
mStreamPlayerView.unpauseNetworkStack();
}
}
/**
* Click handler for the playback button
*/
public void onTogglePlayStream(View v) {
if (mStreamPlayerView.isPlaying()) {
mStreamPlayerView.stop();
} else if (mStreamPlayerView.isReadyToPlay()) {
if(!this.isNetworkAvailable()){
displayErrorDialog("No internet connection, please try again later.");
return;
}
// if(!this.isPlayerConfigReady()){
// displayErrorDialog("Please be sure to include a host, stream, and application to playback a stream.");
// return;
// }
mHelp.setVisibility(View.GONE);
WOWZStreamingError configValidationError = mStreamPlayerConfig.validateForPlayback();
if (configValidationError != null) {
mStatusView.setErrorMessage(configValidationError.getErrorDescription());
} else {
// Set the detail level for network logging output
mStreamPlayerView.setLogLevel(mWZNetworkLogLevel);
// Set the player's pre-buffer duration as stored in the app prefs
float preBufferDuration = GoCoderSDKPrefs.getPreBufferDuration(PreferenceManager.getDefaultSharedPreferences(this));
mStreamPlayerConfig.setPreRollBufferDuration(preBufferDuration);
// Start playback of the live stream
mStreamPlayerView.play(mStreamPlayerConfig, this);
}
}
}
/**
* WOWZStatusCallback interface methods
*/
#Override
public synchronized void onWZStatus(WOWZStatus status) {
final WOWZStatus playerStatus = new WOWZStatus(status);
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
WOWZStatus status = new WOWZStatus(playerStatus.getState());
switch(playerStatus.getState()) {
case WOWZPlayerView.STATE_PLAYING:
// Keep the screen on while we are playing back the stream
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (mStreamPlayerConfig.getPreRollBufferDuration() == 0f) {
mTimerView.startTimer();
}
// Since we have successfully opened up the server connection, store the connection info for auto complete
GoCoderSDKPrefs.storeHostConfig(PreferenceManager.getDefaultSharedPreferences(PlayerActivity.this), mStreamPlayerConfig);
// Log the stream metadata
WOWZLog.debug(TAG, "Stream metadata:\n" + mStreamPlayerView.getMetadata());
break;
case WOWZPlayerView.STATE_READY_TO_PLAY:
// Clear the "keep screen on" flag
WOWZLog.debug(TAG, "STATE_READY_TO_PLAY player activity status!");
if(playerStatus.getLastError()!=null)
displayErrorDialog(playerStatus.getLastError());
playerStatus.clearLastError();
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mTimerView.stopTimer();
break;
case WOWZPlayerView.STATE_PREBUFFERING_STARTED:
WOWZLog.debug(TAG, "Dialog for buffering should show...");
showBuffering();
break;
case WOWZPlayerView.STATE_PREBUFFERING_ENDED:
WOWZLog.debug(TAG, "Dialog for buffering should stop...");
hideBuffering();
// Make sure player wasn't signaled to shutdown
if (mStreamPlayerView.isPlaying()) {
mTimerView.startTimer();
}
break;
default:
break;
}
syncUIControlState();
}
});
}
#Override
public synchronized void onWZError(final WOWZStatus playerStatus) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
displayErrorDialog(playerStatus.getLastError());
syncUIControlState();
}
});
}
public void onToggleMute(View v) {
mBtnMic.toggleState();
if (mStreamPlayerView != null)
mStreamPlayerView.mute(!mBtnMic.isOn());
mSeekVolume.setEnabled(mBtnMic.isOn());
}
public void onToggleScaleMode(View v) {
int newScaleMode = mStreamPlayerView.getScaleMode() == WOWZMediaConfig.RESIZE_TO_ASPECT ? WOWZMediaConfig.FILL_VIEW : WOWZMediaConfig.RESIZE_TO_ASPECT;
mBtnScale.setState(newScaleMode == WOWZMediaConfig.FILL_VIEW);
mStreamPlayerView.setScaleMode(newScaleMode);
}
public void onStreamMetadata(View v) {
WOWZDataMap streamMetadata = mStreamPlayerView.getMetadata();
WOWZDataMap streamStats = mStreamPlayerView.getStreamStats();
// WOWZDataMap streamConfig = mStreamPlayerView.getStreamConfig().toDataMap();
WOWZDataMap streamConfig = new WOWZDataMap();
WOWZDataMap streamInfo = new WOWZDataMap();
streamInfo.put("- Stream Statistics -", streamStats);
streamInfo.put("- Stream Metadata -", streamMetadata);
//streamInfo.put("- Stream Configuration -", streamConfig);
DataTableFragment dataTableFragment = DataTableFragment.newInstance("Stream Information", streamInfo, false, false);
getFragmentManager().beginTransaction()
.add(android.R.id.content, dataTableFragment)
.addToBackStack("metadata_fragment")
.commit();
}
public void onSettings(View v) {
// Display the prefs fragment
GoCoderSDKPrefs.PrefsFragment prefsFragment = new GoCoderSDKPrefs.PrefsFragment();
prefsFragment.setFixedSource(true);
prefsFragment.setForPlayback(true);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, prefsFragment)
.addToBackStack(null)
.commit();
}
private void syncUIControlState() {
boolean disableControls = (!(mStreamPlayerView.isReadyToPlay() || mStreamPlayerView.isPlaying()) || sGoCoderSDK == null);
if (disableControls) {
mBtnPlayStream.setEnabled(false);
mBtnSettings.setEnabled(false);
mSeekVolume.setEnabled(false);
mBtnScale.setEnabled(false);
mBtnMic.setEnabled(false);
mStreamMetadata.setEnabled(false);
} else {
mBtnPlayStream.setState(mStreamPlayerView.isPlaying());
mBtnPlayStream.setEnabled(true);
if (mStreamPlayerConfig.isAudioEnabled()) {
mBtnMic.setVisibility(View.VISIBLE);
mBtnMic.setEnabled(true);
mSeekVolume.setVisibility(View.VISIBLE);
mSeekVolume.setEnabled(mBtnMic.isOn());
mSeekVolume.setProgress(mStreamPlayerView.getVolume());
} else {
mSeekVolume.setVisibility(View.GONE);
mBtnMic.setVisibility(View.GONE);
}
mBtnScale.setVisibility(View.VISIBLE);
mBtnScale.setVisibility(mStreamPlayerView.isPlaying() && mStreamPlayerConfig.isVideoEnabled() ? View.VISIBLE : View.GONE);
mBtnScale.setEnabled(mStreamPlayerView.isPlaying() && mStreamPlayerConfig.isVideoEnabled());
mBtnSettings.setEnabled(!mStreamPlayerView.isPlaying());
mBtnSettings.setVisibility(mStreamPlayerView.isPlaying() ? View.GONE : View.VISIBLE);
mStreamMetadata.setEnabled(mStreamPlayerView.isPlaying());
mStreamMetadata.setVisibility(mStreamPlayerView.isPlaying() ? View.VISIBLE : View.GONE);
}
}
private void showBuffering() {
try {
if (mBufferingDialog == null) return;
mBufferingDialog.show();
}
catch(Exception ex){}
}
private void cancelBuffering(DialogInterface dialogInterface) {
if(mStreamPlayerConfig.getHLSBackupURL()!=null || mStreamPlayerConfig.isHLSEnabled()){
mStreamPlayerView.stop(true);
}
else if (mStreamPlayerView != null && mStreamPlayerView.isPlaying()) {
mStreamPlayerView.stop(true);
}
}
private void hideBuffering() {
if (mBufferingDialog.isShowing())
mBufferingDialog.dismiss();
}
#Override
public void syncPreferences() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
mWZNetworkLogLevel = Integer.valueOf(prefs.getString("wz_debug_net_log_level", String.valueOf(WOWZLog.LOG_LEVEL_DEBUG)));
mStreamPlayerConfig.setIsPlayback(true);
if (mStreamPlayerConfig != null)
GoCoderSDKPrefs.updateConfigFromPrefsForPlayer(prefs, mStreamPlayerConfig);
}
private class StatusCallback implements WOWZStatusCallback {
#Override
public void onWZStatus(WOWZStatus wzStatus) {
}
#Override
public void onWZError(WOWZStatus wzStatus) {
}
}
}
The error I get is;
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.wowza.gocoder.sdk.sampleapp/com.wowza.gocoder.sdk.sampleapp.PlayerActivity}: java.lang.RuntimeException: Invalid surface: null
You start the stream in onCreate. At this time the Surface used by WOWZPlayerView is not ready yet and the app crashes with the 'Invalid surface' error.
If you look at the sample test in the GoCoder SDK, the playback is started when the user clicks a button. Eg. when the Surface is valid.
Create a button and move your 'mStreamPlayerView.play(mStreamPlayerConfig, statusCallback);' to the button.onClick.
Or ... use any GoCoder SDK v1.7 and more recent.
Please, let me know if I can help any further.
Thanks
I have a problem. When I do a query in the stream, I have downloaded the data from the URL, everything works. But when I call AsynsTask example by pressing doInBackground() method that returns the same data, but they are updated on the URL. And they will not be updated as long as the program is restarted.
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL("data.php?"+new Random().nextInt(200));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
jSON_R = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return jSON_R;
}
All code
public class ParseTask extends AsyncTask<Void, Void, String> {
int intRow = 0;
String jSON_R = "";
private List<User> movieList;
Activity act;
ListView list;
LAdapter adapter;
boolean Unique = true;
public ParseTask (Activity act){
this.act = act;
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL("data.php?"+new Random().nextInt(200));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
jSON_R = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return jSON_R;
}
#Override
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
list = (ListView) act.findViewById(R.id.listVew);
Button b = (Button) act.findViewById(R.id.refresh);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//To do
}
});
movieList = new ArrayList<>();
adapter = new LAdapter(act, movieList);
list.setAdapter(adapter);
try {
JSONObject dataJsonObj = new JSONObject(strJson);
JSONArray jsa = dataJsonObj.getJSONArray("data");
for (int i = 0; i < jsa.length(); i++) {
JSONObject data1 = chat.getJSONObject(i);
String mes = data1.getString("mes1");
String mes2 = data1.getString("mes2");
String mes3 = data1.getString("mes3");
User m = new User(mes, mes2, mes3);
movieList.add(0, m);
}
adapter.notifyDataSetChanged();
intRow = jsa.length();
} catch (JSONException e) {
e.printStackTrace();
}
list.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem > 1){
Unique = false;
}else{
Unique = true;
}
}
});
Thread thread = new Thread() {
#Override
public void run() {
try {
while (true){
sleep(5000);
if (Unique){
act.runOnUiThread(new Runnable() {
#Override
public void run() {
Update();
}
});
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
private void Update(){
try {
JSONObject dataJsonObj = new JSONObject(strJson);
JSONArray jsa = dataJsonObj.getJSONArray("data");
for (int i = 0; i < jsa.length(); i++) {
JSONObject data1 = chat.getJSONObject(i);
String mes = data1.getString("mes1");
String mes2 = data1.getString("mes2");
String mes3 = data1.getString("mes3");
User m = new User(mes, mes2, mes3);
movieList.add(0, m);
}
adapter.notifyDataSetChanged();
intRow = jsa.length();
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}
Calling the object in such a way
new ParseTask(getActivity()).execute();
Close the connection.
I mean use (better) reader.close() or inputStream.close()
Or try jsoup library https://jsoup.org/
Until now I could programmatically copy files from the internal memory of the phone to an USB-OTG connected to it. I just had to give root permissions and edit platform.xml. But now my device (Samsung Galaxy S6 Edge +) has been updated to Android 6 and made my code stop working.
I'm getting this error everytime I try to copy files the way I did before:
Caused by java.lang.RuntimeException: java.io.FileNotFoundException: /mnt/media_rw/4265-1803/requiredfiles/Oculus/360Photos/Pisos/Chalet Anna/R0010008.JPG: open failed: EACCES (Permission denied)
String from = Environment.getExternalStorageDirectory() + File.separator + getString(R.string.FOLDER_SDCARD);
String to = Utils.getUsbPath() + File.separator + getString(R.string.FOLDER_USB);
FileManager fileManager = new FileManager(getActivity(), from, to, false);
fileManager.execute(true);
My getUsbPath function
public static String getUsbPath() {
String finalpath = null;
try {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("mount");
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
String line;
String[] patharray = new String[10];
int i = 0;
int available = 0;
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
String mount = new String();
if (line.contains("secure"))
continue;
if (line.contains("asec"))
continue;
if (line.contains("fat")) {// TF card
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
mount = mount.concat(columns[1] + "/requiredfiles");
patharray[i] = mount;
i++;
// check directory is exist or not
File dir = new File(mount);
if (dir.exists() && dir.isDirectory()) {
// do something here
available = 1;
finalpath = mount;
break;
} else {
}
}
}
}
if (available == 1) {
} else if (available == 0) {
finalpath = patharray[0];
}
} catch (Exception e) {
}
return finalpath;
}
My FileManager.class
public class FileManager extends AsyncTask<Boolean, Integer, Boolean> {
private Context context;
private String from;
private String to;
private ProgressDialog progressDialog;
private int filesCount=0;
private int filesTotal=0;
Boolean completed;
Boolean move;
MainActivity main;
public static final String TAG = "FileManager";
public FileManager(Context context, String from, String to, Boolean move) {
this.context = context;
this.from = from;
this.to = to;
this.move = move;
this.main = (MainActivity) context;
}
#Override
protected Boolean doInBackground(Boolean... params) {
File source = new File(from);
File target = new File(to);
try {
countFiles(source);
copyDirectory(source, target);
if (move) {
deleteFiles(source);
}
completed = true;
} catch (Exception error) {
Log.e(TAG, "doInBackground", error);
completed = false;
try {
throw error;
} catch (IOException e) {
e.printStackTrace();
}
throw new RuntimeException(error.toString());
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
if (move) {
progressDialog.setMessage(context.getString(R.string.moving_files));
} else {
progressDialog.setMessage(context.getString(R.string.copying_files));
}
progressDialog.setIndeterminate(true);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
progressDialog.dismiss();
if (completed) {
if (move) {
Snackbar.make(main.findViewById(R.id.frame_layout), context.getString(R.string.move_completed), Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(main.findViewById(R.id.frame_layout), context.getString(R.string.copy_completed), Snackbar.LENGTH_LONG).show();
}
} else {
if (move) {
Snackbar.make(main.findViewById(R.id.frame_layout), context.getString(R.string.move_failed), Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(main.findViewById(R.id.frame_layout), context.getString(R.string.copy_failed), Snackbar.LENGTH_LONG).show();
}
}
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressDialog.setIndeterminate(false);
progressDialog.setMax(filesTotal);
progressDialog.setProgress(filesCount);
}
private void copyDirectory(File sourceLocation, File targetLocation) throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdirs();
}
String[] children = sourceLocation.list();
for (int i = 0; i < sourceLocation.listFiles().length; i++) {
copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, children[i]));
}
} else {
if (!targetLocation.exists()) {
filesCount++;
publishProgress();
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
scanFile(targetLocation.getCanonicalPath(), false);
}
}
}
private void countFiles(File file) {
if (file.isDirectory()) {
String[] children = file.list();
for (int i = 0; i < file.listFiles().length; i++) {
countFiles(new File(file, children[i]));
}
} else {
filesTotal++;
}
}
public void deleteFiles(File folder) {
if (folder.isDirectory()) {
File[] list = folder.listFiles();
if (list != null) {
for (int i = 0; i < list.length; i++) {
File tmpF = list[i];
if (tmpF.isDirectory()) {
deleteFiles(tmpF);
}
tmpF.delete();
String path;
try {
path = tmpF.getCanonicalPath();
} catch (Exception error) {
Log.e(TAG, "", error);
path = tmpF.getAbsolutePath();
}
scanFile(path, true);
}
}
}
}
private void scanFile(String path, final boolean isDelete) {
try {
MediaScannerConnection.scanFile(context, new String[] { path },
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
if (isDelete) {
if (uri != null) {
context.getContentResolver().delete(uri,
null, null);
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
How can I solve it?
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
For some reason in my application, when I try to call openFileOutput(), it throws a NullPointerException and I am not sure what is causing it. I have made sure that all the parameters of the method are not null, but for some reason my app still throws a NullPointerException. Any suggestions?
My MainActivity class
public class MainActivity extends AppCompatActivity {
private static final String TAG_NEWS_FRAGMENT = "news_fragment";
private static final String TAG_SPORTS_FRAGMENT = "sports_fragment";
Context context = MainActivity.this;
private final String[] CATEGORY_NAMES = {"news", "sports"};
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private ProgressBar mProgressBar;
private CoordinatorLayout coordinatorLayout;
private PUNewsFragment mPUNewsFragement;
private PUSportsFragment mPUSportsFragement;
private List<NewspaperMetaObject> newsItems;
private List<List<NewspaperMetaObject>> categories;
private boolean doesFileExist;
private boolean isWebsiteOnline;
private FragmentManager fm;
private ProgressBar pb;
private boolean doRefresh;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
doRefresh = false;
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
Toast.makeText(this, "Loading...", Toast.LENGTH_SHORT).show();
pb = (ProgressBar) findViewById(R.id.progressBar);
try {
isWebsiteOnline = new checkWebsiteStatus().execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
doesFileExist = new File(context.getFilesDir() + "/news").exists();
new RetrieveNewspaperMeta().execute(CATEGORY_NAMES);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new PUNewsFragment(), "News");
adapter.addFragment(new PUSportsFragment(), "Sports");
viewPager.setAdapter(adapter);
}
public void refresh(String[] str) {
doRefresh = true;
new RetrieveNewspaperMeta().execute(str);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
private class RetrieveNewspaperMeta extends AsyncTask<String, Integer, Wrapper> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Wrapper doInBackground(String... params) {
Document doc = null;
categories = new ArrayList<>();
if (!doesFileExist && doRefresh) {
for (int i = 0; i < params.length; i++) {
newsItems = new ArrayList<>();
try {
Log.i("DEBUG", params[i]);
URL url = new URL("http://www.dailyprincetonian.com/category/" + params[i] + "/");
doc = Jsoup.connect(url.toString()).get();
Elements content = doc.select("article.tease-post");
System.out.println();
System.out.println(content);
int count = 0;
NewspaperMetaObject parser;
while (!content.eq(count).isEmpty()) {
parser = new NewspaperMetaObject(content.eq(count));
newsItems.add(parser);
count++;
}
categories.add(newsItems);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
for (NewspaperMetaObject o : newsItems) {
try {
Elements text = Jsoup.connect(o.getDoc().select("h3.h2 a").attr("href")).get().select("section.article-content").select("div.article-bd").select("p");
o.setArticleText(text.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return new Wrapper(categories, params);
} else {
for (int i = 0; i < params.length; i++) {
newsItems = new ArrayList<>();
try {
FileInputStream fis = openFileInput(params[i]);
ObjectInputStream is = new ObjectInputStream(fis);
newsItems = (List<NewspaperMetaObject>) is.readObject();
is.close();
fis.close();
categories.add(newsItems);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return new Wrapper(categories, params);
}
}
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected void onPostExecute(final Wrapper wrapper) {
super.onPostExecute(wrapper);
android.os.Handler mHandler = new android.os.Handler();
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
if (!doRefresh) {
PUNewsFragment.newsItems = categories.get(0);
PUSportsFragment.newsItems = categories.get(1);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
fm = getSupportFragmentManager();
mPUNewsFragement = (PUNewsFragment) fm.findFragmentByTag(TAG_NEWS_FRAGMENT);
mPUSportsFragement = (PUSportsFragment) fm.findFragmentByTag(TAG_SPORTS_FRAGMENT);
if (mPUNewsFragement == null && mPUSportsFragement == null) {
mPUNewsFragement = new PUNewsFragment();
mPUSportsFragement = new PUSportsFragment();
fm.beginTransaction().add(mPUNewsFragement, TAG_NEWS_FRAGMENT).commit();
fm.beginTransaction().add(mPUSportsFragement, TAG_SPORTS_FRAGMENT).commit();
}
} else {
for (int i = 0; i < wrapper.params.length; i++) {
switch (wrapper.params[i]) {
case "news":
PUNewsFragment.newsItems = categories.get(0);
PUNewsFragment.adapter.notifyDataSetChanged();
break;
case "sports":
PUSportsFragment.newsItems = categories.get(1);
PUSportsFragment.adapter.notifyDataSetChanged();
break;
}
}
}
if (pb != null) {
pb.setVisibility(View.GONE);
}
Log.i("DEBUG", "DONE!");
if (doRefresh) {
context = MainActivity.this;
for (int i = 0; i < wrapper.params.length; i++) {
try {
FileOutputStream fos = context.openFileOutput(wrapper.params[i], 0);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(newsItems);
os.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
doRefresh = false;
}
}, 1000);
}
}
private class checkWebsiteStatus extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
try {
URL url = new URL("http://www.dailyprincetonian.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
urlConnection.disconnect();
return true;
} catch (IOException e) {
}
return false;
}
}
private class Wrapper {
List<List<NewspaperMetaObject>> categories;
String[] params;
public Wrapper(List<List<NewspaperMetaObject>> categories, String[] params){
this.categories = categories;
this.params = params;
}
}
}
Snippet of where the Exception is being thrown
if (doRefresh) {
context = MainActivity.this;
for (int i = 0; i < wrapper.params.length; i++) {
try {
FileOutputStream fos = context.openFileOutput(wrapper.params[i], 0);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(newsItems);
//os.flush();
os.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It looks like the wrapper variable is declared (therefore you can do a
for (int i = 0; i < wrapper.params.length; i++)
without any problem) but all items in the array may be null referenced, wich is the cause of the NPE.