Application closed after some time in android - android

I create a image slide show type application, I my application used thread.
My application run successfully but after some time application suddenly close.
I am used following line of code to release memory
System.gc();
Runtime.getRuntime().gc();
without above code same issue occur.
Logcat:
03-13 12:45:09.250 / dalvikvm:
### ABORTING: DALVIK: HEAP MEMORY CORRUPTION IN internal_bulk_free addr=0x0
20713 20715 F03-13 12:45:09.250 / libc
Fatal signal 11 (SIGSEGV) at 0xdeadbaad (code=1), thread 20715 (GC)
How to solve my problem?
Please help me.
MY code is:
public class MyRunnable implements Runnable {
private int delayTime = 0;
private Vector<Integer> my_PlaylistRecord_ContentIds =new Vector<Integer>();
private Vector<Integer> delayArray =new Vector<Integer>();
private Vector<Long> video_Duration_List = new Vector<Long>();
private Vector<Integer> relative_Ids = new Vector<Integer>();
private Vector<RelativeLayout> layouts = new Vector<RelativeLayout>();
private RelativeLayout customRelativeLayout ;
private ArrayList<String> _idArray;
private ArrayList<String> _delayArray;
private int countPlus = 0;
private int totalSize = 0;
private ArrayList<Playlist_record> playlist_records;
private FinalPlaylist finalPlaylist;
private int fullscreenId =0;
private int screenId =0;
private int screenIndex =0;
private long videoDuration = 0;
public MyRunnable(ArrayList<Integer> _playlistRrecord_ContentIds, FinalPlaylist _finalPlaylist, List<Integer> delayLists, List<Long> videoDurationList) {
finalPlaylist = _finalPlaylist;
for (Integer id : _playlistRrecord_ContentIds) {
//System.out.println("content id:"+id);
my_PlaylistRecord_ContentIds.add(id);
}
for (Integer string : delayLists) {
//System.out.println("delay time :"+string);
delayArray.add(string);
}
for (Long videoDuration : videoDurationList) {
video_Duration_List.add(videoDuration);
}
totalSize = delayArray.size();
Iterator<Integer> myVeryOwnIterator = layoutMap.keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
int key=(Integer) myVeryOwnIterator.next();
System.out.println("key:"+key);
customRelativeLayout = layoutMap.get(key);
//System.out.println(" test customRelativeLayout.getChildCount():"+customRelativeLayout.getChildCount());
layouts.add(customRelativeLayout);
relative_Ids.add(key);
}
// Find screen s
List<Container> containers = appDataBase.getAllCotainer();
for (Container container : containers) {
if(container.getName().equals("S")){
System.out.println("screen INVISIBLE index:");
screenId = container.getContainer_id();
System.out.println(" index :"+screenId);
}
if(container.getName().equals("FS")){
fullscreenId = container.getContainer_id();
}
}
// find index number of screen s container
for (int i = 0 ; i < relative_Ids.size() ; i++) {
if(screenId == relative_Ids.get(i)){
screenIndex = i;
}
}
/* for (int i = 0 ; i < relative_Ids.size() ; i++) {
List<Container> containers = appDataBase.getAllCotainer();
for (Container container : containers) {
if(container.getName().equals("FS")){
System.out.println("Full screen INVISIBLE index:"+i);
RelativeLayout relativeLayout = layouts.get(i);
//relativeLayout.setVisibility(View.INVISIBLE);
layouts.set(i, relativeLayout);
} else if(container.getName().equals("S")){
System.out.println("screen INVISIBLE index:"+i);
RelativeLayout relativeLayout = layouts.get(i);
relativeLayout.setVisibility(View.INVISIBLE);
layouts.set(i, relativeLayout);
}
}
}*/
}
public void run() {
System.out.println("screen container id:"+screenId);
while(IS_THREAD_RUN){
if(countPlus < totalSize){
Runnable iRunnable= new Runnable() {
public void run() {
// System.out.println(" ** countPlus:"+ countPlus);
// System.out.println(" ** totalSize:"+ totalSize);
// System.out.println("my_playlist_ids size:"+my_PlaylistRecord_ContentIds.size());
// System.out.println("my_playlist_ids content:"+my_PlaylistRecord_ContentIds.get(countPlus));
// Get all playlist record
List<Playlist_record> playlist_records = finalPlaylist.getPlayerArray();
Playlist_record playlist_record = playlist_records.get(countPlus);
//System.out.println("test run container id:"+playlist_record.getContainer_id());
// ***********************************
// Check playlist_record validation
// ***********************************
//System.out.println("playlist_recordId:"+my_playlist_ids.get(countPlus));
boolean isvalidContent = false;
isvalidContent = appDataBase.isPlayContent(playlist_record.getPlaylist_record_id());
System.out.println("Valid Content:"+isvalidContent);
if(isvalidContent){
// Hide layout, Fetch all container data and get name equals to FS and S then relative layout
/*
for (int i = 0 ; i < relative_Ids.size() ; i++) {
List<Container> containers = appDataBase.getAllCotainer();
for (Container container : containers) {
if(container.getName().equals("FS")){
System.out.println("Full screen INVISIBLE index:"+i);
RelativeLayout relativeLayout = layouts.get(i);
//relativeLayout.setVisibility(View.INVISIBLE);
layouts.set(i, relativeLayout);
} else if(container.getName().equals("S")){
System.out.println("screen INVISIBLE index:"+i);
RelativeLayout relativeLayout = layouts.get(i);
relativeLayout.setVisibility(View.INVISIBLE);
layouts.set(i, relativeLayout);
}
}
}*/
//System.out.println(" layouts:"+layouts.toString());
for (int i = 0 ; i < relative_Ids.size() ; i++) {
if(relative_Ids.get(i) == playlist_record.getContainer_id()){
//System.out.println("countainer id:"+relative_Ids.get(i));
// System.out.println("playlist_record.getContainer_id():"+playlist_record.getContainer_id());
customRelativeLayout = layouts.get(i);
// System.out.println("customRelativeLayout.getChildCount():"+customRelativeLayout.getChildCount());
// Fetch all container data and get name equals to FS and S then relative layout visible
if(screenId == playlist_record.getContainer_id()){
customRelativeLayout.setVisibility(View.VISIBLE);
//customRelativeLayout.bringToFront();
}else {
RelativeLayout relativeLayout = layouts.get(screenIndex);
relativeLayout.setVisibility(View.INVISIBLE);
layouts.set(screenIndex, relativeLayout);
}
//Weather id match
try {
Feature_Defination feature_Defination = appDataBase.getFeatureDefinition(relative_Ids.get(i));
if(relative_Ids.get(i)==feature_Defination.getContainerID()){
System.out.println("match");
displayWeatherData(customRelativeLayout,feature_Defination.getContainerID(),feature_Defination);
}
} catch (Exception e) {
e.printStackTrace();
}
//System.out.println("transition effect:"+playlist_record.getTransition());
//customRelativeLayout.setVisibility(View.VISIBLE);
setContent(my_PlaylistRecord_ContentIds.get(countPlus),customRelativeLayout,getAnimation(playlist_record.getTransition()),delayArray.get(countPlus));
}
} // End for loop
System.out.println("my_playlist_ids:"+my_PlaylistRecord_ContentIds.get(countPlus));
// setContent(my_playlist_ids.get(countPlus),customRelativeLayout);
countPlus =countPlus+1;
if(countPlus >= totalSize){
countPlus = 0;
}
}else{
countPlus =countPlus+2;
if(countPlus >= totalSize){
countPlus = 0;
}
}
} //run method end
};
handler.post(iRunnable);
}else{
countPlus = 0;
}
//System.out.println("countplus before thread sleep:"+delayArray.get(countPlus)+" countPlus:"+countPlus);
//System.out.println("countplus sleep video duration:"+videoDuration);
try {
long sleepTime = delayArray.get(countPlus);
// System.out.println("sleep delay :"+sleepTime);
if(sleepTime==0){
long videoTime = video_Duration_List.get(countPlus);
if(videoTime == 0 ){
sleepTime = 1000;
}else{
sleepTime = videoTime;
}
}else{
sleepTime = (sleepTime * 1000)+1000;
}
/*
if(videoDuration!=0){
System.out.println("sleep count plus"+countPlus);
countPlus = countPlus - 1;
if(countPlus<=0){
countPlus = 0;
}
System.out.println("sleep countPlus:"+countPlus);
sleepTime = videoDuration;
}*/
// new DisplayContentAsync().execute(""+my_PlaylistRecord_ContentIds.get(countPlus));
System.out.println("sleep time:"+sleepTime);
Thread.sleep(sleepTime);
//Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // run method end
}
}
/* class DisplayContentAsync extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
// get video file length
// check video
// *********************************************************
String play_FileName = "";
//Get all record from content table
File conFile = new File( Util.ROOT_PATH + "Contents/"+play_FileName);
//Check image file
ImageFileFilter imageFileFilter = new ImageFileFilter(conFile);
VideoFileFilter videoFileFilter = new VideoFileFilter(conFile);
Content content = appDataBase.getContentTemp(""+params[0]);
System.out.println("content id:"+content.getContent_id());
System.out.println("content path:"+content.getContent());
try {
String[] contentArray = null;
contentArray = content.getContent().split("/");
play_FileName = contentArray[contentArray.length-1];
} catch (Exception e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String filePath = Util.ROOT_PATH + "Contents/"+conFile.getName();
if(videoFileFilter.accept(conFile)){
System.out.println("Video file name:"+play_FileName);
// Get video file play duration
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(filePath);
String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
long time1 = Long.parseLong( time );;
System.out.println("video time: "+time1);
}
// setContent(my_playlist_ids.get(countPlus),customRelativeLayout);
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
*/
#SuppressLint("NewApi")
public void setContent(int content_id,RelativeLayout _customRelativeLayout,List<Animation> _animations, int _videoTimeDuration){
//System.gc();
//Runtime.getRuntime().gc();
List<Animation> animations = _animations;
RelativeLayout customRelativeLayout = _customRelativeLayout;
ImageView imageView = null;
VideoView videoView = null;
WebView webView = null;
int height = customRelativeLayout.getHeight();
int width = customRelativeLayout.getWidth();
final int videoTimeDuration = _videoTimeDuration;
Animation anim1 = null ;
Animation anim2 = null;
Animation anim3 = null;
for(int p=0; p<animations.size();p++){
if(p==0){
anim1 = animations.get(p);
System.out.println("animation 1");
}else if(p==1){
anim2 = animations.get(p);
System.out.println("animation 2");
}else if(p==2){
anim3 = animations.get(p);
System.out.println("animation 3");
}
}
//System.out.println("layout height :"+height);
//System.out.println("layout height :"+height);
// Find all child from relative layout
int childcount = customRelativeLayout.getChildCount();
//System.out.println("get all child:"+childcount);
for (int i=0; i < childcount; i++){
View view = customRelativeLayout.getChildAt(i);
if (view instanceof ImageView) {
imageView = (ImageView) view;
// do what you want with imageView
}else if (view instanceof VideoView) {
videoView = (VideoView) view;
// do what you want with imageView
}else if (view instanceof WebView) {
webView = (WebView) view;
// do what you want with imageView
}
}
String play_FileName = "";
//Get all record from content table
//System.out.println("content id match with:"+content_id);
Content content = appDataBase.getContent(""+content_id);
//System.out.println("content id:"+content.getContent_id());
//System.out.println("content path:"+content.getContent());
try {
String[] contentArray = null;
contentArray = content.getContent().split("/");
play_FileName = contentArray[contentArray.length-1];
} catch (Exception e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
System.out.println("Play file name:"+play_FileName);
//Toast.makeText(Display.this, play_FileName, 1000).show();
//System.out.println("Play file duration:"+duration);
/*
// Set animation
if(animations!=null && animations.size()>=2){
System.out.println("animation 2 available ");
final Animation endanim = anim2;
final RelativeLayout relativeLayout = customRelativeLayout;
customRelativeLayout.startAnimation(anim1);
anim1.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation arg0) {
}
#Override
public void onAnimationRepeat(Animation arg0) {
}
#Override
public void onAnimationEnd(Animation arg0) {
relativeLayout.startAnimation(endanim);
}
});
}else if(animations!=null && animations.size()==1){
System.out.println("animation 1 available");
imageView.setAnimation(anim1);
}else {
System.out.println("animation not available");
}
*/
File conFile = new File( Util.ROOT_PATH + "Contents/"+play_FileName);
//Check image file
ImageFileFilter imageFileFilter = new ImageFileFilter(conFile);
VideoFileFilter videoFileFilter = new VideoFileFilter(conFile);
WebFileFilter webFileFilter = new WebFileFilter(conFile);
String filePath = Util.ROOT_PATH + "Contents/"+conFile.getName();
//check file size is zero or not
File chkFile = new File(filePath);
if(chkFile.length()>0){
if(imageFileFilter.accept(conFile)){
//System.out.println("filter image file name:"+conFile.getName());
videoView.setVisibility(View.GONE);
imageView.setVisibility(View.VISIBLE);
webView.setVisibility(View.GONE);
// Check android os
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH){
//System.out.println("jelly bean");
Drawable drawable = Drawable.createFromPath(filePath);
imageView.setBackground(drawable);
//imageView.setImageBitmap(decodeFile(chkFile, 1000, 1000));
// Set animation
if(animations!=null && animations.size()>=2){
System.out.println("animation 2 available ");
final Animation endanim = anim2;
final ImageView finalImage = imageView;
imageView.startAnimation(anim1);
anim1.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation arg0) {
}
#Override
public void onAnimationRepeat(Animation arg0) {
}

You can try this.Add below line in android manifest file :
android:largeHeap="true"
Thanks.

Related

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.

Adding TextView dynamically under the relativeLayout

enter image description herehow can i add multiple TextView and their inside relative layout dynamically which is already created? Also I have to call the values of those text boxes from database sqlite.
public class DownloadPackagesActivity extends Activity implements AdapterView.OnItemSelectedListener{
private SQLiteDatabase db;
DBHelper dbHelper;
String newFolder = "";
int SId = 1;
TextView subjects;
List<String> categories = new ArrayList<String>();
String FilePart = "";
DownloadManager dManager;
long did;
// private static String file_url = "http://mobileteacher.in/audio/demo/2725.mp3";
String urlString ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download_packages);
// Get DownloadManager instance
dManager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
subjects = (TextView)findViewById(R.id.subjects);
// Spinner element
Spinner spinner = (Spinner) findViewById(R.id.spinnerPackage);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Add textview
dbHelper = new DBHelper(this);
try{
dbHelper.createDataBase();
}
catch(Exception ex)
{
ex.printStackTrace();
}
String myPath = dbHelper.DB_PATH + DBHelper.DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
Cursor c = db.rawQuery("select * from DownloadSubject", null);
while (c.moveToNext()) {
categories.add(c.getString(1));
}
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, categories);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
spinner.setAdapter(dataAdapter1);
showPart();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
SId = position + 1;
showPart();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void showPart()
{
int j=1;
int ii=0;
dbHelper = new DBHelper(this);
try{
dbHelper.createDataBase();
}
catch(Exception ex)
{
ex.printStackTrace();
}
TableLayout stk = (TableLayout) findViewById(R.id.tbl);
stk.removeAllViews();
String myPath = dbHelper.DB_PATH + DBHelper.DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
Cursor c;
if (SId==8 || SId==9)
{
c = db.rawQuery("select * from DownloadSubject", null);
}
else
{
c = db.rawQuery("select * from DownloadSubject where Id = '"+ SId +"'", null);
}
while (c.moveToNext())
{
subjects.clearComposingText();
String[] part = c.getString(2).split(",");
for(int i = 0;i<part.length;i++)
{
TableRow tr1 = new TableRow(this);
Button button = new Button(this);
button.setBackgroundColor(Color.TRANSPARENT);
button.setText(part[i] +"\u00A0 \u00A0 \u00A0 \u00A0 Download");
button.setTextColor(Color.BLUE);
button.setPadding(20, 0, 0, 0);
button.setOnClickListener(downloads());
button.setId(i);
// button.setHint(part[i]);
tr1.addView(button);
stk.addView(tr1);
}
stk = (TableLayout) findViewById(R.id.tbl);
int N = 1;
TextView[] TextViews = new TextView[N]; // create an empty array;
// for (int i = 0; i < N; i++) {
//if(ii!=0) {
// subjects.setText(c.getString(j));
// Toast.makeText(this, c.getString(j), Toast.LENGTH_LONG).show();
// save a reference to the textview for later
// TextViews[j] = TextView;
//}
if(ii==0)
{
subjects.setText(c.getString(j));
ii=ii+1;
}
else
{
final TextView TextView = new TextView(this);
TextView.setText(c.getString(j));
TextView.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT,
TableLayout.LayoutParams.WRAP_CONTENT));
TextView.setPadding(0, 20, 0, 20);
TextView.setTextSize(getResources().getDimension(R.dimen.textsize));
TextView.setTextColor(Color.parseColor("#800080"));
// add the textview to the layout
stk.addView(TextView);
}
}
}
public String part;
View.OnClickListener downloads()
{
return new View.OnClickListener()
{
public void onClick(View v) {
//Button b1 = (Button)v;
//int i = b1.getId();
// Toast.makeText(getApplicationContext(),"Ide = " + i,Toast.LENGTH_LONG).show();
part ="";
TextView subjects = (TextView)findViewById(R.id.subjects);
if(subjects.getText().toString().equals("Modern History (500 MB)"))
{
part = "modern_history";
}
else if(subjects.getText().toString().equals("Polity (250 MB)"))
{
part = "polity";
}
else if(subjects.getText().toString().equals("Economy (100 MB)"))
{
part = "economy";
}
else if(subjects.getText().toString().equals("Ancient History (500 MB)"))
{
part = "ancient_history";
}
else if(subjects.getText().toString().equals("English Grammar (500 MB)"))
{
part = "english_grammar";
}
else if(subjects.getText().toString().equals("Vocabulary (560 MB)"))
{
part = "vocabulary";
}
else if(subjects.getText().toString().equals("Maths (100 MB)"))
{
part = "maths";
}
else if(subjects.getText().toString().equals("One Day Complete(Vol.1(2GB))"))
{
part = "oneday_complete";
}
else if(subjects.getText().toString().equals("Civil Complete (Vol.1 (2GB))"))
{
part = "civil_complete" ;
}
newFolder = "/voice";
subjects = (TextView)findViewById(R.id.subjects);
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myNewFolder = new File(extStorageDirectory + newFolder);
//File f = new File(myNewFolder);
myNewFolder.mkdir();
Button b = (Button)v;
FilePart = b.getText().toString();
String RemoveSpace = FilePart.split("\u00A0")[0].replace(" ","");
try {
urlString = "http://mobileteacher.in/DealerPackage/" + part + "/" + RemoveSpace + ".zip";
downloadFile();
Toast.makeText(getApplicationContext(), "Download Started", Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Please Connect Internet", Toast.LENGTH_LONG).show();
}
}
};
}
public void downloadFile() {
// String urlString = "http://mobileteacher.in/audio/demo/2725.mp3";
if (!urlString.equals("")) {
try {
// Get file name from the url
String fileName = urlString.substring(urlString.lastIndexOf("/") + 1);
// Create Download Request object
DownloadManager.Request request = new DownloadManager.Request(Uri.parse((urlString)));
// Display download progress and status message in notification bar
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
// Set description to display in notification
// request.setDescription("Download " + fileName + " from " + urlString);
request.setDescription("Download " + fileName + " from mobileteacher.in");
// Set title
request.setTitle("Mobile Teacher");
// Set destination location for the downloaded file
request.setDestinationUri(Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/voice/"+fileName.split("\u00A0")[0].replace(" ","")));
// Download the file if the Download manager is ready
did = dManager.enqueue(request);
} catch (Exception e) {
}
}
}
// BroadcastReceiver to receive intent broadcast by DownloadManager
private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(did);
Cursor cursor = dManager.query(q);
if (cursor.moveToFirst()) {
String message = "";
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
message = "Download successful";
} else if (status == DownloadManager.STATUS_FAILED) {
message = "Download failed";
}
//query.setText(message);
}
}
};
protected void onResume() {
super.onResume();
// Register the receiver to receive an intent when download complete
IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(downloadReceiver, intentFilter);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
// Unregister the receiver
unregisterReceiver(downloadReceiver);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_download_packages, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void back(View view)
{
finish();
}
public void Create(View view)
{
String newFolder = "/voice";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myNewFolder = new File(ext[enter image description here][1]StorageDirectory + newFolder);
myNewFolder.mkdir();
}
}
this is the image
create relative layout object from it layout id, then you can add it as below
relativeLayout = findViewById(R.id.yourRelativeLayoutId);
relativeLayout.addView(yourView);
Listview or recyclerview is best for practice but as you want to use textview, you can use like this in your code:
RelativeLayout relativeLayout =
(RelativeLayout) findViewById(R.id.rootlayout);
TextView textView = new TextView(this);
textView.setText("Hey, I am TextView");
relativeLayout.addView(textView);
appending a textview to relativelayout is pretty simple.
just use
TextView textview = new TextView(this);
textview.setText("Text");
relativelayoutobject.addView(textview);
to setup the position use
textview.setLayoutParams(thelayoutparams)
But if you use big database, please, use 'TableLayout' instead of your method due to performance reasons.
Define relative layout in your xml layout. Add multiple textview programmatic ally like this-
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
//use a for loop to define multiple textView in RelativeLayout
//length is no. of textView you required
for (int i = 0; i < length; i++) {
TextView tv = new TextView(relativeLayout.getContext());
tv.setText("Text from sqlite database");
tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
relativeLayout.addView(tv);
}

How can I save my current imageview when onClick?

How can I save my current ImageView when I press onClick?
Im currently having the problem that the image that is next in line is being saved instead of the current actual image..
My Code for saving onLike
public class MainActivity extends Activity implements SwipeView.OnCardSwipedListener {
// Declaring variables
private final static int CARDS_MAX_ELEMENTS = 5;
private FrameLayout contentLayout;
private SwipeView mSwipeView;
private View addCardc41;
private Firebase mRef;
public ImageView imageLogo;
public ImageView imageview;
private static final String TAG = "MyActivity";
// Creating array of meals, getting them from the drawable folder
private int[] meals = {
R.drawable.a,
R.drawable.b,
R.drawable.c,
R.drawable.d,
R.drawable.e,
R.drawable.f,
R.drawable.g,
R.drawable.h,
R.drawable.i,
R.drawable.j
};
// Declaring a counter for the next method
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe_view_demo);
contentLayout = (FrameLayout) findViewById(R.id.contentLayout);
imageLogo = (ImageView) findViewById(R.id.imageView3);
imageview = (ImageView) findViewById(R.id.imageView);
// Add the swipe view
mSwipeView = new SwipeView(this, R.id.imgSwipeLike, R.id.imgSwipeNope,
this);
contentLayout.addView(mSwipeView);
// Adding the cards initially with the maximum limits of cards.
for (int i = 0; i < CARDS_MAX_ELEMENTS; i++) {
addCard(i);
}
}
/**
* On clicked view.
*
* #param clickedView
* the clicked view
*/
public void onClickedView(View clickedView) {
switch (clickedView.getId()) {
case R.id.imgDisLike: {
mSwipeView.dislikeCard();
break;
}
case R.id.imgLike: {
mSwipeView.likeCard();
break;
}
}
}
#Override
public void onLikes() {
imageview.setDrawingCacheEnabled(true); //Add this line.
imageview.buildDrawingCache();
Bitmap bm=imageview.getDrawingCache();
OutputStream fOut = null;
Uri outputFileUri;
try {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "folder_name" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
MediaScannerConnection.scanFile(this, new String[] { sdImageMainDirectory.getAbsolutePath() }, null, null);
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e){}
System.out.println("An Card removed");
// Add a card if you needed after any previous card swiped
addCard(0);
}
#Override
public void onDisLikes() {
System.out.println("An Card removed");
// Add a card if you needed after any previous card swiped
addCard(0);
}
#Override
public void onSingleTap() {
}
/**
* Adds the card to the swipe.
*/
private void addCard(int position) {
final View cardView = LayoutInflater.from(this).inflate(
R.layout.item_swipe_view, null);
final ImageView imgMeal = (ImageView) cardView
.findViewById(R.id.imgMeals);
imgMeal.setImageResource(meals[count]);
count++;
if (count == meals.length) {
count = 0;
}
// Add a card to the swipe view..
mSwipeView.addCard(cardView, position);
// Create OnClickListener for the CookBookActivity
// Declare Button for the Cookbook
Button btn = (Button) findViewById(R.id.button3);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, CookbookActivity.class));
}
});
// Check Authentication
mRef = new Firebase(Constants.FIREBASE_URL);
if (mRef.getAuth() == null) {
loadLoginView();
}
}
private void loadLoginView() {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
The Library that i'm using for the swiping
//
// credits to IntelliJ IDEA
// (powered by Fernflower decompiler)
package com.rk.lib.view;
import android.content.Context;
import android.os.Handler;
import android.os.Build.VERSION;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnTouchListener;
import android.view.animation.AlphaAnimation;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.FrameLayout.LayoutParams;
public class SwipeView extends FrameLayout {
private View mFocusedView;
private View mFocusedViewLike;
private View mFocusedViewNope;
private int mFocusedViewWidth;
private float mPreviousAlpha = 0.0F;
private Integer mLikeResource = Integer.valueOf(0);
private Integer mNopeResource = Integer.valueOf(0);
private static final int MAX_ELEMENTS = 3;
private static final long DELAY_SCROLL_RUNNABLE = 1L;
private static final int SCROLL_LENGTH = 5;
private int mScrolledPixelsX;
private int mScrolledPixelsY;
private int mNeedToScrollX;
private int mNeedToScrollY;
private int mTotalScrolledX;
private int mTotalScrolledY;
private int mScrollLengthX = 5;
private int mScrollLengthY = 5;
private boolean enableTouchSwipe = true;
private Context mContext;
private SwipeView.ScrollMode mScrollModeX;
private SwipeView.ScrollMode mScrollModeY;
private SwipeView.ScrollDirection mScrollDirection;
private int[] paddingX;
private int[] paddingYTop;
private int[] paddingYBottom;
private SwipeView.OnCardSwipedListener mOnCardSwipedListener;
private Handler mScrollHandler;
private Runnable mScrollRunnable;
private final SimpleOnGestureListener simpleOnGestureListener;
public SwipeView(Context context, Integer likeResource, Integer nopeResource, SwipeView.OnCardSwipedListener cardSwipeListener) {
super(context);
this.mScrollModeX = SwipeView.ScrollMode.NONE;
this.mScrollModeY = SwipeView.ScrollMode.NONE;
this.mScrollDirection = SwipeView.ScrollDirection.NONE;
this.paddingX = new int[]{0, 10, 20};
this.paddingYTop = new int[]{0, 10, 20};
this.paddingYBottom = new int[]{20, 10, 0};
this.mScrollHandler = new Handler();
this.mScrollRunnable = new Runnable() {
public void run() {
boolean scrollX;
boolean scrollY;
int scrollX1;
int scrollY1;
if(SwipeView.this.mScrollDirection == SwipeView.ScrollDirection.OUT) {
if(SwipeView.this.mNeedToScrollX <= 0 && SwipeView.this.mNeedToScrollY <= 0) {
SwipeView.this.mScrollHandler.removeCallbacks(SwipeView.this.mScrollRunnable);
SwipeView.this.removeView(SwipeView.this.mFocusedView);
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
SwipeView.this.mOnCardSwipedListener.onLikes();
} else if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.RIGHT) {
SwipeView.this.mOnCardSwipedListener.onDisLikes();
}
SwipeView.this.alignCardsPadding();
} else {
if(SwipeView.this.mNeedToScrollX < SwipeView.this.mScrollLengthX) {
SwipeView.this.mScrollLengthX = SwipeView.this.mNeedToScrollX;
SwipeView.this.mNeedToScrollX = 0;
} else {
SwipeView.this.mNeedToScrollX = SwipeView.this.mNeedToScrollX - SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mNeedToScrollY < SwipeView.this.mScrollLengthY) {
SwipeView.this.mScrollLengthY = SwipeView.this.mNeedToScrollY;
SwipeView.this.mNeedToScrollY = 0;
} else {
SwipeView.this.mNeedToScrollY = SwipeView.this.mNeedToScrollY - SwipeView.this.mScrollLengthY;
}
scrollX = false;
scrollY = false;
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
scrollX1 = -SwipeView.this.mScrollLengthX;
} else {
scrollX1 = SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mScrollModeY == SwipeView.ScrollMode.TOP) {
scrollY1 = -SwipeView.this.mScrollLengthY;
} else {
scrollY1 = SwipeView.this.mScrollLengthY;
}
SwipeView.this.mFocusedView.scrollBy(scrollX1, scrollY1);
SwipeView.this.mScrollHandler.postDelayed(SwipeView.this.mScrollRunnable, 1L);
}
} else if(SwipeView.this.mScrollDirection == SwipeView.ScrollDirection.IN) {
if(SwipeView.this.mTotalScrolledX <= 0 && SwipeView.this.mTotalScrolledY <= 0) {
SwipeView.this.mScrollHandler.removeCallbacks(SwipeView.this.mScrollRunnable);
SwipeView.this.mScrollDirection = SwipeView.ScrollDirection.NONE;
} else {
if(SwipeView.this.mTotalScrolledX < SwipeView.this.mScrollLengthX) {
SwipeView.this.mScrollLengthX = SwipeView.this.mTotalScrolledX;
SwipeView.this.mTotalScrolledX = 0;
} else {
SwipeView.this.mTotalScrolledX = SwipeView.this.mTotalScrolledX - SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mTotalScrolledY < SwipeView.this.mScrollLengthY) {
SwipeView.this.mScrollLengthY = SwipeView.this.mTotalScrolledY;
SwipeView.this.mTotalScrolledY = 0;
} else {
SwipeView.this.mTotalScrolledY = SwipeView.this.mTotalScrolledY - SwipeView.this.mScrollLengthY;
}
scrollX = false;
scrollY = false;
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
scrollX1 = SwipeView.this.mScrollLengthX;
} else {
scrollX1 = -SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mScrollModeY == SwipeView.ScrollMode.TOP) {
scrollY1 = -SwipeView.this.mScrollLengthY;
} else {
scrollY1 = SwipeView.this.mScrollLengthY;
}
SwipeView.this.mFocusedView.scrollBy(scrollX1, scrollY1);
SwipeView.this.mScrollHandler.postDelayed(SwipeView.this.mScrollRunnable, 1L);
}
}
}
};
this.simpleOnGestureListener = new SimpleOnGestureListener() {
public boolean onSingleTapConfirmed(MotionEvent e) {
SwipeView.this.mOnCardSwipedListener.onSingleTap();
return super.onSingleTapConfirmed(e);
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if(SwipeView.this.mFocusedView != null) {
SwipeView.this.mScrolledPixelsX = SwipeView.this.mScrolledPixelsX + (int)distanceX;
SwipeView.this.mScrolledPixelsY = SwipeView.this.mScrolledPixelsY + (int)distanceY;
SwipeView.this.mFocusedView.scrollBy((int)distanceX, (int)distanceY);
float alpha = (float)SwipeView.this.mScrolledPixelsX / (float)SwipeView.this.mFocusedViewWidth;
if(alpha > 0.0F) {
SwipeView.this.mFocusedViewNope.setVisibility(0);
SwipeView.this.mFocusedViewLike.setVisibility(8);
SwipeView.setAlpha(SwipeView.this.mFocusedViewNope, SwipeView.this.mPreviousAlpha, alpha);
SwipeView.this.mPreviousAlpha = alpha;
} else {
SwipeView.this.mFocusedViewNope.setVisibility(8);
SwipeView.this.mFocusedViewLike.setVisibility(0);
SwipeView.setAlpha(SwipeView.this.mFocusedViewLike, SwipeView.this.mPreviousAlpha, -alpha);
SwipeView.this.mPreviousAlpha = -alpha;
}
}
return true;
}
};
this.mContext = context;
this.mLikeResource = likeResource;
this.mNopeResource = nopeResource;
this.mOnCardSwipedListener = cardSwipeListener;
float density = this.getResources().getDisplayMetrics().density;
for(int gestureDetector = 0; gestureDetector < this.paddingX.length; ++gestureDetector) {
this.paddingX[gestureDetector] = (int)((float)this.paddingX[gestureDetector] * density);
this.paddingYTop[gestureDetector] = (int)((float)this.paddingYTop[gestureDetector] * density);
this.paddingYBottom[gestureDetector] = (int)((float)this.paddingYBottom[gestureDetector] * density);
}
final GestureDetector var7 = new GestureDetector(this.mContext, this.simpleOnGestureListener);
this.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if(SwipeView.this.getChildCount() > 0) {
if(SwipeView.this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return false;
} else if(!SwipeView.this.enableTouchSwipe) {
return false;
} else {
var7.onTouchEvent(event);
switch(event.getAction()) {
case 0:
if(SwipeView.this.getChildCount() > 0) {
SwipeView.this.mFocusedView = SwipeView.this.getChildAt(SwipeView.this.getChildCount() - 1);
SwipeView.this.mFocusedViewLike = SwipeView.this.mFocusedView.findViewById(SwipeView.this.mLikeResource.intValue());
SwipeView.this.mFocusedViewNope = SwipeView.this.mFocusedView.findViewById(SwipeView.this.mNopeResource.intValue());
SwipeView.this.mFocusedViewWidth = SwipeView.this.mFocusedView.getWidth();
SwipeView.this.mFocusedView.setPadding(SwipeView.this.paddingX[0], 0, SwipeView.this.paddingX[0], 0);
}
SwipeView.this.resetScrollingValues();
break;
case 1:
SwipeView.this.alignCardsPadding();
if(SwipeView.this.mScrolledPixelsX < 0) {
SwipeView.this.mScrollModeX = SwipeView.ScrollMode.LEFT;
SwipeView.this.mTotalScrolledX = -SwipeView.this.mScrolledPixelsX;
} else {
SwipeView.this.mScrollModeX = SwipeView.ScrollMode.RIGHT;
SwipeView.this.mTotalScrolledX = SwipeView.this.mScrolledPixelsX;
}
if(SwipeView.this.mScrolledPixelsY < 0) {
SwipeView.this.mScrollModeY = SwipeView.ScrollMode.BOTTOM;
SwipeView.this.mTotalScrolledY = -SwipeView.this.mScrolledPixelsY;
} else {
SwipeView.this.mScrollModeY = SwipeView.ScrollMode.TOP;
SwipeView.this.mTotalScrolledY = SwipeView.this.mScrolledPixelsY;
}
SwipeView.this.detectSwipe();
}
return true;
}
} else {
return false;
}
}
});
}
public void addCard(View view, int position) {
if(this.getChildCount() <= 3 && position < 3) {
LinearLayout viewLayout = new LinearLayout(this.mContext);
viewLayout.setLayoutParams(new LayoutParams(-1, -1));
view.setLayoutParams(new LayoutParams(-1, -1));
viewLayout.addView(view);
viewLayout.setPadding(this.paddingX[position], this.paddingYTop[position], this.paddingX[position], this.paddingYBottom[position]);
this.addView(viewLayout, 0);
}
}
public void removeFocusedCard() {
this.removeView(this.mFocusedView);
this.alignCardsPadding();
}
private void alignCardsPadding() {
int i = 0;
for(int j = this.getChildCount() - 1; j >= 0; --j) {
this.getChildAt(j).setPadding(this.paddingX[i], this.paddingYTop[i], this.paddingX[i], this.paddingYBottom[i]);
++i;
}
this.mScrollDirection = SwipeView.ScrollDirection.NONE;
}
private void resetScrollingValues() {
this.mPreviousAlpha = 0.0F;
this.mNeedToScrollX = 0;
this.mScrolledPixelsX = 0;
this.mTotalScrolledX = 0;
this.mNeedToScrollY = 0;
this.mScrolledPixelsY = 0;
this.mTotalScrolledY = 0;
this.mScrollLengthX = 5;
this.mScrollLengthY = 5;
this.mScrollModeX = SwipeView.ScrollMode.NONE;
this.mScrollModeY = SwipeView.ScrollMode.NONE;
}
public void resetFocuedView() {
if(this.getChildCount() > 0) {
View mFocusedView = this.getChildAt(this.getChildCount() - 1);
View mFocusedViewLike = mFocusedView.findViewById(this.mLikeResource.intValue());
View mFocusedViewNope = mFocusedView.findViewById(this.mNopeResource.intValue());
setAlpha(mFocusedViewLike, 0.0F, 0.0F);
setAlpha(mFocusedViewNope, 0.0F, 0.0F);
mFocusedView.scrollTo(0, 0);
}
}
private void detectSwipe() {
int imageHalf = this.mFocusedView.getWidth() / 2;
this.mNeedToScrollX = this.mFocusedView.getWidth() - this.mTotalScrolledX;
if(this.mScrollDirection == SwipeView.ScrollDirection.NONE) {
if(this.mNeedToScrollX < imageHalf) {
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
} else {
this.mScrollDirection = SwipeView.ScrollDirection.IN;
setAlpha(this.mFocusedViewLike, 0.0F, 0.0F);
setAlpha(this.mFocusedViewNope, 0.0F, 0.0F);
}
}
this.mScrollHandler.post(this.mScrollRunnable);
}
public void likeCard() {
if(this.getChildCount() > 0) {
this.mFocusedView = this.getChildAt(this.getChildCount() - 1);
this.mFocusedViewLike = this.mFocusedView.findViewById(this.mLikeResource.intValue());
this.mFocusedViewNope = this.mFocusedView.findViewById(this.mNopeResource.intValue());
if(this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return;
}
this.resetScrollingValues();
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
this.mScrollModeX = SwipeView.ScrollMode.LEFT;
this.mFocusedViewLike.setVisibility(0);
setAlpha(this.mFocusedViewLike, 0.0F, 1.0F);
this.detectSwipe();
}
}
public void dislikeCard() {
if(this.getChildCount() > 0) {
this.mFocusedView = this.getChildAt(this.getChildCount() - 1);
this.mFocusedViewLike = this.mFocusedView.findViewById(this.mLikeResource.intValue());
this.mFocusedViewNope = this.mFocusedView.findViewById(this.mNopeResource.intValue());
if(this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return;
}
this.resetScrollingValues();
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
this.mScrollModeX = SwipeView.ScrollMode.RIGHT;
this.mFocusedViewNope.setVisibility(0);
setAlpha(this.mFocusedViewNope, 0.0F, 1.0F);
this.detectSwipe();
}
}
public void setTouchable(boolean touchable) {
this.enableTouchSwipe = touchable;
}
public static void setAlpha(View view, float fromAlpha, float toAlpha) {
if(VERSION.SDK_INT < 11) {
AlphaAnimation alphaAnimation = new AlphaAnimation(fromAlpha, toAlpha);
alphaAnimation.setDuration(0L);
alphaAnimation.setFillAfter(true);
view.startAnimation(alphaAnimation);
} else {
view.setAlpha(toAlpha);
}
}
public interface OnCardSwipedListener {
void onLikes();
void onDisLikes();
void onSingleTap();
}
private static enum ScrollDirection {
IN,
OUT,
NONE;
private ScrollDirection() {
}
}
private static enum ScrollMode {
LEFT,
RIGHT,
TOP,
BOTTOM,
NONE;
private ScrollMode() {
}
}
}
ATTEMPT #3
This is the code that i've tried but I keep getting the same result (read comment below what I have done:
FrameLayout view = (FrameLayout)findViewById(R.id.contentLayout);
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
I believe the image you are trying to save is getting removed during the onSwipe due to the library code. I think you need to move your code to before the onLike is called.
You're also attempting to get a bitmap from the cache of the entire layout, rather than the wanted ImageView here:
bm=contentLayout.getDrawingCache();
You'll want to get your current card view as a View, then, from my understanding of your code, the ID of your actual ImageView containing the expected bitmap is R.id.imgMeals, so I the suggest replacing the line:
bm=contentLayout.getDrawingCache();
with the following:
ImageView imageView = (ImageView) cardView.findViewById(R.id.imgMeals);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bm = drawable.getBitmap();
Move all of the below code from where you have it, to where I have marked //HERE!! in the following part of your code (or better, move it to a new method and call the method here).
// If the imageview of like is clicked
case R.id.imgLike: {
// HERE!!
// The imageview in the contentlayout will be swiped to the right
mSwipeView.likeCard();
break;
}
This is the code to me moved including the change I mention above:
View cardView = mSwipeView.getChildAt(mSwipeView.getChildCount() - 1);
ImageView imageView = (ImageView) cardView.findViewById(R.id.imgMeals);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bm = drawable.getBitmap();
OutputStream fOut = null;
try {
// Save on my sd card
File root = new File(Environment.getExternalStorageDirectory()
// Making a folder name Food Inspiration
+ File.separator + "Food Inspiration" + File.separator);
root.mkdirs();
File sdImageMainDirectory = null;
// Loop for having a different name for every image
int i = 0;
do {
sdImageMainDirectory = new File(root, "pic-" + i + ".png");
i++;
} while (sdImageMainDirectory.exists());
fOut = new FileOutputStream(sdImageMainDirectory);
// Updates the gallery of your phone with the folder and the "liked" images in it
MediaScannerConnection.scanFile(this, new String[] { sdImageMainDirectory.getAbsolutePath() }, null, null);
// If something goes wrong
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
// Compresses the actual bitmap image
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e){}

Not able to see files while opening file browser using AndroidFileBrowser Library

I am trying to make a File browser for which I am taking help of this library.
Now according their code I am trying to implement, it's opening the desired location in the cell, however I am only able to see directories not files. As instructed I have chosen the option to choose Files only still I am not able to see Files there. Below is the code I am using
Intent fileExploreIntent = new Intent(FileBrowserActivity.INTENT_ACTION_SELECT_DIR,
null, getActivity(), FileBrowserActivity.class
);
startActivityForResult(fileExploreIntent,1);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == 1) {
if(resultCode == getActivity().RESULT_OK) {
String newDir = data.getStringExtra(FileBrowserActivity.returnDirectoryParameter);
Toast.makeText( getActivity(), "Received path from file browser:"+newDir, Toast.LENGTH_LONG).show();
} else {//if(resultCode == this.RESULT_OK) {
Toast.makeText( getActivity(),"Received NO result from file browser",Toast.LENGTH_LONG).show();
}//END } else {//if(resultCode == this.RESULT_OK) {
}//if (requestCode == REQUEST_CODE_PICK_FILE_TO_SAVE_INTERNAL) {
super.onActivityResult(requestCode, resultCode, data);
}
Code for FileBrowserActivity is
public class FileBrowserActivity extends Activity {
// Intent Action Constants
public static final String INTENT_ACTION_SELECT_DIR = "com.afixi.xmppclientandroid.SELECT_DIRECTORY_ACTION";
public static final String INTENT_ACTION_SELECT_FILE = "com.afixi.xmppclientandroid.SELECT_FILE_ACTION";
// Intent parameters names constants
public static final String startDirectoryParameter = "com.afixi.xmppclientandroid.directoryPath";
public static final String returnDirectoryParameter = "com.afixi.xmppclientandroid.directoryPathRet";
public static final String returnFileParameter = "com.afixi.xmppclientandroid.filePathRet";
public static final String showCannotReadParameter = "com.afixi.xmppclientandroid.showCannotRead";
public static final String filterExtension = "com.afixi.xmppclientandroid.filterExtension";
// Stores names of traversed directories
ArrayList<String> pathDirsList = new ArrayList<String>();
// Check if the first level of the directory structure is the one showing
// private Boolean firstLvl = true;
private static final String LOGTAG = "F_PATH";
private List<Item> fileList = new ArrayList<Item>();
private File path = null;
private String chosenFile;
// private static final int DIALOG_LOAD_FILE = 1000;
ArrayAdapter<Item> adapter;
private boolean showHiddenFilesAndDirs = true;
private boolean directoryShownIsEmpty = false;
private String filterFileExtension = null;
// Action constants
private static int currentAction = -1;
private static final int SELECT_DIRECTORY = 1;
private static final int SELECT_FILE = 2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// In case of
// ua.com.vassiliev.androidfilebrowser.SELECT_DIRECTORY_ACTION
// Expects com.mburman.fileexplore.directoryPath parameter to
// point to the start folder.
// If empty or null, will start from SDcard root.
setContentView(R.layout.ua_com_vassiliev_filebrowser_layout);
// Set action for this activity
Intent thisInt = this.getIntent();
currentAction = SELECT_DIRECTORY;// This would be a default action in
// case not set by intent
if (thisInt.getAction().equalsIgnoreCase(INTENT_ACTION_SELECT_FILE)) {
Log.d(LOGTAG, "SELECT ACTION - SELECT FILE");
currentAction = SELECT_FILE;
}
showHiddenFilesAndDirs = thisInt.getBooleanExtra(
showCannotReadParameter, true);
filterFileExtension = thisInt.getStringExtra(filterExtension);
setInitialDirectory();
parseDirectoryPath();
loadFileList();
this.createFileListAdapter();
this.initializeButtons();
this.initializeFileListView();
updateCurrentDirectoryTextView();
Log.d(LOGTAG, path.getAbsolutePath());
}
private void setInitialDirectory() {
Intent thisInt = this.getIntent();
String requestedStartDir = thisInt
.getStringExtra(startDirectoryParameter);
if (requestedStartDir != null && requestedStartDir.length() > 0) {// if(requestedStartDir!=null
File tempFile = new File(requestedStartDir);
if (tempFile.isDirectory())
this.path = tempFile;
}// if(requestedStartDir!=null
if (this.path == null) {// No or invalid directory supplied in intent
// parameter
if (Environment.getExternalStorageDirectory().isDirectory()
&& Environment.getExternalStorageDirectory().canRead())
path = Environment.getExternalStorageDirectory();
else
path = new File("/");
}// if(this.path==null) {//No or invalid directory supplied in intent
// parameter
}// private void setInitialDirectory() {
private void parseDirectoryPath() {
pathDirsList.clear();
String pathString = path.getAbsolutePath();
String[] parts = pathString.split("/");
int i = 0;
while (i < parts.length) {
pathDirsList.add(parts[i]);
i++;
}
}
private void initializeButtons() {
Button upDirButton = (Button) this.findViewById(R.id.upDirectoryButton);
upDirButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d(LOGTAG, "onclick for upDirButton");
loadDirectoryUp();
loadFileList();
adapter.notifyDataSetChanged();
updateCurrentDirectoryTextView();
}
});// upDirButton.setOnClickListener(
Button selectFolderButton = (Button) this
.findViewById(R.id.selectCurrentDirectoryButton);
if (currentAction == SELECT_DIRECTORY) {
selectFolderButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d(LOGTAG, "onclick for selectFolderButton");
returnDirectoryFinishActivity();
}
});
} else {// if(currentAction == this.SELECT_DIRECTORY) {
selectFolderButton.setVisibility(View.GONE);
}// } else {//if(currentAction == this.SELECT_DIRECTORY) {
}// private void initializeButtons() {
private void loadDirectoryUp() {
// present directory removed from list
String s = pathDirsList.remove(pathDirsList.size() - 1);
// path modified to exclude present directory
path = new File(path.toString().substring(0,
path.toString().lastIndexOf(s)));
fileList.clear();
}
private void updateCurrentDirectoryTextView() {
int i = 0;
String curDirString = "";
while (i < pathDirsList.size()) {
curDirString += pathDirsList.get(i) + "/";
i++;
}
if (pathDirsList.size() == 0) {
((Button) this.findViewById(R.id.upDirectoryButton))
.setEnabled(false);
curDirString = "/";
} else
((Button) this.findViewById(R.id.upDirectoryButton))
.setEnabled(true);
long freeSpace = getFreeSpace(curDirString);
String formattedSpaceString = formatBytes(freeSpace);
if (freeSpace == 0) {
Log.d(LOGTAG, "NO FREE SPACE");
File currentDir = new File(curDirString);
if(!currentDir.canWrite())
formattedSpaceString = "NON Writable";
}
((Button) this.findViewById(R.id.selectCurrentDirectoryButton))
.setText("Select\n[" + formattedSpaceString
+ "]");
((TextView) this.findViewById(R.id.currentDirectoryTextView))
.setText("Current directory: " + curDirString);
}// END private void updateCurrentDirectoryTextView() {
private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
private void initializeFileListView() {
ListView lView = (ListView) this.findViewById(R.id.fileListView);
lView.setBackgroundColor(Color.LTGRAY);
LinearLayout.LayoutParams lParam = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
lParam.setMargins(15, 5, 15, 5);
lView.setAdapter(this.adapter);
lView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
chosenFile = fileList.get(position).file;
File sel = new File(path + "/" + chosenFile);
Log.d(LOGTAG, "Clicked:" + chosenFile);
if (sel.isDirectory()) {
if (sel.canRead()) {
// Adds chosen directory to list
pathDirsList.add(chosenFile);
path = new File(sel + "");
Log.d(LOGTAG, "Just reloading the list");
loadFileList();
adapter.notifyDataSetChanged();
updateCurrentDirectoryTextView();
Log.d(LOGTAG, path.getAbsolutePath());
} else {// if(sel.canRead()) {
showToast("Path does not exist or cannot be read");
}// } else {//if(sel.canRead()) {
}// if (sel.isDirectory()) {
// File picked or an empty directory message clicked
else {// if (sel.isDirectory()) {
Log.d(LOGTAG, "item clicked");
if (!directoryShownIsEmpty) {
Log.d(LOGTAG, "File selected:" + chosenFile);
returnFileFinishActivity(sel.getAbsolutePath());
}
}// else {//if (sel.isDirectory()) {
}// public void onClick(DialogInterface dialog, int which) {
});// lView.setOnClickListener(
}// private void initializeFileListView() {
private void returnDirectoryFinishActivity() {
Intent retIntent = new Intent();
retIntent.putExtra(returnDirectoryParameter, path.getAbsolutePath());
this.setResult(RESULT_OK, retIntent);
this.finish();
}// END private void returnDirectoryFinishActivity() {
private void returnFileFinishActivity(String filePath) {
Intent retIntent = new Intent();
retIntent.putExtra(returnFileParameter, filePath);
this.setResult(RESULT_OK, retIntent);
this.finish();
}// END private void returnDirectoryFinishActivity() {
private void loadFileList() {
try {
path.mkdirs();
} catch (SecurityException e) {
Log.e(LOGTAG, "unable to write on the sd card ");
}
fileList.clear();
if (path.exists() && path.canRead()) {
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
boolean showReadableFile = showHiddenFilesAndDirs
|| sel.canRead();
// Filters based on whether the file is hidden or not
if (currentAction == SELECT_DIRECTORY) {
return (sel.isDirectory() && showReadableFile);
}
if (currentAction == SELECT_FILE) {
// If it is a file check the extension if provided
if (sel.isFile() && filterFileExtension != null) {
return (showReadableFile && sel.getName().endsWith(
filterFileExtension));
}
return (showReadableFile);
}
return true;
}// public boolean accept(File dir, String filename) {
};// FilenameFilter filter = new FilenameFilter() {
String[] fList = path.list(filter);
this.directoryShownIsEmpty = false;
for (int i = 0; i < fList.length; i++) {
// Convert into file path
File sel = new File(path, fList[i]);
Log.d(LOGTAG,
"File:" + fList[i] + " readable:"
+ (Boolean.valueOf(sel.canRead())).toString());
int drawableID = R.drawable.file_icon;
boolean canRead = sel.canRead();
// Set drawables
if (sel.isDirectory()) {
if (canRead) {
drawableID = R.drawable.folder_icon;
} else {
drawableID = R.drawable.folder_icon_light;
}
}
fileList.add(i, new Item(fList[i], drawableID, canRead));
}// for (int i = 0; i < fList.length; i++) {
if (fileList.size() == 0) {
// Log.d(LOGTAG, "This directory is empty");
this.directoryShownIsEmpty = true;
fileList.add(0, new Item("Directory is empty", -1, true));
} else {// sort non empty list
Collections.sort(fileList, new ItemFileNameComparator());
}
} else {
Log.e(LOGTAG, "path does not exist or cannot be read");
}
// Log.d(TAG, "loadFileList finished");
}// private void loadFileList() {
private void createFileListAdapter() {
adapter = new ArrayAdapter<Item>(this,
android.R.layout.select_dialog_item, android.R.id.text1,
fileList) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// creates view
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view
.findViewById(android.R.id.text1);
// put the image on the text view
int drawableID = 0;
if (fileList.get(position).icon != -1) {
// If icon == -1, then directory is empty
drawableID = fileList.get(position).icon;
}
textView.setCompoundDrawablesWithIntrinsicBounds(drawableID, 0,
0, 0);
textView.setEllipsize(null);
// add margin between image and text (support various screen
// densities)
// int dp5 = (int) (5 *
// getResources().getDisplayMetrics().density + 0.5f);
int dp3 = (int) (3 * getResources().getDisplayMetrics().density + 0.5f);
// TODO: change next line for empty directory, so text will be
// centered
textView.setCompoundDrawablePadding(dp3);
textView.setBackgroundColor(Color.LTGRAY);
return view;
}// public View getView(int position, View convertView, ViewGroup
};// adapter = new ArrayAdapter<Item>(this,
}// private createFileListAdapter(){
private class Item {
public String file;
public int icon;
public boolean canRead;
public Item(String file, Integer icon, boolean canRead) {
this.file = file;
this.icon = icon;
}
#Override
public String toString() {
return file;
}
}// END private class Item {
private class ItemFileNameComparator implements Comparator<Item> {
public int compare(Item lhs, Item rhs) {
return lhs.file.toLowerCase().compareTo(rhs.file.toLowerCase());
}
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Log.d(LOGTAG, "ORIENTATION_LANDSCAPE");
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
Log.d(LOGTAG, "ORIENTATION_PORTRAIT");
}
// Layout apparently changes itself, only have to provide good onMeasure
// in custom components
// TODO: check with keyboard
// if(newConfig.keyboard == Configuration.KEYBOARDHIDDEN_YES)
}// END public void onConfigurationChanged(Configuration newConfig) {
public static long getFreeSpace(String path) {
StatFs stat = new StatFs(path);
long availSize = (long) stat.getAvailableBlocks()
* (long) stat.getBlockSize();
return availSize;
}// END public static long getFreeSpace(String path) {
public static String formatBytes(long bytes) {
// TODO: add flag to which part is needed (e.g. GB, MB, KB or bytes)
String retStr = "";
// One binary gigabyte equals 1,073,741,824 bytes.
if (bytes > 1073741824) {// Add GB
long gbs = bytes / 1073741824;
retStr += (new Long(gbs)).toString() + "GB ";
bytes = bytes - (gbs * 1073741824);
}
// One MB - 1048576 bytes
if (bytes > 1048576) {// Add GB
long mbs = bytes / 1048576;
retStr += (new Long(mbs)).toString() + "MB ";
bytes = bytes - (mbs * 1048576);
}
if (bytes > 1024) {
long kbs = bytes / 1024;
retStr += (new Long(kbs)).toString() + "KB";
bytes = bytes - (kbs * 1024);
} else
retStr += (new Long(bytes)).toString() + " bytes";
return retStr;
}// public static String formatBytes(long bytes){
}// END public class FileBrowserActivity extends Activity {

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