片段对getResources()的IllegalStatexception

时间:2017-12-08 22:29:41

标签: android fragment illegalstateexception

我在 int pid; int in = 0, out = 0, append = 0, j; int fd0, fd1, fda; char* args[MAX_ARGS]; char inFileName[64], outFileName[64]; //used to get arguements for desired command //i.e. ls -a -l -t get_args(cmdline, args); //Commands used to exit the shell. if(!strcmp(args[0], "quit") || !strcmp(args[0], "exit")) { exit(0); } pid = fork(); if(pid == 0) { /* child process */ for(j = 0; args[j] != '\0'; ++j) { if(strcmp(args[j], ">>") == 0) { args[j] = NULL; strcpy(outFileName, args[j + 1]); printf("You want to append data to existing file\n"); append = 2; } if(strcmp(args[j], "<") == 0) { args[j] = NULL; strcpy(inFileName, args[j + 1]); printf("input file name is %s\n", inFileName); in = 2; } if(strcmp(args[j], ">") == 0) { args[j] = NULL; strcpy(outFileName, args[j + 1]); printf("output file name is %s\n", outFileName); out = 2; } } //printf("in is %d and out is %d\n", in, out); if(!strcmp(args[0], "|")) { printf("You want to pipe info\n"); } if(append) { **//here is where my issue occurs** if((fda = open(outFileName, O_RDWR|O_APPEND)) < 0) { perror("Error appending data\n"); exit(0); } dup2(fda, STDOUT_FILENO);//1 close(fda); } if(in) { if((fd0 = open(inFileName, O_RDONLY, 0)) < 0) { perror("Couldn't read from input file\n"); exit(0); } //Changes where the command will read from STDIN to a input file. dup2(fd0, 0); close(fd0); } if(out) { if((fd1 = creat(outFileName , 0644)) < 0) { perror("Coudln't create output file\n"); exit(0); } dup2(fd1, STDOUT_FILENO);//1 close(fd1); } execvp(*args, args); perror("exec failed"); exit(-1); } else if(pid > 0) { /* parent process */ waitpid(pid, NULL, 0); } else { /* error occurred */ perror("fork failed"); exit(1); } 内有这一行:

SubCategoryFragment

我的理解是通过添加SubCategoryFragment.this来防止IllegalStatexception。

这是s.group_name = SubCategoryFragment.this.getResources().getString(R.string.everything_else); // line 315 in stacktrace 。当有人点击此片段中的列表项并转到另一个列表项时,会发生这种情况;然后点击后退按钮并返回ListFragmentSubCategoryFragment上面这一行的最终位置。

我在onActivityCreated()内没有做与此相关的任何事情。

onDetach()

1 个答案:

答案 0 :(得分:1)

Fragment.getResources()是一个便捷调用,可以从您的片段当前所附加的Resources内抓取Activity个对象。如果您的片段未附加到任何活动,则会抛出IllegalStateException

SubCategoryFragment.this.getResources()getResources()进行通话不会有任何区别。

这个问题有两种可能的解决方案。第一种方法是将呼叫转移到保证您的片段将附加到某些活动的位置。另一种是从片段以外的某个地方获取Resources对象(因此片段的活动)。如果您有权访问其他Context个对象(可能有View,则可以致电View.getContext()),您可以致电Context.getResources()