Get Cached data storage programmatically - android

I want to get cached data size at "Internal storage" in "settings", like this:
I tried to get all application cache by invoking getPackageSizeInfo using Java Reflection. Yes it did got all cached size of apps, but the size is smaller than the cached data size in "settings" above. This is the picture when I used this method:
in settings, the cached data size 840 MB, but when in my app is 493 MB.
These are my codes
Main Activity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final int FETCH_PACKAGE_SIZE_COMPLETED = 100;
public static final int ALL_PACKAGE_SIZE_COMPLETED = 200;
IDataStatus onIDataStatus;
TextView lbl_cache_size;
ProgressDialog pd;
long packageSize = 0, size = 0, dataSize = 0, data = 0;
AppDetails cAppDetails;
public ArrayList<AppDetails.PackageInfoStruct> res;
int totalSize;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_get_cacheSize).setOnClickListener(this);
findViewById(R.id.btn_delete_cache).setOnClickListener(this);
lbl_cache_size = (TextView) findViewById(R.id.lbl_cache_size);
}
private void showProgress(String message) {
pd = new ProgressDialog(this);
pd.setIcon(R.mipmap.ic_launcher);
pd.setTitle("Please wait...");
pd.setMessage(message);
pd.setCancelable(false);
pd.show();
}
private void getPackageSize() {
cAppDetails = new AppDetails(this);
res = cAppDetails.getPackages();
if (res == null)
return;
for (int m = 0; m < res.size(); m++) {
PackageManager pm = getPackageManager();
Method getPackageSizeInfo;
try {
getPackageSizeInfo = pm.getClass().getMethod(
"getPackageSizeInfo", String.class,
IPackageStatsObserver.class);
getPackageSizeInfo.invoke(pm, res.get(m).pname,
new cachePackState());
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
handle.sendEmptyMessage(ALL_PACKAGE_SIZE_COMPLETED);
Log.v("Total Cache Size", " " + packageSize);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_get_cacheSize:
size = 0;
packageSize = 0;
dataSize = 0;
data = 0;
showProgress("Calculating Cache Size..!!!");
/*
* You can also use sync task
*/
new Thread(new Runnable() {
#Override
public void run() {
getPackageSize();
}
}).start();
//getPackageSize();
break;
case R.id.btn_delete_cache:
deleteCache();
break;
default:
break;
}
}
private Handler handle = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case FETCH_PACKAGE_SIZE_COMPLETED:
String sizeInHuman = "";
if (packageSize > 0) {
// size = (packageSize / 1024000);
//data = (dataSize / 1024000); //boy
sizeInHuman = humanReadableByteCount(packageSize, true);
}
//lbl_cache_size.setText("Cache Size : " + size + " MB and Data Size : "+ data + " MB");
lbl_cache_size.setText("Cache Size : " + sizeInHuman);
break;
case ALL_PACKAGE_SIZE_COMPLETED:
if (null != pd)
if (pd.isShowing())
pd.dismiss();
break;
default:
break;
}
}
};
private class cachePackState extends IPackageStatsObserver.Stub {
#Override
public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException {
Log.d("Package Size", pStats.packageName + "");
Log.i("Cache Size", pStats.cacheSize + "");
Log.w("Data Size", pStats.dataSize + "");
packageSize = packageSize + pStats.cacheSize;
Log.v("Total Cache Size", " " + packageSize );
handle.sendEmptyMessage(FETCH_PACKAGE_SIZE_COMPLETED);
}
}
private void deleteCache() {
PackageManager pm = getPackageManager();
//Get all methods on the packageManager
Method[] methods = pm.getClass().getDeclaredMethods();
for (Method m : methods) {
if (m.getName().equals("freeStorage")) {
//Found the method I want to use
try {
m.invoke(pm, Long.MAX_VALUE, null);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
break;
}
}
}
public static String humanReadableByteCount(long bytes, boolean si) {
int unit = si ? 1000 : 1024;
if (bytes < unit) return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
}
AppDetails
public class AppDetails {
Activity mActivity;
public ArrayList<PackageInfoStruct> res = new ArrayList<PackageInfoStruct>();
public ListView list;
public String app_labels[];
public AppDetails(Activity mActivity) {
this.mActivity = mActivity;
}
public ArrayList<PackageInfoStruct> getPackages() {
ArrayList<PackageInfoStruct> apps = getInstalledApps(true); /*
* false =
* no system
* packages
*/
final int max = apps.size();
for (int i = 0; i < max; i++) {
apps.get(i);
}
return apps;
}
private ArrayList<PackageInfoStruct> getInstalledApps(boolean getSysPackages) {
List<PackageInfo> packs = mActivity.getPackageManager()
.getInstalledPackages(0);
try {
app_labels = new String[packs.size()];
} catch (Exception e) {
Toast.makeText(mActivity.getApplicationContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
for (int i = 0; i < packs.size(); i++) {
PackageInfo p = packs.get(i);
//if ((!getSysPackages) && (p.versionName == null)) {
// continue;
//}
PackageInfoStruct newInfo = new PackageInfoStruct();
newInfo.appname = p.applicationInfo.loadLabel(
mActivity.getPackageManager()).toString();
newInfo.pname = p.packageName;
newInfo.datadir = p.applicationInfo.dataDir;
newInfo.versionName = p.versionName;
newInfo.versionCode = p.versionCode;
newInfo.icon = p.applicationInfo.loadIcon(mActivity
.getPackageManager());
res.add(newInfo);
app_labels[i] = newInfo.appname;
}
return res;
}
class PackageInfoStruct {
String appname = "";
String pname = "";
String versionName = "";
int versionCode = 0;
Drawable icon;
String datadir = "";
}
}
Is there any way to get cached data size in storage?
The reference:
reference

Related

Stop() called but track is not started

Here is my logcat:
System.err:java.lang.IllegalStateException: Failed to add the track to the muxer
W/System.err: at android.media.MediaMuxer.nativeAddTrack(Native Method)
W/System.err: at android.media.MediaMuxer.addTrack(MediaMuxer.java:626)
W/System.err: at com.marvhong.videoeffect.composer.MuxRender.onSetOutputFormat(MuxRender.java:64)
W/System.err: at com.marvhong.videoeffect.composer.VideoComposer.drainEncoder(VideoComposer.java:224)
W/System.err: at com.marvhong.videoeffect.composer.VideoComposer.stepPipeline(VideoComposer.java:113)
W/System.err: at com.marvhong.videoeffect.composer.Mp4ComposerEngine.runPipelines(Mp4ComposerEngine.java:181)
W/System.err: at com.marvhong.videoeffect.composer.Mp4ComposerEngine.compose(Mp4ComposerEngine.java:127)
W/System.err: at com.marvhong.videoeffect.composer.Mp4Composer$1.run(Mp4Composer.java:198)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
W/System.err: at java.lang.Thread.run(Thread.java:764)
E/TrimVideoActivity: filterVideo---onFailed()
In my application, I'm trying to add filters on video. But sometimes my app crashes and sometimes it works fine. The error is Failed to add the track to the muxer
I have debugged code and found the issue for video under audio available then apply filter and save it but doesn't work save filter video.
MuxRender Class :
class MuxRender {
private static final String TAG = "MuxRender";
private static final int BUFFER_SIZE = 64 * 1024; // I have no idea whether this value is appropriate or not...
private final MediaMuxer muxer;
private MediaFormat videoFormat;
private MediaFormat audioFormat;
private int videoTrackIndex;
private int audioTrackIndex;
private ByteBuffer byteBuffer;
private final List<SampleInfo> sampleInfoList;
private boolean started;
MuxRender(MediaMuxer muxer) {
this.muxer = muxer;
sampleInfoList = new ArrayList<>();
}
void setOutputFormat(SampleType sampleType, MediaFormat format) {
switch (sampleType) {
case VIDEO:
videoFormat = format;
break;
case AUDIO:
ObLogger.i(TAG, "format > " + format);
audioFormat = format;
break;
default:
throw new AssertionError();
}
}
void onSetOutputFormat() {
if (videoFormat != null && audioFormat != null) {
videoTrackIndex = muxer.addTrack(videoFormat);
ObLogger.v(TAG, "Added track #" + videoTrackIndex + " with " + videoFormat.getString(
MediaFormat.KEY_MIME) + " to muxer");
ObLogger.i(TAG, "audioFormat > " + audioFormat);
audioTrackIndex = muxer.addTrack(audioFormat);
ObLogger.v(TAG, "Added track #" + audioTrackIndex + " with " + audioFormat.getString(
MediaFormat.KEY_MIME) + " to muxer");
} else if (videoFormat != null) {
videoTrackIndex = muxer.addTrack(videoFormat);
ObLogger.v(TAG, "Added track #" + videoTrackIndex + " with " + videoFormat.getString(
MediaFormat.KEY_MIME) + " to muxer");
}
muxer.start();
started = true;
if (byteBuffer == null) {
byteBuffer = ByteBuffer.allocate(0);
}
byteBuffer.flip();
ObLogger.v(TAG, "Output format determined, writing " + sampleInfoList.size() +
" samples / " + byteBuffer.limit() + " bytes to muxer.");
MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
int offset = 0;
for (SampleInfo sampleInfo : sampleInfoList) {
sampleInfo.writeToBufferInfo(bufferInfo, offset);
muxer.writeSampleData(getTrackIndexForSampleType(sampleInfo.sampleType), byteBuffer, bufferInfo);
offset += sampleInfo.size;
}
sampleInfoList.clear();
byteBuffer = null;
}
void writeSampleData(SampleType sampleType, ByteBuffer byteBuf, MediaCodec.BufferInfo bufferInfo) {
if (started) {
muxer.writeSampleData(getTrackIndexForSampleType(sampleType), byteBuf, bufferInfo);
return;
}
byteBuf.limit(bufferInfo.offset + bufferInfo.size);
byteBuf.position(bufferInfo.offset);
if (byteBuffer == null) {
byteBuffer = ByteBuffer.allocateDirect(BUFFER_SIZE).order(ByteOrder.nativeOrder());
}
byteBuffer.put(byteBuf);
sampleInfoList.add(new SampleInfo(sampleType, bufferInfo.size, bufferInfo));
}
private int getTrackIndexForSampleType(SampleType sampleType) {
switch (sampleType) {
case VIDEO:
return videoTrackIndex;
case AUDIO:
return audioTrackIndex;
default:
throw new AssertionError();
}
}
public enum SampleType {VIDEO, AUDIO}
private static class SampleInfo {
private final SampleType sampleType;
private final int size;
private final long presentationTimeUs;
private final int flags;
private SampleInfo(SampleType sampleType, int size, MediaCodec.BufferInfo bufferInfo) {
this.sampleType = sampleType;
this.size = size;
presentationTimeUs = bufferInfo.presentationTimeUs;
flags = bufferInfo.flags;
}
private void writeToBufferInfo(MediaCodec.BufferInfo bufferInfo, int offset) {
bufferInfo.set(offset, size, presentationTimeUs, flags);
}
}
}
Mp4ComposerEngine Class:
class Mp4ComposerEngine {
private static final String TAG = "Mp4ComposerEngine";
private static final double PROGRESS_UNKNOWN = -1.0;
private static final long SLEEP_TO_WAIT_TRACK_TRANSCODERS = 10;
private static final long PROGRESS_INTERVAL_STEPS = 10;
private FileDescriptor inputFileDescriptor;
private VideoComposer videoComposer;
private IAudioComposer audioComposer;
private MediaExtractor mediaExtractor;
private MediaMuxer mediaMuxer;
private ProgressCallback progressCallback;
private long durationUs;
void setDataSource(FileDescriptor fileDescriptor) {
inputFileDescriptor = fileDescriptor;
}
void setProgressCallback(ProgressCallback progressCallback) {
this.progressCallback = progressCallback;
}
void compose(
final String destPath,
final Resolution outputResolution,
final GlFilter filter,
final int bitrate,
final boolean mute,
final Rotation rotation,
final Resolution inputResolution,
final FillMode fillMode,
final FillModeCustomItem fillModeCustomItem,
final int timeScale,
final boolean flipVertical,
final boolean flipHorizontal
) throws IOException {
try {
mediaExtractor = new MediaExtractor();
mediaExtractor.setDataSource(inputFileDescriptor);
if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR2) {
mediaMuxer = new MediaMuxer(destPath, OutputFormat.MUXER_OUTPUT_MPEG_4);
}
MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(inputFileDescriptor);
try {
durationUs = Long
.parseLong(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)) * 1000;
} catch (NumberFormatException e) {
durationUs = -1;
}
ObLogger.d(TAG, "Duration (us): " + durationUs);
MediaFormat videoOutputFormat = MediaFormat
.createVideoFormat("video/avc", outputResolution.width(), outputResolution.height());
videoOutputFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitrate);
videoOutputFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 30);
videoOutputFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1);
videoOutputFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, CodecCapabilities.COLOR_FormatSurface);
MuxRender muxRender = new MuxRender(mediaMuxer);
// identify track indices
MediaFormat format = mediaExtractor.getTrackFormat(0);
String mime = format.getString(MediaFormat.KEY_MIME);
final int videoTrackIndex;
final int audioTrackIndex;
if (mime.startsWith("video/")) {
videoTrackIndex = 0;
audioTrackIndex = 1;
} else {
videoTrackIndex = 1;
audioTrackIndex = 0;
}
// setup video composer
videoComposer = new VideoComposer(mediaExtractor, videoTrackIndex, videoOutputFormat, muxRender, timeScale);
videoComposer.setUp(filter, rotation, outputResolution, inputResolution, fillMode, fillModeCustomItem, flipVertical, flipHorizontal);
mediaExtractor.selectTrack(videoTrackIndex);
// setup audio if present and not muted
if (mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_AUDIO) != null && !mute) {
// has Audio video
if (timeScale < 2) {
audioComposer = new AudioComposer(mediaExtractor, audioTrackIndex, muxRender);
} else {
audioComposer = new RemixAudioComposer(mediaExtractor, audioTrackIndex, mediaExtractor.getTrackFormat(audioTrackIndex), muxRender, timeScale);
}
audioComposer.setup();
mediaExtractor.selectTrack(audioTrackIndex);
runPipelines();
} else {
// no audio video
runPipelinesNoAudio();
}
if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR2) {
mediaMuxer.stop();
}
} finally {
try {
if (videoComposer != null) {
videoComposer.release();
videoComposer = null;
}
if (audioComposer != null) {
audioComposer.release();
audioComposer = null;
}
if (mediaExtractor != null) {
mediaExtractor.release();
mediaExtractor = null;
}
} catch (RuntimeException e) {
e.printStackTrace();
// Too fatal to make alive the app, because it may leak native resources.
// throw new Error("Could not shutdown mediaExtractor, codecs and mediaMuxer pipeline.", e);
}
try {
if (mediaMuxer != null) {
if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR2) {
mediaMuxer.release();
}
mediaMuxer = null;
}
} catch (RuntimeException e) {
ObLogger.e(TAG, "Failed to release mediaMuxer.", e);
}
}
}
private void runPipelines() {
long loopCount = 0;
if (durationUs <= 0) {
if (progressCallback != null) {
progressCallback.onProgress(PROGRESS_UNKNOWN);
}// unknown
}
while (!(videoComposer.isFinished() && audioComposer.isFinished())) {
boolean stepped = videoComposer.stepPipeline()
|| audioComposer.stepPipeline();
loopCount++;
if (durationUs > 0 && loopCount % PROGRESS_INTERVAL_STEPS == 0) {
double videoProgress = videoComposer.isFinished() ? 1.0 : Math
.min(1.0, (double) videoComposer.getWrittenPresentationTimeUs() / durationUs);
double audioProgress = audioComposer.isFinished() ? 1.0 : Math
.min(1.0, (double) audioComposer.getWrittenPresentationTimeUs() / durationUs);
double progress = (videoProgress + audioProgress) / 2.0;
if (progressCallback != null) {
progressCallback.onProgress(progress);
}
}
if (!stepped) {
try {
Thread.sleep(SLEEP_TO_WAIT_TRACK_TRANSCODERS);
} catch (InterruptedException e) {
// nothing to do
}
}
}
}
private void runPipelinesNoAudio() {
long loopCount = 0;
if (durationUs <= 0) {
if (progressCallback != null) {
progressCallback.onProgress(PROGRESS_UNKNOWN);
} // unknown
}
while (!videoComposer.isFinished()) {
boolean stepped = videoComposer.stepPipeline();
loopCount++;
if (durationUs > 0 && loopCount % PROGRESS_INTERVAL_STEPS == 0) {
double videoProgress = videoComposer.isFinished() ? 1.0 : Math
.min(1.0, (double) videoComposer.getWrittenPresentationTimeUs() / durationUs);
if (progressCallback != null) {
progressCallback.onProgress(videoProgress);
}
}
if (!stepped) {
try {
Thread.sleep(SLEEP_TO_WAIT_TRACK_TRANSCODERS);
} catch (InterruptedException e) {
// nothing to do
}
}
}
}
interface ProgressCallback {
/**
* Called to notify progress. Same thread which initiated transcode is used.
*
* #param progress Progress in [0.0, 1.0] range, or negative value if progress is unknown.
*/
void onProgress(double progress);
}
}
Mp4Composer Class :
public class Mp4Composer {
private final static String TAG = Mp4Composer.class.getSimpleName();
private final String srcPath;
private final String destPath;
private GlFilter filter;
private Resolution outputResolution;
private int bitrate = -1;
private boolean mute = false;
private Rotation rotation = Rotation.NORMAL;
private Listener listener;
private FillMode fillMode = FillMode.PRESERVE_ASPECT_FIT;
private FillModeCustomItem fillModeCustomItem;
private int timeScale = 1;
private boolean flipVertical = false;
private boolean flipHorizontal = false;
private ExecutorService executorService;
public Mp4Composer(#NonNull final String srcPath, #NonNull final String destPath) {
this.srcPath = srcPath;
this.destPath = destPath;
}
public Mp4Composer filter(#NonNull GlFilter filter) {
this.filter = filter;
return this;
}
public Mp4Composer size(int width, int height) {
this.outputResolution = new Resolution(width, height);
return this;
}
public Mp4Composer videoBitrate(int bitrate) {
this.bitrate = bitrate;
return this;
}
public Mp4Composer mute(boolean mute) {
this.mute = mute;
return this;
}
public Mp4Composer flipVertical(boolean flipVertical) {
this.flipVertical = flipVertical;
return this;
}
public Mp4Composer flipHorizontal(boolean flipHorizontal) {
this.flipHorizontal = flipHorizontal;
return this;
}
public Mp4Composer rotation(#NonNull Rotation rotation) {
this.rotation = rotation;
return this;
}
public Mp4Composer fillMode(#NonNull FillMode fillMode) {
this.fillMode = fillMode;
return this;
}
public Mp4Composer customFillMode(#NonNull FillModeCustomItem fillModeCustomItem) {
this.fillModeCustomItem = fillModeCustomItem;
this.fillMode = FillMode.CUSTOM;
return this;
}
public Mp4Composer listener(#NonNull Listener listener) {
this.listener = listener;
return this;
}
public Mp4Composer timeScale(final int timeScale) {
this.timeScale = timeScale;
return this;
}
private ExecutorService getExecutorService() {
if (executorService == null) {
executorService = Executors.newSingleThreadExecutor();
}
return executorService;
}
public Mp4Composer start() {
getExecutorService().execute(new Runnable() {
#Override
public void run() {
Mp4ComposerEngine engine = new Mp4ComposerEngine();
engine.setProgressCallback(new Mp4ComposerEngine.ProgressCallback() {
#Override
public void onProgress(final double progress) {
if (listener != null) {
listener.onProgress(progress);
}
}
});
final File srcFile = new File(srcPath);
final FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(srcFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
if (listener != null) {
listener.onFailed(e);
}
return;
}
try {
engine.setDataSource(fileInputStream.getFD());
} catch (IOException e) {
e.printStackTrace();
if (listener != null) {
listener.onFailed(e);
}
return;
}
final int videoRotate = getVideoRotation(srcPath);
final Resolution srcVideoResolution = getVideoResolution(srcPath, videoRotate);
if (filter == null) {
filter = new GlFilter();
}
if (fillMode == null) {
fillMode = FillMode.PRESERVE_ASPECT_FIT;
}
if (fillModeCustomItem != null) {
fillMode = FillMode.CUSTOM;
}
if (outputResolution == null) {
if (fillMode == FillMode.CUSTOM) {
outputResolution = srcVideoResolution;
} else {
Rotation rotate = Rotation.fromInt(rotation.getRotation() + videoRotate);
if (rotate == Rotation.ROTATION_90 || rotate == Rotation.ROTATION_270) {
outputResolution = new Resolution(srcVideoResolution.height(), srcVideoResolution.width());
} else {
outputResolution = srcVideoResolution;
}
}
}
if (filter instanceof IResolutionFilter) {
((IResolutionFilter) filter).setResolution(outputResolution);
}
if (timeScale < 2) {
timeScale = 1;
}
ObLogger.d(TAG, "rotation = " + (rotation.getRotation() + videoRotate));
ObLogger.d(TAG, "inputResolution width = " + srcVideoResolution.width() + " height = " + srcVideoResolution.height());
ObLogger.d(TAG, "outputResolution width = " + outputResolution.width() + " height = " + outputResolution.height());
ObLogger.d(TAG, "fillMode = " + fillMode);
try {
if (bitrate < 0) {
bitrate = calcBitRate(outputResolution.width(), outputResolution.height());
}
engine.compose(
destPath,
outputResolution,
filter,
bitrate,
mute,
Rotation.fromInt(rotation.getRotation() + videoRotate),
srcVideoResolution,
fillMode,
fillModeCustomItem,
timeScale,
flipVertical,
flipHorizontal
);
} catch (Exception e) {
e.printStackTrace();
if (listener != null) {
listener.onFailed(e);
}
executorService.shutdown();
return;
}
if (listener != null) {
listener.onCompleted();
}
executorService.shutdown();
}
});
return this;
}
public void cancel() {
getExecutorService().shutdownNow();
}
public interface Listener {
/**
* Called to notify progress.
*
* #param progress Progress in [0.0, 1.0] range, or negative value if progress is unknown.
*/
void onProgress(double progress);
/**
* Called when transcode completed.
*/
void onCompleted();
/**
* Called when transcode canceled.
*/
void onCanceled();
void onFailed(Exception exception);
}
private int getVideoRotation(String videoFilePath) {
try {
MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(videoFilePath);
ObLogger.e("MediaMetadataRetriever", "getVideoRotation error");
String orientation = mediaMetadataRetriever.extractMetadata(
MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
return Integer.valueOf(orientation);
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return 0;
}
private int calcBitRate(int width, int height) {
final int bitrate = (int) (0.25 * 30 * width * height);
ObLogger.i(TAG, "bitrate=" + bitrate);
return bitrate;
}
private Resolution getVideoResolution(final String path, final int rotation) {
int width = 0;
int height = 0;
if (path != null && !path.isEmpty()) {
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(path);
try {
String Strwidth = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
String Strheight = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
if (Strwidth != null && Strheight != null) {
width = Integer.valueOf(Strwidth);
height = Integer.valueOf(Strheight);
}
retriever.release();
} catch (NumberFormatException e) {
retriever.release();
e.printStackTrace();
} catch (IllegalArgumentException e) {
retriever.release();
e.printStackTrace();
}
}
return new Resolution(width, height);
}
}
Main Activity Call Mp4Composer:
private void startMediaCodec(String srcPath,String outputPath) {
mMp4Composer = new Mp4Composer(srcPath, outputPath)
// .rotation(Rotation.ROTATION_270)
//.size(720, 1280)
.fillMode(FillMode.PRESERVE_ASPECT_FIT)
.filter(MagicFilterFactory.getFilter())
.mute(false)
.flipHorizontal(false)
.flipVertical(false)
.listener(new Listener() {
#Override
public void onProgress(double progress) {
ObLogger.d(TAG, "filterVideo---onProgress: " + (int) (progress * 100));
runOnUiThread(new Runnable() {
#Override
public void run() {
//show progress
}
});
}
#Override
public void onCompleted() {
ObLogger.d(TAG, "filterVideo---onCompleted");
runOnUiThread(new Runnable() {
#Override
public void run() {
ObLogger.i(TAG, "run: Editor Screen is >>> ");
Intent intent = new Intent();
intent.putExtra(Extras.EXTRA_FILTER_SCREEN, outputPath);
setResult(RESULT_OK, intent);
finish();
}
});
}
#Override
public void onCanceled() {
ObLogger.e(TAG, "onCanceled");
NormalProgressDialog.stopLoading();
}
#Override
public void onFailed(Exception exception) {
ObLogger.e(TAG, "filterVideo---onFailed()");
NormalProgressDialog.stopLoading();
// Toast.makeText(TrimVideoActivity.this, "Video processing failed", Toast.LENGTH_SHORT).show();
}
})
.start();
}
The below links were used but my problem is not solved.
https://stackoverflow.com/a/53140941/11138845
https://stackoverflow.com/a/21759073/11138845

How to fix Runtime Exception Unable to start Activity

06-28 17:05:23.694 13262-13262/io.hypertrack.sendeta.debug
E/AndroidRuntime: FATAL EXCEPTION: main
Process: io.hypertrack.sendeta.debug, PID: 13262
java.lang.RuntimeException: Unable to start activity ComponentInfo{io.hypertrack.sendeta.debug/io.hypertrack.sendeta.activities.MainActivity}:
android.view.InflateException: Binary XML file line #4: Error
inflating class java.lang.reflect.Constructor
io.hypertrack.sendeta.activities.MainActivity.onCreate(MainActivity.java:109)
public class MainActivity extends AppCompatActivity implements LocationListener {
protected static final int MY_PERMISSIONS_ACCESS_FINE_LOCATION = 1;
// Time in milliseconds; only reload weather if last update is longer ago than this value
private static final int NO_UPDATE_REQUIRED_THRESHOLD = 300000;
private static Map<String, Integer> speedUnits = new HashMap<>(3);
private static Map<String, Integer> pressUnits = new HashMap<>(3);
private static boolean mappingsInitialised = false;
Typeface weatherFont;
Weather todayWeather = new Weather();
TextView todayTemperature;
TextView todayDescription;
TextView todayWind;
TextView todayPressure;
TextView todayHumidity;
TextView todaySunrise;
TextView todaySunset;
TextView lastUpdate;
TextView todayIcon;
ViewPager viewPager;
TabLayout tabLayout;
View appView;
LocationManager locationManager;
ProgressDialog progressDialog;
int theme;
boolean destroyed = false;
private List<Weather> longTermWeather = new ArrayList<>();
private List<Weather> longTermTodayWeather = new ArrayList<>();
private List<Weather> longTermTomorrowWeather = new ArrayList<>();
public String recentCity = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
// Initialize the associated SharedPreferences file with default values
PreferenceManager.setDefaultValues(this, R.xml.prefs, false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
setTheme(theme = getTheme(prefs.getString("theme", "fresh")));
boolean darkTheme = theme == R.style.AppTheme_NoActionBar_Dark ||
theme == R.style.AppTheme_NoActionBar_Classic_Dark;
boolean blackTheme = theme == R.style.AppTheme_NoActionBar_Black ||
theme == R.style.AppTheme_NoActionBar_Classic_Black;
// Initiate activity
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrolling);
appView = findViewById(R.id.viewApp);
progressDialog = new ProgressDialog(MainActivity.this);
// Load toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (darkTheme) {
toolbar.setPopupTheme(R.style.AppTheme_PopupOverlay_Dark);
} else if (blackTheme) {
toolbar.setPopupTheme(R.style.AppTheme_PopupOverlay_Black);
}
// Initialize textboxes
todayTemperature = (TextView) findViewById(R.id.todayTemperature);
todayDescription = (TextView) findViewById(R.id.todayDescription);
todayWind = (TextView) findViewById(R.id.todayWind);
todayPressure = (TextView) findViewById(R.id.todayPressure);
todayHumidity = (TextView) findViewById(R.id.todayHumidity);
todaySunrise = (TextView) findViewById(R.id.todaySunrise);
todaySunset = (TextView) findViewById(R.id.todaySunset);
lastUpdate = (TextView) findViewById(R.id.lastUpdate);
todayIcon = (TextView) findViewById(R.id.todayIcon);
weatherFont = Typeface.createFromAsset(this.getAssets(), "fonts/weather.ttf");
todayIcon.setTypeface(weatherFont);
// Initialize viewPager
viewPager = (ViewPager) findViewById(R.id.viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
destroyed = false;
initMappings();
// Preload data from cache
preloadWeather();
updateLastUpdateTime();
// Set autoupdater
AlarmReceiver.setRecurringAlarm(this);
}
public WeatherRecyclerAdapter getAdapter(int id) {
WeatherRecyclerAdapter weatherRecyclerAdapter;
if (id == 0) {
weatherRecyclerAdapter = new WeatherRecyclerAdapter(this, longTermTodayWeather);
} else if (id == 1) {
weatherRecyclerAdapter = new WeatherRecyclerAdapter(this, longTermTomorrowWeather);
} else {
weatherRecyclerAdapter = new WeatherRecyclerAdapter(this, longTermWeather);
}
return weatherRecyclerAdapter;
}
#Override
public void onStart() {
super.onStart();
updateTodayWeatherUI();
updateLongTermWeatherUI();
}
#Override
public void onResume() {
super.onResume();
if (getTheme(PreferenceManager.getDefaultSharedPreferences(this).getString("theme", "fresh")) != theme) {
// Restart activity to apply theme
overridePendingTransition(0, 0);
finish();
overridePendingTransition(0, 0);
startActivity(getIntent());
} else if (shouldUpdate() && isNetworkAvailable()) {
getTodayWeather();
getLongTermWeather();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
destroyed = true;
if (locationManager != null) {
try {
locationManager.removeUpdates(MainActivity.this);
} catch (SecurityException e) {
e.printStackTrace();
}
}
}
private void preloadWeather() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
String lastToday = sp.getString("lastToday", "");
if (!lastToday.isEmpty()) {
new TodayWeatherTask(this, this, progressDialog).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "cachedResponse", lastToday);
}
String lastLongterm = sp.getString("lastLongterm", "");
if (!lastLongterm.isEmpty()) {
new LongTermWeatherTask(this, this, progressDialog).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "cachedResponse", lastLongterm);
}
}
private void getTodayWeather() {
new TodayWeatherTask(this, this, progressDialog).execute();
}
private void getLongTermWeather() {
new LongTermWeatherTask(this, this, progressDialog).execute();
}
private void searchCities() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(this.getString(R.string.search_title));
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
input.setMaxLines(1);
input.setSingleLine(true);
alert.setView(input, 32, 0, 32, 0);
alert.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String result = input.getText().toString();
if (!result.isEmpty()) {
saveLocation(result);
}
}
});
alert.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Cancelled
}
});
alert.show();
}
private void saveLocation(String result) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
recentCity = preferences.getString("city", Constants.DEFAULT_CITY);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("city", result);
editor.commit();
if (!recentCity.equals(result)) {
// New location, update weather
getTodayWeather();
getLongTermWeather();
}
}
private void aboutDialog() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Forecastie");
final WebView webView = new WebView(this);
String about = "<p>1.6.1</p>" +
"<p>A lightweight, opensource weather app.</p>" +
"<p>Developed by <a href='mailto:t.martykan#gmail.com'>Tomas Martykan</a></p>" +
"<p>Data provided by <a href='https://openweathermap.org/'>OpenWeatherMap</a>, under the <a href='http://creativecommons.org/licenses/by-sa/2.0/'>Creative Commons license</a>" +
"<p>Icons are <a href='https://erikflowers.github.io/weather-icons/'>Weather Icons</a>, by <a href='http://www.twitter.com/artill'>Lukas Bischoff</a> and <a href='http://www.twitter.com/Erik_UX'>Erik Flowers</a>, under the <a href='http://scripts.sil.org/OFL'>SIL OFL 1.1</a> licence.";
TypedArray ta = obtainStyledAttributes(new int[]{android.R.attr.textColorPrimary, R.attr.colorAccent});
String textColor = String.format("#%06X", (0xFFFFFF & ta.getColor(0, Color.BLACK)));
String accentColor = String.format("#%06X", (0xFFFFFF & ta.getColor(1, Color.BLUE)));
ta.recycle();
about = "<style media=\"screen\" type=\"text/css\">" +
"body {\n" +
" color:" + textColor + ";\n" +
"}\n" +
"a:link {color:" + accentColor + "}\n" +
"</style>" +
about;
webView.setBackgroundColor(Color.TRANSPARENT);
webView.loadData(about, "text/html", "UTF-8");
alert.setView(webView, 32, 0, 32, 0);
alert.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
}
private String setWeatherIcon(int actualId, int hourOfDay) {
int id = actualId / 100;
String icon = "";
if (actualId == 800) {
if (hourOfDay >= 7 && hourOfDay < 20) {
icon = this.getString(R.string.weather_sunny);
} else {
icon = this.getString(R.string.weather_clear_night);
}
} else {
switch (id) {
case 2:
icon = this.getString(R.string.weather_thunder);
break;
case 3:
icon = this.getString(R.string.weather_drizzle);
break;
case 7:
icon = this.getString(R.string.weather_foggy);
break;
case 8:
icon = this.getString(R.string.weather_cloudy);
break;
case 6:
icon = this.getString(R.string.weather_snowy);
break;
case 5:
icon = this.getString(R.string.weather_rainy);
break;
}
}
return icon;
}
public static String getRainString(JSONObject rainObj) {
String rain = "0";
if (rainObj != null) {
rain = rainObj.optString("3h", "fail");
if ("fail".equals(rain)) {
rain = rainObj.optString("1h", "0");
}
}
return rain;
}
private ParseResult parseTodayJson(String result) {
try {
JSONObject reader = new JSONObject(result);
final String code = reader.optString("cod");
if ("404".equals(code)) {
return ParseResult.CITY_NOT_FOUND;
}
String city = reader.getString("name");
String country = "";
JSONObject countryObj = reader.optJSONObject("sys");
if (countryObj != null) {
country = countryObj.getString("country");
todayWeather.setSunrise(countryObj.getString("sunrise"));
todayWeather.setSunset(countryObj.getString("sunset"));
}
todayWeather.setCity(city);
todayWeather.setCountry(country);
JSONObject coordinates = reader.getJSONObject("coord");
if (coordinates != null) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.edit().putFloat("latitude", (float) coordinates.getDouble("lon")).putFloat("longitude", (float) coordinates.getDouble("lat")).commit();
}
JSONObject main = reader.getJSONObject("main");
todayWeather.setTemperature(main.getString("temp"));
todayWeather.setDescription(reader.getJSONArray("weather").getJSONObject(0).getString("description"));
JSONObject windObj = reader.getJSONObject("wind");
todayWeather.setWind(windObj.getString("speed"));
if (windObj.has("deg")) {
todayWeather.setWindDirectionDegree(windObj.getDouble("deg"));
} else {
Log.e("parseTodayJson", "No wind direction available");
todayWeather.setWindDirectionDegree(null);
}
todayWeather.setPressure(main.getString("pressure"));
todayWeather.setHumidity(main.getString("humidity"));
JSONObject rainObj = reader.optJSONObject("rain");
String rain;
if (rainObj != null) {
rain = getRainString(rainObj);
} else {
JSONObject snowObj = reader.optJSONObject("snow");
if (snowObj != null) {
rain = getRainString(snowObj);
} else {
rain = "0";
}
}
todayWeather.setRain(rain);
final String idString = reader.getJSONArray("weather").getJSONObject(0).getString("id");
todayWeather.setId(idString);
todayWeather.setIcon(setWeatherIcon(Integer.parseInt(idString), Calendar.getInstance().get(Calendar.HOUR_OF_DAY)));
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
editor.putString("lastToday", result);
editor.commit();
} catch (JSONException e) {
Log.e("JSONException Data", result);
e.printStackTrace();
return ParseResult.JSON_EXCEPTION;
}
return ParseResult.OK;
}
private void updateTodayWeatherUI() {
try {
if (todayWeather.getCountry().isEmpty()) {
preloadWeather();
return;
}
} catch (Exception e) {
preloadWeather();
return;
}
String city = todayWeather.getCity();
String country = todayWeather.getCountry();
DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(getApplicationContext());
getSupportActionBar().setTitle(city + (country.isEmpty() ? "" : ", " + country));
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
// Temperature
float temperature = UnitConvertor.convertTemperature(Float.parseFloat(todayWeather.getTemperature()), sp);
if (sp.getBoolean("temperatureInteger", false)) {
temperature = Math.round(temperature);
}
// Rain
double rain = Double.parseDouble(todayWeather.getRain());
String rainString = UnitConvertor.getRainString(rain, sp);
// Wind
double wind;
try {
wind = Double.parseDouble(todayWeather.getWind());
} catch (Exception e) {
e.printStackTrace();
wind = 0;
}
wind = UnitConvertor.convertWind(wind, sp);
// Pressure
double pressure = UnitConvertor.convertPressure((float) Double.parseDouble(todayWeather.getPressure()), sp);
todayTemperature.setText(new DecimalFormat("0.#").format(temperature) + " " + sp.getString("unit", "°C"));
todayDescription.setText(todayWeather.getDescription().substring(0, 1).toUpperCase() +
todayWeather.getDescription().substring(1) + rainString);
if (sp.getString("speedUnit", "m/s").equals("bft")) {
todayWind.setText(getString(R.string.wind) + ": " +
UnitConvertor.getBeaufortName((int) wind) +
(todayWeather.isWindDirectionAvailable() ? " " + getWindDirectionString(sp, this, todayWeather) : ""));
} else {
todayWind.setText(getString(R.string.wind) + ": " + new DecimalFormat("0.0").format(wind) + " " +
localize(sp, "speedUnit", "m/s") +
(todayWeather.isWindDirectionAvailable() ? " " + getWindDirectionString(sp, this, todayWeather) : ""));
}
todayPressure.setText(getString(R.string.pressure) + ": " + new DecimalFormat("0.0").format(pressure) + " " +
localize(sp, "pressureUnit", "hPa"));
todayHumidity.setText(getString(R.string.humidity) + ": " + todayWeather.getHumidity() + " %");
todaySunrise.setText(getString(R.string.sunrise) + ": " + timeFormat.format(todayWeather.getSunrise()));
todaySunset.setText(getString(R.string.sunset) + ": " + timeFormat.format(todayWeather.getSunset()));
todayIcon.setText(todayWeather.getIcon());
}
public ParseResult parseLongTermJson(String result) {
int i;
try {
JSONObject reader = new JSONObject(result);
final String code = reader.optString("cod");
if ("404".equals(code)) {
if (longTermWeather == null) {
longTermWeather = new ArrayList<>();
longTermTodayWeather = new ArrayList<>();
longTermTomorrowWeather = new ArrayList<>();
}
return ParseResult.CITY_NOT_FOUND;
}
longTermWeather = new ArrayList<>();
longTermTodayWeather = new ArrayList<>();
longTermTomorrowWeather = new ArrayList<>();
JSONArray list = reader.getJSONArray("list");
for (i = 0; i < list.length(); i++) {
Weather weather = new Weather();
JSONObject listItem = list.getJSONObject(i);
JSONObject main = listItem.getJSONObject("main");
weather.setDate(listItem.getString("dt"));
weather.setTemperature(main.getString("temp"));
weather.setDescription(listItem.optJSONArray("weather").getJSONObject(0).getString("description"));
JSONObject windObj = listItem.optJSONObject("wind");
if (windObj != null) {
weather.setWind(windObj.getString("speed"));
weather.setWindDirectionDegree(windObj.getDouble("deg"));
}
weather.setPressure(main.getString("pressure"));
weather.setHumidity(main.getString("humidity"));
JSONObject rainObj = listItem.optJSONObject("rain");
String rain = "";
if (rainObj != null) {
rain = getRainString(rainObj);
} else {
JSONObject snowObj = listItem.optJSONObject("snow");
if (snowObj != null) {
rain = getRainString(snowObj);
} else {
rain = "0";
}
}
weather.setRain(rain);
final String idString = listItem.optJSONArray("weather").getJSONObject(0).getString("id");
weather.setId(idString);
final String dateMsString = listItem.getString("dt") + "000";
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(Long.parseLong(dateMsString));
weather.setIcon(setWeatherIcon(Integer.parseInt(idString), cal.get(Calendar.HOUR_OF_DAY)));
Calendar today = Calendar.getInstance();
if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) {
longTermTodayWeather.add(weather);
} else if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR) + 1) {
longTermTomorrowWeather.add(weather);
} else {
longTermWeather.add(weather);
}
}
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
editor.putString("lastLongterm", result);
editor.commit();
} catch (JSONException e) {
Log.e("JSONException Data", result);
e.printStackTrace();
return ParseResult.JSON_EXCEPTION;
}
return ParseResult.OK;
}
private void updateLongTermWeatherUI() {
if (destroyed) {
return;
}
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
Bundle bundleToday = new Bundle();
bundleToday.putInt("day", 0);
RecyclerViewFragment recyclerViewFragmentToday = new RecyclerViewFragment();
recyclerViewFragmentToday.setArguments(bundleToday);
viewPagerAdapter.addFragment(recyclerViewFragmentToday, getString(R.string.today));
Bundle bundleTomorrow = new Bundle();
bundleTomorrow.putInt("day", 1);
RecyclerViewFragment recyclerViewFragmentTomorrow = new RecyclerViewFragment();
recyclerViewFragmentTomorrow.setArguments(bundleTomorrow);
viewPagerAdapter.addFragment(recyclerViewFragmentTomorrow, getString(R.string.tomorrow));
Bundle bundle = new Bundle();
bundle.putInt("day", 2);
RecyclerViewFragment recyclerViewFragment = new RecyclerViewFragment();
recyclerViewFragment.setArguments(bundle);
viewPagerAdapter.addFragment(recyclerViewFragment, getString(R.string.later));
int currentPage = viewPager.getCurrentItem();
viewPagerAdapter.notifyDataSetChanged();
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
if (currentPage == 0 && longTermTodayWeather.isEmpty()) {
currentPage = 1;
}
viewPager.setCurrentItem(currentPage, false);
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private boolean shouldUpdate() {
long lastUpdate = PreferenceManager.getDefaultSharedPreferences(this).getLong("lastUpdate", -1);
boolean cityChanged = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("cityChanged", false);
// Update if never checked or last update is longer ago than specified threshold
return cityChanged || lastUpdate < 0 || (Calendar.getInstance().getTimeInMillis() - lastUpdate) > NO_UPDATE_REQUIRED_THRESHOLD;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}

what is the reason of java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 error in code?

i have this error in my code:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nooshindroid.yastashir/com.nooshindroid.yastashir.MainActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
in dess3 and dess 4 this error has accurred!
idon't know why .but the size of dess3 and dess 4 is 0!
Route class of this code is here:
public class Route extends Activity {
String diff;
Context context;
ArrayList<String> sources, destinations, destinations2,destinations3,destinations4, answer;
public static ArrayList<Models> routeItems;
public Route(Context context) {
this.context = context;
}
public Route(String part) {
XmlPullParserFactory pullParserFactory;
try {
pullParserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = pullParserFactory.newPullParser();
Bundle bundle = getIntent().getExtras();
diff = bundle.getString("level");
InputStream in_s = this.context.getAssets().open(diff);
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in_s, null);
parseXML(parser);
}
catch (XmlPullParserException e) {
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void parseXML(XmlPullParser parser) throws XmlPullParserException, IOException
{
int eventType = parser.getEventType();
Models currentRout = null;
sources = new ArrayList<String>();
sources.clear();
destinations = new ArrayList<String>();
destinations.clear();
destinations2 = new ArrayList<String>();
destinations2.clear();
destinations3 = new ArrayList<String>();
destinations3.clear();
destinations4 = new ArrayList<String>();
destinations4.clear();
answer = new ArrayList<String>();
answer.clear();
while (eventType != XmlPullParser.END_DOCUMENT) {
String name = null;
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
routeItems = new ArrayList<Models>();
break;
case XmlPullParser.START_TAG:
name = parser.getName();
if (name.equalsIgnoreCase("route")) {
currentRout = new Models();
} else if (currentRout != null) {
if (name.equalsIgnoreCase("source")) {
currentRout.source = parser.nextText();
if ( !sources.contains(currentRout.source))
sources.add(currentRout.source);
} else if (name.equalsIgnoreCase("destination")) {
currentRout.destination = parser.nextText();
try {
//if ( !destinations.contains(currentRout.destination))
destinations.add(currentRout.destination);
}
catch (Exception ex)
{
}
} else if (name.equalsIgnoreCase("destination2")) {
currentRout.destination2 = parser.nextText();
try {
//if ( !destinations2.contains(currentRout.destination2))
destinations2.add(currentRout.destination2);
}
catch (Exception ex)
{
}
} else if (name.equalsIgnoreCase("destination2")) {
currentRout.destination3 = parser.nextText();
try {
//if ( !destinations2.contains(currentRout.destination2))
destinations3.add(currentRout.destination3);
}
catch (Exception ex)
{
}
} else if (name.equalsIgnoreCase("destination2")) {
currentRout.destination4 = parser.nextText();
try {
//if ( !destinations2.contains(currentRout.destination2))
destinations4.add(currentRout.destination4);
}
catch (Exception ex)
{
}
} else if (name.equalsIgnoreCase("answer")) {
currentRout.answer = parser.nextText();
try {
//if ( !destinations2.contains(currentRout.destination2))
answer.add(currentRout.answer);
}
catch (Exception ex)
{
}
}
}
break;
case XmlPullParser.END_TAG:
name = parser.getName();
if (name.equalsIgnoreCase("route") && currentRout != null) {
routeItems.add(currentRout);
}
}
eventType = parser.next();
}
}
}
main activiy of my code is as bellow:
public class MainActivity extends Activity {
public int nextque;
ArrayList<String> sourcess;
ArrayList<String> dess;
ArrayList<String> dess2;
ArrayList<String> dess3;
ArrayList<String> dess4;
ArrayList<String> answer;
int randomInt;
Random random;
Button buttons[] = new Button[8];
String j[] = new String[3];
int sumscore1 = 0;
int sumscore2 = 0;
String diff;
ProgressBar mProgressBar, mProgressBar1;
int edtTimerValue;
TextView textViewShowTime;
CountDownTimer countDownTimer;
long totalTimeCountInMilliseconds;
public void nextque() {
if ((nextque) + 1 < sourcess.size()) {
nextque++;
}
}
private void setTimer() {
int time = 0;
time = edtTimerValue;
totalTimeCountInMilliseconds = time * 1000;
mProgressBar1.setMax(time * 1000);
}
public void startTimer() {
countDownTimer = new CountDownTimer(totalTimeCountInMilliseconds, 1) {
#Override
public void onTick(long leftTimeInMilliseconds) {
long seconds = leftTimeInMilliseconds / 1000;
mProgressBar1.setProgress((int) (leftTimeInMilliseconds));
textViewShowTime.setText(String.format("%02d", seconds % 60));
}
#Override
public void onFinish() {
buttons[7].setBackgroundResource(R.drawable.blank_button);
textViewShowTime.setText("10");
textViewShowTime.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
mProgressBar1.setVisibility(View.GONE);
nextStep();
}
}.start();
}
public void nextStep() {
textViewShowTime.setVisibility(View.VISIBLE);
equation1.setVisibility(View.VISIBLE);
equation2.setVisibility(View.VISIBLE);
setTimer();
mProgressBar.setVisibility(View.INVISIBLE);
startTimer();
mProgressBar1.setVisibility(View.VISIBLE);
if(sumscore1==100){
sumscore1=0;
sumscore2=0;
score1.setText(String.valueOf(sumscore1));
score2.setText(String.valueOf(sumscore2));
}
if (sumscore2==100){
sumscore1=0;
sumscore2=0;
score1.setText(String.valueOf(sumscore1));
score2.setText(String.valueOf(sumscore2));
}
random = new Random();
randomInt = random.nextInt(sourcess.size());
equation1.setText(sourcess.get(nextque));
equation2.setText(sourcess.get(nextque));
Random rn = new Random();
int index = rn.nextInt(3) + 0;
Log.e("rand poduct", String.valueOf(index));
nextque();
equation1 = (TextView) findViewById(R.id.equation1);
buttons[index].setText( answer.get(nextque));
dess.size();
int k = 0;
for (int i = 0; i <= 3; i++) {
Log.e("prod", "loop " + i);
if (i != index ) {
if(!(answer.get(nextque).equals(j[k]))){
buttons[i].setText((j[k]));
}
k++;
}
}
equation2 = (TextView) findViewById(R.id.equation2);
Random rt = new Random();
int index2 = rt.nextInt(3) + 0;
int index3 = index2 + 4;
buttons[index3].setText( answer.get(nextque));
int d = 0;
for (int i = 4; i <= 7; i++) {
if (i != index3) {
if(!(answer.get(nextque).equals(j[d]))){
buttons[i].setText((j[d]));
}
d++;
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
equal1 = (TextView) findViewById(R.id.equal1);
equal2 = (TextView) findViewById(R.id.equal2);
bord1 = (TextView) findViewById(R.id.bord1);
bord2 = (TextView) findViewById(R.id.bord2);
bakht1 = (TextView) findViewById(R.id.bakht1);
bakht2 = (TextView) findViewById(R.id.bakht2);
refreash = (ImageView) findViewById(R.id.refreash);
textViewShowTime = (TextView) findViewById(R.id.textView_timerview_time);
edtTimerValue = 10;
mProgressBar = (ProgressBar) findViewById(R.id.progressbar_timerview);
mProgressBar1 = (ProgressBar) findViewById(R.id.progressbar1_timerview);
Bundle bundle = getIntent().getExtras();
Typeface font = Typeface.createFromAsset(getAssets(), "BYekan.ttf");
diff = bundle.getString("level");
textViewShowTime.setTypeface(font);
route = new Route(getApplicationContext());
XmlPullParserFactory pullParserFactory;
try {
pullParserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = pullParserFactory.newPullParser();
InputStream in_s = getApplicationContext().getAssets().open("easys.xml");
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in_s, null);
route.parseXML(parser);
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sourcess = new ArrayList<String>();
for (int i = 0; i < route.sources.size(); i++) {
sourcess.add(i, route.sources.get(i));
}
dess = new ArrayList<String>();
for (int i = 0; i < route.destinations.size(); i++) {
dess.add(i, route.destinations.get(i));
}
dess2 = new ArrayList<String>();
for (int i = 0; i < route.destinations2.size(); i++) {
dess2.add(i, route.destinations2.get(i));
}
dess3 = new ArrayList<String>();
for (int i = 0; i < route.destinations3.size(); i++) {
dess3.add(i, route.destinations3.get(i));
}
dess4 = new ArrayList<String>();
for (int i = 0; i < route.destinations4.size(); i++) {
dess4.add(i, route.destinations4.get(i));
}
answer = new ArrayList<String>();
for (int i = 0; i < route.answer.size(); i++) {
answer.add(i, route.answer.get(i));
}
nextStep();
}
}
can anyone help me to solve it?thank alot for your attention.
The array size of array j is 3. But when you are using it inside the loop, you are iterating it more than its size.. Try increasing the size of the arrays and check.
Along with the error you get the line number too of the error, post it if possible.

Getting SDard(s) path and size in KitKat 4.4.2

I have a device info app on Google Play, and within the app I have storage information. I know in Android 4.4 there has been some changes in regards to accessing external SDcards. Internal doesn't seem to give me a problem. My question is, how can I reliably get the size of SDcards on KitKat?
I have the required permissions listed, as this worked fine on earlier versions of Android. I have searched here on SO, and I always seem to get one of the same errors. I do not need to write to SDcards, only read for size availabilty.
I have a StorageUtils class that came from SO, sorry I can't remember the link.
public class StorageUtils {
private static final String TAG = "StorageUtils";
public static class StorageInfo {
public final String path;
public final boolean internal;
public final boolean readonly;
public final int display_number;
StorageInfo(String path, boolean internal, boolean readonly,
int display_number) {
this.path = path;
this.internal = internal;
this.readonly = readonly;
this.display_number = display_number;
}
}
public static ArrayList<StorageInfo> getStorageList() {
ArrayList<StorageInfo> list = new ArrayList<StorageInfo>();
String def_path = Environment.getExternalStorageDirectory().getPath();
boolean def_path_internal = !Environment.isExternalStorageRemovable();
String def_path_state = Environment.getExternalStorageState();
boolean def_path_available = def_path_state
.equals(Environment.MEDIA_MOUNTED)
|| def_path_state.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
boolean def_path_readonly = Environment.getExternalStorageState()
.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
BufferedReader buf_reader = null;
try {
HashSet<String> paths = new HashSet<String>();
buf_reader = new BufferedReader(new FileReader("/proc/mounts"));
String line;
int cur_display_number = 1;
Log.d(TAG, "/proc/mounts");
while ((line = buf_reader.readLine()) != null) {
Log.d(TAG, line);
if (line.contains("vfat") || line.contains("/mnt")) {
StringTokenizer tokens = new StringTokenizer(line, " ");
String unused = tokens.nextToken(); // device
String mount_point = tokens.nextToken(); // mount point
if (paths.contains(mount_point)) {
continue;
}
unused = tokens.nextToken(); // file system
List<String> flags = Arrays.asList(tokens.nextToken()
.split(",")); // flags
boolean readonly = flags.contains("ro");
if (mount_point.equals(def_path)) {
paths.add(def_path);
list.add(new StorageInfo(def_path, def_path_internal,
readonly, -1));
} else if (line.contains("/dev/block/vold")) {
if (!line.contains("/mnt/secure")
&& !line.contains("/mnt/asec")
&& !line.contains("/mnt/obb")
&& !line.contains("/dev/mapper")
&& !line.contains("tmpfs")) {
paths.add(mount_point);
list.add(new StorageInfo(mount_point, false,
readonly, cur_display_number++));
}
}
}
}
if (!paths.contains(def_path) && def_path_available) {
list.add(new StorageInfo(def_path, def_path_internal,
def_path_readonly, -1));
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (buf_reader != null) {
try {
buf_reader.close();
} catch (IOException ex) {
}
}
}
return list;
}
public static String getReadableFileSize(long bytes, boolean si) {
int unit = si ? 1000 : 1024;
if (bytes < unit)
return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1)
+ (si ? "" : "i");
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
#SuppressLint("NewApi")
public static long getFreeSpace(String path) {
StatFs statFs = new StatFs(path);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
long sdAvailSize = statFs.getFreeBlocksLong()
* statFs.getBlockSizeLong();
return sdAvailSize;
} else {
#SuppressWarnings("deprecation")
double sdAvailSize = (double) statFs.getFreeBlocks()
* (double) statFs.getBlockSize();
return (long) sdAvailSize;
}
}
public static long getUsedSpace(String path) {
return getTotalSpace(path) - getFreeSpace(path);
}
#SuppressLint("NewApi")
public static long getTotalSpace(String path) {
StatFs statFs = new StatFs(path);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
long sdTotalSize = statFs.getBlockCountLong()
* statFs.getBlockSizeLong();
return sdTotalSize;
} else {
#SuppressWarnings("deprecation")
double sdTotalSize = (double) statFs.getBlockCount()
* statFs.getBlockSize();
return (long) sdTotalSize;
}
}
/**
* getSize()[0] is /mnt/sdcard. getSize()[1] is size of sd (example 12.0G),
* getSize()[2] is used, [3] is free, [4] is blksize
*
* #return
* #throws IOException
*/
public static String[] getSize() throws IOException {
String memory = "";
Process p = Runtime.getRuntime().exec("df /mnt/sdcard");
InputStream is = p.getInputStream();
int by = -1;
while ((by = is.read()) != -1) {
memory += new String(new byte[] { (byte) by });
}
for (String df : memory.split("/n")) {
if (df.startsWith("/mnt/sdcard")) {
String[] par = df.split(" ");
List<String> pp = new ArrayList<String>();
for (String pa : par) {
if (!pa.isEmpty()) {
pp.add(pa);
}
}
return pp.toArray(new String[pp.size()]);
}
}
return null;
}
}
And here is my fragment in which I try to display the SDcard path and size.
public class CpuMemFragment extends Fragment {
// CPU
String devCpuInfo;
TextView tvCpuInfo;
// RAM
String devRamInfo;
TextView tvRamInfo;
// Storage
String devStorageA, devStorageB;
TextView tvStorageAName, tvStorageA, tvStorageB, tvStorageBName;
AdView adView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.cpu_mem, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
// *** CPU ***
//
devCpuInfo = readCpuInfo();
//
// #################################
// *** RAM ***
//
devRamInfo = readTotalRam();
//
// #################################
// *** STORAGE ***
//
ArrayList<StorageInfo> storageInfoList = StorageUtils.getStorageList();
tvStorageAName = (TextView) getView().findViewById(R.id.tvStorageAName);
tvStorageBName = (TextView) getView().findViewById(R.id.tvStorageBName);
if (storageInfoList.size() > 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
&& !storageInfoList.get(0).internal) {
kitKatWorkaround(0);
}
tvStorageAName.setText(storageInfoList.get(0).path);
devStorageA = StorageUtils.getReadableFileSize(
(StorageUtils.getUsedSpace(storageInfoList.get(0).path)),
true)
+ "/"
+ StorageUtils.getReadableFileSize((StorageUtils
.getTotalSpace(storageInfoList.get(0).path)), true);
if (storageInfoList.size() > 1) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
&& !storageInfoList.get(0).internal) {
kitKatWorkaround(1);
}
tvStorageBName.setText(storageInfoList.get(1).path);
devStorageB = StorageUtils.getReadableFileSize(
StorageUtils.getUsedSpace(storageInfoList.get(1).path)
+ (StorageUtils.getUsedSpace("system/")), true)
+ "/"
+ StorageUtils.getReadableFileSize((StorageUtils
.getTotalSpace(storageInfoList.get(1).path)),
true);
} else {
devStorageB = "N/A";
}
} else {
devStorageA = "N/A";
devStorageB = "N/A";
}
//
// #################################
// CPU
tvCpuInfo = (TextView) getView().findViewById(R.id.tvCpuInfo);
tvCpuInfo.setText(devCpuInfo);
//
// #################################
// RAM
tvRamInfo = (TextView) getView().findViewById(R.id.tvRamInfo);
tvRamInfo.setText(devRamInfo);
//
// #################################
// STORAGE
tvStorageA = (TextView) getView().findViewById(R.id.tvStorageA);
tvStorageA.setText(devStorageA);
tvStorageB = (TextView) getView().findViewById(R.id.tvStorageB);
tvStorageB.setText(devStorageB);
//
// #################################
// Look up the AdView as a resource and load a request.
adView = (AdView) getActivity().findViewById(R.id.adCpuMemBanner);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
}
#Override
public void onPause() {
if (adView != null) {
adView.pause();
}
super.onPause();
}
#Override
public void onResume() {
super.onResume();
if (adView != null) {
adView.resume();
}
}
#Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
private static synchronized String readCpuInfo() {
ProcessBuilder cmd;
String result = "";
try {
String[] args = { "/system/bin/cat", "/proc/cpuinfo" };
cmd = new ProcessBuilder(args);
Process process = cmd.start();
InputStream in = process.getInputStream();
byte[] re = new byte[1024];
while (in.read(re) != -1) {
System.out.println(new String(re));
result = result + new String(re);
}
in.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return result;
}
public static synchronized String readTotalRam() {
String load = "";
try {
RandomAccessFile reader = new RandomAccessFile("/proc/meminfo", "r");
load = reader.readLine();
reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return load;
}
public void kitKatWorkaround(int index) {
String path1 = Environment.getExternalStorageDirectory().getPath();
//Storage A
if (index == 0) {
tvStorageAName.setText(path1);
devStorageA = StorageUtils.getReadableFileSize(
(StorageUtils.getUsedSpace(path1)), true)
+ "/"
+ StorageUtils.getReadableFileSize(
(StorageUtils.getTotalSpace(path1)), true);
}
//Storage B
if (index == 1) {
tvStorageBName.setText(path1);
devStorageB = StorageUtils.getReadableFileSize(
StorageUtils.getUsedSpace(path1)), true)
+ "/"
+ StorageUtils.getReadableFileSize(
(StorageUtils.getTotalSpace(path1)), true);
}
}
}
This results in the EACCES error, or an invalid path (access denied) on KitKat. Please help, and thank you greatly for your time.
You can find all shared storage devices by calling Context.getExternalFilesDirs() or Context.getExternalCacheDirs(). Then, you can call File.getUsableSpace() or use android.os.StatFs to check available disk space at each location.
These APIs are also available in ContextCompat in the support library to seamlessly work on pre-KitKat devices.

only the original thread that created a view hierarchy can touch its views. android

public class master extends Activity {
ProgressDialog progressDialog;
EditText tahmini_kelime;
EditText girilen_sayi ;
EditText toplam_harf_sayisi ;
Button tamamdir;
TextView jTextArea1;
Vector vector_all,vect_end,vect,recent_search;
BufferedReader read;
String recent_tahmin_kelime;
boolean bayrak,bayrak2 ;
int column_number ;
InputStreamReader inputreader ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.master);
column_number=0;
bayrak=true;
toplam_harf_sayisi=(EditText)findViewById(R.id.toplam_harf);
tahmini_kelime=(EditText)findViewById(R.id.tahmini_kelime);
girilen_sayi=(EditText)findViewById(R.id.sayi_gir);
tamamdir=(Button)findViewById(R.id.tamamdirrrr);
jTextArea1=(TextView)findViewById(R.id.jte);
bayrak2=true;
recent_search = new Vector();
InputStream inputStream = getResources().openRawResource(R.raw.sozluk);
try {
inputreader = new InputStreamReader(inputStream,"utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
};
read = new BufferedReader(inputreader);
int k = 0;
String result = "";
try {
vector_all = new Vector();
while (read.ready()) {
result = read.readLine();
vector_all.add(result);
jTextArea1.append(result + "\n");
k = k + 1;
}
String size = "" + k;
} catch (IOException ex) {
}
tamamdir.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if( bayrak2 )
{
if(Integer.parseInt(toplam_harf_sayisi.getText().toString())>8 || Integer.parseInt(toplam_harf_sayisi.getText().toString())<=1)
{
toplam_harf_sayisi.setText("");
Dialog dl=new Dialog(master.this);
dl.setTitle("hatalı giriş");
dl.setCanceledOnTouchOutside(true);
dl.show();
return;
}
int findwordlength = Integer.parseInt(toplam_harf_sayisi.getText().toString());
int k = 0;
String result = "";
jTextArea1.setText("");
InputStream inputStream = getResources().openRawResource(R.raw.sozluk);
try {
inputreader = new InputStreamReader(inputStream,"utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
};
read = new BufferedReader(inputreader);
String resultword = "";
try {
vect = new Vector();
while (read.ready()) {
result = read.readLine();
if (result.length() == findwordlength) {
vect.addElement(result);
resultword = resultword + result + "\n";
k = k + 1;
}
jTextArea1.setText("");
}
jTextArea1.append(resultword + "\n");
RandomKelime(vector_all,0 );
} catch (IOException ex) {
}
toplam_harf_sayisi.setEnabled(false);
girilen_sayi.setEnabled(true);
bayrak2=false;
}
else
{
progressDialog = ProgressDialog.show(master.this, "Bir Düşüneyim :D", "lütfen bekleyiniz...");
Thread thread = new Thread(new Runnable() {
public void run() {
mainGuessWord(column_number);
handler.sendEmptyMessage(0);
}
});
thread.start();
girilen_sayi.setText("");
}
}
});
}
private void mainGuessWord(int look) {
int result_int = 0;
String randomword = "";
int randomword2 = 0;
randomword = tahmini_kelime.getText().toString();
result_int = Integer.parseInt(girilen_sayi.getText().toString());
if (result_int == 0) {
mevcut_degil(vect, randomword);
} else {
elemeAgaci(vect, randomword, result_int);
}
}
public void elemeAgaci(Vector vect, String elem, int length) {
String word = elem.toString();
Vector cmp_vect;
cmp_vect = new Vector();
vect_end = new Vector();
int count = 0;
int countword = 0; // toplam word sayısı
int each_word_total = 0; // her kelimede bulunan harf sayısı
jTextArea1.setText("");
String compare = "";
for (int i = 0; i < vect.size(); i++) {
each_word_total = 0;
compare = "";
for (int j = 0; j < word.length(); j++) {
if(!compare.contains(""+word.charAt(j)))
{
for (int k = 0; k < vect.get(i).toString().length(); k++) {
if (vect.get(i).toString().charAt(k) == word.charAt(j)) {
each_word_total++;
}
}
compare=""+compare+word.charAt(j);
}
}
System.out.println("" + vect.get(i) + " => " + each_word_total);
if (length == each_word_total) {
cmp_vect.add(vect.get(i));
jTextArea1.append(vect.get(i) + "\n");
countword++;
}
}
vect.clear();
for (int l = 0; l < cmp_vect.size(); l++) {
vect.add(cmp_vect.get(l));
}
if (countword == 1) {
Dialog dl=new Dialog(master.this);
dl.setTitle("The Word id : "+jTextArea1.getText().toString());
dl.setCanceledOnTouchOutside(true);
dl.show();
} else {
column_number = column_number + 1;
if(vect.size()<10){
RandomKelime_Table(vect);
}else{
RandomKelime(vector_all, column_number);
}
}
}
public void mevcut_degil(Vector vect, String m) {
char control[];
control = m.toCharArray();
boolean flag = false;
int countword = 0;
Vector detect;
detect = new Vector();
jTextArea1.setText("");
for (int k = 0; k < vect.size(); k++) {
flag = false;
for (int s = 0; s < control.length; s++) {
if (vect.get(k).toString().contains("" + control[s])) {
flag = true;
}
}
if (!flag) {
detect.addElement(vect.get(k));
countword = countword + 1;
}
}
vect.clear();
for (int s = 0; s < detect.size(); s++) {
vect.addElement(detect.get(s));
}
for (int a = 0; a < countword; a++) {
jTextArea1.append(vect.get(a).toString() + "\n");
}
if (countword == 1) {
Dialog dl=new Dialog(master.this);
dl.setTitle("The Word id : "+jTextArea1.getText().toString());
dl.setCanceledOnTouchOutside(true);
dl.show();
}
else {
column_number = column_number + 1;
RandomKelime(vect, column_number);
}
}
public void RandomKelime(Vector vector, int k)
{
String sesli[]={"a","e","ı","i","o","ö","u","ü"};
Random a = new Random();
if (k == 0) {
String passedword = "";
passedword = vector_all.get((int) (Math.random() * vector_all.size())).toString();
while (passedword.length() < 8) {
passedword = vector_all.get((int) (Math.random() * vector_all.size())).toString();
}
tahmini_kelime.setText(passedword);
recent_tahmin_kelime=passedword;
// jTable1.setValueAt(vector_all.get((int) (Math.random() * vector_all.size())), k, 0);
} else {
recent_search.addElement(recent_tahmin_kelime );
int say = 0;
String design = "";
String guess_words = "";
String as="";
int f=0;
int count=0;
int calculate_all=0;
for (int u = 0; u < recent_search.size(); u++) {
design = recent_search.get(u).toString();
bayrak = false;
as="";
count=0;
for(int s=0;s<sesli.length;s++)
{
if(design.contains(""+sesli[s]) && count==0){
as+=""+sesli[s];
count++;
}
}
guess_words = vector_all.get((int) a.nextInt(vector_all.size())).toString();
while (guess_words.length() < 8) {
guess_words = vector_all.get((int) (Math.random() * vector_all.size())).toString();
}
while (say < design.length()) {
calculate_all=0;
while (guess_words.contains("" + as) && !design.equals(guess_words)) {
say = 0;
calculate_all++;
guess_words = vector_all.get( a.nextInt(vector_all.size())).toString();
while (guess_words.length() < 8) {
guess_words = vector_all.get((int) (Math.random() * vector_all.size())).toString();
}
f=f+1;
System.out.println("Tahmın: " + guess_words + " => " + design);
if(calculate_all>vect.size())
{
break;
}
}
say++;
System.out.println("coutn: " + say);
}
}
if (true) {
tahmini_kelime.setText(guess_words);
}
}
}
public void RandomKelime_Table(Vector vector ) {
String passedword = "";
Random a = new Random();
try {
passedword = vect.get(a.nextInt(vect.size())).toString();
} catch (Exception e) {
Dialog dl=new Dialog(master.this);
dl.setTitle("Hatalı Giriş.Yeniden Başlayın.");
dl.setCanceledOnTouchOutside(true);
dl.show();
yeniden_basla();
}
tahmini_kelime.setText(passedword );
}
public void yeniden_basla()
{
bayrak2=true;
girilen_sayi.setEnabled(false);
toplam_harf_sayisi.setEnabled(true);
toplam_harf_sayisi.setText("");
vect.clear();
vector_all.clear();
vect_end.clear();
recent_search.clear();
jTextArea1.setText("");
recent_tahmin_kelime="";
column_number=0;
bayrak=true;
InputStream inputStream = getResources().openRawResource(R.raw.sozluk);
try {
inputreader = new InputStreamReader(inputStream,"utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
};
read = new BufferedReader(inputreader);
int k = 0;
String result = "";
try {
vector_all = new Vector();
while (read.ready()) {
result = read.readLine();
vector_all.add(result);
jTextArea1.append(result + "\n");
k = k + 1;
}
String size = "" + k;
} catch (IOException ex) {
}
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
progressDialog.dismiss();
}
};
}
this all of my code.
You don't show where you create your handler (onCreate ? onStart ? somewhere else ?). Is it started from the main thread ? If so, you need to be provide a more complete stack trace so we can understand.
If you're starting it from another thread then that's the issue because it's attempting to change progressDialog and that must be done from the main thread.
PS: if you used an AsyncTask you wouldn't have to scratch your head around this as it's designed to do exactly what you want and be thread safe.
Post comment : use an AsyncThread : add the progress bar in onPreExecute(), change run() to doInBackground() and move the dismiss() to onPostExecute(

Categories

Resources