XML wont display stored SQLite data - java

I have some XML which should be displaying the hour from TimePicker data but every time I try to view the data it force closes. I've narrowed the issue down to an incorrect setup in my XML file(s) but I can't seem to correct the issue and keep the app from force closing.
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/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="#string/code_lbl"/>
<TextView
android:id="#+id/codeText"
style="#style/StyleText"/>
</TableRow>
<TableRow>
<TextView
style="#style/StyleLabel"
android:text="Linked Users"/>
<TextView
style="#style/StyleText"/>
</TableRow>
<TableRow>
<TextView
style="#style/StyleLabel"
android:text="Time Limit"/>
<TextView
android:id="#+id/timeEdit"
style="#style/StyleText"/>
</TableRow>
</TableLayout>
ViewCountry 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 ViewCountry extends Activity {
private long rowID;
private TextView nameTv;
private TextView capTv;
private TextView codeTv;
private TextView timeTv;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.view_country);
setUpViews();
Bundle extras = getIntent().getExtras();
rowID = extras.getLong(CountryList.ROW_ID);
}
private void setUpViews() {
nameTv = (TextView) findViewById(R.id.nameText);
capTv = (TextView) findViewById(R.id.capText);
timeTv = (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(ViewCountry.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));
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(CountryList.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(ViewCountry.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(ViewCountry.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();
}
}
Database Connector
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseConnector {
private static final String DB_NAME = "WorldCountries";
private SQLiteDatabase database;
private DatabaseOpenHelper dbOpenHelper;
public DatabaseConnector(Context context) {
dbOpenHelper = new DatabaseOpenHelper(context, DB_NAME, null, 1);
}
public void open() throws SQLException
{
//open database in reading/writing mode
database = dbOpenHelper.getWritableDatabase();
}
public void close()
{
if (database != null)
database.close();
}
public void insertContact(String name, String cap, String code, String time)
{
ContentValues newCon = new ContentValues();
newCon.put("name", name);
newCon.put("cap", cap);
newCon.put("time", time);
newCon.put("code", code);
open();
database.insert("country", null, newCon);
close();
}
public void updateContact(long id, String name, String cap,String code, String time)
{
ContentValues editCon = new ContentValues();
editCon.put("name", name);
editCon.put("cap", cap);
editCon.put("time", time);
editCon.put("code", code);
open();
database.update("country", editCon, "_id=" + id, null);
close();
}
public Cursor getAllContacts()
{
return database.query("country", new String[] {"_id", "name"},
null, null, null, null, "name");
}
public Cursor getOneContact(long id)
{
return database.query("country", null, "_id=" + id, null, null, null, null);
}
public void deleteContact(long id)
{
open();
database.delete("country", "_id=" + id, null);
close();
}
}
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;
public class AddEditCountry extends Activity {
private long rowID;
private EditText nameEt;
private EditText capEt;
private EditText codeEt;
private TimePicker timeEt;
#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);
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"));
}
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(),
codeEt.getText().toString());
}
else
{
dbConnector.updateContact(rowID,
nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString(),
codeEt.getText().toString());
}
}
}
add_country xml (where TimePicker data which is causing the crash is first entered into the system)
<?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>
(UPDATED) LOGCAT:
03-22 06:14:34.855: D/Activity(4860): Activity.onPause(), editTextTapSensorList size: 0
03-22 06:14:34.915: I/Adreno200-EGLSUB(4860): <ConfigWindowMatch:2165>: Format RGBA_8888.
03-22 06:14:34.915: D/memalloc(4860): ion: Mapped buffer base:0x5d4c3000 size:614400 offset:0 fd:60
03-22 06:14:34.965: D/memalloc(4860): ion: Mapped buffer base:0x5d8f7000 size:614400 offset:0 fd:64
03-22 06:14:34.985: D/memalloc(4860): ion: Unmapping buffer base:0x5ca41000 size:614400
03-22 06:14:34.985: D/memalloc(4860): ion: Unmapping buffer base:0x5dc05000 size:614400
03-22 06:14:34.985: D/memalloc(4860): ion: Unmapping buffer base:0x5dc9b000 size:614400
03-22 06:14:35.035: D/memalloc(4860): ion: Mapped buffer base:0x5ca41000 size:614400 offset:0 fd:56
03-22 06:14:37.748: D/Activity(4860): Activity.onPause(), editTextTapSensorList size: 0
03-22 06:14:37.828: I/Adreno200-EGLSUB(4860): <ConfigWindowMatch:2165>: Format RGBA_8888.
03-22 06:14:37.828: D/memalloc(4860): ion: Mapped buffer base:0x5e131000 size:614400 offset:0 fd:59
03-22 06:14:37.828: W/ResourceType(4860): No package identifier when getting value for resource number 0x00000000
03-22 06:14:37.828: W/dalvikvm(4860): threadid=1: thread exiting with uncaught exception (group=0x410889d8)
03-22 06:14:37.838: E/AndroidRuntime(4860): FATAL EXCEPTION: main
03-22 06:14:37.838: E/AndroidRuntime(4860): android.content.res.Resources$NotFoundException: String resource ID #0x0
03-22 06:14:37.838: E/AndroidRuntime(4860): at android.content.res.Resources.getText(Resources.java:247)
03-22 06:14:37.838: E/AndroidRuntime(4860): at android.widget.TextView.setText(TextView.java:3622)
03-22 06:14:37.838: E/AndroidRuntime(4860): at com.nfc.linkingmanager.ViewCountry$LoadContacts.onPostExecute(ViewCountry.java:74)
03-22 06:14:37.838: E/AndroidRuntime(4860): at com.nfc.linkingmanager.ViewCountry$LoadContacts.onPostExecute(ViewCountry.java:1)
03-22 06:14:37.838: E/AndroidRuntime(4860): at android.os.AsyncTask.finish(AsyncTask.java:602)
03-22 06:14:37.838: E/AndroidRuntime(4860): at android.os.AsyncTask.access$600(AsyncTask.java:156)
03-22 06:14:37.838: E/AndroidRuntime(4860): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
03-22 06:14:37.838: E/AndroidRuntime(4860): at android.os.Handler.dispatchMessage(Handler.java:99)
03-22 06:14:37.838: E/AndroidRuntime(4860): at android.os.Looper.loop(Looper.java:137)
03-22 06:14:37.838: E/AndroidRuntime(4860): at android.app.ActivityThread.main(ActivityThread.java:4477)
03-22 06:14:37.838: E/AndroidRuntime(4860): at java.lang.reflect.Method.invokeNative(Native Method)
03-22 06:14:37.838: E/AndroidRuntime(4860): at java.lang.reflect.Method.invoke(Method.java:511)
03-22 06:14:37.838: E/AndroidRuntime(4860): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:788)
03-22 06:14:37.838: E/AndroidRuntime(4860): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
03-22 06:14:37.838: E/AndroidRuntime(4860): at dalvik.system.NativeStart.main(Native Method)

UI element "#+id/timeEdit" defined in layout view_country.xml is a TextView. You are tring to cast it to android.widget.TimePicker in your activity ViewCountry.
There is another UI element with same id ("#+id/timeEdit") which indeed IS TimePicker but it's placed in layout for AddEditCountry activity.
Check your ViewCountry layout and code, probably element #+id/timeEdit shouldn't be a TextView, or you should cast it to TextView in your onCreate method.

Related

Application worked before but now it just stops

Im new to android programming and i have searched my eyes out for a solution to my problem but i cant find it anywhere. Im building an application with 3 screen layouts but i have a problem with the last screen:
The problem:
The application starts and the 2 first screens works good but when i go to the last screen(activity_katag.xml & katagActivity.java) and press "Deal1" the application stops and gives me the error "Unfortunately, "AppName" has stopped."
LogCat Error File:
13:32:12.270: W/dalvikvm(614): threadid=1: thread exiting with uncaught exception (group=0x40a122a0)
03-12 13:32:12.290: E/AndroidRuntime(614): FATAL EXCEPTION: main
03-12 13:32:12.290: E/AndroidRuntime(614): java.lang.NullPointerException
03-12 13:32:12.290: E/AndroidRuntime(614): at com.appname.fundeals.DealsAdapter.getChildrenCount(DealsAdapter.java:42)
03-12 13:32:12.290: E/AndroidRuntime(614): at android.widget.ExpandableListConnector.refreshExpGroupMetadataList(ExpandableListConnector.java:563)
03-12 13:32:12.290: E/AndroidRuntime(614): at android.widget.ExpandableListConnector.expandGroup(ExpandableListConnector.java:688)
03-12 13:32:12.290: E/AndroidRuntime(614): at android.widget.ExpandableListView.handleItemClick(ExpandableListView.java:562)
03-12 13:32:12.290: E/AndroidRuntime(614): at android.widget.ExpandableListView.performItemClick(ExpandableListView.java:522)
03-12 13:32:12.290: E/AndroidRuntime(614): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2859)
03-12 13:32:12.290: E/AndroidRuntime(614): at android.widget.AbsListView$1.run(AbsListView.java:3533)
03-12 13:32:12.290: E/AndroidRuntime(614): at android.os.Handler.handleCallback(Handler.java:615)
03-12 13:32:12.290: E/AndroidRuntime(614): at android.os.Handler.dispatchMessage(Handler.java:92)
03-12 13:32:12.290: E/AndroidRuntime(614): at android.os.Looper.loop(Looper.java:137)
03-12 13:32:12.290: E/AndroidRuntime(614): at android.app.ActivityThread.main(ActivityThread.java:4745)
03-12 13:32:12.290: E/AndroidRuntime(614): at java.lang.reflect.Method.invokeNative(Native Method)
03-12 13:32:12.290: E/AndroidRuntime(614): at java.lang.reflect.Method.invoke(Method.java:511)
03-12 13:32:12.290: E/AndroidRuntime(614): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
03-12 13:32:12.290: E/AndroidRuntime(614): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-12 13:32:12.290: E/AndroidRuntime(614): at dalvik.system.NativeStart.main(Native Method)
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.appname.fundeals"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".inloggActivity" />
<activity android:name=".katagActivity" />
</application>
</manifest>
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bakgrund"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.appname.fundeals.MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Random Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="75dp"
android:layout_marginLeft="10dp"
android:text="Username:"
android:textAppearance="?android:attr/textAppearanceMedium" />
/>
<EditText
android:id="#+id/usernameET"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView2"
android:layout_marginLeft="35dp"
android:layout_toRightOf="#+id/textView2"
android:hint="Användarnamn" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_below="#+id/textView2"
android:layout_marginTop="40dp"
android:text="Password:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/passwordET"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView3"
android:layout_alignLeft="#+id/usernameET"
android:layout_alignRight="#+id/usernameET"
android:hint="lösenord"
android:inputType="textPassword" />
<TextView
android:id="#+id/attemptsLeftTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView3"
android:layout_below="#+id/textView3"
android:layout_marginLeft="30dp"
android:layout_marginTop="48dp"
android:text="Attempts Left:"
android:visibility="invisible"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/numberOfRemainingLoginAttemptsTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/textView1"
android:layout_alignTop="#+id/attemptsLeftTV"
android:visibility="invisible" />
<TextView
android:id="#+id/loginLockedTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/loginBtn"
android:layout_marginTop="35dp"
android:layout_centerHorizontal="true"
android:textAppearance="?android:attr/textAppearanceMedium"
android:visibility="invisible" />
<Button
android:id="#+id/loginBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/numberOfRemainingLoginAttemptsTV"
android:layout_centerHorizontal="true"
android:onClick="authenticateLogin"
android:text="Login" />
<Button
android:id="#+id/FacebookBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/loginBtn"
android:layout_toLeftOf="#+id/usernameET"
android:onClick="authenticateLogin"
android:text="Facebook" />
MainActivity.java:
package com.appname.fundeals;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import com.appname.fundeals.R;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
#SuppressLint("NewApi")
public class MainActivity extends ActionBarActivity {
public class onClick implements OnClickListener {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(MainActivity.this, inloggActivity.class));
}
}
private EditText username;
private EditText password;
private Button login;
private TextView loginLockedTV;
private Button facebookBtn;
private TextView attemptsLeftTV;
private TextView numberOfRemainingLoginAttemptsTV;
int numberOfRemainingLoginAttempts = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
facebookBtn = (Button) findViewById(R.id.FacebookBtn);
facebookBtn.setOnClickListener(new onClick());
setupVariables();
}
public void authenticateLogin(View view) {
if (username.getText().toString().equals("admin") &&
password.getText().toString().equals("admin")) {
Toast.makeText(getApplicationContext(), "Hello admin!",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Seems like you 're not admin!",
Toast.LENGTH_SHORT).show();
numberOfRemainingLoginAttempts--;
attemptsLeftTV.setVisibility(View.VISIBLE);
numberOfRemainingLoginAttemptsTV.setVisibility(View.VISIBLE);
numberOfRemainingLoginAttemptsTV.setText(Integer.toString(numberOfRemainingLoginAttempts));
if (numberOfRemainingLoginAttempts == 0) {
login.setEnabled(false);
loginLockedTV.setVisibility(View.VISIBLE);
loginLockedTV.setBackgroundColor(Color.RED);
loginLockedTV.setText("LOGIN LOCKED!!!");
}
}
}
private void setupVariables() {
username = (EditText) findViewById(R.id.usernameET);
password = (EditText) findViewById(R.id.passwordET);
login = (Button) findViewById(R.id.loginBtn);
loginLockedTV = (TextView) findViewById(R.id.loginLockedTV);
attemptsLeftTV = (TextView) findViewById(R.id.attemptsLeftTV);
numberOfRemainingLoginAttemptsTV = (TextView) findViewById(R.id.numberOfRemainingLoginAttemptsTV);
numberOfRemainingLoginAttemptsTV.setText(Integer.toString(numberOfRemainingLoginAttempts));
}
}
activity_inlogg.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bakgrund" >
<TextView
android:id="#+id/textViewFirst"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="14dp"
android:layout_marginTop="20dp"
android:text="Random Text."
android:textStyle="bold" />
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textViewFirst"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:background="#00000000"
android:src="#drawable/rkeepklar" />
<ImageButton
android:id="#+id/imageButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageButton2"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginTop="6dp"
android:background="#00000000"
android:src="#drawable/stklarmarkerad" />
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageButton1"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginTop="4dp"
android:background="#00000000"
android:src="#drawable/ndklar" />
</RelativeLayout>
inloggActivity.java (screen2):
package com.appname.fundeals;
import com.appname.fundeals.inloggActivity.OnClick;
import com.appname.fundeals.R;
import android.app.Activity;
import android.graphics.Color;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.widget.Toast;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class inloggActivity extends Activity {
public class OnClick implements OnClickListener {
#Override
public void onClick(View v) {
startActivity(new Intent(inloggActivity.this, katagActivity.class));
}
}
private Button imageButton1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inlogg);
Button imageButton1 = (Button) findViewById(R.id.imageButton1);
imageButton1.setOnClickListener(new OnClick());
}
}
activity_katag.xml (screen3):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#drawable/bakgrund"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
>
<ExpandableListView
android:id="#+id/exp_list"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:indicatorLeft="?android:attr/expandableListPreferredItemIndicatorLeft"
android:divider="#A4C739"
android:dividerHeight="0.5dp"
></ExpandableListView>
</RelativeLayout>
katagActivity.java:
package com.appname.fundeals;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.ExpandableListView;
public class katagActivity extends Activity {
private static final HashMap<String, List<String>> Deals_Catagory = null;
HashMap<String, List<String>> Deals_category;
List<String> Deals_list;
ExpandableListView Exp_list;
DealsAdapter adapter;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_katag);
Exp_list = (ExpandableListView) findViewById(R.id.exp_list);
Deals_category = DataProvider.getInfo();
Deals_list = new ArrayList<String>(Deals_category.keySet());
adapter = new DealsAdapter(this, Deals_Catagory, Deals_list);
Exp_list.setAdapter(adapter);
}
}
DealsAdapter.java:
package com.appname.fundeals;
import java.util.HashMap;
import java.util.List;
import com.appname.fundeals.R;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
public class DealsAdapter extends BaseExpandableListAdapter {
private Context ctx;
private HashMap<String, List<String>> Deals_Catagory;
private List<String> Deals_List;
public DealsAdapter(Context ctx, HashMap<String, List<String>> Deals_Catagory, List<String> Deals_List) {
this.ctx = ctx;
this.Deals_Catagory = Deals_Catagory;
this.Deals_List = Deals_List;
// TODO Auto-generated constructor stub
}
#Override
public int getGroupCount() {
return Deals_List.size();
}
#Override
public int getChildrenCount(int arg0) {
return Deals_Catagory.get(Deals_List.get(arg0)).size();
}
#Override
public Object getGroup(int arg0) {
return Deals_List.get(arg0);
}
#Override
public Object getChild(int parent, int child) {
// TODO Auto-generated method stub
return Deals_Catagory.get(Deals_List.get(parent)).get(child);
}
#Override
public long getGroupId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getChildId(int parent, int child) {
// TODO Auto-generated method stub
return child;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public View getGroupView(int parent, boolean isExpanded, View convertView, ViewGroup parentView) {
// TODO Auto-generated method stub
String group_title = (String) getGroup(parent);
if(convertView == null)
{
LayoutInflater inflator = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.parent_deal1, parentView, false);
}
TextView parent_textView = (TextView) convertView.findViewById(R.id.parent_deal1);
parent_textView.setTypeface(null, Typeface.BOLD);
parent_textView.setText(group_title);
return convertView;
}
#Override
public View getChildView(int parent, int child, boolean lastChild, View convertView,
ViewGroup parentview) {
String child_title = (String) getChild(parent, child);
if (convertView == null)
{
LayoutInflater inflator = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.child_deal1, parentview, false);
}
// TODO Auto-generated method stub
TextView child_textView = (TextView) convertView.findViewById(R.id.child_deal1);
child_textView.setText(child_title);
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return false;
}
}
DataProvider.java:
package com.appname.fundeals;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class DataProvider {
public static HashMap<String, List<String>> getInfo()
{
HashMap<String, List<String>> DealsDetails = new HashMap<String, List<String>>();
List<String> Deal_1 = new ArrayList<String>();
Deal_1.add("Text");
List<String> Deal_2 = new ArrayList<String>();
Deal_2.add("Text");
List<String> Deal_3 = new ArrayList<String>();
Deal_3.add("Text");
List<String> Deal_4 = new ArrayList<String>();
Deal_4.add("Text");
DealsDetails.put("Deal 1", Deal_1);
DealsDetails.put("Deal 2", Deal_2);
DealsDetails.put("Deal 3", Deal_3);
DealsDetails.put("Deal 4", Deal_4);
return DealsDetails;
}
}
You try to convert ImageButton to Button so Error come.
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textViewFirst"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:background="#00000000"
android:src="#drawable/rkeepklar" />
Button imageButton1 = (Button) findViewById(R.id.imageButton1);
imageButton1.setOnClickListener(new OnClick());
Do same in other Button also
Updated code
ImageButton imageButton1 = (ImageButton) findViewById(R.id.imageButton1);
imageButton1.setOnClickListener(new OnClick());
Caused by: java.lang.ClassCastException: android.widget.ImageButton
cannot be cast to android.widget.Button
A ClassCastException is an Exception that can occur in a Java program when you try to improperly convert a class from one type to another.
Don't
Button imageButton1 = (Button) findViewById(R.id.imageButton1);
Do
ImageButton imageButton1 = (ImageButton) findViewById(R.id.imageButton1);
Because your XML
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textViewFirst"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:background="#00000000"
android:src="#drawable/rkeepklar" />

java.lang.ClassCastException: android.widget.EditText

Here is my JAVA Code. When I run my app it crashes and i get following errors in my log
11-21 00:21:48.828: E/AndroidRuntime(349): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.geekosoft.contactsonline/com.geekosoft.contactsonline.AddContact}: java.lang.ClassCastException: android.widget.EditText
11-21 00:21:48.828: E/AndroidRuntime(349): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
11-21 00:21:48.828: E/AndroidRuntime(349): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
11-21 00:21:48.828: E/AndroidRuntime(349): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
11-21 00:21:48.828: E/AndroidRuntime(349): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
11-21 00:21:48.828: E/AndroidRuntime(349): at android.os.Handler.dispatchMessage(Handler.java:99)
11-21 00:21:48.828: E/AndroidRuntime(349): at android.os.Looper.loop(Looper.java:123)
11-21 00:21:48.828: E/AndroidRuntime(349): at android.app.ActivityThread.main(ActivityThread.java:3683)
11-21 00:21:48.828: E/AndroidRuntime(349): at java.lang.reflect.Method.invokeNative(Native Method)
11-21 00:21:48.828: E/AndroidRuntime(349): at java.lang.reflect.Method.invoke(Method.java:507)
11-21 00:21:48.828: E/AndroidRuntime(349): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-21 00:21:48.828: E/AndroidRuntime(349): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-21 00:21:48.828: E/AndroidRuntime(349): at dalvik.system.NativeStart.main(Native Method)
11-21 00:21:48.828: E/AndroidRuntime(349): Caused by: java.lang.ClassCastException: android.widget.EditText
11-21 00:21:48.828: E/AndroidRuntime(349): at com.geekosoft.contactsonline.AddContact.initilizeEditContactInfo(AddContact.java:123)
11-21 00:21:48.828: E/AndroidRuntime(349): at com.geekosoft.contactsonline.AddContact.initilize(AddContact.java:68)
11-21 00:21:48.828: E/AndroidRuntime(349): at com.geekosoft.contactsonline.AddContact.onCreate(AddContact.java:42)
11-21 00:21:48.828: E/AndroidRuntime(349): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-21 00:21:48.828: E/AndroidRuntime(349): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
and here is my Java code
package com.geekosoft.contactsonline;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TableLayout;
public class AddContact extends Activity implements OnClickListener {
public static final String TAG = AddContact.class.getSimpleName();
ArrayList contactPhoneTypes, contactEmailTypes, contactIMTypes, contactAddressTypes;
String contactid;
int phoneNumbersIdStarter, emailIdStarter, imIdStarter, addressIdStarter;
LayoutInflater layoutInflater;
EditText name, number;
Spinner phoneType, emailType, addressType;
Button addPhoneField, addEmailField, addIMField, addAddressField;
TableLayout phoneFiledsCont, emailFiledsCont, imFiledsCont, addressFiledsCont;
#Override
protected void onCreate (Bundle contactsOnline) {
super.onCreate(contactsOnline);
setContentView(R.layout.add_contact);
initilize();
}
public void initilize () {
initilizeSpinnerTypes();
phoneNumbersIdStarter = 1000;
emailIdStarter = 2000;
imIdStarter = 3000;
addressIdStarter = 4000;
layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
name = (EditText) findViewById(R.id.etContactName);
addPhoneField = (Button) findViewById(R.id.bAddPhoneField);
addEmailField = (Button) findViewById(R.id.bAddEmailField);
addIMField = (Button) findViewById(R.id.bAddIMField);
addAddressField = (Button) findViewById(R.id.bAddaddressField);
phoneFiledsCont = (TableLayout) findViewById(R.id.tlPhoneFiledCont);
emailFiledsCont = (TableLayout) findViewById(R.id.tlEmailFiledsCont);
imFiledsCont = (TableLayout) findViewById(R.id.tlIMFiledsCont);
addressFiledsCont = (TableLayout) findViewById(R.id.tlAddressFiledsCont);
addPhoneField.setOnClickListener(this);
addEmailField.setOnClickListener(this);
addIMField.setOnClickListener(this);
addAddressField.setOnClickListener(this);
initilizeEditContactInfo();
}
public void initilizeSpinnerTypes() {
contactPhoneTypes = new ArrayList();
contactPhoneTypes.add(ContactsContract.CommonDataKinds.Phone.TYPE_HOME);
contactPhoneTypes.add(ContactsContract.CommonDataKinds.Phone.TYPE_WORK);
contactPhoneTypes.add(ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
contactPhoneTypes.add(ContactsContract.CommonDataKinds.Phone.TYPE_OTHER);
// contactPhoneTypes.add(ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM);
contactEmailTypes = new ArrayList();
contactEmailTypes.add(ContactsContract.CommonDataKinds.Email.TYPE_HOME);
contactEmailTypes.add(ContactsContract.CommonDataKinds.Email.TYPE_WORK);
contactEmailTypes.add(ContactsContract.CommonDataKinds.Email.TYPE_MOBILE);
contactEmailTypes.add(ContactsContract.CommonDataKinds.Email.TYPE_OTHER);
contactIMTypes = new ArrayList();
contactIMTypes.add(ContactsContract.CommonDataKinds.Im.TYPE_HOME);
contactIMTypes.add(ContactsContract.CommonDataKinds.Im.TYPE_WORK);
contactIMTypes.add(ContactsContract.CommonDataKinds.Im.TYPE_OTHER);
contactAddressTypes = new ArrayList();
contactAddressTypes.add(ContactsContract.CommonDataKinds.SipAddress.TYPE_HOME);
contactAddressTypes.add(ContactsContract.CommonDataKinds.SipAddress.TYPE_WORK);
contactAddressTypes.add(ContactsContract.CommonDataKinds.SipAddress.TYPE_OTHER);
}
public void initilizeEditContactInfo () {
contactid = getIntent().getStringExtra("contactId");
Log.d(TAG, "id = "+contactid);
Log.d(TAG, "query = "+ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
ContentResolver cr = getContentResolver();
Cursor contact = cr.query(ContactsContract.Contacts.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone._ID+" = ?",new String[]{contactid}, "DISPLAY_NAME ASC");
// Cursor contacts = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
if (contact.getCount() > 0) {
contact.moveToFirst();
String name = contact.getString(contact.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
Log.d(TAG, "name = "+name);
this.name.setText(name);
int loopCounter = 0;
if (Integer.parseInt(contact.getString(contact.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID+" = ?",new String[]{contactid}, null);
while (phones.moveToNext()) {
loopCounter++;
int phoneType = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.d(TAG, "phone = "+phoneNumber);
addTextField("phone");
EditText phoneNumberField = (EditText) findViewById(8084+phoneNumbersIdStarter);
phoneNumberField.setText(phoneNumber);
Log.d("Spinner Getting", "Spinner Id = " + (8083+phoneNumbersIdStarter));
Spinner phoneNumberSpinner = (Spinner) findViewById(8083+phoneNumbersIdStarter);
Log.d("After Spinner", "phone counter = " + phoneNumbersIdStarter);
switch (phoneType) {
case Phone.TYPE_MOBILE:
// phoneNumberSpinner.setSelection(2, false);
break;
case Phone.TYPE_HOME:
// phoneNumberSpinner.setSelection(0, false);
String phoneTypesCodes = "home = "+Phone.TYPE_HOME+"mobile = "+Phone.TYPE_MOBILE+"work = "+Phone.TYPE_WORK
+"other = "+Phone.TYPE_OTHER;
Log.d(name + "(home number)", phoneNumber + phoneTypesCodes);
break;
case Phone.TYPE_WORK:
// phoneNumberSpinner.setSelection(1, false);
break;
case Phone.TYPE_OTHER:
// phoneNumberSpinner.setSelection(3, false);
break;
}
}
phones.close();
}
}
contact.close();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bAddPhoneField:
addTextField("phone");
break;
case R.id.bAddEmailField:
addTextField("email");
break;
case R.id.bAddIMField:
addTextField("im");
break;
case R.id.bAddaddressField:
addTextField("address");
break;
}
}
public void addTextField(String fieldType) {
// for text field code is 84
// for spinner code is 83
if (fieldType.equals("phone")) {
// for phone number code is 80
phoneNumbersIdStarter++;
View view = layoutInflater.inflate(R.layout.add_phone_row, null);
EditText phoneNumberField = (EditText) view.findViewById(R.id.etContactPhone);
Spinner phoneTypeSpinner = (Spinner) view.findViewById(R.id.sContactPhoneType);
Log.d(TAG, "spinner id = " + phoneTypeSpinner.getId());
phoneNumberField.setId(8084+phoneNumbersIdStarter);
phoneTypeSpinner.setId(8083+phoneNumbersIdStarter);
Log.d("Spinner Created", "Spinner Id = " + phoneTypeSpinner.getId());
setSpinnerValues(phoneTypeSpinner, "phone");
phoneFiledsCont.addView(view);
} else if (fieldType.equals("email")) {
// for email code is 69
emailIdStarter++;
View view = layoutInflater.inflate(R.layout.add_email_row, null);
EditText emailAddressField = (EditText) view.findViewById(R.id.etContactEmail);
Spinner emailTypeSpinner = (Spinner) view.findViewById(R.id.sContactEmailType);
emailAddressField.setId(6984+emailIdStarter);
emailTypeSpinner.setId(6983+emailIdStarter);
Log.d(TAG, "inside true");
setSpinnerValues(emailTypeSpinner, "email");
Log.d(TAG, "inside true 2");
emailFiledsCont.addView(view);
} else if (fieldType.equals("im")) {
// for address code is 65
imIdStarter++;
View view = layoutInflater.inflate(R.layout.add_im_row, null);
EditText imField = (EditText) view.findViewById(R.id.etContactIM);
Spinner imTypeSpinner = (Spinner) view.findViewById(R.id.sContactIMType);
imField.setId(6584+imIdStarter);
imTypeSpinner.setId(6583+imIdStarter);
setSpinnerValues(imTypeSpinner, "im");
imFiledsCont.addView(view);
} else if (fieldType.equals("address")) {
// for im code is 73
addressIdStarter++;
View view = layoutInflater.inflate(R.layout.add_address_row, null);
EditText addressField = (EditText) view.findViewById(R.id.etContactAddress);
Spinner addressTypeSpinner = (Spinner) view.findViewById(R.id.sContactAddressType);
addressField.setId(7384+addressIdStarter);
addressTypeSpinner.setId(7383+addressIdStarter);
setSpinnerValues(addressTypeSpinner, "address");
addressFiledsCont.addView(view);
}
}
public void setSpinnerValues (Spinner spinner, String spinnerType) {
ArrayAdapter spinnerAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Iterator iter = null;
if (spinnerType.equals("phone")) {
iter = contactPhoneTypes.iterator();
} else if (spinnerType.equals("email")) {
iter = contactEmailTypes.iterator();
} else if (spinnerType.equals("im")) {
iter = contactIMTypes.iterator();
} else if (spinnerType.equals("address")) {
iter = contactAddressTypes.iterator();
}
while (iter.hasNext()) {
if (spinnerType.equals("phone")) {
spinnerAdapter.add(ContactsContract.CommonDataKinds.Phone.getTypeLabel(this.getResources(), iter.next(), getString(R.string.undefinedTypeLabel)).toString());
} else if (spinnerType.equals("email")) {
spinnerAdapter.add(ContactsContract.CommonDataKinds.Email.getTypeLabel(this.getResources(), iter.next(), getString(R.string.undefinedTypeLabel)).toString());
} else if (spinnerType.equals("im")) {
spinnerAdapter.add(ContactsContract.CommonDataKinds.Im.getTypeLabel(this.getResources(), iter.next(), getString(R.string.undefinedTypeLabel)).toString());
} else if (spinnerType.equals("address")) {
spinnerAdapter.add(ContactsContract.CommonDataKinds.Im.getTypeLabel(this.getResources(), iter.next(), getString(R.string.undefinedTypeLabel)).toString());
}
}
spinner.setAdapter(spinnerAdapter);
spinner.setPrompt(getString(R.string.selectLabel));
}
}
here is my add_contact.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="fill_parent">
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="wrap_content">
<TableLayout
android:layout_width="fill_parent" android:layout_height="wrap_content">
<TableRow>
<TextView android:text="Target Account"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<Spinner android:id="#+id/accountSpinner"
android:layout_height="wrap_content" android:layout_width="fill_parent"
android:layout_weight="1" />
</TableRow>
<TableRow>
<TextView android:text="Contact Name"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<EditText android:id="#+id/etContactName"
android:layout_height="wrap_content" android:layout_width="wrap_content"
android:layout_weight="1"/>
</TableRow>
<TableRow>
<TextView android:text="Contact Phone"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</TableRow>
<TableRow>
<Button android:id="#+id/bAddPhoneField"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Add Field"/>
</TableRow>
</TableLayout>
<TableLayout android:id="#+id/tlPhoneFiledCont"
android:layout_width="fill_parent" android:layout_height="wrap_content">
</TableLayout>
<TableLayout
android:layout_width="fill_parent" android:layout_height="wrap_content">
<TableRow>
<TextView android:text="Contact Email"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</TableRow>
</TableLayout>
<Button android:id="#+id/bAddEmailField"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Add Field"/>
<TableLayout android:id="#+id/tlEmailFiledsCont"
android:layout_width="fill_parent" android:layout_height="wrap_content">
</TableLayout>
<TextView android:text="Contact IM"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<Button android:id="#+id/bAddIMField"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Add Field"/>
<TableLayout android:id="#+id/tlIMFiledsCont"
android:layout_width="fill_parent" android:layout_height="wrap_content">
</TableLayout>
<TextView android:text="Contact Address"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<Button android:id="#+id/bAddaddressField"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Add Field"/>
<TableLayout android:id="#+id/tlAddressFiledsCont"
android:layout_width="fill_parent" android:layout_height="wrap_content">
</TableLayout>
<TableLayout
android:layout_width="fill_parent" android:layout_height="wrap_content">
<TableRow>
<Button android:text="#string/save"
android:layout_height="wrap_content" android:layout_width="fill_parent"
android:id="#+id/contactSaveButton" android:layout_weight="1"/>
</TableRow>
</TableLayout>
</LinearLayout>
</ScrollView>
and here is my add_phone_row.xml
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent" >
<EditText android:id="#+id/etContactPhone"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_weight="1" android:inputType="phone" />
<Spinner android:id="#+id/sContactPhoneType"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
</TableRow>
I am creating Spinner and EditText dynamically in bellow fucntion
if (fieldType.equals("phone")) {
// for phone number code is 80
phoneNumbersIdStarter++;
View view = layoutInflater.inflate(R.layout.add_phone_row, null);
EditText phoneNumberField = (EditText) view.findViewById(R.id.etContactPhone);
Spinner phoneTypeSpinner = (Spinner) view.findViewById(R.id.sContactPhoneType);
Log.d(TAG, "spinner id = " + phoneTypeSpinner.getId());
phoneNumberField.setId(8084+phoneNumbersIdStarter);
phoneTypeSpinner.setId(8083+phoneNumbersIdStarter);
Log.d("Spinner Created", "Spinner Id = " + phoneTypeSpinner.getId());
setSpinnerValues(phoneTypeSpinner, "phone");
phoneFiledsCont.addView(view);
}
and getting their values like below lines
EditText phoneNumberField = (EditText) findViewById(8084+phoneNumbersIdStarter);
Spinner phoneNumberSpinner = (Spinner) findViewById(8083+phoneNumbersIdStarter);
and each time i add these fields also add 1 in phoneNumbersIdStarter
if I comment the following line in my code it runs great
Spinner phoneNumberSpinner = (Spinner) findViewById(8083+phoneNumbersIdStarter);
Do you have some specific reason to not access the widgets using R.id.?
I don't think a good idea to use "8083+phoneNumbersIdStarter", because the int id which is generated in class R will change in each compilation, so probably the int 8083+phoneNumbersIdStarter is referring to a widget which is not an EditText.
So, change to something like this:
Spinner phoneNumberSpinner = (Spinner) findViewById(R.id.your_spinner_id);
I found error by myself. Error was because of id confliction. Because I was adding 1 in phoneNumbersIdStarter on click of Add Phone Button. So my EditText ID starer was 8084+phoneNumbersIdStarter and Spinner ID starter 8083+phoneNumbersIdStarter thats why Spinnner was conflicting with EditText when creating fields second time.
Solved error by changing Spinner ID starter from 8083+phoneNumbersIdStarter to 9083+phoneNumbersIdStarter as shown below now it is working great.
EditText phoneNumberField = (EditText) findViewById(8084+phoneNumbersIdStarter);
Spinner phoneNumberSpinner = (Spinner) findViewById(9083+phoneNumbersIdStarter);

Attempting to Save Data In a SQLite Database - Cleaned (no major issues) Still Force Closes

I'm a bit new to StackOverflow and I was wondering if I could have a bit of input on the following issue: I'm attempting to save a bit of data in a sqlite database but each time I attempt to do so the app force closes and I'm not sure why. I've cleaned the file and there are no issues. (I have no idea what I've done wrong - but something has been programmed incorrectly.)
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.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.text.format.DateFormat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TimePicker;
import com.nfc.linkingmanager.TimePickerFragment.TimePickedListener;
import java.util.Calendar;
public class AddEditCountry extends Activity implements TimePickedListener
{
private TextView mPickedTimeText;
private Button mPickTimeButton;
private long rowID;
private EditText nameEt;
private EditText capEt;
private EditText codeEt;
private TimePicker timeEt;
public static final String KEY_BUNDLE_TIME = "time";
public static final String KEY_BUNDLE_MIN = "min";
#Override
public void onCreate(Bundle savedInstanceState)
{
setContentView(R.layout.add_country); // where your_layout is the name of the xml file with the layout you want to use minus the .xml extention
//this layout must contain all of these views below that you are trying to initialize
nameEt = (EditText) findViewById(R.id.nameEdit);
capEt = (EditText) findViewById(R.id.capEdit);
codeEt = (EditText) findViewById(R.id.codeEdit);
timeEt = (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"));
String time = extras.getString("time");
String[] parts = time.split(":");
timeEt.setCurrentHour(Integer.valueOf(parts[0]));
timeEt.setCurrentMinute(Integer.valueOf(parts[1]));
timeEt.setIs24HourView(false);
}
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() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString());
}
else
{
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString());
}
}
#Override
public void onTimePicked(Calendar time)
{
// display the selected time in the TextView
mPickedTimeText.setText(DateFormat.format("h:mm a", time));
}
}
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>
PROBLEMS:
Cleaned - No Problems
LOGCAT:
03-29 13:23:28.950: D/OpenGLRenderer(20744): Enabling debug mode 0
03-29 13:23:33.780: D/AndroidRuntime(20744): Shutting down VM
03-29 13:23:33.780: W/dalvikvm(20744): threadid=1: thread exiting with uncaught exception (group=0x41f7b930)
03-29 13:23:33.790: E/AndroidRuntime(20744): FATAL EXCEPTION: main
03-29 13:23:33.790: E/AndroidRuntime(20744): android.app.SuperNotCalledException: Activity {com.app.gamedemo/com.app.gamedemo.AddEditCountry} did not call through to super.onCreate()
03-29 13:23:33.790: E/AndroidRuntime(20744): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2146)
03-29 13:23:33.790: E/AndroidRuntime(20744): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-29 13:23:33.790: E/AndroidRuntime(20744): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-29 13:23:33.790: E/AndroidRuntime(20744): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-29 13:23:33.790: E/AndroidRuntime(20744): at android.os.Handler.dispatchMessage(Handler.java:99)
03-29 13:23:33.790: E/AndroidRuntime(20744): at android.os.Looper.loop(Looper.java:137)
03-29 13:23:33.790: E/AndroidRuntime(20744): at android.app.ActivityThread.main(ActivityThread.java:5041)
03-29 13:23:33.790: E/AndroidRuntime(20744): at java.lang.reflect.Method.invokeNative(Native Method)
03-29 13:23:33.790: E/AndroidRuntime(20744): at java.lang.reflect.Method.invoke(Method.java:511)
03-29 13:23:33.790: E/AndroidRuntime(20744): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-29 13:23:33.790: E/AndroidRuntime(20744): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-29 13:23:33.790: E/AndroidRuntime(20744): at dalvik.system.NativeStart.main(Native Method)
03-29 13:23:35.390: I/Process(20744): Sending signal. PID: 20744 SIG: 9
The problem is here in your onCreate()
#Override
public void onCreate(Bundle savedInstanceState)
{
nameEt = (EditText) findViewById(R.id.nameEdit);
capEt = (EditText) findViewById(R.id.capEdit);
codeEt = (EditText) findViewById(R.id.codeEdit);
timeEt = (TimePicker) findViewById(R.id.timeEdit);
You need to call setContentView() before trying to access your EditTexts and so on. Your Views "live" within your layout (xml file) so they are null until you inflate the layout. Change it to someting like
#Override
public void onCreate(Bundle savedInstanceState)
{
setContentView(R.layout.your_layout); // where your_layout is the name of the xml file with the layout you want to use minus the .xml extention
//this layout must contain all of these views below that you are trying to initialize
nameEt = (EditText) findViewById(R.id.nameEdit);
capEt = (EditText) findViewById(R.id.capEdit);
codeEt = (EditText) findViewById(R.id.codeEdit);
timeEt = (TimePicker) findViewById(R.id.timeEdit);
Edit
Just like the error says, you are trying to cast a TextView to a TimePicker. Here
timeEt = (TimePicker) findViewById(R.id.timeEdit);
(R.id.timeEdit) points to a TextView but here
private TimePicker timeEt;
you declare it as a TimePicker. If you want it to be a TimePicker then change it in your xml
`<TimePicker
android:id="#+id/timeEdit"
style="#style/StyleText"/> `
Also, you have multiple ids in your xml
android:id="#+id/codeText"
might want to change that
Second Edit
03-29 13:23:33.790: E/AndroidRuntime(20744): android.app.SuperNotCalledException: Activity {com.app.gamedemo/com.app.gamedemo.AddEditCountry} did not call through to super.onCreate()
This line in the logcat says it all. You didn't call super.onCreate(). Add the following line as the first line in your onCreate() method
super.onCreate(savedInstanceState);
When reading your logcat, look for where it says Fatal Exception. The next line should say what it is (Null Pointer Exception, Class Cast Exception, etc...) then look for the first line that references your package name and it will tell you where to start looking for the error. Ex. Main.java 57 tells you that whatever the fatal exception was occurs in your Main.java file at line 57. The problem may originally come from somewhere else but this is always a good place to start so you can narrow it down and post relevant code if you need help.

Saving TimePicker data in a sqlite database

Ok - So I'm really lost at this point...
I have an xml layout where a user can input several settings. My goal is to be able to save these settings and retrieve them at a later date - which I've done successfully up until this point. I have sqlite database which stores several values including the currentHour from the timepicker as well as another xml layout which outputs the settings saved in the database.
Currently - the timePicker only saves the currentHour to the database and then to the string I'm using to display it in the view_country XML file.
What I'd like to do is display the entire time - not just the currentHour (ex. currentHour : currentMinute in order to display the full time 4:00AM) as a string I can use to display the time in another xml layout.
P.S.
I really need a straightforward answer on how this can be done (just assume I know nothing) I've been trying to accomplish this for several days and I still need assistance getting the currentMinute displayed next to my currentHour.
I've made several attempts at this however at this time I feel its best to revert back to my last known working state (I've been getting force close issues when attempting different methods of concatenating the two fields) and ask for help. (I know it can't be TOO hard to store and display a time value from a TimePicker - especially for some of you more skilled StackOverflow ninjas)
add_country.xml (where the TimePicker buttons are)
<?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>
AddEditCountry.java (Java file for the layout containing the TimePicker buttons)
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;
public class AddEditCountry extends Activity {
private long rowID;
private EditText nameEt;
private EditText capEt;
private EditText codeEt;
private TimePicker timeEt;
#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);
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"));
String time = extras.getInt("time");
String[] parts = time.split(":");
timeEt.setCurrentHour(parts[0]);
timeEt.setCurrentMinute(parts[1]);
}
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() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString());
}
else
{
dbConnector.updateContact(rowID,
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString());
}
}
}
DatbaseConnector.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseConnector {
private static final String DB_NAME = "WorldCountries";
private SQLiteDatabase database;
private DatabaseOpenHelper dbOpenHelper;
public DatabaseConnector(Context context) {
dbOpenHelper = new DatabaseOpenHelper(context, DB_NAME, null, 1);
}
public void open() throws SQLException
{
//open database in reading/writing mode
database = dbOpenHelper.getWritableDatabase();
}
public void close()
{
if (database != null)
database.close();
}
public void insertContact(String name, String cap, String code, String time)
{
ContentValues newCon = new ContentValues();
newCon.put("name", name);
newCon.put("cap", cap);
newCon.put("time", time);
newCon.put("code", code);
open();
database.insert("country", null, newCon);
close();
}
public void updateContact(long id, String name, String cap,String code, String time)
{
ContentValues editCon = new ContentValues();
editCon.put("name", name);
editCon.put("cap", cap);
editCon.put("time", time);
editCon.put("code", code);
open();
database.update("country", editCon, "_id=" + id, null);
close();
}
public Cursor getAllContacts()
{
return database.query("country", new String[] {"_id", "name"},
null, null, null, null, "name");
}
public Cursor getOneContact(long id)
{
return database.query("country", null, "_id=" + id, null, null, null, null);
}
public void deleteContact(long id)
{
open();
database.delete("country", "_id=" + id, null);
close();
}
}
view_country.xml (where the currentHour is displayed at the moment - but needs to display the currentHour and currentMinute together as one string I can display as the time)
<?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/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="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>
LOGCAT:
03-25 12:50:45.175: D/Activity(10602): Activity.onPause(), editTextTapSensorList size: 0
03-25 12:50:45.265: I/Adreno200-EGLSUB(10602): <ConfigWindowMatch:2165>: Format RGBA_8888.
03-25 12:50:45.276: D/memalloc(10602): ion: Mapped buffer base:0x5ca42000 size:614400 offset:0 fd:57
03-25 12:50:45.276: E/(10602): Can't open file for reading
03-25 12:50:45.276: E/(10602): Can't open file for reading
03-25 12:50:45.316: D/memalloc(10602): ion: Mapped buffer base:0x5d12f000 size:614400 offset:0 fd:61
03-25 12:50:45.326: W/IInputConnectionWrapper(10602): showStatusIcon on inactive InputConnection
03-25 12:50:45.326: W/IInputConnectionWrapper(10602): getExtractedText on inactive InputConnection
03-25 12:50:47.248: D/memalloc(10602): ion: Unmapping buffer base:0x5ca42000 size:614400
03-25 12:50:47.248: D/memalloc(10602): ion: Unmapping buffer base:0x5d12f000 size:614400
03-25 12:50:47.288: D/Activity(10602): Activity.onPause(), editTextTapSensorList size: 0
03-25 12:50:47.318: I/Adreno200-EGLSUB(10602): <ConfigWindowMatch:2165>: Format RGBA_8888.
03-25 12:50:47.318: D/memalloc(10602): ion: Mapped buffer base:0x5cd67000 size:614400 offset:0 fd:58
03-25 12:50:47.388: D/memalloc(10602): ion: Mapped buffer base:0x5d05f000 size:614400 offset:0 fd:63
03-25 12:50:47.388: W/IInputConnectionWrapper(10602): getExtractedText on inactive InputConnection
03-25 12:50:48.549: D/memalloc(10602): ion: Mapped buffer base:0x5d12f000 size:614400 offset:0 fd:66
You can add the minutes by keeping one column in the database and one string. Then you must split the time string, when setting the TimePicker
String time = extras.getString("time");
String[] parts = time.split(":");
timeEt.setCurrentHour(Integer.valueOf(parts[0]));
timeEt.setCurrentMinute(Integer.valueOf(parts[1]));
and concat it, when inserting or updating
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString());
Or keep a separate hour and minute. This means extending the database schema and DatabaseConnector to cope for an additional parameter, but avoids splitting the string, when you need the parts.

Implementing Android TimePicker from Tutorial - Source Force Closes

I'm trying to implement a TimePicker into my source code from the following tutorial:
http://www.lukehorvat.com/blog/android-time-picker-example/
However when implementing it in my app - I'm getting force close issues.
Any suggestions?
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.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.text.format.DateFormat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TimePicker;
import com.nfc.linkingmanager.TimePickerFragment.TimePickedListener;
import java.util.Calendar;
public class AddEditCountry extends Activity implements TimePickedListener
{
private TextView mPickedTimeText;
private Button mPickTimeButton;
private long rowID;
private EditText nameEt;
private EditText capEt;
private EditText codeEt;
private TimePicker timeEt;
public static final String KEY_BUNDLE_TIME = "time";
public static final String KEY_BUNDLE_MIN = "min";
#Override
public void onCreate(Bundle savedInstanceState)
{
nameEt = (EditText) findViewById(R.id.nameEdit);
capEt = (EditText) findViewById(R.id.capEdit);
codeEt = (EditText) findViewById(R.id.codeEdit);
timeEt = (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.containsKey(KEY_BUNDLE_TIME) ? extras.getInt(KEY_BUNDLE_TIME) : 0);
}
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(),
codeEt.getText().toString());
}
else
{
dbConnector.updateContact(rowID,
nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString(),
codeEt.getText().toString());
}
}
#Override
public void onTimePicked(Calendar time)
{
// display the selected time in the TextView
mPickedTimeText.setText(DateFormat.format("h:mm a", time));
}
}
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" />
<TextView
android:id="#+id/text_picked_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
<Button
android:id="#+id/button_pick_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_below="#id/text_picked_time"
android:text="Pick a time" />
<EditText
android:id="#+id/codeEdit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/code_hint"
android:imeOptions="actionNext"
android:inputType="textUri"
android:lines="1" >
<requestFocus />
</EditText>
<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>
TIMEPICKERFRAGMENT.JAVA
package com.nfc.linkingmanager;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TimePicker;
import java.util.Calendar;
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener
{
private TimePickedListener mListener;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
// use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
}
#Override
public void onAttach(Activity activity)
{
// when the fragment is initially shown (i.e. attached to the activity), cast the activity to the callback interface type
super.onAttach(activity);
try
{
mListener = (TimePickedListener) activity;
}
catch (ClassCastException e)
{
throw new ClassCastException(activity.toString() + " must implement " + TimePickedListener.class.getName());
}
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
// when the time is selected, send it to the activity via its callback interface method
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
mListener.onTimePicked(c);
}
public static interface TimePickedListener
{
public void onTimePicked(Calendar time);
}
}
LOGCAT:
03-25 02:50:06.783: I/Adreno200-EGLSUB(27045): <ConfigWindowMatch:2165>: Format RGBA_8888.
03-25 02:50:06.783: D/memalloc(27045): ion: Mapped buffer base:0x5ca43000 size:614400 offset:0 fd:57
03-25 02:50:06.783: E/(27045): Can't open file for reading
03-25 02:50:06.783: E/(27045): Can't open file for reading
03-25 02:50:06.823: D/memalloc(27045): ion: Mapped buffer base:0x5d234000 size:614400 offset:0 fd:61
03-25 02:50:08.695: D/Activity(27045): Activity.onPause(), editTextTapSensorList size: 0
03-25 02:50:08.715: W/dalvikvm(27045): threadid=1: thread exiting with uncaught exception (group=0x4108b9d8)
03-25 02:50:08.715: E/AndroidRuntime(27045): FATAL EXCEPTION: main
03-25 02:50:08.715: E/AndroidRuntime(27045): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nfc.linkingmanager/com.nfc.linkingmanager.AddEditCountry}: java.lang.NullPointerException
03-25 02:50:08.715: E/AndroidRuntime(27045): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1960)
03-25 02:50:08.715: E/AndroidRuntime(27045): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1985)
03-25 02:50:08.715: E/AndroidRuntime(27045): at android.app.ActivityThread.access$600(ActivityThread.java:127)
03-25 02:50:08.715: E/AndroidRuntime(27045): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1151)
03-25 02:50:08.715: E/AndroidRuntime(27045): at android.os.Handler.dispatchMessage(Handler.java:99)
03-25 02:50:08.715: E/AndroidRuntime(27045): at android.os.Looper.loop(Looper.java:137)
03-25 02:50:08.715: E/AndroidRuntime(27045): at android.app.ActivityThread.main(ActivityThread.java:4477)
03-25 02:50:08.715: E/AndroidRuntime(27045): at java.lang.reflect.Method.invokeNative(Native Method)
03-25 02:50:08.715: E/AndroidRuntime(27045): at java.lang.reflect.Method.invoke(Method.java:511)
03-25 02:50:08.715: E/AndroidRuntime(27045): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:788)
03-25 02:50:08.715: E/AndroidRuntime(27045): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
03-25 02:50:08.715: E/AndroidRuntime(27045): at dalvik.system.NativeStart.main(Native Method)
03-25 02:50:08.715: E/AndroidRuntime(27045): Caused by: java.lang.NullPointerException
03-25 02:50:08.715: E/AndroidRuntime(27045): at com.nfc.linkingmanager.AddEditCountry.onCreate(AddEditCountry.java:73)
03-25 02:50:08.715: E/AndroidRuntime(27045): at android.app.Activity.performCreate(Activity.java:4701)
03-25 02:50:08.715: E/AndroidRuntime(27045): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1051)
03-25 02:50:08.715: E/AndroidRuntime(27045): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1924)
03-25 02:50:08.715: E/AndroidRuntime(27045): ... 11 more
You don't have an element called TimeEdit in your xml. So when you try to set its text, it crashes with a null pointer exception.
where you define Timepicker
timeEt = (TimePicker) findViewById(R.id.timeEdit);
in your xml file.
Check your xml file and give different id to all.

Categories