我正在动态创建一个表,并将其保存在同一活动的文件中。时间表是根据用户输入创建的。
修改: - 这是我的课程,我正在为时间表生成动态布局。
public class CreateTimeTable extends Activity {
public static String[] tokens= new String[100];
public static int a,b;
Context con=this;
public int m,n,prod;
public final static String SAVETT="SAVETT.txt";
public static String str1="null";
public static String str2="\t";
public static String message="abc";
public static String message2="abc";
public static String EXTRA_MESSAGE="abc";
public static String str3="\n";
DatabaseHandler db =new DatabaseHandler(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_time_table);
// Get the message from the intent
Intent intent = getIntent();
message = intent.getStringExtra(NewTT.EXTRA_MESSAGE); //day
message2 = intent.getStringExtra(NewTT.INPUT_SERVICE); //lec
int lec = Integer.parseInt(message2);
int day = Integer.parseInt(message);
Button bt = new Button(this);
a=lec; b=day;
m =lec+1;
n =day+1;
prod=m*n;
ScrollView sv = new ScrollView(this);
sv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
TableLayout ll=new TableLayout(this);
HorizontalScrollView hsv = new HorizontalScrollView(this);
int t=0;
if(day==1)
{for(int i=-1;i<=lec;i++)
{ TableRow trow=new TableRow(this);
if(i==-1)
{ EditText tv1=new EditText(this);
EditText tv2=new EditText(this);
tv1.setText(" TIME ");
tv1.setId(t);
tv1.setEnabled(false);
tv1.setFocusable(false);
t++;
tv1.setTextSize(30);
tv1.setBackgroundResource(R.drawable.cell_shape);
trow.addView(tv1);
tv2.setText(" MONDAY ");
tv2.setTextSize(30);
tv2.setId(t);
tv2.setEnabled(false);
tv2.setFocusable(false);
t++;
tv2.setBackgroundResource(R.drawable.cell_shape);
trow.addView(tv2);
}
else if (i==lec)
{
bt.setText("SAVE");
bt.setTextSize(30);
trow.addView(bt);
}
else
{EditText e1=new EditText(this);
e1.setId(t);
e1.setTextSize(30);
t++;
e1.setBackgroundResource(R.drawable.cell_shape);
trow.addView(e1);
EditText e2=new EditText(this);
e2.setId(t);
t++;
e2.setTextSize(30);
e2.setBackgroundResource(R.drawable.cell_shape);
trow.addView(e2);
}
ll.addView(trow);
View v = new View(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 5);
v.setLayoutParams(params);
v.setBackgroundColor(getResources().getColor(android.R.color.transparent));
ll.addView(v);
}
}
// Similar 6 cases
}
hsv.addView(ll);
sv.addView(hsv);
sv.setBackgroundResource(R.drawable.blackboard);
setContentView(sv);
// Button that calls asynctask to save file
bt.setOnClickListener(new View.OnClickListener()
{ public void onClick(View view)
{
SaveFile sf = new SaveFile();
sf.execute(new String[] {"SAVETT.txt"});
Intent k = new Intent(getApplicationContext(), MainActivity.class);
k.addFlags(k.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(k);
}
}); }
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.create_time_table, menu);
return true;
}
private class SaveFile extends AsyncTask<String, Void, String>
{
protected String doInBackground(String... name)
{ String inputString ="abc";
System.out.println("Inside AsyncTask/n File Name is" + name[0]);
int i=0;
int t=0;
try
{ FileOutputStream fos = openFileOutput(name[0],Context.MODE_PRIVATE);
while(prod>0)
{ if(t%n==0)
{
EditText editText = (EditText) findViewById(t);
str1= editText.getText().toString();
fos.write(str1.getBytes());
fos.write("\t".getBytes());
t++;
}
else
{
EditText editText = (EditText) findViewById(t);
str1= editText.getText().toString();
fos.write(str1.getBytes());
fos.write("\t".getBytes());
t++;
}
prod--;
}
fos.close();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(
openFileInput(name[0])));
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null)
{
stringBuffer.append(inputString + "\n");
StringTokenizer tokenizer = new StringTokenizer(inputString);
int count = tokenizer.countTokens();
String[] arr = new String[tokenizer.countTokens()];
while(tokenizer.hasMoreElements())
{
arr[i]= tokenizer.nextToken();
i++;
}
i=0;
while(i<count)
{ System.out.println(arr[i]+"\n");
tokens[i]=arr[i];
i++;
}
}
}
catch( IOException e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result)
{
System.out.println("Starting Service " + a + b);
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(getApplicationContext(), Service_Notification.class);
intent.putExtra("DAYS",b);
int requestCode = (int) System.currentTimeMillis();
PendingIntent pintent = PendingIntent.getService(getApplicationContext(), requestCode, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
// Start every 60 seconds
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 60*1000, pintent);
ComponentName receiver = new ComponentName(getApplicationContext(), BootReciever.class);
PackageManager pm = getApplicationContext().getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
}
}
当我点击保存按钮时,会创建一个文件并保存内容。现在,因为我使用的是Asynctask,所以文件创建完美。但是当我在onPostExecute中启动一个服务时,问题就出现了,程序显示了一个logcat错误循环,如下所示:
03-17 04:15:51.605: W/System.err(3730): at android.os.Looper.loop(Looper.java:137)
03-17 04:15:51.605: W/System.err(3730): at android.app.ActivityThread.main(ActivityThread.java:5103)
03-17 04:15:51.605: W/System.err(3730): at java.lang.reflect.Method.invokeNative(Native Method)
03-17 04:15:51.616: W/System.err(3730): at java.lang.reflect.Method.invoke(Method.java:525)
03-17 04:15:51.616: W/System.err(3730): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-17 04:15:51.625: W/System.err(3730): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-17 04:15:51.625: W/System.err(3730): at dalvik.system.NativeStart.main(Native Method)
03-17 04:15:51.635: W/System.err(3730): java.text.ParseException: Unparseable date: "d" (at offset 0)
03-17 04:15:51.635: W/System.err(3730): at java.text.DateFormat.parse(DateFormat.java:555)
03-17 04:15:51.645: W/System.err(3730): at com.example.eduhub.Service_Notification.onStartCommand(Service_Notification.java:98)
03-17 04:15:51.645: W/System.err(3730): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2704)
03-17 04:15:51.645: W/System.err(3730): at android.app.ActivityThread.access$1900(ActivityThread.java:141)
03-17 04:15:51.655: W/System.err(3730): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1353)
03-17 04:15:51.655: W/System.err(3730): at android.os.Handler.dispatchMessage(Handler.java:99)
03-17 04:15:51.655: W/System.err(3730): at android.os.Looper.loop(Looper.java:137)
03-17 04:15:51.655: W/System.err(3730): at android.app.ActivityThread.main(ActivityThread.java:5103)
03-17 04:15:51.655: W/System.err(3730): at java.lang.reflect.Method.invokeNative(Native Method)
03-17 04:15:51.655: W/System.err(3730): at java.lang.reflect.Method.invoke(Method.java:525)
03-17 04:15:51.655: W/System.err(3730): at com.android.internal.os.ZygoteInit$Meth
我的服务类如下:
public class Service_Notification extends Service
{ boolean i = true;
Context c = this;
CreateTimeTable obj = new CreateTimeTable();
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
NotificationManager nm = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Resources res = this.getResources();
Notification.Builder builder = new Notification.Builder(this);
String inputString;
String[] alarm= new String[100];
int days = obj.b;
int lecs = obj.a;
System.out.println(" A is " + lecs + "B is "+ days);
int time;
int i=lecs,k=0;
long minutes;
long hours;
File name = new File(getFilesDir()+"/SAVETT.txt");
Calendar calendar = Calendar.getInstance();
int today = calendar.get(calendar.DAY_OF_WEEK);
long hour=calendar.get(calendar.HOUR_OF_DAY);
long min=calendar.get(calendar.MINUTE);
try{
if(name.exists())
{
BufferedReader inputReader = new BufferedReader(new InputStreamReader(
openFileInput("SAVETT.txt")));
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null)
{
stringBuffer.append(inputString + "\n");
StringTokenizer tokenizer = new StringTokenizer(inputString);
int count = tokenizer.countTokens();
String[] arr = new String[tokenizer.countTokens()];
while(tokenizer.hasMoreElements())
{
arr[k]= tokenizer.nextToken();
k++;
}
k=0;
while(k<count)
{ System.out.println(arr[k]+"\n");
alarm[k]=arr[k];
k++;
}
}
System.out.println("Days:"+ days );
System.out.println("Lecs"+ lecs );
if(days!=0 && lecs!=0)
{
switch (today)
{
case 2: time = days+1;
while(i>0)
{
String str = alarm[time];
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm");
try {
Date date = (Date)formatter.parse(str);
Calendar c2 = GregorianCalendar.getInstance(); // creates a new calendar instance
c2.setTime(date); // assigns calendar to given date
hours=c2.get(Calendar.HOUR_OF_DAY); // gets hour in 24h format
minutes=c2.get(Calendar.MINUTE);
System.out.println("TIME TABLE Hour:" + hours);
System.out.println("TIME TABLE minutes:" + minutes);
if(hours==hour && min==minutes)
{
Intent notificationIntent = new Intent(this, Attendance.class);
notificationIntent.putExtra("class",alarm[time+1]);
PendingIntent contentIntent = PendingIntent.getActivity(this,
0, notificationIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_launcher))
.setTicker(res.getString(R.string.Cal))
.setWhen(System.currentTimeMillis())
.setContentTitle("You Have a Lecture !!")
.setAutoCancel(true)
//.addAction(R.drawable.cross,"Cancel", btPendingIntent)
//.addAction(R.drawable.attn,"Attend" ,pIn)
.setLights(0xff00ff00,1000 * 6,1000*6)
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
.setContentText(alarm[time+1]);
Notification n = builder.getNotification();
nm.notify(0, n);
}
i--;
time=time+days;
}
catch (java.text.ParseException e) {
e.printStackTrace();
}
}
break;
case 3: time = days+1;
while(i>0)
{
String str = alarm[time];
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm");
try {
Date date = (Date)formatter.parse(str);
Calendar c2 = GregorianCalendar.getInstance(); // creates a new calendar instance
c2.setTime(date); // assigns calendar to given date
hours=c2.get(Calendar.HOUR_OF_DAY); // gets hour in 24h format
minutes=c2.get(Calendar.MINUTE);
System.out.println("TIME TABLE Hour:" + hours);
System.out.println("TIME TABLE minutes:" + minutes);
if(hours==hour && min==minutes)
{
Intent notificationIntent = new Intent(this, Attendance.class);
notificationIntent.putExtra("class",alarm[time+2]);
PendingIntent contentIntent = PendingIntent.getActivity(this,
0, notificationIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
/*Intent in = new Intent(getApplicationContext(), Record.class);
in.putExtra("class",alarm[time+1]);
PendingIntent pIn = PendingIntent.getBroadcast(getApplicationContext(), 0, in,0);
*/
builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.ic_books)
.setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_launcher))
.setTicker(res.getString(R.string.Cal))
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentTitle("You Have a Lecture !!")
//.addAction(R.drawable.cross, "Cancell", btPendingIntent)
//.addAction(R.drawable.attn,"Attending",pIn)
.setLights(0xff00ff00,1000 * 6,1000*6)
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
.setContentText(alarm[time+2]);
Notification n = builder.getNotification();
nm.notify(0, n);
}
i--;
time=time+days;
}
catch (java.text.ParseException e) {
e.printStackTrace();
}
}
break;
case 4: time = days+1;
while(i>0)
{
String str = alarm[time];
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm");
try {
Date date = (Date)formatter.parse(str);
Calendar c2 = GregorianCalendar.getInstance(); // creates a new calendar instance
c2.setTime(date); // assigns calendar to given date
hours=c2.get(Calendar.HOUR_OF_DAY); // gets hour in 24h format
minutes=c2.get(Calendar.MINUTE);
System.out.println("TIME TABLE Hour:" + hours);
System.out.println("TIME TABLE minute:" + minutes);
if(hours==hour && min==minutes)
{
Intent notificationIntent = new Intent(this, Attendance.class);
notificationIntent.putExtra("class",alarm[time+3]);
PendingIntent contentIntent = PendingIntent.getActivity(this,
0, notificationIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
/*Intent in = new Intent(getApplicationContext(), Record.class);
in.putExtra("class",alarm[time+1]);
PendingIntent pIn = PendingIntent.getBroadcast(getApplicationContext(), 0, in,0);*/
builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.ic_books)
.setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_launcher))
.setTicker(res.getString(R.string.Cal))
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentTitle("You Have a Lecture !!")
// .addAction(R.drawable.cross, "Cancell", btPendingIntent)
//.addAction(R.drawable.attn,"Attending",pIn)
.setLights(0xff00ff00,1000 * 6,1000*6)
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
.setContentText(alarm[time+3]);
Notification n = builder.getNotification();
nm.notify(0, n);
}
i--;
time=time+days;
}
catch (java.text.ParseException e) {
e.printStackTrace();
}
}
break;
case 5: time = days+1;
while(i>0)
{
String str = alarm[time];
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm");
try {
Date date = (Date)formatter.parse(str);
Calendar c2 = GregorianCalendar.getInstance(); // creates a new calendar instance
c2.setTime(date); // assigns calendar to given date
hours=c2.get(Calendar.HOUR_OF_DAY); // gets hour in 24h format
minutes=c2.get(Calendar.MINUTE);
System.out.println("TIME TABLE Hour:" + hours);
System.out.println("TIME TABLE minute:" + minutes);
if(hours==hour && min==minutes)
{
Intent notificationIntent = new Intent(this, Attendance.class);
notificationIntent.putExtra("class",alarm[time+4]);
PendingIntent contentIntent = PendingIntent.getActivity(this,
0, notificationIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
/*Intent in = new Intent(getApplicationContext(), Record.class);
in.putExtra("class",alarm[time+1]);
PendingIntent pIn = PendingIntent.getBroadcast(getApplicationContext(), 0, in,0);
*/
builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.ic_books)
.setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_launcher))
.setTicker(res.getString(R.string.Cal))
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentTitle("You Have a Lecture !!")
//.addAction(R.drawable.cross, "Cancell", btPendingIntent)
//.addAction(R.drawable.attn,"Attending",pIn)
.setLights(0xff00ff00,1000 * 6,1000*6)
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
.setContentText(alarm[time+4]);
Notification n = builder.getNotification();
nm.notify(0, n);
}
i--;
time=days;
}
catch (java.text.ParseException e) {
e.printStackTrace();
}
}
break;
case 6: time = days+1;
while(i>0)
{
String str = alarm[time];
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm");
try {
Date date = (Date)formatter.parse(str);
Calendar c2 = GregorianCalendar.getInstance(); // creates a new calendar instance
c2.setTime(date); // assigns calendar to given date
hours=c2.get(c2.HOUR_OF_DAY); // gets hour in 24h format
minutes=c2.get(c2.MINUTE);
System.out.println("TIME TABLE Hour:" + hours);
System.out.println("TIME TABLE minute:" + minutes);
if(hours==hour && min==minutes)
{
Intent notificationIntent = new Intent(this, Attendance.class);
notificationIntent.putExtra("class",alarm[time+5]);
PendingIntent contentIntent = PendingIntent.getActivity(this,
0, notificationIntent,
PendingIntent.FLAG_CANCEL_CURRENT); builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.ic_books)
.setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_launcher))
.setTicker(res.getString(R.string.Cal))
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentTitle("You Have a Lecture !!")
//.addAction(R.drawable.cross, "Cancell", btPendingIntent)
//.addAction(R.drawable.attn,"Attending",pIn)
.setLights(0xff00ff00,1000 * 6,1000*6)
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
.setContentText(alarm[time+5]);
Notification n = builder.getNotification();
nm.notify(0, n);
}
i--;
time=time+days;
}
catch (java.text.ParseException e) {
e.printStackTrace();
}
}
break;
case 7:
time = days+1;
while(i>0)
{
String str = alarm[time];
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm");
try {
Date date = (Date)formatter.parse(str);
Calendar c2 = GregorianCalendar.getInstance(); // creates a new calendar instance
c2.setTime(date); // assigns calendar to given date
hours=c2.get(Calendar.HOUR_OF_DAY); // gets hour in 24h format
minutes=c2.get(Calendar.MINUTE);
System.out.println("TIME TABLE Hour:" + hours);
System.out.println("TIME TABLE minute:" + minutes);if(hours==hour && min==minutes)
{
Intent notificationIntent = new Intent(this, Attendance.class);
notificationIntent.putExtra("class",alarm[time+6]);
PendingIntent contentIntent = PendingIntent.getActivity(this,
0, notificationIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
/*Intent in = new Intent(getApplicationContext(), Record.class);
in.putExtra("class",alarm[time+1]);
PendingIntent pIn = PendingIntent.getBroadcast(getApplicationContext(), 0, in,0);
*/
builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.ic_books)
.setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_launcher))
.setTicker(res.getString(R.string.Cal))
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentTitle("You Have a Lecture !!")
//.addAction(R.drawable.cross, "Cancell", btPendingIntent)
// .addAction(R.drawable.attn,"Attending",pIn)
.setLights(0xff00ff00,1000 * 6,1000*6)
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
.setContentText(alarm[time+6]);
Notification n = builder.getNotification();
nm.notify(0, n);
}
i--;
time=time+days;
}
catch (java.text.ParseException e) {
e.printStackTrace();
}
}
break;
}
}
}
}
catch(IOException e)
{
e.printStackTrace();
}
return Service.START_REDELIVER_INTENT;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
无法弄清楚问题所在。 ;(请帮助
答案 0 :(得分:0)
当应用程序在应用程序主线程(UI线程)上执行代码时,会出现ANR对话框,执行该代码的时间不合理。
在某些情况下,不合理的时间可能只是几毫秒...... onClick
方法,与任何其他View
组件回调一样 - 在应用程序主线程上执行。
基本上,你正在做one of the few worst things can be done from main thread - 执行IO文件操作!如果这还不够 - 如果您的prod
参数从未丰富条件,或者可能重复数千次,那么您的while循环可能会进入无限循环。
你应该从一个单独的线程执行IO文件操作,使用android API允许它such AsyncTask
class。
第二件事 - 再次检查运行时prod
的值是多少。我不知道你试图通过这个while循环完成什么,但它闻起来像麻烦..