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.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
package com.example.alex.askii;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
//Alex Levin
public class Login extends AppCompatActivity {
Button login;
Button signUp;
EditText userNameET;
EditText passWordET;
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login = (Button)findViewById(R.id.Login);
signUp = (Button)findViewById(R.id.signUp);
userNameET = (EditText)findViewById(R.id.username);
passWordET = (EditText)findViewById(R.id.password);
login.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
//get text valiues
String userName = userNameET.getText().toString();
String passWord = passWordET.getText().toString();
//Query in java the username
String actualPassword = helper.searchPass(userName);
//If Correct
if(passWord.equals(actualPassword)){
Toast.makeText(getApplicationContext(),
"Redirecting...", Toast.LENGTH_SHORT).show();
/*
Intent i = new Intent(mainActivity.this, display.class);
i.putExtra("UserName", str);
startActivity(i)
Example code to go to next activity ^^
*/
}else{
Toast.makeText(getApplicationContext(), "Invalid Username Or Password", Toast.LENGTH_SHORT).show();
}
}
});
signUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Login.this, signUP.class);
startActivity(i);
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.alex.askii.Login">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Askii Login"
android:textSize = "30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.033"
tools:layout_constraintRight_creator="1"
tools:layout_constraintLeft_creator="1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text= "Username:"
android:textSize="20dp"
app:layout_constraintRight_toLeftOf="#+id/username"
tools:layout_constraintRight_creator="1"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toBottomOf="#+id/username"
android:layout_marginEnd="7dp"
android:layout_marginBottom="4dp"
android:layout_marginRight="7dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text= "Password:"
android:textSize="20dp"
android:id="#+id/textView"
tools:layout_constraintBottom_creator="1"
android:layout_marginStart="16dp"
app:layout_constraintBottom_toBottomOf="parent"
tools:layout_constraintLeft_creator="1"
android:layout_marginBottom="169dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginLeft="16dp" />
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:onClick="login"
tools:layout_constraintRight_creator="1"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginEnd="84dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginBottom="88dp"
android:layout_marginRight="130dp" />
<EditText
android:id="#+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="#+id/username"
app:layout_constraintBaseline_toBaselineOf="#+id/textView"
tools:layout_constraintBaseline_creator="1"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="#+id/username" />
<EditText
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Enter Username"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toTopOf="#+id/password"
android:layout_marginStart="11dp"
tools:layout_constraintLeft_creator="1"
android:layout_marginBottom="20dp"
app:layout_constraintLeft_toRightOf="#+id/textView"
android:layout_marginLeft="11dp" />
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/signUp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sign Up"
tools:layout_constraintRight_creator="1"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginEnd="84dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginRight="216dp"
android:layout_marginBottom="47dp" />
</android.support.constraint.ConstraintLayout>
package com.example.alex.askii;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
* Created by Alex on 12/30/2017.
*/
public class signUP extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
}
Button signUpOnPage = (Button)findViewById(R.id.signUpOnPage);
public void onSignUpOnPage(View v){
if(v.getId() == R.id.signUpOnPage){
EditText userName = (EditText)findViewById(R.id.newUserName);
EditText passWord = (EditText)findViewById(R.id.newPassWord);
EditText confPassword = (EditText)findViewById(R.id.newUserName);
String userNameString = userName.getText().toString();
String passWordString = passWord.getText().toString();
String confPasswordString = confPassword.getText().toString();
if(!passWordString.equals(confPasswordString)){
Toast check = Toast.makeText(signUP.this, "Passwords Don't Match", Toast.LENGTH_SHORT);
check.show();
}
}
}
}
For some reason I am getting the following error
12-30 02:39:59.308 1969-1969/com.example.alex.askii E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.alex.askii/com.example.alex.askii.signUP}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1880)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:118)
at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:152)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:29)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:53)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:204)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:184)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:518)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:189)
at com.example.alex.askii.signUP.<init>(signUP.java:16)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1319)
at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1871)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
I am really unsure why this is happening maybe it is something wrong with my manifests but I doubt it because the manifest was autogenerated. Please help I can't find the answer online because it seems like I followed everything online correctly this is the last place I came to for help I am so frustrated right now!
Move
signUpOnPage = (Button)findViewById(R.id.signUpOnPage);
to onCreate()
I'm having a problem with Null Pointer Exception which is threw by setOnClickListener.
I'm trying to make an application processing an image, and I want to load and image from gallery.
I've been reading lots of posts here but I still don't understand what's happening.
Why Am I getting NullPointerException?
Here is my code:
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.graphics.*;
import android.graphics.drawable.*;
import android.content.Intent;
import android.app.Activity;
public class MainActivity extends ActionBarActivity {
Bitmap oryginal;
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
image = (ImageView) findViewById(R.id.imageView);
image.setOnClickListener(new View.OnClickListener() { here is the Null Pointer Exception
#Override
public void onClick(View view) {
Intent gallery = new Intent();
gallery.setType("image/*");
gallery.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(gallery,"Select Image"),1);
}
});
}
public void onActivityResult(int requestCode , int resultCode, Intent data)
{
if(resultCode == RESULT_OK)
{
if(requestCode ==1)
{
image.setImageURI(data.getData());
}
}
}
Here is my fragment_main.xml where I have my ImageView (in the first paragraph)
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.app.MainActivity$PlaceholderFragment"
android:background="#ffe93d"
android:focusable="false">
<ImageView
android:layout_width="300dp"
android:layout_height="400dp"
android:id="#+id/imageView"
android:src="#drawable/tucano"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/oryginal"
android:id="#+id/oryginal"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="Oryginal" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/kotim"
android:layout_below="#+id/imageView"
android:layout_toLeftOf="#+id/oryginal"
android:visibility="invisible"
android:src="#drawable/kot" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/lennaim"
android:layout_above="#+id/oryginal"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:visibility="invisible"
android:src="#drawable/lenna" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/lennaim"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:visibility="invisible"
android:src="#drawable/obrazek"
android:id="#+id/stworim"
android:focusableInTouchMode="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/help"
android:id="#+id/help"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="Help" />
Details:
Details:
04-07 16:01:14.162 1451-1451/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.app/com.example.app.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.app.MainActivity.onCreate(MainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
The problem is that you're setting your content as this:
setContentView(R.layout.activity_main);
But as per your code, the required ImageView is in this file: Here is my fragment_main.xml where I have my ImageView (in the first paragraph), therefore my assumption of:
image = (ImageView) findViewById(R.id.imageView); is returning null
is true and you're getting the NullPointerException error. You can just find Views that correspond to the layout declared in your setContentView() statement, otherwise it will return null.
Your ImageView is in Fragment Layout while you are trying to initialize variable using Activity's method FindViewByID. To do that properly get your fragment's View reference and then call View.FindViewByID(). Also I would advise to change your Image's View ID just in case.
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.
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.
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.