Saving TimePicker data in a sqlite database - java

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.

Related

How can call to refresh my fragment class in another method (I Tried all the solution on stackoverflow)

I have a void method synchronizeNum(String String String) Which will be trigger in onViewCreated , This Line.
new DisDepartmentSender(myView.getContext(), urlAddress, accountEmail, departmentName).execute();
It will get data from database and finally pass back and set the data into this method synchronizeNum (String String String).After i set the data i wish to display it using TextView. I think the only way is execute again onViewCreated method, since we cannot setText inside synchronizeNum method.I have tried many detach and attach method inside the method but the problem is it get NullPointer i donno how to solve i have been looking around for 1 day just for this little problem. I need you guys help please.
CurrentDepartmentView FragmentClass
package com.example.cheng.freequeue.DisplayDepartmentStatus;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.cheng.freequeue.R;
/**
* Created by cheng on 11/4/2018.
*/
public class CurrentStatusView extends Fragment {
DisDepartmentList disDepartmentList=new DisDepartmentList();
final static String urlAddress = "https://kokcheng95.000webhostapp.com/departmentStatus.php";
private String CompanyName, accountEmail, departmentName, imageUrl;
private String num1room1, num2room2, num3room3, num1, num2, num3, room1, room2, room3;
private final Handler handler = new Handler();
View myView;
Context c;
ViewGroup container;
private LayoutInflater inflater;
TextView company_name, department_name, num_1, num_2, num_3, room_1, room_2, room_3;
de.hdodenhof.circleimageview.CircleImageView image_department;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.current_department_view, container, false);
this.container=container;
company_name = (TextView) myView.findViewById(R.id.company_name);
department_name = (TextView) myView.findViewById(R.id.department_name);
image_department = (de.hdodenhof.circleimageview.CircleImageView) myView.findViewById(R.id.image_department);
num_1 = (TextView) myView.findViewById(R.id.number1);
num_1 = (TextView) myView.findViewById(R.id.number1);
num_2 = (TextView) myView.findViewById(R.id.number2);
num_3 = (TextView) myView.findViewById(R.id.number3);
room_1 = (TextView) myView.findViewById(R.id.room1);
room_2 = (TextView) myView.findViewById(R.id.room2);
room_3 = (TextView) myView.findViewById(R.id.room3);
new DisDepartmentSender(myView.getContext(), urlAddress, accountEmail, departmentName).execute();
//Set data
company_name.setText("Company Name : " + CompanyName);
department_name.setText("Department : " + departmentName);
PicassoClientDepartment.dowloadImage(myView.getContext(), imageUrl, image_department);
//Set Data
num_1.setText(num1);
num_2.setText(num1);
num_3.setText(num1);
room_1.setText(room1);
room_2.setText(room2);
room_3.setText(room3);
return myView;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
if (bundle != null) {
CompanyName = bundle.getString("CompanyName", "noText");
accountEmail = bundle.getString("accountEmail", "noText");
departmentName = bundle.getString("departmentName", "noText");
imageUrl = bundle.getString("imageUrl", "noText");
}
}
public void synchronizeNum(String num1room1, String num2room2, String num3room3) {
String path1[] = num1room1.split("_");
String path2[] = num2room2.split("_");
String path3[] = num3room3.split("_");
num1 = path1[0];
room1 = path1[1];
num2 = path2[0];
room2 = path2[1];
num3 = path3[0];
room3 = path3[1];
/* Fragment currentFragment = getActivity().getFragmentManager().findFragmentByTag("CurrentStatusView");
FragmentTransaction fragTransaction = (getActivity()).getFragmentManager().beginTransaction();
fragTransaction.detach(currentFragment);
fragTransaction.attach(currentFragment);
fragTransaction.commit();*/
}
public void setNum1room1(String num1room1) {
this.num1room1 = num1room1;
}
public String getNum1room1() {
return num1room1;
}
public void setNum2room2(String num2room2) {
this.num2room2 = num2room2;
}
public String getNum2room2() {
return num2room2;
}
public void setNum3room3(String num3room3) {
this.num3room3 = num3room3;
}
public String getNum3room3() {
return num3room3;
}
}
current_department_view.xml
<?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.cheng.freequeue.LoginPage">
<TextView
android:id="#+id/department_name"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="4dp"
android:text="Department : Orthopedic"
android:textSize="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.163" />
<TableLayout
android:id="#+id/tableLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.515"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.458">
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/textView6"
android:layout_width="200dp"
android:layout_height="80dp"
android:layout_margin="0.1sp"
android:background="#drawable/cell_shape"
android:text="Number"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="40dp"
android:textStyle="bold" />
<TextView
android:id="#+id/textView5"
android:layout_width="150dp"
android:layout_height="80dp"
android:layout_marginTop="0.1sp"
android:background="#drawable/cell_shape"
android:text="Room"
android:textAlignment="center"
android:textColor="#080808"
android:textSize="40dp"
android:textStyle="bold" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-5dp">
<TextView
android:id="#+id/number1"
android:layout_width="200dp"
android:layout_height="50dp"
android:layout_margin="0.1sp"
android:background="#drawable/cell_shape_body"
android:text="1001"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="30dp"
android:textStyle="bold" />
<TextView
android:id="#+id/room1"
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_marginTop="0.1sp"
android:background="#drawable/cell_shape_body"
android:text="2"
android:textAlignment="center"
android:textColor="#080808"
android:textSize="30dp"
android:textStyle="bold" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-5dp">
<TextView
android:id="#+id/number2"
android:layout_width="200dp"
android:layout_height="50dp"
android:layout_margin="0.1sp"
android:background="#drawable/cell_shape_body"
android:text="1002"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="30dp"
android:textStyle="bold" />
<TextView
android:id="#+id/room2"
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_marginTop="0.1sp"
android:background="#drawable/cell_shape_body"
android:text="2"
android:textAlignment="center"
android:textColor="#080808"
android:textSize="30dp"
android:textStyle="bold" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-5dp">
<TextView
android:id="#+id/number3"
android:layout_width="200dp"
android:layout_height="50dp"
android:layout_margin="0.1sp"
android:background="#drawable/cell_shape_body"
android:text="1003"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="30dp"
android:textStyle="bold" />
<TextView
android:id="#+id/room3"
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_marginTop="0.1sp"
android:background="#drawable/cell_shape_body"
android:text="2"
android:textAlignment="center"
android:textColor="#080808"
android:textSize="30dp"
android:textStyle="bold" />
</TableRow>
</TableLayout>
<Button
android:id="#+id/btn_booking"
android:layout_width="350dp"
android:layout_height="50dp"
android:background="#d7b9b9b9"
android:text="BOOKING"
android:textColor="#ffffff"
android:textSize="20dp"
android:textStyle="bold"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.965" />
<de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/image_department"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.015"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.048"
app:civ_border_color="#ffffff"
app:srcCompat="#mipmap/ic_launcher" />
<TextView
android:id="#+id/company_name"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Company Name: TNB"
android:textSize="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.064" />
</android.support.constraint.ConstraintLayout>
This Line Error ,NullPointer
Fragment currentFragment=getActivity().getFragmentManager().findFragmentByTag("CurrentStatusView");
Logcat error
04-12 20:52:13.112 3021-3021/com.example.cheng.freequeue E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.cheng.freequeue.DisplayDepartmentStatus.CurrentStatusView.synchronizeNum(CurrentStatusView.java:104)
at com.example.cheng.freequeue.DisplayDepartmentStatus.DisDepartmentParse.onPostExecute(DisDepartmentParse.java:64)
at com.example.cheng.freequeue.DisplayDepartmentStatus.DisDepartmentParse.onPostExecute(DisDepartmentParse.java:18)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5166)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:745)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:561)
at dalvik.system.NativeStart.main(Native Method)
I recommend to create an interface for updating data.
public interface SynchronizeCallback {
void synchronizeNum(String num1room1, String num2room2, String num3room3);
}
Your fragment should implement this interface.
Also set the text to the TextViews inside synchronizeNum():
num_1.setText(num1);
num_2.setText(num1);
num_3.setText(num1);
room_1.setText(room1);
room_2.setText(room2);
room_3.setText(room3);
Pass the interface to your task when you create it:
new DisDepartmentSender(myView.getContext(), urlAddress, accountEmail, departmentName, this).execute();
In onPostExecute of your AsyncTask call
syncronizeCallback.updateValues(newNum1room1, newNum2room2, newNum3room3);
Then you should see the new data.

java.lang.IllegalStateException: Could not find method btnSubmit(View) in a parent or ancestor Context for android:onClick

This Java takes the inputs of Edit Text fields and outputs them into Toast.
I have no idea where or what the error is, any help would be greatly appreciated:
Java
package colonyapplication.colony;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class tenantReg extends Activity {
EditText fullName = (EditText) findViewById(R.id.etFname);
EditText userEmail = (EditText) findViewById(R.id.etEmail);
EditText userPass = (EditText) findViewById(R.id.etPass);
String fName = fullName.getText().toString();
String uEmail = userEmail.getText().toString();
String uPass = userPass.getText().toString();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tenant_reg);
}
public void btnSubmit() {
String tenant = "Tenant";
Toast.makeText(tenantReg.this, "UserName is: " + fName + ". Password is: " + uPass + "email is: " + uEmail + tenant, Toast.LENGTH_LONG).show();
}
}
XML
<?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="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:background="#fcdfaa"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="colonyapplication.colony.tenantReg">
<ImageView
android:id="#+id/imageView2"
android:layout_width="300dp"
android:layout_height="300dp"
android:src="#drawable/colonylogo"
android:layout_above="#+id/passTextBox"
android:layout_centerHorizontal="true"
android:layout_marginBottom="61dp" />
<EditText
android:id="#+id/etFname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/imageView2"
android:layout_alignStart="#+id/imageView2"
android:layout_below="#+id/imageView2"
android:ems="10"
android:hint="Full Name"
android:inputType="textPersonName" />
<EditText
android:id="#+id/etEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/etFname"
android:layout_alignStart="#+id/etFname"
android:layout_centerVertical="true"
android:ems="10"
android:hint="Email"
android:inputType="textEmailAddress" />
<EditText
android:id="#+id/etPass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="29dp"
android:ems="10"
android:hint="Password"
android:inputType="textPassword"
android:layout_below="#+id/etEmail"
android:layout_alignStart="#+id/etEmail"
android:layout_alignEnd="#+id/etEmail" />
<EditText
android:id="#+id/etPassconfirm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="34dp"
android:ems="10"
android:hint="Confirm Password"
android:inputType="textPassword"
android:layout_below="#+id/etPass"
android:layout_alignStart="#+id/etPass"
android:layout_alignEnd="#+id/etPass" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="47dp"
android:background="#EE7600"
android:onClick="btnSubmit"
android:text="Submit"
android:textAllCaps="false"
android:textColor="#ffffff"
android:textSize="17sp"
android:layout_below="#+id/etPassconfirm"
android:layout_alignStart="#+id/etPassconfirm" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"
android:background="#EE7600"
android:textAllCaps="false"
android:textColor="#ffffff"
android:textSize="17sp"
android:layout_alignBaseline="#+id/button"
android:layout_alignBottom="#+id/button"
android:layout_alignEnd="#+id/etPassconfirm"
android:layout_marginEnd="33dp" />
</RelativeLayout>
For whatever reason, when the submit button is clicked, the program stops in the emulator. The error in the Android Monitor states: "java.lang.IllegalStateException: Could not find method btnSubmit(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'button'"
As I see you have 2 Button but I dont know which one is submit button.
well also I can not find the meaning of public void btnSubmit(). As I know you should define tn submit:
Button btnSubmit = (Button) findViewById(R.id.your_btnSubmit_id);
and then use onClickListener method to do somthing when btn clicked
btnsubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Do somthing
}
});
Edit:
You can use your code just replace
public void btnSubmit()
with this:
public void btnSubmit(View v)

java.lang.nullpointerexception : Attempt to invoke void android.widget.EditText.setText(java.lang.CharSequence) on a null object refrence

I am trying to retrieve value from the database and am using EditText to display in the android application. But the project is stopped whenever I try to retrieve it. I am using eclipse to develop the android project.
Select.java
package com.example.erp_medlabplus;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
#SuppressLint("NewApi")
public class SelectActivity extends Activity {
#SuppressLint("NewApi")
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select);
Bundle b = getIntent().getExtras();
EditText ed = (EditText) findViewById(R.id.patient_id);
ed.setText(b.getCharSequence("Contents"));
Button button = (Button) findViewById(R.id.button1);
StrictMode.setThreadPolicy(policy);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String result = null;
InputStream is = null;
EditText editText = (EditText) findViewById(R.id.patient_id);
String v1 = editText.getText().toString();
EditText editText1 = (EditText) findViewById(R.id.CT_Scan);
EditText editText2 = (EditText) findViewById(R.id.MRI_Scan);
EditText editText3 = (EditText) findViewById(R.id.xray);
EditText editText4 = (EditText) findViewById(R.id.ECG);
EditText editText5 = (EditText) findViewById(R.id.Radiology);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", v1));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.42.100:8888/ImageUpload/select.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("log_tag", "connection success ");
}
catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();
}
//parse json data
try {
JSONObject object = new JSONObject(result);
String ch = object.getString("re");
if (ch.equals("success")) {
Toast.makeText(getApplicationContext(), "Retrieval Sucess", Toast.LENGTH_SHORT).show();
JSONObject no = object.getJSONObject("0");
String w = no.getString("CT_Scan");
String w1 = no.getString("MRI_Scan");
String w2 = no.getString("XRay");
String w3 = no.getString("ECG");
String w4 = no.getString("Radiology");
editText1.setText(w);
editText2.setText(w1);
editText3.setText(w2);
editText4.setText(w3);
editText5.setText(w4);
} else {
Toast.makeText(getApplicationContext(), "Record is not available.. Enter valid number", Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_select, menu);
return true;
}
}
activity_select.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
android:background="#drawable/bg3">
<TextView
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_margin="3dp"
android:text="Sample Retrieval"
android:gravity="center"
android:background="#drawable/bg"
android:textColor="#FFFFFF"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/patid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginTop="20dp"
android:text="Patient ID"
android:textColor="#0E52AB"
android:layout_below="#+id/header"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textStyle="bold"
/>
<EditText
android:id="#+id/patient_id"
android:layout_width="130dp"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_height="wrap_content"
android:layout_below="#+id/header"
android:layout_toRightOf="#+id/patid"
android:background="#drawable/edittextdesign"
android:ems="10"
android:numeric="integer" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:text="Retrieve"
android:radius="14dp"
android:layout_below="#+id/patid"
android:gravity="center"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_marginTop="20dp"
android:layout_width="120dp"
android:layout_height="40dp"
android:shadowColor="#259FA8"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="5"
android:background="#drawable/bg"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Tests to be taken:"
android:textColor="#0E52AB"
android:layout_marginTop="20dp"
android:id="#+id/test"
android:layout_below="#+id/button1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textStyle="bold"/>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="20dp"
android:layout_below="#+id/test"
android:textColor="#0E52AB"
android:text="CT Scan"
/>
<EditText
android:id="#+id/CT_Scan"
android:layout_width="130dp"
android:layout_marginTop="10dp"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:inputType="text"
android:ellipsize="start"
android:gravity="center"
android:background="#drawable/edittextdesign"
android:ems="10"
/>
<Button
android:id="#+id/CTScan"
android:layout_width="80dp"
android:layout_height="40dp"
android:textColor="#FFFFFF"
android:ellipsize="start"
android:gravity="center"
android:onClick="scan"
android:text="Scan"
android:background="#drawable/bg"
android:layout_above="#+id/textView2"
android:layout_toRightOf="#+id/patient_id"
android:layout_toEndOf="#+id/patient_id" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/CT_Scan"
android:layout_marginTop="10dp"
android:text="MRI Scan"
android:textColor="#0E52AB"/>
<EditText
android:id="#+id/MRI_Scan"
android:layout_width="130dp"
android:layout_height="wrap_content"
android:inputType="text"
android:background="#drawable/edittextdesign"
android:layout_marginTop="10dp"
android:ellipsize="start"
android:gravity="center"
android:layout_below="#+id/textView2"
android:ems="10" />
<Button
android:id="#+id/MRIScan"
android:layout_width="80dp"
android:layout_height="40dp"
android:textColor="#FFFFFF"
android:ellipsize="start"
android:gravity="center"
android:onClick="scan"
android:text="Scan"
android:background="#drawable/bg"
android:layout_above="#+id/textView3"
android:layout_alignLeft="#+id/CTScan"
android:layout_alignStart="#+id/CTScan" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/MRI_Scan"
android:layout_marginTop="10dp"
android:text="XRay"
android:textColor="#0E52AB"/>
<EditText
android:id="#+id/XRay"
android:layout_width="130dp"
android:layout_height="wrap_content"
android:inputType="text"
android:background="#drawable/edittextdesign"
android:ellipsize="start"
android:gravity="center"
android:layout_below="#+id/textView3"
android:layout_marginTop="10dp"
android:ems="10" />
<Button
android:id="#+id/xRay"
android:layout_width="80dp"
android:layout_height="40dp"
android:textColor="#FFFFFF"
android:ellipsize="start"
android:gravity="center"
android:onClick="scan"
android:text="Scan"
android:background="#drawable/bg"
android:layout_above="#+id/textView4"
android:layout_alignLeft="#+id/MRIScan"
android:layout_alignStart="#+id/MRIScan" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp"
android:layout_below="#+id/XRay"
android:text="ECG"
android:textColor="#0E52AB"/>
<EditText
android:id="#+id/ECG"
android:layout_width="130dp"
android:layout_height="wrap_content"
android:inputType="text"
android:background="#drawable/edittextdesign"
android:ellipsize="start"
android:gravity="center"
android:layout_below="#+id/textView4"
android:layout_marginTop="10dp"
android:ems="10" />
<Button
android:id="#+id/E_C_G"
android:layout_width="80dp"
android:layout_height="40dp"
android:textColor="#FFFFFF"
android:ellipsize="start"
android:gravity="center"
android:onClick="scan"
android:text="Scan"
android:background="#drawable/bg"
android:layout_above="#+id/textView5"
android:layout_alignLeft="#+id/xRay"
android:layout_alignStart="#+id/xRay" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Radiology"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp"
android:layout_below="#+id/ECG"
android:textColor="#0E52AB"/>
<EditText
android:id="#+id/Radiology"
android:layout_width="130dp"
android:layout_height="wrap_content"
android:inputType="text"
android:background="#drawable/edittextdesign"
android:ellipsize="start"
android:gravity="center"
android:layout_below="#+id/textView5"
android:layout_marginTop="10dp"
android:ems="10" />
<Button
android:id="#+id/radiologyScan"
android:layout_width="80dp"
android:layout_height="40dp"
android:textColor="#FFFFFF"
android:ellipsize="start"
android:gravity="center"
android:onClick="scan"
android:text="Scan"
android:background="#drawable/bg"
android:layout_alignBottom="#+id/Radiology"
android:layout_alignLeft="#+id/E_C_G"
android:layout_alignStart="#+id/E_C_G" />
</RelativeLayout>
select.php:
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("erp", $con);
$v1=$_REQUEST['id'];
//$v1=2;
if($v1==NULL) {
$r["re"]="Enter the number!!!";
print(json_encode($r));
die('Could not connect: ' . mysql_error());
}
else {
$i=mysql_query("SELECT * FROM scan_entry_value WHERE id='$v1'",$con);
$check='';
//if($i === FALSE) {
//die(mysql_error());} // TODO: better error handling
while($row = mysql_fetch_array($i)) {
//echo $row['CT_Scan'];
$r[]=$row;
$check=$row['id'];
}
if($check==NULL) {
$r["re"]="Record is not available";
print(json_encode($r));
}
else {
$r["re"]="success";
print(json_encode($r));
}
}
mysql_close($con);
?>
I'm going to assume that this line's the cause of your problem:
EditText editText3=(EditText)findViewById(R.id.xray);
Your activity_select.xml doesn't define a control with the ID xray hence the call to findViewById returns a null and your call to editText3.setText() results in an NPE. It does, however, have TextViews with IDs XRay and xRay. Try using one of those instead.

XML wont display stored SQLite data

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.

getting a force close error on activity for doing set text

This is the error i get. You can see all the codes that are affected by this session below. Where i put the intent, where i get it, the classes and paremeters involved.
11-30 20:37:32.870: E/AndroidRuntime(809): FATAL EXCEPTION: main
11-30 20:37:32.870: E/AndroidRuntime(809): java.lang.RuntimeException: Unable to start activity ComponentInfo{kfc.project/kfc.project.productdetail}: java.lang.NullPointerException
11-30 20:37:32.870: E/AndroidRuntime(809): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
11-30 20:37:32.870: E/AndroidRuntime(809): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
11-30 20:37:32.870: E/AndroidRuntime(809): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
11-30 20:37:32.870: E/AndroidRuntime(809): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
11-30 20:37:32.870: E/AndroidRuntime(809): at android.os.Handler.dispatchMessage(Handler.java:99)
11-30 20:37:32.870: E/AndroidRuntime(809): at android.os.Looper.loop(Looper.java:123)
11-30 20:37:32.870: E/AndroidRuntime(809): at android.app.ActivityThread.main(ActivityThread.java:3683)
11-30 20:37:32.870: E/AndroidRuntime(809): at java.lang.reflect.Method.invokeNative(Native Method)
11-30 20:37:32.870: E/AndroidRuntime(809): at java.lang.reflect.Method.invoke(Method.java:507)
11-30 20:37:32.870: E/AndroidRuntime(809): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-30 20:37:32.870: E/AndroidRuntime(809): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-30 20:37:32.870: E/AndroidRuntime(809): at dalvik.system.NativeStart.main(Native Method)
11-30 20:37:32.870: E/AndroidRuntime(809): Caused by: java.lang.NullPointerException
11-30 20:37:32.870: E/AndroidRuntime(809): at kfc.project.productdetail.onCreate(productdetail.java:19)
11-30 20:37:32.870: E/AndroidRuntime(809): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-30 20:37:32.870: E/AndroidRuntime(809): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
11-30 20:37:32.870: E/AndroidRuntime(809): ... 11 more
This is the code of the java file
package kfc.project;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class productdetail extends Activity{
#Override
protected void onCreate(Bundle bundle) {
// TODO Auto-generated method stub
super.onCreate(bundle);
setContentView(R.layout.productdetail);
Bundle extras = getIntent().getExtras();
String name = extras.getString("name");
if (name != null) {
TextView text1 = (TextView) findViewById(R.id.servingsize);
text1.setText(name);
}
/*
Intent intent = getIntent();
String str = intent.getStringExtra("name");*/
}
}
This is the code for the xml file wherein the error goes comes in when i go to this page. It isnt about cleaning the project and the manifest as well cause it works when i delete the settext code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:scrollbarAlwaysDrawVerticalTrack="true"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:gravity="top|center"
android:background="#drawable/bg">
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:gravity="right">
<Button
android:id="#+id/button1"
android:background="#drawable/button2"
android:textColor="#FFFFFF"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text="ADD TO MENU" android:gravity="right" android:paddingRight="4sp" android:paddingTop="10sp"/>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:gravity="left">
</TableRow>
<TableLayout
android:id="#+id/tableLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TableRow
android:id="#+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TableRow>
<TableRow
android:id="#+id/tableRow6"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:text="Amount Per Serving: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="20"
android:textAppearance="?android:attr/textAppearanceMedium" />
</TableRow>
<TableRow
android:id="#+id/tableRow7"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calories:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView17"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="30"
android:textAppearance="?android:attr/textAppearanceMedium" />
</TableRow>
<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:src="#android:drawable/divider_horizontal_dark"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingBottom="2dp"
android:paddingTop="2dp" />
<TableRow
android:id="#+id/tableRow8"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TableRow
android:id="#+id/tableRow14"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:text="% Daily Value: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView21"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="35"
android:textAppearance="?android:attr/textAppearanceMedium" />
</TableRow>
</TableRow>
</TableLayout>
<TableLayout
android:id="#+id/tableLayout3"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TableRow
android:id="#+id/tableRow9"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Total Fat:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView22"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="60"
android:textAppearance="?android:attr/textAppearanceMedium" />
</TableRow>
<TableRow
android:id="#+id/tableRow10"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Saturated Fat:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView23"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="34"
android:textAppearance="?android:attr/textAppearanceMedium" />
</TableRow>
<TableRow
android:id="#+id/tableRow11"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView10"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Trans Fat:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView24"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="53"
android:textAppearance="?android:attr/textAppearanceMedium" />
</TableRow>
<TableRow
android:id="#+id/tableRow12"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cholesterol:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView25"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="25"
android:textAppearance="?android:attr/textAppearanceMedium" />
</TableRow>
<TableRow
android:id="#+id/tableRow13"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sodium:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView26"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="10"
android:textAppearance="?android:attr/textAppearanceMedium" />
</TableRow>
<TableRow
android:id="#+id/tableRow15"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView13"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Total Carbohydrate:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView27"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="200"
android:textAppearance="?android:attr/textAppearanceMedium" />
</TableRow>
<TableRow
android:id="#+id/tableRow16"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView14"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Dietary Fiber:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView28"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="34"
android:textAppearance="?android:attr/textAppearanceMedium" />
</TableRow>
<TableRow
android:id="#+id/tableRow17"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView15"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Sugars:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView29"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="16"
android:textAppearance="?android:attr/textAppearanceMedium" />
</TableRow>
<TableRow
android:id="#+id/tableRow18"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView16"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Protein:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView30"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="40"
android:textAppearance="?android:attr/textAppearanceMedium" />
</TableRow>
<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:src="#android:drawable/divider_horizontal_dark"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingBottom="2dp"
android:paddingTop="2dp" />
<TableRow
android:id="#+id/tableRow24"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TableRow>
<TableRow
android:id="#+id/tableRow19"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TableRow>
</TableLayout>
<TableLayout
android:id="#+id/tableLayout4"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TableRow
android:id="#+id/tableRow20"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TableRow>
<TableRow
android:id="#+id/tableRow21"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TableRow>
<TableRow
android:id="#+id/tableRow22"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView19"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Vitamin A: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView31"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="40"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView20"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Vitamin C: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView32"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="30"
android:textAppearance="?android:attr/textAppearanceMedium" />
</TableRow>
<TableRow
android:id="#+id/tableRow23"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calcium: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView33"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="35"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView18"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Iron: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView34"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="40"
android:textAppearance="?android:attr/textAppearanceMedium" />
</TableRow>
<TableRow
android:id="#+id/tableRow25"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TableRow>
</TableLayout>
</LinearLayout>
This is where i put the extras
package kfc.project;
import java.util.ArrayList;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class ProductListView extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ProductList pl = new ProductList();
//setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, PRODUCTS));
setListAdapter(new ArrayAdapter<Product>(this, R.layout.list_item, pl.getList() ));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), "View Product", Toast.LENGTH_SHORT).show();
Product product = pl.getList().get(position);
Intent intent = new Intent(ProductListView.this, productdetail.class);
intent.putExtra("name",product.getName());
intent.putExtra("calories", product.getCalories());
intent.putExtra("serving size", product.getServingSize());
intent.putExtra("fat", product.getFat());
intent.putExtra("saturated fat", product.getSaturatedFat());
intent.putExtra("trans fat", product.getTransFat());
intent.putExtra("cholesterol", product.getCholesterol());
intent.putExtra("sodium", product.getSodium());
intent.putExtra("carbs", product.getCarbs());
intent.putExtra("protein", product.getProtein());
ProductListView.this.startActivity(intent);
startActivity(new Intent("kfc.project.PRODUCTDETAIL"));
}
});
}
//TEST STRING ARRAY
static String[] PRODUCTS = new String[] {
"Chicken", "Rice", "Coke", "Chicken Burger"
};
}
This is where the array list items are added
package kfc.project;
import java.util.ArrayList;
public class ProductList {
ArrayList<Product> list;
public ProductList (){
list = new ArrayList<Product>();
//CREATE PRODUCT HERE
Product chicken;
list.add(new Product("ChickenTest",99));
Product rice;
list.add(new Product("RiceTest",11));
}
public String[] getNames (){
int c = 0;
int size = list.size() - 1;
String[] names = new String[size];
while (size >= c) {
//names.add(list.get(c).getName());
names[c] = list.get(c).getName();
c++;
}
c = 0;
return names;
}
public ArrayList<Product> getList (){
return list;
}
}
This is the code for the parameteres
package kfc.project;
public class Product {
String name;
int servingSize;
int calories;
int fat;
int saturatedFat;
int transFat;
int cholesterol;
int sodium;
int carbs;
int protein;
public Product (String name, int servingSize, int calories, int fat, int saturatedFat, int transFat, int cholesterol, int sodium, int carbs, int protein){
this.name=name;
this.calories=calories;
this.servingSize=servingSize;
this.fat=fat;
this.saturatedFat=saturatedFat;
this.transFat=transFat;
this.cholesterol=cholesterol;
this.sodium=sodium;
this.carbs=carbs;
this.protein=protein;
}
public Product (String name, int servingSize){
this.name=name;
this.servingSize=servingSize;
}
public String getName() {
return name;
}
public int getServingSize() {
return servingSize;
}
public int getCalories() {
return calories;
}
public int getFat() {
return fat;
}
public int getSaturatedFat() {
return saturatedFat;
}
public int getTransFat() {
return transFat;
}
public int getCholesterol() {
return cholesterol;
}
public int getSodium() {
return sodium;
}
public int getCarbs() {
return carbs;
}
public int getProtein() {
return protein;
}
}
the extras variable is NULL
Bundle extras = getIntent().getExtras();
String name = extras.getString("name");
Update:
First, this line is not needed
startActivity(new Intent("kfc.project.PRODUCTDETAIL"));
Second, you need to getExtra() from getIntent() in productdetail, not getExtras().
For sample:
// get intent object once
Intent receivedIntent = getIntent();
// get product name
String productName = receivedIntent.getExtra("name");
// get serving size
int servingSize = receivedIntent.getExtra("serving size");
// do the same for other props
Bundle extras = getIntent().getExtras();
String name = extras.getString("name");
getExtras() may return null if there are no extras stored in the intent. Check the extras for null.
You might need to do a null check for the extras.
Just remove this line
startActivity(new Intent("kfc.project.PRODUCTDETAIL"));
It starts your activity without extra, causing your extras to be null

Categories