2013-10-03 1 views
0

모든 기능이 제대로 실행되고 있지만 하루에 대한 세부 정보를 기록하고 탭을 기록 탭으로 전환하면 하나의 문제 만 존재합니다. 새 레코드를 보면 히스토리 클래스의 뷰리스트에 해당 레코드가 표시되어야합니다. 그러나보기 목록 은 최신 레코드을 표시하지 않으며 데이터베이스를 검사하면 최신 레코드가 데이터베이스에 기록됩니다. 새 레코드를 보는 유일한 방법은 에뮬레이터를 닫고 다시 시작하는 것입니다.같은 페이지에서 변경, 두 번째 시간 OnCreate() 작동하지 않습니다

I 시작시 레코더와 기록 탭이 모두 OnCreate() 메서드에서 초기화된다는 문제가 발견되었습니다. 하지만이 두 탭 사이를 전환하면 초기화되지 않습니다. 따라서 history.class에서 데이터베이스를 열어 데이터를 읽지는 않습니다. 그것이 문제이다. 누군가가 감사

, 좀 도와 주 시겠어요

탭 프로토 타입 클래스

package com.example.tabpro; 

import android.app.TabActivity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.widget.TabHost; 
import android.widget.TabHost.OnTabChangeListener; 
import android.widget.TabHost.TabSpec; 

public class TabBar extends TabActivity{ 

static TabHost tabHost=null; 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.tab); 

    tabHost = (TabHost)findViewById(android.R.id.tabhost); 

    tabHost = getTabHost(); 
    Intent recorderIntent = new Intent(TabBar.this, Recorder.class); 
    TabSpec recorderTabSpec = tabHost.newTabSpec("tab1"); 
    recorderTabSpec.setIndicator("Recorder"); 
    recorderTabSpec.setContent(recorderIntent); 
    tabHost.addTab(recorderTabSpec); 

    Intent historyIntent = new Intent(TabBar.this,History.class); 
    TabSpec historyTabSpec = tabHost.newTabSpec("tab2"); 
    historyTabSpec.setIndicator("History"); 
    historyTabSpec.setContent(historyIntent); 
    tabHost.addTab(historyTabSpec); 

    tabHost.setCurrentTab(0); 


} 
public void switchTab(int tab) 
{ 
    tabHost.setCurrentTab(tab); 
} 
} 

Recorder.class

package com.example.tabpro; 

import java.util.Calendar; 

import android.app.Activity; 
import android.app.DatePickerDialog; 
import android.app.Dialog; 
import android.app.DatePickerDialog.OnDateSetListener; 
import android.content.Intent; 
import android.database.Cursor; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.DatePicker; 
import android.widget.SeekBar; 
import android.widget.SeekBar.OnSeekBarChangeListener; 
import android.widget.TabHost; 
import android.widget.TextView; 
import android.widget.Toast; 

public class Recorder extends Activity implements OnSeekBarChangeListener { 


int mYear; 
int mMonth; 
int mDay; 


TextView dateDisplay; 
Button pickDateButton; 

TextView sbHourValue; 
TextView sbMinValue; 

int hours; 
int mins; 

static final int DATE_DIALOG_ID = 0; 



public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.recorder); 

    initialDatePicker(); 
    initialSeekBar(); 
    initialSaveButton(); 

} 

public void initialDatePicker() 
{ 
    dateDisplay = (TextView)findViewById(R.id.dateDisplay); 
    pickDateButton = (Button)findViewById(R.id.pickDate); 
    pickDateButton.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      showDialog(DATE_DIALOG_ID); 
     } 
    }); 

    final Calendar currentDate = Calendar.getInstance(); 
    mYear = currentDate.get(Calendar.YEAR); 
    mMonth = currentDate.get(Calendar.MONTH); 
    mDay = currentDate.get(Calendar.DAY_OF_MONTH); 
    dateDisplay.setText(new StringBuilder() 
       .append(mYear).append("-") 
       .append(mMonth + 1).append("-") 
       .append(mDay)); 


} 

public DatePickerDialog.OnDateSetListener mDateSetListener = new OnDateSetListener() { 
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { 
     mYear = year; 
     mMonth = monthOfYear; 
     mDay = dayOfMonth; 

     dateDisplay.setText(new StringBuilder() 
        .append(mYear).append("-") 
        .append(mMonth + 1).append("-")//start from 0 
        .append(mDay)); 
    } 
}; 

protected Dialog onCreateDialog(int id){ 
    switch(id) 
    { 
    case DATE_DIALOG_ID: 
     return new DatePickerDialog(this,mDateSetListener,mYear, mMonth, mDay); 
    } 
    return null; 
} 



public void initialSeekBar() 
{ 
    SeekBar sbHour = (SeekBar)findViewById(R.id.seekBar_hour); 
    sbHour.setMax(23); 
    sbHour.setProgress(0); 
    sbHour.setOnSeekBarChangeListener(this); 
    sbHourValue = (TextView)findViewById(R.id.textView_hour); 
    sbHourValue.setText("0"+ " hour(s)"); 

    SeekBar sbMin = (SeekBar)findViewById(R.id.seekBar_min); 
    sbMin.setMax(59); 
    sbMin.setProgress(0); 
    sbMin.setOnSeekBarChangeListener(this); 
    sbMinValue = (TextView)findViewById(R.id.TextView_min); 
    sbMinValue.setText("0" + " minute(s)"); 
} 

public void initialSaveButton() 
{ 

    Button saveButton = (Button)findViewById(R.id.button_save); 

    saveButton.setOnClickListener(new View.OnClickListener(){ 

     @Override 
     public void onClick(View arg0) { 
      // TODO Auto-generated method stub 
      String time; 
      String date; 

      date = dateDisplay.getText().toString(); 
      time = hours + " hour(s) " + mins + " minute(s)"; 


      TabProDB db; 
      db = new TabProDB(Recorder.this); 
      db.open(); 

      boolean findSameDay = false; 
      Cursor c = db.GetAllRecords(); 

       if(c!=null) 
       { 
        if (c.moveToFirst()) 
        { 
        do { 
         String dateToCompare = c.getString(c.getColumnIndex(TabProDB.KEY_DATE)); 
         if(dateToCompare.equalsIgnoreCase(date)) 
         { 
          findSameDay = true; 
         } 
        } while (c.moveToNext()); 
        } 
       } 
      if(findSameDay!=true) 
      { 
       long id = db.insertRecord(date, time); 
       db.close(); 
       Toast.makeText(Recorder.this, "Record Saved" , Toast.LENGTH_SHORT).show(); 
      } 
      else 
      { 
       Toast.makeText(Recorder.this, "You have already recorded the today: " + date, Toast.LENGTH_SHORT).show(); 
       db.close(); 
      } 
      switchTabInActivity(1); 
     } 

    }); 

} 

public void switchTabInActivity(int index) 
{ 
    TabBar parentActivity; 
    parentActivity = (TabBar)this.getParent(); 
    parentActivity.switchTab(index); 

} 

@Override 
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) { 
// TODO Auto-generated method stub 
if(arg0.getId() == R.id.seekBar_hour){ 
    // update hour value 
    hours = arg1; 
    sbHourValue.setText(Integer.toString(arg1)+" hour(s)"); 

} 
else{ 
    // update minute value 
    mins = arg1; 
    sbMinValue.setText(Integer.toString(arg1)+" minute(s)"); 
}  
} 

@Override 
public void onStartTrackingTouch(SeekBar arg0) { 
    // TODO Auto-generated method stub 

} 

@Override 
public void onStopTrackingTouch(SeekBar arg0) { 
    // TODO Auto-generated method stub 

} 
} 

History.class

package com.example.tabpro; 

import java.util.ArrayList; 

import android.app.Activity; 
import android.app.AlertDialog; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.database.Cursor; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemClickListener; 
import android.widget.AdapterView.OnItemLongClickListener; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 
import android.widget.TextView; 
import android.widget.Toast; 

public class History extends Activity implements OnItemClickListener { 


int getdbID; 
String Date; 
String Time; 
ListView date_time_ListView; 
ArrayList<String> listItems = null; 
ArrayAdapter arrayAdapter = null; 

public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.history); 

    date_time_ListView = (ListView) findViewById(R.id.listView1); 

    TabProDB db = new TabProDB(this); 

     try{ 
      listItems = new ArrayList<String>(); 
      db.open(); 
      Cursor c = db.GetAllRecords(); 
      if(c!=null) 
      { 
       if (c.moveToFirst()) 
       { 
        do{ 
         String date1 = c.getString(c.getColumnIndex(TabProDB.KEY_DATE)); 
         String time1 = c.getString(c.getColumnIndex(TabProDB.KEY_TIME)); 
         String date_time1 = date1 + "\n" +time1; 
         listItems.add(date_time1); 
        }while (c.moveToNext()); 
        } 
       } 
       db.close(); 

     }catch (Exception e) {} 

     arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, listItems); 

     date_time_ListView.setAdapter(arrayAdapter); 
     date_time_ListView.setOnItemClickListener(this); 


     date_time_ListView.setOnItemLongClickListener(new OnItemLongClickListener(){ 

       @Override 
       public boolean onItemLongClick(AdapterView<?> arg0, View arg1, 
         int position, long arg3) { 
        // TODO Auto-generated method stub 
        AlertDialog.Builder ad = new AlertDialog.Builder(History.this); 
        ad.setTitle("Delete?"); 
        ad.setMessage("Are you sure you want to delete this record?"); 
        final int positionToRemove = position; 
        String selectedFromList = (date_time_ListView.getItemAtPosition(position).toString()); 
        String[] splitDateTime = selectedFromList.split("\n"); 
        final String splitDate = splitDateTime[0]; 
        Toast.makeText(History.this, splitDate, Toast.LENGTH_SHORT).show(); 
        String splitTime = splitDateTime[1]; 
        ad.setNegativeButton("Cancel", null); 
        ad.setPositiveButton("Ok", new AlertDialog.OnClickListener() { 

         @Override 
         public void onClick(DialogInterface arg0, int arg1) { 
          // TODO Auto-generated method stub 
          TabProDB db = new TabProDB(History.this); 
          try 
          { 
           db.open(); 
           Cursor c = db.GetAllRecords(); 
           if(c!=null) 
           { 
            if(c.moveToFirst()) 
            { 
             do 
             { 
              //search database to find a date that equals the date on the listview 
              String findDate = c.getString(c.getColumnIndex(TabProDB.KEY_DATE)); 
              if(splitDate.equalsIgnoreCase(findDate)) 
              { 
               getdbID =c.getInt(c.getColumnIndex(TabProDB.KEY_ROWID)); 

               db.deleteRow(getdbID); 
               break; 
              } 
              else 
              { 

              } 
             }while(c.moveToNext()); 

            } 
           } 
          } 
          catch(Exception e){} 
          db.close(); 

          listItems.remove(positionToRemove); 
          arrayAdapter.notifyDataSetChanged();  

         } 

        }); 
        ad.show(); 
        return false; 
       } 

      }); 
} 

@Override 
public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) { 
    // TODO Auto-generated method stub 
    Intent i = new Intent(History.this, Update.class); 
    String str1[] = ((TextView) view).getText().toString().split("\n"); 
    String str2 = str1[0]; 
    String str3 = str1[1]; 

    i.putExtra("date", str2); 
    i.putExtra("time", str3); 
    i.putExtra("position", position); 
    startActivity(i); 

} 

} 
+0

tabHost.setCurrentTab (0); 이 줄을 제거하고 –

+0

제거 tabHost.setCurrentTab (0); 아무것도 바뀌지 않았다. – user2799726

답변

0
final Intent i = new Intent().setClass(TabBar.this, 
      Recorder.class); 
    TabSpec spec1 = tabHost.newTabSpec("Recoder"); 
    spec1.setContent(i); 
    spec1.setIndicator(getResources().getString(R.string.title_card_post1), 
      getResources().getDrawable(R.drawable.tab1)); 


    final Intent i = new Intent().setClass(TabBar.this, 
     History.class); 
     TabSpec spec1 = tabHost.newTabSpec("History"); 
    spec1.setContent(i); 
    spec1.setIndicator(getResources().getString(R.string.title_card_post1), 
      getResources().getDrawable(R.drawable.tab1)); 

    tabHost.addTab(spec1); 
    tabHost.addTab(spec2); 

이 코드를 시도하고 저를 보자 이것이 효과가 있는지 여부를 알아라. 당신이 솔루션은 나를 위해 일하고 내 응용 프로그램 중 하나는 그것을 가지고 있기 때문에.

+0

작동하지 않는 것 같습니다. 사실 뭔가 발견했지만, 나는 매우 안드로이드 프로그래밍에 새로운, 따라서이 솔루션을 적용하는 방법을 알아낼 수 없습니다 : http://stackoverflow.com/questions/6467209/not-run-oncreate-on-tab- 동일한 페이지에서 두 번째로 변경 – user2799726