2013-03-22 2 views
0

Итак, я хотел бы отображать текущие переменные currentMinute и currentHour, которые я определил с помощью TimePicker в своем макете add_country.xml - я думал, что правильно закодировал все, но я не могу показать новую переменную, которую я имею созданный с двумя комбинированными значениями времени @ + идентификатор/normalTimeFormat расположен в view_country-х:Как объединить currentMinute и currentHour в одно значение времени, которое может отображаться в XML-файле?

<TableRow>  
    <TextView 
    style="@style/StyleLabel" 
    android:text="Time Limit"/>      
<TextView 
    android:id="@+id/normalTimeFormat" 
    style="@style/StyleText"/>   
</TableRow> 
<TableRow> 

view_country.xml

<?xml version="1.0" encoding="utf-8"?> 

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:stretchColumns="1" 
android:layout_margin="5dp"> 
<TableRow>   
    <TextView 
    style="@style/StyleLabel" 
    android:text="@string/time_lbl"/> 
<TextView 
    android:id="@+id/timeText" 
    style="@style/StyleText"/>   
</TableRow> 
<TableRow>   
    <TextView 
    style="@style/StyleLabel" 
    android:text="@string/name_lbl"/> 
<TextView 
    android:id="@+id/nameText" 
    style="@style/StyleText"/>   
</TableRow> 

<TableRow>   
<TextView 
    style="@style/StyleLabel" 
    android:text="@string/cap_lbl"/>   
<TextView 
    android:id="@+id/capText" 
    style="@style/StyleText"/>   
</TableRow> 

    <TableRow>  
    <TextView 
    style="@style/StyleLabel" 
    android:text="Time Limit"/>      
<TextView 
    android:id="@+id/codeText" 
    style="@style/StyleText"/>   
</TableRow> 
<TableRow>  
    <TextView 
    style="@style/StyleLabel" 
    android:text="Time Limit"/>      
<TextView 
    android:id="@+id/normalTimeFormat" 
    style="@style/StyleText"/>   
</TableRow> 
<TableRow>   
<TextView 
    style="@style/StyleLabel" 
    android:text="Linked Users"/>   
<TextView 
android:id="@+id/codeText" 
    style="@style/StyleText"/>   
</TableRow> 
<TableRow>   
<TextView 
    style="@style/StyleLabel" 
    android:text="@string/code_lbl"/>   
<TextView 
    android:id="@+id/timeEdit" 
    style="@style/StyleText"/> 

</TableRow> 


</TableLayout> 

ViewCoreDevice.java

import android.app.Activity; 
import android.app.AlertDialog; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.database.Cursor; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuInflater; 
import android.view.MenuItem; 
import android.widget.TextView; 
import android.widget.TimePicker; 

public class ViewCoreDevice extends Activity { 

     private long rowID; 
     private TextView nameTv; 
     private TextView capTv; 
     private TextView codeTv; 
     private TextView timeTv; 
     private TextView minTv; 

     @Override 
     public void onCreate(Bundle savedInstanceState) 
     { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.view_country); 

      setUpViews(); 
      Bundle extras = getIntent().getExtras(); 
      rowID = extras.getLong(CoreDeviceList.ROW_ID); 
     } 

     private void setUpViews() { 
      nameTv = (TextView) findViewById(R.id.nameText); 
      capTv = (TextView) findViewById(R.id.capText); 
      timeTv = (TextView) findViewById(R.id.timeEdit); 
      minTv = (TextView) findViewById(R.id.timeEdit); 
      codeTv = (TextView) findViewById(R.id.codeText); 
     } 

     @Override 
     protected void onResume() 
     { 
      super.onResume(); 
      new LoadContacts().execute(rowID); 
     } 

     private class LoadContacts extends AsyncTask<Long, Object, Cursor> 
     { 
      DatabaseConnector dbConnector = new DatabaseConnector(ViewCoreDevice.this); 

      @Override 
      protected Cursor doInBackground(Long... params) 
      { 
      dbConnector.open(); 
      return dbConnector.getOneContact(params[0]); 
      } 

      @Override 
      protected void onPostExecute(Cursor result) 
      { 
      super.onPostExecute(result); 

      result.moveToFirst(); 
      // get the column index for each data item 
      int nameIndex = result.getColumnIndex("name"); 
      int capIndex = result.getColumnIndex("cap"); 
      int codeIndex = result.getColumnIndex("code"); 
      int timeIndex = result.getColumnIndex("time"); 

      nameTv.setText(result.getString(nameIndex)); 
      capTv.setText(result.getString(capIndex)); 
//   timeTv.setText(result.getInt(timeIndex)); // <--- HERE WAS AN ERROR 
      timeTv.setText(result.getString(timeIndex)); // time was stored as Sting all the time 
      minTv.setText(result.getString(timeIndex)); 
      codeTv.setText(result.getString(codeIndex)); 

      result.close(); 
      dbConnector.close(); 
      } 
     } 


     @Override 
     public boolean onCreateOptionsMenu(Menu menu) 
     { 
      super.onCreateOptionsMenu(menu); 
      MenuInflater inflater = getMenuInflater(); 
      inflater.inflate(R.menu.view_country_menu, menu); 
      return true; 
     } 

     @Override 
     public boolean onOptionsItemSelected(MenuItem item) 
     { 
      switch (item.getItemId()) 
      { 
      case R.id.editItem: 
       Intent addEditContact = 
        new Intent(this, AddEditCountry.class); 

       addEditContact.putExtra(CoreDeviceList.ROW_ID, rowID); 
       addEditContact.putExtra("name", nameTv.getText()); 
       addEditContact.putExtra("cap", capTv.getText()); 
       addEditContact.putExtra("code", codeTv.getText()); 
       startActivity(addEditContact); 
       return true; 

      case R.id.deleteItem: 
       deleteContact(); 
       return true; 

      default: 
       return super.onOptionsItemSelected(item); 
      } 
     } 

     private void deleteContact() 
     { 

      AlertDialog.Builder alert = new AlertDialog.Builder(ViewCoreDevice.this); 

      alert.setTitle(R.string.confirmTitle); 
      alert.setMessage(R.string.confirmMessage); 

      alert.setPositiveButton(R.string.delete_btn, 
      new DialogInterface.OnClickListener() 
      { 
       public void onClick(DialogInterface dialog, int button) 
       { 
        final DatabaseConnector dbConnector = 
         new DatabaseConnector(ViewCoreDevice.this); 

        AsyncTask<Long, Object, Object> deleteTask = 
         new AsyncTask<Long, Object, Object>() 
         { 
         @Override 
         protected Object doInBackground(Long... params) 
         { 
          dbConnector.deleteContact(params[0]); 
          return null; 
         } 

         @Override 
         protected void onPostExecute(Object result) 
         { 
          finish(); 
         } 
         }; 

        deleteTask.execute(new Long[] { rowID });    
       } 
      } 
     ); 

      alert.setNegativeButton(R.string.cancel_btn, null).show(); 
     } 
    } 

AddEditCountry.java

import android.app.Activity; 
import android.app.AlertDialog; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.view.ViewGroup; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.FrameLayout; 
import android.widget.TimePicker; 
import android.content.ContentValues; 
import android.content.Context; 
import android.database.Cursor; 
import android.database.SQLException; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteDatabase.CursorFactory; 
import android.database.sqlite.SQLiteOpenHelper; 
import android.content.Context; 


public class AddEditCountry extends Activity { 

    private long rowID; 
    private EditText nameEt; 
    private EditText capEt; 
    private EditText codeEt; 
    private TimePicker timeEt; 
    private TimePicker minEt; 
    private String cHour; 
    private String cMinute; 
    private String normalTimeFormat; 

     @Override 
     public void onCreate(Bundle savedInstanceState) 
     { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.add_country); 

      nameEt = (EditText) findViewById(R.id.nameEdit); 
      capEt = (EditText) findViewById(R.id.capEdit); 
      codeEt = (EditText) findViewById(R.id.codeEdit); 
      timeEt = (TimePicker) findViewById(R.id.timeEdit); 
      minEt = (TimePicker) findViewById(R.id.timeEdit); 



      Bundle extras = getIntent().getExtras(); 

      if (extras != null) 
      { 
      rowID = extras.getLong("row_id"); 
      nameEt.setText(extras.getString("name")); 
      capEt.setText(extras.getString("cap")); 
      codeEt.setText(extras.getString("code")); 
      timeEt.setCurrentHour(extras.getInt("time")); 
      minEt.setCurrentMinute(extras.getInt("min")); 
      } 

      Button saveButton =(Button) findViewById(R.id.saveBtn); 
      saveButton.setOnClickListener(new OnClickListener() { 

       public void onClick(View v) 
       { 
       if (nameEt.getText().length() != 0) 
       { 
        AsyncTask<Object, Object, Object> saveContactTask = 
         new AsyncTask<Object, Object, Object>() 
         { 
          @Override 
          protected Object doInBackground(Object... params) 
          { 
          saveContact(); 
          return null; 
          } 

          @Override 
          protected void onPostExecute(Object result) 
          { 
          finish(); 
          } 
         }; 

        saveContactTask.execute((Object[]) null); 
       } 

       else 
       { 
        AlertDialog.Builder alert = new AlertDialog.Builder(AddEditCountry.this); 
        alert.setTitle(R.string.errorTitle); 
        alert.setMessage(R.string.errorMessage); 
        alert.setPositiveButton(R.string.errorButton, null); 
        alert.show(); 
       } 
       } 
     }); 
     } 


      private void saveContact() 
      { 
       DatabaseConnector dbConnector = new DatabaseConnector(this); 

       if (getIntent().getExtras() == null) 
       { 
        dbConnector.insertContact(nameEt.getText().toString(), 
          capEt.getText().toString(), 
          timeEt.getCurrentHour().toString(), 
          minEt.getCurrentMinute().toString(), 
          codeEt.getText().toString()); 
       } 
       else 
       { 
        dbConnector.updateContact(rowID, nameEt.getText().toString(),capEt.getText().toString(),timeEt.getCurrentHour().toString()+":"+minEt.getCurrentMinute().toString(), codeEt.getText().toString()); 
        } 
      } 
} 

add_country.xml

<?xml version="1.0" encoding="utf-8"?> 
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" android:layout_weight="1"> 

    <LinearLayout android:id="@+id/linearLayout" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:orientation="vertical" 
     android:padding="5dp"> 

     <EditText android:id="@+id/nameEdit" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:imeOptions="actionNext" 
     android:hint="@string/name_hint" 
     android:inputType="textPersonName|textCapWords"/> 

     <EditText android:id="@+id/capEdit" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:imeOptions="actionNext" 
     android:hint="@string/cap_hint" 
     android:inputType="textPersonName|textCapWords"/> 

    <TextView 
     android:id="@+id/textView3" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Data Limit" 
     android:textColor="#ffffff" 
     android:textAppearance="?android:textAppearanceMedium" /> 

    <SeekBar 
     android:id="@+id/seekBar1" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" /> 

    <LinearLayout 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal" > 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_weight="1.0" 
      android:gravity="left" 
      android:textColor="#ffffff" 
      android:text="10MB" /> 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_weight="1.0" 
      android:gravity="right" 
      android:textColor="#ffffff" 
      android:text="Unlimited Data" /> 
    </LinearLayout> 

    <TextView 
     android:id="@+id/textView3" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Bandwidth Limit" 
     android:textColor="#ffffff" 
     android:textAppearance="?android:textAppearanceMedium" /> 

    <SeekBar 
     android:id="@+id/seekBar1" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" /> 

    <LinearLayout 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal" > 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_weight="1.0" 
      android:gravity="left" 
      android:textColor="#ffffff" 
      android:text="10kbs" /> 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_weight="1.0" 
      android:textColor="#ffffff" 
      android:gravity="right" 
      android:text="Unlimited Bandwidth" /> 
    </LinearLayout> 

    <TextView 
     android:id="@+id/TextView02" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:textAppearanceSmall" /> 

    <TextView 
     android:id="@+id/TextView02" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="WiFi Time Limit" 
     android:textColor="#ffffff" 
     android:textAppearance="?android:textAppearanceMedium" /> 

    <TimePicker 
     android:id="@+id/timeEdit" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center" 
     android:gravity="center" 
     android:layout_weight="1.0" /> 

    <EditText 
     android:id="@+id/codeEdit" 
     android:inputType="textUri" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:ems="10" 
     android:lines="1" 
     android:hint="@string/code_hint" 
     android:imeOptions="actionNext" /> 




     <Button android:id="@+id/saveBtn" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginTop="15dp" 
     android:layout_gravity="center_horizontal" 
     android:text="@string/save_btn"/> 
    </LinearLayout> 
</ScrollView> 
+0

http://stackoverflow.com/questions/15579715/how-can-i-combine-the-currentminute-and-currenthour-into -one-text-field-so-it-di? – fish

+0

По-прежнему нужна помощь - проблема немного изменилась - я понял, что сделаю новую запись и проясню свой последний исходный код, так как мы сделали так много изменений с того момента, как я изначально разместил его до – NoobNinja

+0

. Этот пост слишком длинный для мы попытаемся выяснить, почему ваша ценность не отображается в пользовательском интерфейсе. Сделайте небольшой пример, демонстрирующий вашу проблему без постороннего кода, такого как база данных или дополнительные действия. 9 раз из 10 упражнение консолидации вашей проблемы покажет вам решение. Удачи! –

ответ

1

Вы должны использовать то, что вернуть текущее время, как new Date() или Calendar.getInstance() в сочетании с SimpleDateFormat.format(Date). Что-то вроде этого

SimpleDateFormat format = new SimpleDateFormat("HH:m"); 
Date date = new Date(); 
format.format(date); 

Вы можете выбрать правильный формат для вас.

+0

Мне не нужно возвращать текущее время ... Мне нужно вернуть время из TimePicker, которое я выполнил выше. – NoobNinja

+0

Но в AddEditCountry.java у вас есть переменная 'String'' normalTimeFormat' и 'id/normalTimeFormat' не инициализируется, правильно? Недостаточно TimePicker timePicker = (TimePicker) findViewById (R.id.timePicker1); TextView normal = (TextView) findViewById (R.id.normalTimeFormat); normal.setText (timePicker.getCurrentHour() + ":" + timePicker.getCurrentMinute()); ?? Если это правильно, дайте мне знать, чтобы отредактировать/создать другой ответ. – Moesio

+0

Я обновил мою AddEditCountry. Я создал комбинированную переменную. Я просто пытаюсь решить проблему, где я получаю ошибку: «Метод updateContact (long, String, String, String, String, String) в типе DatabaseConnector не применим для аргументов « при очистке AddEditCountry (как показано/обновлено в сообщении выше) – NoobNinja

0

Я бы сделал это таким образом.

Во-первых, я бы изменил тип вашего поля «время» в вашей базе данных. String -> длинный

  • Изменить Ваш SQL
  • Измените методы CRUD

при вставке момент, вы бы использовать System.currentTimeMillis хранить его на базе данных.

Итак, когда вы получите информацию о своей базе данных, вы получите длинный. В это время вам нужно просто конвертировать для формата лучше для вас.

На данный момент вы можете сделать, как @Moesio сказал:

 SimpleDateFormat format = new SimpleDateFormat("HH:m"); 
     Date date = new Date(); 
     timeTv.setText(format.format(date).toString());